context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
//------------------------------------------------------------------------------
// <copyright file="AssetTagService.cs">
// Copyright (c) 2014-present Andrea Di Giorgi
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
// </copyright>
// <author>Andrea Di Giorgi</author>
// <website>https://github.com/Ithildir/liferay-sdk-builder-windows</website>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace Liferay.SDK.Service.V62.AssetTag
{
public class AssetTagService : ServiceBase
{
public AssetTagService(ISession session)
: base(session)
{
}
public async Task<dynamic> AddTagAsync(string name, IEnumerable<string> tagProperties, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("name", name);
_parameters.Add("tagProperties", tagProperties);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/assettag/add-tag", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task DeleteTagAsync(long tagId)
{
var _parameters = new JsonObject();
_parameters.Add("tagId", tagId);
var _command = new JsonObject()
{
{ "/assettag/delete-tag", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task DeleteTagsAsync(IEnumerable<long> tagIds)
{
var _parameters = new JsonObject();
_parameters.Add("tagIds", tagIds);
var _command = new JsonObject()
{
{ "/assettag/delete-tags", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task<IEnumerable<dynamic>> GetGroupTagsAsync(long groupId)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
var _command = new JsonObject()
{
{ "/assettag/get-group-tags", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<IEnumerable<dynamic>> GetGroupTagsAsync(long groupId, int start, int end, JsonObjectWrapper obc)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("start", start);
_parameters.Add("end", end);
this.MangleWrapper(_parameters, "obc", "com.liferay.portal.kernel.util.OrderByComparator", obc);
var _command = new JsonObject()
{
{ "/assettag/get-group-tags", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<long> GetGroupTagsCountAsync(long groupId)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
var _command = new JsonObject()
{
{ "/assettag/get-group-tags-count", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (long)_obj;
}
public async Task<dynamic> GetGroupTagsDisplayAsync(long groupId, string name, int start, int end)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("name", name);
_parameters.Add("start", start);
_parameters.Add("end", end);
var _command = new JsonObject()
{
{ "/assettag/get-group-tags-display", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<IEnumerable<dynamic>> GetGroupsTagsAsync(IEnumerable<long> groupIds)
{
var _parameters = new JsonObject();
_parameters.Add("groupIds", groupIds);
var _command = new JsonObject()
{
{ "/assettag/get-groups-tags", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<dynamic> GetJsonGroupTagsAsync(long groupId, string name, int start, int end)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("name", name);
_parameters.Add("start", start);
_parameters.Add("end", end);
var _command = new JsonObject()
{
{ "/assettag/get-json-group-tags", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> GetTagAsync(long tagId)
{
var _parameters = new JsonObject();
_parameters.Add("tagId", tagId);
var _command = new JsonObject()
{
{ "/assettag/get-tag", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<IEnumerable<dynamic>> GetTagsAsync(string className, long classPK)
{
var _parameters = new JsonObject();
_parameters.Add("className", className);
_parameters.Add("classPK", classPK);
var _command = new JsonObject()
{
{ "/assettag/get-tags", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<IEnumerable<dynamic>> GetTagsAsync(long groupId, long classNameId, string name)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("classNameId", classNameId);
_parameters.Add("name", name);
var _command = new JsonObject()
{
{ "/assettag/get-tags", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<IEnumerable<dynamic>> GetTagsAsync(long groupId, string name, IEnumerable<string> tagProperties, int start, int end)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("name", name);
_parameters.Add("tagProperties", tagProperties);
_parameters.Add("start", start);
_parameters.Add("end", end);
var _command = new JsonObject()
{
{ "/assettag/get-tags", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<IEnumerable<dynamic>> GetTagsAsync(IEnumerable<long> groupIds, string name, IEnumerable<string> tagProperties, int start, int end)
{
var _parameters = new JsonObject();
_parameters.Add("groupIds", groupIds);
_parameters.Add("name", name);
_parameters.Add("tagProperties", tagProperties);
_parameters.Add("start", start);
_parameters.Add("end", end);
var _command = new JsonObject()
{
{ "/assettag/get-tags", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<IEnumerable<dynamic>> GetTagsAsync(long groupId, long classNameId, string name, int start, int end, JsonObjectWrapper obc)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("classNameId", classNameId);
_parameters.Add("name", name);
_parameters.Add("start", start);
_parameters.Add("end", end);
this.MangleWrapper(_parameters, "obc", "com.liferay.portal.kernel.util.OrderByComparator", obc);
var _command = new JsonObject()
{
{ "/assettag/get-tags", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<long> GetTagsCountAsync(long groupId, string name)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("name", name);
var _command = new JsonObject()
{
{ "/assettag/get-tags-count", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (long)_obj;
}
public async Task<long> GetTagsCountAsync(long groupId, long classNameId, string name)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("classNameId", classNameId);
_parameters.Add("name", name);
var _command = new JsonObject()
{
{ "/assettag/get-tags-count", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (long)_obj;
}
public async Task<long> GetTagsCountAsync(long groupId, string name, IEnumerable<string> tagProperties)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("name", name);
_parameters.Add("tagProperties", tagProperties);
var _command = new JsonObject()
{
{ "/assettag/get-tags-count", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (long)_obj;
}
public async Task MergeTagsAsync(long fromTagId, long toTagId, bool overrideProperties)
{
var _parameters = new JsonObject();
_parameters.Add("fromTagId", fromTagId);
_parameters.Add("toTagId", toTagId);
_parameters.Add("overrideProperties", overrideProperties);
var _command = new JsonObject()
{
{ "/assettag/merge-tags", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task MergeTagsAsync(IEnumerable<long> fromTagIds, long toTagId, bool overrideProperties)
{
var _parameters = new JsonObject();
_parameters.Add("fromTagIds", fromTagIds);
_parameters.Add("toTagId", toTagId);
_parameters.Add("overrideProperties", overrideProperties);
var _command = new JsonObject()
{
{ "/assettag/merge-tags", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task<IEnumerable<dynamic>> SearchAsync(long groupId, string name, IEnumerable<string> tagProperties, int start, int end)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("name", name);
_parameters.Add("tagProperties", tagProperties);
_parameters.Add("start", start);
_parameters.Add("end", end);
var _command = new JsonObject()
{
{ "/assettag/search", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<IEnumerable<dynamic>> SearchAsync(IEnumerable<long> groupIds, string name, IEnumerable<string> tagProperties, int start, int end)
{
var _parameters = new JsonObject();
_parameters.Add("groupIds", groupIds);
_parameters.Add("name", name);
_parameters.Add("tagProperties", tagProperties);
_parameters.Add("start", start);
_parameters.Add("end", end);
var _command = new JsonObject()
{
{ "/assettag/search", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<dynamic> UpdateTagAsync(long tagId, string name, IEnumerable<string> tagProperties, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("tagId", tagId);
_parameters.Add("name", name);
_parameters.Add("tagProperties", tagProperties);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/assettag/update-tag", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
}
}
| |
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using SharpDX.D3DCompiler;
using SharpDX.Direct3D;
using SharpDX.Direct3D11;
using SharpDX.IO;
using SharpDX.Toolkit.Diagnostics;
namespace SharpDX.Toolkit.Graphics
{
/// <summary>
/// Main class used to compile a Toolkit FX file.
/// </summary>
internal class EffectCompilerInternal
{
private static Regex MatchVariableArray = new Regex(@"(.*)\[(\d+)\]");
private static readonly Dictionary<string, ValueConverter> ValueConverters = new Dictionary<string, ValueConverter>()
{
{
"float4",
new ValueConverter("float4", 4, ToFloat,
(compiler, parameters) => new Vector4((float) parameters[0], (float) parameters[1], (float) parameters[2], (float) parameters[3]))
},
{
"float3",
new ValueConverter("float3", 3, ToFloat, (compiler, parameters) => new Vector3((float) parameters[0], (float) parameters[1], (float) parameters[2]))
},
{"float2", new ValueConverter("float2", 2, ToFloat, (compiler, parameters) => new Vector2((float) parameters[0], (float) parameters[1]))},
{"float", new ValueConverter("float", 1, ToFloat, (compiler, parameters) => (float) parameters[0])},
};
private readonly List<string> currentExports = new List<string>();
private EffectCompilerFlags compilerFlags;
private EffectData effectData;
private EffectData.Effect effect;
private List<string> includeDirectoryList;
public IncludeFileDelegate IncludeFileDelegate;
private Include includeHandler;
private FeatureLevel level;
private EffectCompilerLogger logger;
private List<ShaderMacro> macros;
private EffectParserResult parserResult;
private EffectData.Pass pass;
private string preprocessorText;
private EffectData.Technique technique;
private int nextSubPassCount;
private StreamOutputElement[] currentStreamOutputElements;
private FileDependencyList dependencyList;
public EffectCompilerInternal()
{
}
/// <summary>
/// Checks for changes from a dependency file.
/// </summary>
/// <param name="dependencyFilePath">The dependency file path.</param>
/// <returns><c>true</c> if a file has been updated, <c>false</c> otherwise</returns>
public bool CheckForChanges(string dependencyFilePath)
{
return FileDependencyList.FromFile(dependencyFilePath).CheckForChanges();
}
/// <summary>
/// Compiles an effect from file.
/// </summary>
/// <param name="filePath">The file path.</param>
/// <param name="flags">The flags.</param>
/// <param name="macros">The macrosArgs.</param>
/// <param name="includeDirectoryList">The include directory list.</param>
/// <param name="alloDynamicCompiling">if set to <c>true</c> [allo dynamic compiling].</param>
/// <param name="dependencyFilePath">The dependency file path.</param>
/// <returns>The result of compilation.</returns>
public EffectCompilerResult CompileFromFile(string filePath, EffectCompilerFlags flags = EffectCompilerFlags.None, List<EffectData.ShaderMacro> macros = null, List<string> includeDirectoryList = null, bool alloDynamicCompiling = false, string dependencyFilePath = null)
{
return Compile(NativeFile.ReadAllText(filePath, Encoding.UTF8, NativeFileShare.ReadWrite), filePath, flags, macros, includeDirectoryList, alloDynamicCompiling, dependencyFilePath);
}
/// <summary>
/// Compiles an effect from the specified source code and file path.
/// </summary>
/// <param name="sourceCode">The source code.</param>
/// <param name="filePath">The file path.</param>
/// <param name="flags">The flags.</param>
/// <param name="macrosArgs">The macrosArgs.</param>
/// <param name="includeDirectoryList">The include directory list.</param>
/// <param name="allowDynamicCompiling">if set to <c>true</c> [allow dynamic compiling].</param>
/// <param name="dependencyFilePath">The dependency file path.</param>
/// <returns>The result of compilation.</returns>
public EffectCompilerResult Compile(string sourceCode, string filePath, EffectCompilerFlags flags = EffectCompilerFlags.None, List<EffectData.ShaderMacro> macrosArgs = null, List<string> includeDirectoryList = null, bool allowDynamicCompiling = false, string dependencyFilePath = null)
{
var nativeMacros = new List<ShaderMacro>();
if (macrosArgs != null)
{
foreach (var macro in macrosArgs)
{
nativeMacros.Add(new ShaderMacro(macro.Name, macro.Value));
}
}
compilerFlags = flags;
this.macros = nativeMacros;
this.includeDirectoryList = includeDirectoryList ?? new List<string>();
InternalCompile(sourceCode, filePath);
var result = new EffectCompilerResult(dependencyFilePath, effectData, logger);
// Handle Dependency FilePath
if (!result.HasErrors && dependencyFilePath != null && dependencyList != null)
{
dependencyList.Save(dependencyFilePath);
// If dynamic compiling, store the parameters used to compile this effect directly in the bytecode
if (allowDynamicCompiling && result.EffectData != null)
{
var compilerArguments = new EffectData.CompilerArguments { FilePath = filePath, DependencyFilePath = dependencyFilePath, Macros = new List<EffectData.ShaderMacro>(), IncludeDirectoryList = new List<string>() };
if (macrosArgs != null)
{
compilerArguments.Macros.AddRange(macrosArgs);
}
if (includeDirectoryList != null)
{
compilerArguments.IncludeDirectoryList.AddRange(includeDirectoryList);
}
result.EffectData.Description.Arguments = compilerArguments;
}
}
return result;
}
/// <summary>
/// Disassembles a shader HLSL bytecode to asm code.
/// </summary>
/// <param name="shader">The shader.</param>
/// <returns>A string containing asm code decoded from HLSL bytecode.</returns>
public string DisassembleShader(EffectData.Shader shader)
{
return new ShaderBytecode(shader.Bytecode).Disassemble(DisassemblyFlags.EnableColorCode | DisassemblyFlags.EnableInstructionNumbering);
}
private void InternalCompile(string sourceCode, string fileName)
{
effectData = null;
fileName = fileName.Replace(@"\\", @"\");
logger = new EffectCompilerLogger();
var parser = new EffectParser { Logger = logger, IncludeFileCallback = IncludeFileDelegate};
parser.Macros.AddRange(macros);
parser.IncludeDirectoryList.AddRange(includeDirectoryList);
parserResult = parser.Parse(sourceCode, fileName);
dependencyList = parserResult.DependencyList;
if (logger.HasErrors) return;
// Get back include handler.
includeHandler = parserResult.IncludeHandler;
effectData = new EffectData
{
Shaders = new List<EffectData.Shader>(),
Description = new EffectData.Effect()
{
Name = Path.GetFileNameWithoutExtension(fileName),
Techniques = new List<EffectData.Technique>(),
}
};
effect = effectData.Description;
if (parserResult.Shader != null)
{
foreach (var techniqueAst in parserResult.Shader.Techniques)
{
HandleTechnique(techniqueAst);
}
}
}
private void HandleTechnique(Ast.Technique techniqueAst)
{
technique = new EffectData.Technique()
{
Name = techniqueAst.Name,
Passes = new List<EffectData.Pass>()
};
// Check that the name of this technique is not already used.
if (technique.Name != null)
{
foreach (var registeredTechnique in effect.Techniques)
{
if (registeredTechnique.Name == technique.Name)
{
logger.Error("A technique with the same name [{0}] already exist", techniqueAst.Span, technique.Name);
break;
}
}
}
// Adds the technique to the list of technique for the current effect
effect.Techniques.Add(technique);
// Process passes for this technique
foreach (var passAst in techniqueAst.Passes)
{
HandlePass(passAst);
}
}
private void HandlePass(Ast.Pass passAst)
{
pass = new EffectData.Pass()
{
Name = passAst.Name,
Pipeline = new EffectData.Pipeline(),
Properties = new CommonData.PropertyCollection()
};
// Clear current exports
currentExports.Clear();
// Check that the name of this pass is not already used.
if (pass.Name != null)
{
foreach (var registeredPass in technique.Passes)
{
if (registeredPass.Name == pass.Name)
{
logger.Error("A pass with the same name [{0}] already exist", passAst.Span, pass.Name);
break;
}
}
}
// Adds the pass to the list of pass for the current technique
technique.Passes.Add(pass);
if (nextSubPassCount > 0)
{
pass.IsSubPass = true;
nextSubPassCount--;
}
// Process all statements inside this pass.
foreach (var statement in passAst.Statements)
{
var expressionStatement = statement as Ast.ExpressionStatement;
if (expressionStatement == null)
continue;
HandleExpression(expressionStatement.Expression);
}
// Check pass consistency (mainly for the GS)
var gsLink = pass.Pipeline[EffectShaderType.Geometry];
if (gsLink != null && gsLink.IsNullShader && (gsLink.StreamOutputRasterizedStream >= 0 || gsLink.StreamOutputElements != null))
{
if (pass.Pipeline[EffectShaderType.Vertex] == null || pass.Pipeline[EffectShaderType.Vertex].IsNullShader)
{
logger.Error("Cannot specify StreamOutput for null geometry shader / vertex shader", passAst.Span);
}
else
{
// For null geometry shaders with StreamOutput, directly use the VertexShader
gsLink.Index = pass.Pipeline[EffectShaderType.Vertex].Index;
gsLink.ImportName = pass.Pipeline[EffectShaderType.Vertex].ImportName;
}
}
}
private void HandleExpression(Ast.Expression expression)
{
if (expression is Ast.AssignExpression)
{
HandleAssignExpression((Ast.AssignExpression) expression);
}
else if (expression is Ast.MethodExpression)
{
HandleMethodExpression((Ast.MethodExpression) expression);
}
else
{
logger.Error("Unsupported expression type [{0}]", expression.Span, expression.GetType().Name);
}
}
private void HandleAssignExpression(Ast.AssignExpression expression)
{
switch (expression.Name.Text)
{
case "Export":
HandleExport(expression.Value);
break;
case EffectData.PropertyKeys.Blending:
case EffectData.PropertyKeys.DepthStencil:
case EffectData.PropertyKeys.Rasterizer:
HandleAttribute<string>(expression);
break;
case EffectData.PropertyKeys.BlendingColor:
HandleAttribute<Vector4>(expression);
break;
case EffectData.PropertyKeys.BlendingSampleMask:
HandleAttribute<uint>(expression);
break;
case EffectData.PropertyKeys.DepthStencilReference:
HandleAttribute<int>(expression);
break;
case "ShareConstantBuffers":
HandleShareConstantBuffers(expression.Value);
break;
case "EffectName":
HandleEffectName(expression.Value);
break;
case "SubPassCount":
HandleSubPassCount(expression.Value);
break;
case "Preprocessor":
HandlePreprocessor(expression.Value);
break;
case "Profile":
HandleProfile(expression.Value);
break;
case "VertexShader":
CompileShader(EffectShaderType.Vertex, expression.Value);
break;
case "PixelShader":
CompileShader(EffectShaderType.Pixel, expression.Value);
break;
case "GeometryShader":
CompileShader(EffectShaderType.Geometry, expression.Value);
break;
case "StreamOutput":
HandleStreamOutput(expression.Value);
break;
case "StreamOutputRasterizedStream":
HandleStreamOutputRasterizedStream(expression.Value);
break;
case "DomainShader":
CompileShader(EffectShaderType.Domain, expression.Value);
break;
case "HullShader":
CompileShader(EffectShaderType.Hull, expression.Value);
break;
case "ComputeShader":
CompileShader(EffectShaderType.Compute, expression.Value);
break;
default:
HandleAttribute(expression);
break;
}
}
private void HandleStreamOutputRasterizedStream(Ast.Expression expression)
{
object value;
if (!ExtractValue(expression, out value))
return;
if (!(value is int))
{
logger.Error("StreamOutputRasterizedStream value [{0}] must be an integer", expression.Span, value);
return;
}
if (pass.Pipeline[EffectShaderType.Geometry] == null)
{
pass.Pipeline[EffectShaderType.Geometry] = new EffectData.ShaderLink();
}
pass.Pipeline[EffectShaderType.Geometry].StreamOutputRasterizedStream = (int)value;
}
private static readonly Regex splitSODeclartionRegex = new Regex(@"\s*;\s*");
private static readonly Regex soDeclarationItemRegex = new Regex(@"^\s*(\d+)?\s*:?\s*([A-Za-z][A-Za-z0-9_]*)(\.[xyzw]+|\.[rgba]+)?$");
private static readonly Regex soSemanticIndex = new Regex(@"^([A-Za-z][A-Za-z0-9_]*?)([0-9]*)?$");
private static readonly List<char> xyzwrgbaComponents = new List<char>() { 'x', 'y', 'z', 'w', 'r', 'g', 'b', 'a' };
private void HandleStreamOutput(Ast.Expression expression)
{
var values = ExtractStringOrArrayOfStrings(expression);
if (values == null) return;
if (values.Count == 0 || values.Count > 4)
{
logger.Error("Invalid number [{0}] of stream output declarations. Maximum allowed is 4", expression.Span, values.Count);
return;
}
var elements = new List<StreamOutputElement>();
int streamIndex = 0;
foreach (var soDeclarationTexts in values)
{
if (string.IsNullOrEmpty(soDeclarationTexts))
{
logger.Error("StreamOutput declaration cannot be null or empty", expression.Span);
return;
}
// Parse a single string "[<slot> :] <semantic>[<index>][.<mask>]; [[<slot> :] <semantic>[<index>][.<mask>][;]]"
var text = soDeclarationTexts.Trim(' ', '\t', ';');
var declarationTextItems = splitSODeclartionRegex.Split(text);
foreach (var soDeclarationText in declarationTextItems)
{
StreamOutputElement element;
if (!ParseStreamOutputElement(soDeclarationText, expression.Span, out element))
{
return;
}
element.Stream = streamIndex;
elements.Add(element);
}
streamIndex++;
}
if (elements.Count == 0)
{
logger.Error("Invalid number [0] of stream output declarations. Expected > 0", expression.Span);
return;
}
if (pass.Pipeline[EffectShaderType.Geometry] == null)
{
pass.Pipeline[EffectShaderType.Geometry] = new EffectData.ShaderLink();
}
pass.Pipeline[EffectShaderType.Geometry].StreamOutputElements = elements.ToArray();
}
private bool ParseStreamOutputElement(string text, SourceSpan span, out StreamOutputElement streamOutputElement)
{
streamOutputElement = new StreamOutputElement();
var match = soDeclarationItemRegex.Match(text);
if (!match.Success)
{
logger.Error("Invalid StreamOutput declaration [{0}]. Must be of the form [<slot> :] <semantic>[<index>][.<mask>]", span, text);
return false;
}
// Parse slot if any
var slot = match.Groups[1].Value;
int slotIndex = 0;
if (!string.IsNullOrEmpty(slot))
{
int.TryParse(slot, out slotIndex);
streamOutputElement.OutputSlot = (byte)slotIndex;
}
// Parse semantic index if any
var semanticAndIndex = match.Groups[2].Value;
var matchSemanticAndIndex = soSemanticIndex.Match(semanticAndIndex);
streamOutputElement.SemanticName = matchSemanticAndIndex.Groups[1].Value;
var semanticIndexText = matchSemanticAndIndex.Groups[2].Value;
int semanticIndex = 0;
if (!string.IsNullOrEmpty(semanticIndexText))
{
int.TryParse(semanticIndexText, out semanticIndex);
streamOutputElement.SemanticIndex = (byte)semanticIndex;
}
// Parse the mask
var mask = match.Groups[3].Value;
int startComponent = -1;
int currentIndex = 0;
int countComponent = 1;
if (!string.IsNullOrEmpty(mask))
{
mask = mask.Substring(1);
foreach (var maskItem in mask.ToCharArray())
{
var nextIndex = xyzwrgbaComponents.IndexOf(maskItem);
if (startComponent < 0)
{
startComponent = nextIndex;
}
else if (nextIndex != (currentIndex + 1))
{
logger.Error("Invalid mask [{0}]. Must be of the form [xyzw] or [rgba] with increasing consecutive component and no duplicate", span, mask);
return false;
}
else
{
countComponent++;
}
currentIndex = nextIndex;
}
// If rgba components?
if (startComponent > 3)
{
startComponent -= 4;
}
}
else
{
startComponent = 0;
countComponent = 4;
}
streamOutputElement.StartComponent = (byte)startComponent;
streamOutputElement.ComponentCount = (byte)countComponent;
return true;
}
private void HandleExport(Ast.Expression expression)
{
var values = ExtractStringOrArrayOfStrings(expression);
if (values != null)
{
currentExports.AddRange(values);
}
}
private List<string> ExtractStringOrArrayOfStrings(Ast.Expression expression)
{
// TODO implement this method using generics
object value;
if (!ExtractValue(expression, out value))
return null;
var values = new List<string>();
if (value is string)
{
values.Add((string)value);
}
else if (value is object[])
{
var arrayValue = (object[])value;
foreach (var exportItem in arrayValue)
{
if (!(exportItem is string))
{
logger.Error("Unexpected value [{0}]. Expecting a string.", expression.Span, exportItem);
return null;
}
values.Add((string)exportItem);
}
}
else
{
logger.Error("Unexpected value. Expecting a identifier/string or an array of identifier/string.", expression.Span);
}
return values;
}
private void HandleShareConstantBuffers(Ast.Expression expression)
{
object value;
if (!ExtractValue(expression, out value))
return;
if (!(value is bool))
{
logger.Error("ShareConstantBuffers must be a bool", expression.Span);
}
else
{
effect.ShareConstantBuffers = (bool)value;
}
}
private void HandleEffectName(Ast.Expression expression)
{
object value;
if (!ExtractValue(expression, out value))
return;
if (!(value is string))
{
logger.Error("Effect name must be a string/identifier", expression.Span);
}
else
{
effect.Name = (string)value;
}
}
private void HandleSubPassCount(Ast.Expression expression)
{
object value;
if (!ExtractValue(expression, out value))
return;
if (!(value is int))
{
logger.Error("SubPassCount must be an integer", expression.Span);
}
else
{
nextSubPassCount = (int)value;
}
}
private void HandlePreprocessor(Ast.Expression expression)
{
object value;
if (!ExtractValue(expression, out value))
return;
// If null, then preprocessor is reset
if (value == null)
preprocessorText = null;
// Else parse preprocessor directive
var builder = new StringBuilder();
if (value is string)
{
builder.AppendLine((string) value);
}
else if (value is object[])
{
var arrayValue = (object[]) value;
foreach (var stringItem in arrayValue)
{
if (!(stringItem is string))
{
logger.Error("Unexpected type. Preprocessor only support strings in array declaration", expression.Span);
}
builder.AppendLine((string) stringItem);
}
}
preprocessorText = builder.ToString();
}
private void HandleAttribute(Ast.AssignExpression expression)
{
// Extract the value and store it in the attribute
object value;
if (ExtractValue(expression.Value, out value))
{
pass.Properties[expression.Name.Text] = value;
}
}
private void HandleAttribute<T>(Ast.AssignExpression expression)
{
// Extract the value and store it in the attribute
object value;
if (ExtractValue(expression.Value, out value))
{
if (typeof(T) == typeof(uint) && value is int)
{
value = unchecked((uint) (int) value);
}
else
{
try
{
value = Convert.ChangeType(value, typeof (T));
}
catch (Exception ex)
{
logger.Error("Invalid type for attribute [{0}]. Expecting [{1}]", expression.Value.Span, expression.Name.Text, typeof (T).Name);
}
}
pass.Properties[expression.Name.Text] = value;
}
}
private bool ExtractValue(Ast.Expression expression, out object value)
{
value = null;
if (expression is Ast.LiteralExpression)
{
value = ((Ast.LiteralExpression) expression).Value.Value;
}
else if (expression is Ast.IdentifierExpression)
{
value = ((Ast.IdentifierExpression) expression).Name.Text;
}
else if (expression is Ast.ArrayInitializerExpression)
{
var arrayExpression = (Ast.ArrayInitializerExpression) expression;
var arrayValue = new object[arrayExpression.Values.Count];
for (int i = 0; i < arrayValue.Length; i++)
{
if (!ExtractValue(arrayExpression.Values[i], out arrayValue[i]))
return false;
}
value = arrayValue;
}
else if (expression is Ast.MethodExpression)
{
var methodExpression = (Ast.MethodExpression) expression;
value = ExtractValueFromMethodExpression(methodExpression);
if (value == null)
{
logger.Error("Unable to convert method expression to value.", expression.Span);
return false;
}
}
else
{
logger.Error("Unsupported value type. Only [literal, identifier, array]", expression.Span);
return false;
}
return true;
}
private object ExtractValueFromMethodExpression(Ast.MethodExpression methodExpression)
{
ValueConverter converter;
if (!ValueConverters.TryGetValue(methodExpression.Name.Text, out converter))
{
logger.Error("Unexpected method [{0}]", methodExpression.Span, methodExpression.Name.Text);
return null;
}
// Check for arguments
if (converter.ArgumentCount != methodExpression.Arguments.Count)
{
logger.Error("Unexpected number of arguments (expecting {0} arguments)", methodExpression.Span, converter.ArgumentCount);
return null;
}
var values = new object[methodExpression.Arguments.Count];
for (int i = 0; i < methodExpression.Arguments.Count; i++)
{
object localValue;
if (!ExtractValue(methodExpression.Arguments[i], out localValue))
return null;
values[i] = converter.ConvertItem(this, localValue);
if (localValue == null)
return null;
}
return converter.ConvertFullItem(this, values);
}
private void ProfileToFeatureLevel(string expectedPrefix, string profile, out FeatureLevel level)
{
level = 0;
if (profile.StartsWith(expectedPrefix))
{
var shortProfile = profile.Substring(expectedPrefix.Length);
switch (shortProfile)
{
case "2_0":
level = FeatureLevel.Level_9_1;
break;
case "3_0":
level = FeatureLevel.Level_9_3;
break;
case "4_0_level_9_1":
level = FeatureLevel.Level_9_1;
break;
case "4_0_level_9_2":
level = FeatureLevel.Level_9_2;
break;
case "4_0_level_9_3":
level = FeatureLevel.Level_9_3;
break;
case "4_0":
level = FeatureLevel.Level_10_0;
break;
case "4_1":
level = FeatureLevel.Level_10_1;
break;
case "5_0":
level = FeatureLevel.Level_11_0;
break;
}
}
if (level == 0)
logger.Error("Unsupported profile [{0}]", profile);
}
private void HandleProfile(Ast.Expression expression)
{
var identifierExpression = expression as Ast.IdentifierExpression;
if (identifierExpression != null)
{
var profile = identifierExpression.Name.Text;
ProfileToFeatureLevel("fx_", profile, out level);
}
else if (expression is Ast.LiteralExpression)
{
var literalValue = ((Ast.LiteralExpression) expression).Value.Value;
try
{
var rawLevel = (int) (Convert.ToSingle(literalValue, CultureInfo.InvariantCulture) * 10);
switch (rawLevel)
{
case 91:
level = FeatureLevel.Level_9_1;
break;
case 92:
level = FeatureLevel.Level_9_2;
break;
case 93:
level = FeatureLevel.Level_9_3;
break;
case 100:
level = FeatureLevel.Level_10_0;
break;
case 101:
level = FeatureLevel.Level_10_1;
break;
case 110:
level = FeatureLevel.Level_11_0;
break;
#if DIRECTX11_1
case 111:
level = FeatureLevel.Level_11_1;
break;
#endif
}
}
catch (Exception ex)
{
}
}
if (level == 0)
logger.Error("Unexpected assignement for [Profile] attribute: expecting only [identifier (fx_4_0, fx_4_1... etc.), or number (9.3, 10.0, 11.0... etc.)]", expression.Span);
}
private string ExtractShaderName(EffectShaderType effectShaderType, Ast.Expression expression)
{
string shaderName = null;
if (expression is Ast.IdentifierExpression)
{
shaderName = ((Ast.IdentifierExpression) expression).Name.Text;
}
else if (expression is Ast.LiteralExpression)
{
var value = ((Ast.LiteralExpression) expression).Value.Value;
if (Equals(value, 0) || Equals(value, null))
{
return null;
}
}
else if (expression is Ast.CompileExpression)
{
var compileExpression = (Ast.CompileExpression) expression;
var profileName = compileExpression.Profile.Text;
ProfileToFeatureLevel(StageTypeToString(effectShaderType) + "_", profileName, out level);
if (compileExpression.Method is Ast.MethodExpression)
{
var shaderMethod = (Ast.MethodExpression)compileExpression.Method;
if (shaderMethod.Arguments.Count > 0)
{
logger.Error("Default arguments for shader methods are not supported", shaderMethod.Span);
return null;
}
shaderName = shaderMethod.Name.Text;
}
else
{
logger.Error("Unsupported expression for compile. Excepting method", expression.Span);
return null;
}
}
else if (expression is Ast.MethodExpression)
{
// CompileShader( vs_4_0, VS() )
var compileExpression = (Ast.MethodExpression) expression;
if (compileExpression.Name.Text == "CompileShader")
{
if (compileExpression.Arguments.Count != 2)
{
logger.Error("Unexpected number of arguments [{0}] instead of 2", expression.Span, compileExpression.Arguments.Count);
return null;
}
// Extract level (11.0 10.0) from profile name (
object profileName;
if (!ExtractValue(compileExpression.Arguments[0], out profileName))
return null;
if (!(profileName is string))
{
logger.Error("Invalid profile [{0}]. Expecting identifier", compileExpression.Arguments[0].Span, profileName);
return null;
}
ProfileToFeatureLevel(StageTypeToString(effectShaderType) + "_", (string) profileName, out level);
var shaderMethod = compileExpression.Arguments[1] as Ast.MethodExpression;
if (shaderMethod == null)
{
logger.Error("Unexpected expression. Only method expression are supported", compileExpression.Arguments[1].Span);
return null;
}
if (shaderMethod.Arguments.Count > 0)
{
logger.Error("Default arguments for shader methods are not supported", shaderMethod.Span);
return null;
}
shaderName = shaderMethod.Name.Text;
}
}
if (shaderName == null)
{
logger.Error("Unexpected compile expression", expression.Span);
}
return shaderName;
}
private void CompileShader(EffectShaderType type, Ast.Expression assignValue)
{
CompileShader(type, ExtractShaderName(type, assignValue), assignValue.Span);
}
private void CompileShader(EffectShaderType type, string shaderName, SourceSpan span)
{
var level = this.level;
if (shaderName == null)
{
pass.Pipeline[type] = EffectData.ShaderLink.NullShader;
return;
}
//// If the shader has been already compiled, skip it
//foreach (var shader in EffectData.Shaders)
//{
// if (shader.Name == shaderName)
// return;
//}
// If the level is not setup, return an error
if (level == 0)
{
logger.Error("Expecting setup of [Profile = fx_4_0/fx_5_0...etc.] before compiling a shader.", span);
return;
}
string profile = StageTypeToString(type) + "_";
switch (this.level)
{
case FeatureLevel.Level_9_1:
profile += "4_0_level_9_1";
break;
case FeatureLevel.Level_9_2:
profile += "4_0_level_9_2";
break;
case FeatureLevel.Level_9_3:
profile += "4_0_level_9_3";
break;
case FeatureLevel.Level_10_0:
profile += "4_0";
break;
case FeatureLevel.Level_10_1:
profile += "4_1";
break;
case FeatureLevel.Level_11_0:
profile += "5_0";
break;
#if DIRECTX11_1
case FeatureLevel.Level_11_1:
profile += "5_0";
break;
#endif
}
var saveState = Configuration.ThrowOnShaderCompileError;
Configuration.ThrowOnShaderCompileError = false;
try
{
var sourcecodeBuilder = new StringBuilder();
if (!string.IsNullOrEmpty(preprocessorText))
sourcecodeBuilder.Append(preprocessorText);
sourcecodeBuilder.Append(parserResult.PreprocessedSource);
var sourcecode = sourcecodeBuilder.ToString();
var filePath = replaceBackSlash.Replace(parserResult.SourceFileName, @"\");
var result = ShaderBytecode.Compile(sourcecode, shaderName, profile, (ShaderFlags)compilerFlags, D3DCompiler.EffectFlags.None, null, includeHandler, filePath);
var compilerMessages = result.Message;
if (result.HasErrors)
{
logger.LogMessage(new LogMessageRaw(LogMessageType.Error, compilerMessages));
}
else
{
if (!string.IsNullOrEmpty(compilerMessages))
{
logger.LogMessage(new LogMessageRaw(LogMessageType.Warning, compilerMessages));
}
// Check if this shader is exported
if (currentExports.Contains(shaderName))
{
// the exported name is EffectName::ShaderName
shaderName = effect.Name + "::" + shaderName;
}
else
{
// If the shader is not exported, set the name to null
shaderName = null;
}
var shader = new EffectData.Shader()
{
Name = shaderName,
Level = this.level,
Bytecode = result.Bytecode,
Type = type,
ConstantBuffers = new List<EffectData.ConstantBuffer>(),
ResourceParameters = new List<EffectData.ResourceParameter>(),
InputSignature = new EffectData.Signature(),
OutputSignature = new EffectData.Signature()
};
using (var reflect = new ShaderReflection(shader.Bytecode))
{
BuiltSemanticInputAndOutput(shader, reflect);
BuildParameters(shader, reflect);
}
if (logger.HasErrors)
{
return;
}
// Strip reflection data, as we are storing it in the toolkit format.
var byteCodeNoDebugReflection = result.Bytecode.Strip(StripFlags.CompilerStripReflectionData | StripFlags.CompilerStripDebugInformation);
// Compute Hashcode
shader.Hashcode = Utilities.ComputeHashFNVModified(byteCodeNoDebugReflection);
// if No debug is required, take the bytecode without any debug/reflection info.
if ((compilerFlags & EffectCompilerFlags.Debug) == 0)
{
shader.Bytecode = byteCodeNoDebugReflection;
}
// Check that this shader was not already generated
int shaderIndex;
for (shaderIndex = 0; shaderIndex < effectData.Shaders.Count; shaderIndex++)
{
var shaderItem = effectData.Shaders[shaderIndex];
if (shaderItem.IsSimilar(shader))
{
break;
}
}
// Check if there is a new shader to store in the archive
if (shaderIndex >= effectData.Shaders.Count)
{
shaderIndex = effectData.Shaders.Count;
// If this is a Vertex shader, compute the binary signature for the input layout
if (shader.Type == EffectShaderType.Vertex)
{
// Gets the signature from the stripped bytecode and compute the hashcode.
shader.InputSignature.Bytecode = ShaderSignature.GetInputSignature(byteCodeNoDebugReflection);
shader.InputSignature.Hashcode = Utilities.ComputeHashFNVModified(shader.InputSignature.Bytecode);
}
effectData.Shaders.Add(shader);
}
if (pass.Pipeline[type] == null)
{
pass.Pipeline[type] = new EffectData.ShaderLink();
}
pass.Pipeline[type].Index = shaderIndex;
}
}
finally
{
Configuration.ThrowOnShaderCompileError = saveState;
}
}
private void HandleMethodExpression(Ast.MethodExpression expression)
{
if (expression.Arguments.Count == 1)
{
var argument = expression.Arguments[0];
switch (expression.Name.Text)
{
case "SetVertexShader":
CompileShader(EffectShaderType.Vertex, argument);
break;
case "SetPixelShader":
CompileShader(EffectShaderType.Pixel, argument);
break;
case "SetGeometryShader":
CompileShader(EffectShaderType.Geometry, argument);
break;
case "SetDomainShader":
CompileShader(EffectShaderType.Domain, argument);
break;
case "SetHullShader":
CompileShader(EffectShaderType.Hull, argument);
break;
case "SetComputeShader":
CompileShader(EffectShaderType.Compute, argument);
break;
default:
logger.Warning("Unhandled method [{0}]", expression.Span, expression.Name);
break;
}
}
else
{
logger.Warning("Unhandled method [{0}]", expression.Span, expression.Name);
}
}
private static string StageTypeToString(EffectShaderType type)
{
string profile = null;
switch (type)
{
case EffectShaderType.Vertex:
profile = "vs";
break;
case EffectShaderType.Domain:
profile = "ds";
break;
case EffectShaderType.Hull:
profile = "hs";
break;
case EffectShaderType.Geometry:
profile = "gs";
break;
case EffectShaderType.Pixel:
profile = "ps";
break;
case EffectShaderType.Compute:
profile = "cs";
break;
}
return profile;
}
private void BuiltSemanticInputAndOutput(EffectData.Shader shader, ShaderReflection reflect)
{
var description = reflect.Description;
shader.InputSignature.Semantics = new EffectData.Semantic[description.InputParameters];
for (int i = 0; i < description.InputParameters; i++)
shader.InputSignature.Semantics[i] = ConvertToSemantic(reflect.GetInputParameterDescription(i));
shader.OutputSignature.Semantics = new EffectData.Semantic[description.OutputParameters];
for (int i = 0; i < description.OutputParameters; i++)
shader.OutputSignature.Semantics[i] = ConvertToSemantic(reflect.GetOutputParameterDescription(i));
}
private EffectData.Semantic ConvertToSemantic(ShaderParameterDescription shaderParameterDescription)
{
return new EffectData.Semantic(
shaderParameterDescription.SemanticName,
(byte) shaderParameterDescription.SemanticIndex,
(byte) shaderParameterDescription.Register,
(byte) shaderParameterDescription.SystemValueType,
(byte) shaderParameterDescription.ComponentType,
(byte) shaderParameterDescription.UsageMask,
(byte) shaderParameterDescription.ReadWriteMask,
(byte) shaderParameterDescription.Stream
);
}
/// <summary>
/// Builds the parameters for a particular shader.
/// </summary>
/// <param name="shader"> The shader to build parameters. </param>
private void BuildParameters(EffectData.Shader shader, ShaderReflection reflect)
{
var description = reflect.Description;
// Iterate on all Constant buffers used by this shader
// Build all ParameterBuffers
for (int i = 0; i < description.ConstantBuffers; i++)
{
var reflectConstantBuffer = reflect.GetConstantBuffer(i);
var reflectConstantBufferDescription = reflectConstantBuffer.Description;
// Skip non pure constant-buffers and texture buffers
if (reflectConstantBufferDescription.Type != ConstantBufferType.ConstantBuffer
&& reflectConstantBufferDescription.Type != ConstantBufferType.TextureBuffer)
continue;
// Create the buffer
var parameterBuffer = new EffectData.ConstantBuffer()
{
Name = reflectConstantBufferDescription.Name,
Size = reflectConstantBufferDescription.Size,
Parameters = new List<EffectData.ValueTypeParameter>(),
};
shader.ConstantBuffers.Add(parameterBuffer);
// Iterate on each variable declared inside this buffer
for (int j = 0; j < reflectConstantBufferDescription.VariableCount; j++)
{
var variableBuffer = reflectConstantBuffer.GetVariable(j);
// Build constant buffer parameter
var parameter = BuildConstantBufferParameter(variableBuffer);
// Add this parameter to the ConstantBuffer
parameterBuffer.Parameters.Add(parameter);
}
}
var resourceParameters = new Dictionary<string, EffectData.ResourceParameter>();
var indicesUsedByName = new Dictionary<string, List<IndexedInputBindingDescription>>();
// Iterate on all resources bound in order to resolve resource dependencies for this shader.
// If the shader is dependent from an object variable, then create this variable as well.
for (int i = 0; i < description.BoundResources; i++)
{
var bindingDescription = reflect.GetResourceBindingDescription(i);
string name = bindingDescription.Name;
// Handle special case for indexable variable in SM5.0 that is different from SM4.0
// In SM4.0, reflection on a texture array declared as "Texture2D textureArray[4];" will
// result into a single "textureArray" InputBindingDescription
// While in SM5.0, we will have several textureArray[1], textureArray[2]...etc, and
// indices depending on the usage. Fortunately, it seems that in SM5.0, there is no hole
// so we can rebuilt a SM4.0 like description for SM5.0.
// This is the purpose of this code.
var matchResult = MatchVariableArray.Match(name);
if (matchResult.Success)
{
name = matchResult.Groups[1].Value;
int arrayIndex = int.Parse(matchResult.Groups[2].Value);
if (bindingDescription.BindCount != 1)
{
logger.Error("Unexpected BindCount ({0}) instead of 1 for indexable variable '{1}'", new SourceSpan(), bindingDescription.BindCount, name);
return;
}
List<IndexedInputBindingDescription> indices;
if (!indicesUsedByName.TryGetValue(name, out indices))
{
indices = new List<IndexedInputBindingDescription>();
indicesUsedByName.Add(name, indices);
}
indices.Add(new IndexedInputBindingDescription(arrayIndex, bindingDescription));
}
// In the case of SM5.0 and texture array, there can be several input binding descriptions, so we ignore them
// here, as we are going to recover them outside this loop.
if (!resourceParameters.ContainsKey(name))
{
// Build resource parameter
var parameter = BuildResourceParameter(name, bindingDescription);
shader.ResourceParameters.Add(parameter);
resourceParameters.Add(name, parameter);
}
}
// Do we have any SM5.0 Indexable array to fix?
if (indicesUsedByName.Count > 0)
{
foreach (var resourceParameter in resourceParameters)
{
var name = resourceParameter.Key;
List<IndexedInputBindingDescription> indexedBindings;
if (indicesUsedByName.TryGetValue(name, out indexedBindings))
{
// Just make sure to sort the list in index ascending order
indexedBindings.Sort((left, right) => left.Index.CompareTo(right.Index));
int minIndex = -1;
int maxIndex = -1;
int previousIndex = -1;
int minBindingIndex = -1;
int previousBindingIndex = -1;
// Check that indices have only a delta of 1
foreach (var indexedBinding in indexedBindings)
{
if (minIndex < 0)
{
minIndex = indexedBinding.Index;
}
if (minBindingIndex < 0)
{
minBindingIndex = indexedBinding.Description.BindPoint;
}
if (indexedBinding.Index > maxIndex)
{
maxIndex = indexedBinding.Index;
}
if (previousIndex >= 0)
{
if ((indexedBinding.Index - previousIndex) != 1)
{
logger.Error("Unexpected sparse index for indexable variable '{0}'", new SourceSpan(), name);
return;
}
if ((indexedBinding.Description.BindPoint - previousBindingIndex) != 1)
{
logger.Error("Unexpected sparse index for indexable variable '{0}'", new SourceSpan(), name);
return;
}
}
previousIndex = indexedBinding.Index;
previousBindingIndex = indexedBinding.Description.BindPoint;
}
// Fix the slot and count
resourceParameter.Value.Slot = (byte)(minBindingIndex - minIndex);
resourceParameter.Value.Count = (byte)(maxIndex + 1);
}
}
}
}
private class IndexedInputBindingDescription
{
public IndexedInputBindingDescription(int index, InputBindingDescription description)
{
Index = index;
Description = description;
}
public int Index;
public InputBindingDescription Description;
}
/// <summary>
/// Builds an effect parameter from a reflection variable.
/// </summary>
/// <returns> an EffectParameter, null if not handled </returns>
private EffectData.ValueTypeParameter BuildConstantBufferParameter(ShaderReflectionVariable variable)
{
var variableType = variable.GetVariableType();
var variableDescription = variable.Description;
var variableTypeDescription = variableType.Description;
var parameter = new EffectData.ValueTypeParameter()
{
Name = variableDescription.Name,
Offset = variableDescription.StartOffset,
Size = variableDescription.Size,
Count = variableTypeDescription.ElementCount,
Class = (EffectParameterClass) variableTypeDescription.Class,
Type = (EffectParameterType) variableTypeDescription.Type,
RowCount = (byte) variableTypeDescription.RowCount,
ColumnCount = (byte) variableTypeDescription.ColumnCount,
};
if (variableDescription.DefaultValue != IntPtr.Zero)
{
parameter.DefaultValue = new byte[variableDescription.Size];
Utilities.Read(variableDescription.DefaultValue, parameter.DefaultValue, 0, parameter.DefaultValue.Length);
}
return parameter;
}
/// <summary>
/// Builds an effect parameter from a reflection variable.
/// </summary>
/// <returns> an EffectParameter, null if not handled </returns>
private static EffectData.ResourceParameter BuildResourceParameter(string name, InputBindingDescription variableBinding)
{
var parameter = new EffectData.ResourceParameter()
{
Name = name,
Class = EffectParameterClass.Object,
Slot = (byte) variableBinding.BindPoint,
Count = (byte) variableBinding.BindCount,
};
switch (variableBinding.Type)
{
case ShaderInputType.TextureBuffer:
parameter.Type = EffectParameterType.TextureBuffer;
break;
case ShaderInputType.ConstantBuffer:
parameter.Type = EffectParameterType.ConstantBuffer;
break;
case ShaderInputType.Texture:
switch (variableBinding.Dimension)
{
case ShaderResourceViewDimension.Buffer:
parameter.Type = EffectParameterType.Buffer;
break;
case ShaderResourceViewDimension.Texture1D:
parameter.Type = EffectParameterType.Texture1D;
break;
case ShaderResourceViewDimension.Texture1DArray:
parameter.Type = EffectParameterType.Texture1DArray;
break;
case ShaderResourceViewDimension.Texture2D:
parameter.Type = EffectParameterType.Texture2D;
break;
case ShaderResourceViewDimension.Texture2DArray:
parameter.Type = EffectParameterType.Texture2DArray;
break;
case ShaderResourceViewDimension.Texture2DMultisampled:
parameter.Type = EffectParameterType.Texture2DMultisampled;
break;
case ShaderResourceViewDimension.Texture2DMultisampledArray:
parameter.Type = EffectParameterType.Texture2DMultisampledArray;
break;
case ShaderResourceViewDimension.Texture3D:
parameter.Type = EffectParameterType.Texture3D;
break;
case ShaderResourceViewDimension.TextureCube:
parameter.Type = EffectParameterType.TextureCube;
break;
case ShaderResourceViewDimension.TextureCubeArray:
parameter.Type = EffectParameterType.TextureCubeArray;
break;
}
break;
case ShaderInputType.Structured:
parameter.Type = EffectParameterType.StructuredBuffer;
break;
case ShaderInputType.ByteAddress:
parameter.Type = EffectParameterType.ByteAddressBuffer;
break;
case ShaderInputType.UnorderedAccessViewRWTyped:
switch (variableBinding.Dimension)
{
case ShaderResourceViewDimension.Buffer:
parameter.Type = EffectParameterType.RWBuffer;
break;
case ShaderResourceViewDimension.Texture1D:
parameter.Type = EffectParameterType.RWTexture1D;
break;
case ShaderResourceViewDimension.Texture1DArray:
parameter.Type = EffectParameterType.RWTexture1DArray;
break;
case ShaderResourceViewDimension.Texture2D:
parameter.Type = EffectParameterType.RWTexture2D;
break;
case ShaderResourceViewDimension.Texture2DArray:
parameter.Type = EffectParameterType.RWTexture2DArray;
break;
case ShaderResourceViewDimension.Texture3D:
parameter.Type = EffectParameterType.RWTexture3D;
break;
}
break;
case ShaderInputType.UnorderedAccessViewRWStructured:
parameter.Type = EffectParameterType.RWStructuredBuffer;
break;
case ShaderInputType.UnorderedAccessViewRWByteAddress:
parameter.Type = EffectParameterType.RWByteAddressBuffer;
break;
case ShaderInputType.UnorderedAccessViewAppendStructured:
parameter.Type = EffectParameterType.AppendStructuredBuffer;
break;
case ShaderInputType.UnorderedAccessViewConsumeStructured:
parameter.Type = EffectParameterType.ConsumeStructuredBuffer;
break;
case ShaderInputType.UnorderedAccessViewRWStructuredWithCounter:
parameter.Type = EffectParameterType.RWStructuredBuffer;
break;
case ShaderInputType.Sampler:
parameter.Type = EffectParameterType.Sampler;
break;
}
return parameter;
}
private static readonly Regex replaceBackSlash = new Regex(@"\\+");
private static object ToFloat(EffectCompilerInternal compiler, object value)
{
try
{
return Convert.ToSingle(value);
}
catch (Exception ex)
{
compiler.logger.Error("Unable to convert [{0}] to float", new SourceSpan(), value);
}
return null;
}
#region Nested type: ConvertFullItem
private delegate object ConvertFullItem(EffectCompilerInternal compiler, object[] parameters);
#endregion
#region Nested type: ConvertItem
private delegate object ConvertItem(EffectCompilerInternal compiler, object value);
#endregion
#region Nested type: ValueConverter
private struct ValueConverter
{
public int ArgumentCount;
public ConvertFullItem ConvertFullItem;
public ConvertItem ConvertItem;
public ValueConverter(string name, int argumentCount, ConvertItem convertItem, ConvertFullItem convertFullItem)
{
ArgumentCount = argumentCount;
ConvertItem = convertItem;
ConvertFullItem = convertFullItem;
}
}
#endregion
}
}
| |
// 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!
using gax = Google.Api.Gax;
using gcdcv = Google.Cloud.Dialogflow.Cx.V3;
using sys = System;
namespace Google.Cloud.Dialogflow.Cx.V3
{
/// <summary>Resource name for the <c>Changelog</c> resource.</summary>
public sealed partial class ChangelogName : gax::IResourceName, sys::IEquatable<ChangelogName>
{
/// <summary>The possible contents of <see cref="ChangelogName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/locations/{location}/agents/{agent}/changelogs/{changelog}</c>.
/// </summary>
ProjectLocationAgentChangelog = 1,
}
private static gax::PathTemplate s_projectLocationAgentChangelog = new gax::PathTemplate("projects/{project}/locations/{location}/agents/{agent}/changelogs/{changelog}");
/// <summary>Creates a <see cref="ChangelogName"/> 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="ChangelogName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static ChangelogName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new ChangelogName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="ChangelogName"/> with the pattern
/// <c>projects/{project}/locations/{location}/agents/{agent}/changelogs/{changelog}</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="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="changelogId">The <c>Changelog</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="ChangelogName"/> constructed from the provided ids.</returns>
public static ChangelogName FromProjectLocationAgentChangelog(string projectId, string locationId, string agentId, string changelogId) =>
new ChangelogName(ResourceNameType.ProjectLocationAgentChangelog, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), agentId: gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)), changelogId: gax::GaxPreconditions.CheckNotNullOrEmpty(changelogId, nameof(changelogId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ChangelogName"/> with pattern
/// <c>projects/{project}/locations/{location}/agents/{agent}/changelogs/{changelog}</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="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="changelogId">The <c>Changelog</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ChangelogName"/> with pattern
/// <c>projects/{project}/locations/{location}/agents/{agent}/changelogs/{changelog}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string agentId, string changelogId) =>
FormatProjectLocationAgentChangelog(projectId, locationId, agentId, changelogId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ChangelogName"/> with pattern
/// <c>projects/{project}/locations/{location}/agents/{agent}/changelogs/{changelog}</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="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="changelogId">The <c>Changelog</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ChangelogName"/> with pattern
/// <c>projects/{project}/locations/{location}/agents/{agent}/changelogs/{changelog}</c>.
/// </returns>
public static string FormatProjectLocationAgentChangelog(string projectId, string locationId, string agentId, string changelogId) =>
s_projectLocationAgentChangelog.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)), gax::GaxPreconditions.CheckNotNullOrEmpty(changelogId, nameof(changelogId)));
/// <summary>Parses the given resource name string into a new <see cref="ChangelogName"/> 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}/agents/{agent}/changelogs/{changelog}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="changelogName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="ChangelogName"/> if successful.</returns>
public static ChangelogName Parse(string changelogName) => Parse(changelogName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="ChangelogName"/> 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}/agents/{agent}/changelogs/{changelog}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="changelogName">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="ChangelogName"/> if successful.</returns>
public static ChangelogName Parse(string changelogName, bool allowUnparsed) =>
TryParse(changelogName, allowUnparsed, out ChangelogName 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="ChangelogName"/> 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}/agents/{agent}/changelogs/{changelog}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="changelogName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ChangelogName"/>, 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 changelogName, out ChangelogName result) => TryParse(changelogName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ChangelogName"/> 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}/agents/{agent}/changelogs/{changelog}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="changelogName">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="ChangelogName"/>, 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 changelogName, bool allowUnparsed, out ChangelogName result)
{
gax::GaxPreconditions.CheckNotNull(changelogName, nameof(changelogName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationAgentChangelog.TryParseName(changelogName, out resourceName))
{
result = FromProjectLocationAgentChangelog(resourceName[0], resourceName[1], resourceName[2], resourceName[3]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(changelogName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private ChangelogName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string agentId = null, string changelogId = null, string locationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
AgentId = agentId;
ChangelogId = changelogId;
LocationId = locationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="ChangelogName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/agents/{agent}/changelogs/{changelog}</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="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="changelogId">The <c>Changelog</c> ID. Must not be <c>null</c> or empty.</param>
public ChangelogName(string projectId, string locationId, string agentId, string changelogId) : this(ResourceNameType.ProjectLocationAgentChangelog, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), agentId: gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)), changelogId: gax::GaxPreconditions.CheckNotNullOrEmpty(changelogId, nameof(changelogId)))
{
}
/// <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>Agent</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string AgentId { get; }
/// <summary>
/// The <c>Changelog</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ChangelogId { 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>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.ProjectLocationAgentChangelog: return s_projectLocationAgentChangelog.Expand(ProjectId, LocationId, AgentId, ChangelogId);
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 ChangelogName);
/// <inheritdoc/>
public bool Equals(ChangelogName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(ChangelogName a, ChangelogName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(ChangelogName a, ChangelogName b) => !(a == b);
}
public partial class ListChangelogsRequest
{
/// <summary><see cref="AgentName"/>-typed view over the <see cref="Parent"/> resource name property.</summary>
public AgentName ParentAsAgentName
{
get => string.IsNullOrEmpty(Parent) ? null : AgentName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetChangelogRequest
{
/// <summary>
/// <see cref="gcdcv::ChangelogName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdcv::ChangelogName ChangelogName
{
get => string.IsNullOrEmpty(Name) ? null : gcdcv::ChangelogName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class Changelog
{
/// <summary>
/// <see cref="gcdcv::ChangelogName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdcv::ChangelogName ChangelogName
{
get => string.IsNullOrEmpty(Name) ? null : gcdcv::ChangelogName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Reflection;
using System.Xml;
using log4net;
using OpenMetaverse;
namespace OpenSim.Framework
{
public class ConfigurationMember
{
#region Delegates
public delegate bool ConfigurationOptionResult(string configuration_key, object configuration_result);
public delegate void ConfigurationOptionsLoad();
#endregion
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private int cE = 0;
private string configurationDescription = String.Empty;
private string configurationFilename = String.Empty;
private XmlNode configurationFromXMLNode = null;
private List<ConfigurationOption> configurationOptions = new List<ConfigurationOption>();
private IGenericConfig configurationPlugin = null;
/// <summary>
/// This is the default configuration DLL loaded
/// </summary>
private string configurationPluginFilename = "OpenSim.Framework.Configuration.XML.dll";
private ConfigurationOptionsLoad loadFunction;
private ConfigurationOptionResult resultFunction;
private bool useConsoleToPromptOnError = true;
public ConfigurationMember(string configuration_filename, string configuration_description,
ConfigurationOptionsLoad load_function, ConfigurationOptionResult result_function, bool use_console_to_prompt_on_error)
{
configurationFilename = configuration_filename;
configurationDescription = configuration_description;
loadFunction = load_function;
resultFunction = result_function;
useConsoleToPromptOnError = use_console_to_prompt_on_error;
}
public ConfigurationMember(XmlNode configuration_xml, string configuration_description,
ConfigurationOptionsLoad load_function, ConfigurationOptionResult result_function, bool use_console_to_prompt_on_error)
{
configurationFilename = String.Empty;
configurationFromXMLNode = configuration_xml;
configurationDescription = configuration_description;
loadFunction = load_function;
resultFunction = result_function;
useConsoleToPromptOnError = use_console_to_prompt_on_error;
}
public void setConfigurationFilename(string filename)
{
configurationFilename = filename;
}
public void setConfigurationDescription(string desc)
{
configurationDescription = desc;
}
public void setConfigurationResultFunction(ConfigurationOptionResult result)
{
resultFunction = result;
}
public void forceConfigurationPluginLibrary(string dll_filename)
{
configurationPluginFilename = dll_filename;
}
private void checkAndAddConfigOption(ConfigurationOption option)
{
if ((option.configurationKey != String.Empty && option.configurationQuestion != String.Empty) ||
(option.configurationKey != String.Empty && option.configurationUseDefaultNoPrompt))
{
if (!configurationOptions.Contains(option))
{
configurationOptions.Add(option);
}
}
else
{
m_log.Info(
"Required fields for adding a configuration option is invalid. Will not add this option (" +
option.configurationKey + ")");
}
}
public void addConfigurationOption(string configuration_key,
ConfigurationOption.ConfigurationTypes configuration_type,
string configuration_question, string configuration_default,
bool use_default_no_prompt)
{
ConfigurationOption configOption = new ConfigurationOption();
configOption.configurationKey = configuration_key;
configOption.configurationQuestion = configuration_question;
configOption.configurationDefault = configuration_default;
configOption.configurationType = configuration_type;
configOption.configurationUseDefaultNoPrompt = use_default_no_prompt;
configOption.shouldIBeAsked = null; //Assumes true, I can ask whenever
checkAndAddConfigOption(configOption);
}
public void addConfigurationOption(string configuration_key,
ConfigurationOption.ConfigurationTypes configuration_type,
string configuration_question, string configuration_default,
bool use_default_no_prompt,
ConfigurationOption.ConfigurationOptionShouldBeAsked shouldIBeAskedDelegate)
{
ConfigurationOption configOption = new ConfigurationOption();
configOption.configurationKey = configuration_key;
configOption.configurationQuestion = configuration_question;
configOption.configurationDefault = configuration_default;
configOption.configurationType = configuration_type;
configOption.configurationUseDefaultNoPrompt = use_default_no_prompt;
configOption.shouldIBeAsked = shouldIBeAskedDelegate;
checkAndAddConfigOption(configOption);
}
// TEMP - REMOVE
public void performConfigurationRetrieve()
{
if (cE > 1)
m_log.Error("READING CONFIGURATION COUT: " + cE.ToString());
configurationPlugin = LoadConfigDll(configurationPluginFilename);
configurationOptions.Clear();
if (loadFunction == null)
{
m_log.Error("Load Function for '" + configurationDescription +
"' is null. Refusing to run configuration.");
return;
}
if (resultFunction == null)
{
m_log.Error("Result Function for '" + configurationDescription +
"' is null. Refusing to run configuration.");
return;
}
//m_log.Debug("[CONFIG]: Calling Configuration Load Function...");
loadFunction();
if (configurationOptions.Count <= 0)
{
m_log.Error("[CONFIG]: No configuration options were specified for '" + configurationOptions +
"'. Refusing to continue configuration.");
return;
}
bool useFile = true;
if (configurationPlugin == null)
{
m_log.Error("[CONFIG]: Configuration Plugin NOT LOADED!");
return;
}
if (configurationFilename.Trim() != String.Empty)
{
configurationPlugin.SetFileName(configurationFilename);
try
{
configurationPlugin.LoadData();
useFile = true;
}
catch (XmlException e)
{
m_log.WarnFormat("[CONFIG] Not using {0}: {1}",
configurationFilename,
e.Message.ToString());
//m_log.Error("Error loading " + configurationFilename + ": " + e.ToString());
useFile = false;
}
}
else
{
if (configurationFromXMLNode != null)
{
m_log.Info("Loading from XML Node, will not save to the file");
configurationPlugin.LoadDataFromString(configurationFromXMLNode.OuterXml);
}
m_log.Info("XML Configuration Filename is not valid; will not save to the file.");
useFile = false;
}
foreach (ConfigurationOption configOption in configurationOptions)
{
bool convertSuccess = false;
object return_result = null;
string errorMessage = String.Empty;
bool ignoreNextFromConfig = false;
while (convertSuccess == false)
{
string console_result = String.Empty;
string attribute = null;
if (useFile || configurationFromXMLNode != null)
{
if (!ignoreNextFromConfig)
{
attribute = configurationPlugin.GetAttribute(configOption.configurationKey);
}
else
{
ignoreNextFromConfig = false;
}
}
if (attribute == null)
{
if (configOption.configurationUseDefaultNoPrompt || useConsoleToPromptOnError == false)
{
console_result = configOption.configurationDefault;
}
else
{
if ((configOption.shouldIBeAsked != null &&
configOption.shouldIBeAsked(configOption.configurationKey)) ||
configOption.shouldIBeAsked == null)
{
if (configurationDescription.Trim() != String.Empty)
{
console_result =
MainConsole.Instance.CmdPrompt(
configurationDescription + ": " + configOption.configurationQuestion,
configOption.configurationDefault);
}
else
{
console_result =
MainConsole.Instance.CmdPrompt(configOption.configurationQuestion,
configOption.configurationDefault);
}
}
else
{
//Dont Ask! Just use default
console_result = configOption.configurationDefault;
}
}
}
else
{
console_result = attribute;
}
// if the first character is a "$", assume it's the name
// of an environment variable and substitute with the value of that variable
if (console_result.StartsWith("$"))
console_result = Environment.GetEnvironmentVariable(console_result.Substring(1));
switch (configOption.configurationType)
{
case ConfigurationOption.ConfigurationTypes.TYPE_STRING:
return_result = console_result;
convertSuccess = true;
break;
case ConfigurationOption.ConfigurationTypes.TYPE_STRING_NOT_EMPTY:
if (console_result.Length > 0)
{
return_result = console_result;
convertSuccess = true;
}
errorMessage = "a string that is not empty";
break;
case ConfigurationOption.ConfigurationTypes.TYPE_BOOLEAN:
bool boolResult;
if (Boolean.TryParse(console_result, out boolResult))
{
convertSuccess = true;
return_result = boolResult;
}
errorMessage = "'true' or 'false' (Boolean)";
break;
case ConfigurationOption.ConfigurationTypes.TYPE_BYTE:
byte byteResult;
if (Byte.TryParse(console_result, out byteResult))
{
convertSuccess = true;
return_result = byteResult;
}
errorMessage = "a byte (Byte)";
break;
case ConfigurationOption.ConfigurationTypes.TYPE_CHARACTER:
char charResult;
if (Char.TryParse(console_result, out charResult))
{
convertSuccess = true;
return_result = charResult;
}
errorMessage = "a character (Char)";
break;
case ConfigurationOption.ConfigurationTypes.TYPE_INT16:
short shortResult;
if (Int16.TryParse(console_result, out shortResult))
{
convertSuccess = true;
return_result = shortResult;
}
errorMessage = "a signed 32 bit integer (short)";
break;
case ConfigurationOption.ConfigurationTypes.TYPE_INT32:
int intResult;
if (Int32.TryParse(console_result, out intResult))
{
convertSuccess = true;
return_result = intResult;
}
errorMessage = "a signed 32 bit integer (int)";
break;
case ConfigurationOption.ConfigurationTypes.TYPE_INT64:
long longResult;
if (Int64.TryParse(console_result, out longResult))
{
convertSuccess = true;
return_result = longResult;
}
errorMessage = "a signed 32 bit integer (long)";
break;
case ConfigurationOption.ConfigurationTypes.TYPE_IP_ADDRESS:
IPAddress ipAddressResult;
if (IPAddress.TryParse(console_result, out ipAddressResult))
{
convertSuccess = true;
return_result = ipAddressResult;
}
errorMessage = "an IP Address (IPAddress)";
break;
case ConfigurationOption.ConfigurationTypes.TYPE_UUID:
UUID uuidResult;
if (UUID.TryParse(console_result, out uuidResult))
{
convertSuccess = true;
return_result = uuidResult;
}
errorMessage = "a UUID (UUID)";
break;
case ConfigurationOption.ConfigurationTypes.TYPE_UUID_NULL_FREE:
UUID uuidResult2;
if (UUID.TryParse(console_result, out uuidResult2))
{
convertSuccess = true;
if (uuidResult2 == UUID.Zero)
uuidResult2 = UUID.Random();
return_result = uuidResult2;
}
errorMessage = "a non-null UUID (UUID)";
break;
case ConfigurationOption.ConfigurationTypes.TYPE_Vector3:
Vector3 vectorResult;
if (Vector3.TryParse(console_result, out vectorResult))
{
convertSuccess = true;
return_result = vectorResult;
}
errorMessage = "a vector (Vector3)";
break;
case ConfigurationOption.ConfigurationTypes.TYPE_UINT16:
ushort ushortResult;
if (UInt16.TryParse(console_result, out ushortResult))
{
convertSuccess = true;
return_result = ushortResult;
}
errorMessage = "an unsigned 16 bit integer (ushort)";
break;
case ConfigurationOption.ConfigurationTypes.TYPE_UINT32:
uint uintResult;
if (UInt32.TryParse(console_result, out uintResult))
{
convertSuccess = true;
return_result = uintResult;
}
errorMessage = "an unsigned 32 bit integer (uint)";
break;
case ConfigurationOption.ConfigurationTypes.TYPE_UINT64:
ulong ulongResult;
if (UInt64.TryParse(console_result, out ulongResult))
{
convertSuccess = true;
return_result = ulongResult;
}
errorMessage = "an unsigned 64 bit integer (ulong)";
break;
case ConfigurationOption.ConfigurationTypes.TYPE_FLOAT:
float floatResult;
if (
float.TryParse(console_result, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, Culture.NumberFormatInfo,
out floatResult))
{
convertSuccess = true;
return_result = floatResult;
}
errorMessage = "a single-precision floating point number (float)";
break;
case ConfigurationOption.ConfigurationTypes.TYPE_DOUBLE:
double doubleResult;
if (
Double.TryParse(console_result, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, Culture.NumberFormatInfo,
out doubleResult))
{
convertSuccess = true;
return_result = doubleResult;
}
errorMessage = "an double-precision floating point number (double)";
break;
}
if (convertSuccess)
{
if (useFile)
{
configurationPlugin.SetAttribute(configOption.configurationKey, console_result);
}
if (!resultFunction(configOption.configurationKey, return_result))
{
m_log.Info(
"The handler for the last configuration option denied that input, please try again.");
convertSuccess = false;
ignoreNextFromConfig = true;
}
}
else
{
if (configOption.configurationUseDefaultNoPrompt)
{
m_log.Error(string.Format(
"[CONFIG]: [{3}]:[{1}] is not valid default for parameter [{0}].\nThe configuration result must be parsable to {2}.\n",
configOption.configurationKey, console_result, errorMessage,
configurationFilename));
convertSuccess = true;
}
else
{
m_log.Warn(string.Format(
"[CONFIG]: [{3}]:[{1}] is not a valid value [{0}].\nThe configuration result must be parsable to {2}.\n",
configOption.configurationKey, console_result, errorMessage,
configurationFilename));
ignoreNextFromConfig = true;
}
}
}
}
if (useFile)
{
configurationPlugin.Commit();
configurationPlugin.Close();
}
}
private static IGenericConfig LoadConfigDll(string dllName)
{
Assembly pluginAssembly = Assembly.LoadFrom(dllName);
IGenericConfig plug = null;
foreach (Type pluginType in pluginAssembly.GetTypes())
{
if (pluginType.IsPublic)
{
if (!pluginType.IsAbstract)
{
Type typeInterface = pluginType.GetInterface("IGenericConfig", true);
if (typeInterface != null)
{
plug =
(IGenericConfig) Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString()));
}
}
}
}
pluginAssembly = null;
return plug;
}
public void forceSetConfigurationOption(string configuration_key, string configuration_value)
{
configurationPlugin.LoadData();
configurationPlugin.SetAttribute(configuration_key, configuration_value);
configurationPlugin.Commit();
configurationPlugin.Close();
}
}
}
| |
// 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.12.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsAzureBodyDuration
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// DurationOperations operations.
/// </summary>
internal partial class DurationOperations : IServiceOperations<AutoRestDurationTestService>, IDurationOperations
{
/// <summary>
/// Initializes a new instance of the DurationOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal DurationOperations(AutoRestDurationTestService client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestDurationTestService
/// </summary>
public AutoRestDurationTestService Client { get; private set; }
/// <summary>
/// Get null duration value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<TimeSpan?>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "GetNull", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "duration/null").ToString();
List<string> queryParameters = new List<string>();
if (queryParameters.Count > 0)
{
url += "?" + string.Join("&", queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
if (this.Client.AcceptLanguage != null)
{
if (httpRequest.Headers.Contains("accept-language"))
{
httpRequest.Headers.Remove("accept-language");
}
httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new AzureOperationResponse<TimeSpan?>();
result.Request = httpRequest;
result.Response = httpResponse;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<TimeSpan?>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Put a positive duration value
/// </summary>
/// <param name='durationBody'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> PutPositiveDurationWithHttpMessagesAsync(TimeSpan? durationBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (durationBody == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "durationBody");
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("durationBody", durationBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "PutPositiveDuration", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "duration/positiveduration").ToString();
List<string> queryParameters = new List<string>();
if (queryParameters.Count > 0)
{
url += "?" + string.Join("&", queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PUT");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
if (this.Client.AcceptLanguage != null)
{
if (httpRequest.Headers.Contains("accept-language"))
{
httpRequest.Headers.Remove("accept-language");
}
httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
}
// Serialize Request
string requestContent = JsonConvert.SerializeObject(durationBody, this.Client.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new AzureOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Get a positive duration value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<TimeSpan?>> GetPositiveDurationWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "GetPositiveDuration", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "duration/positiveduration").ToString();
List<string> queryParameters = new List<string>();
if (queryParameters.Count > 0)
{
url += "?" + string.Join("&", queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
if (this.Client.AcceptLanguage != null)
{
if (httpRequest.Headers.Contains("accept-language"))
{
httpRequest.Headers.Remove("accept-language");
}
httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new AzureOperationResponse<TimeSpan?>();
result.Request = httpRequest;
result.Response = httpResponse;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<TimeSpan?>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Get an invalid duration value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<TimeSpan?>> GetInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "GetInvalid", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "duration/invalid").ToString();
List<string> queryParameters = new List<string>();
if (queryParameters.Count > 0)
{
url += "?" + string.Join("&", queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
if (this.Client.AcceptLanguage != null)
{
if (httpRequest.Headers.Contains("accept-language"))
{
httpRequest.Headers.Remove("accept-language");
}
httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new AzureOperationResponse<TimeSpan?>();
result.Request = httpRequest;
result.Response = httpResponse;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<TimeSpan?>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="OdbcConnectionStringBuilder.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
namespace System.Data.Odbc {
[DefaultProperty("Driver")]
[System.ComponentModel.TypeConverterAttribute(typeof(OdbcConnectionStringBuilder.OdbcConnectionStringBuilderConverter))]
public sealed class OdbcConnectionStringBuilder : DbConnectionStringBuilder {
private enum Keywords { // must maintain same ordering as _validKeywords array
// NamedConnection,
Dsn,
Driver,
}
private static readonly string[] _validKeywords;
private static readonly Dictionary<string,Keywords> _keywords;
private string[] _knownKeywords;
private string _dsn = DbConnectionStringDefaults.Dsn;
// private string _namedConnection = DbConnectionStringDefaults.NamedConnection;
private string _driver = DbConnectionStringDefaults.Driver;
static OdbcConnectionStringBuilder() {
string[] validKeywords = new string[2];
validKeywords[(int)Keywords.Driver] = DbConnectionStringKeywords.Driver;
validKeywords[(int)Keywords.Dsn] = DbConnectionStringKeywords.Dsn;
// validKeywords[(int)Keywords.NamedConnection] = DbConnectionStringKeywords.NamedConnection;
_validKeywords = validKeywords;
Dictionary<string,Keywords> hash = new Dictionary<string,Keywords>(2, StringComparer.OrdinalIgnoreCase);
hash.Add(DbConnectionStringKeywords.Driver, Keywords.Driver);
hash.Add(DbConnectionStringKeywords.Dsn, Keywords.Dsn);
// hash.Add(DbConnectionStringKeywords.NamedConnection, Keywords.NamedConnection);
Debug.Assert(2 == hash.Count, "initial expected size is incorrect");
_keywords = hash;
}
public OdbcConnectionStringBuilder() : this((string)null) {
}
public OdbcConnectionStringBuilder(string connectionString) : base(true) {
if (!ADP.IsEmpty(connectionString)) {
ConnectionString = connectionString;
}
}
public override object this[string keyword] {
get {
ADP.CheckArgumentNull(keyword, "keyword");
Keywords index;
if (_keywords.TryGetValue(keyword, out index)) {
return GetAt(index);
}
else {
return base[keyword];
}
}
set {
ADP.CheckArgumentNull(keyword, "keyword");
if (null != value) {
Keywords index;
if (_keywords.TryGetValue(keyword, out index)) {
switch(index) {
case Keywords.Driver: Driver = ConvertToString(value); break;
case Keywords.Dsn: Dsn = ConvertToString(value); break;
// case Keywords.NamedConnection: NamedConnection = ConvertToString(value); break;
default:
Debug.Assert(false, "unexpected keyword");
throw ADP.KeywordNotSupported(keyword);
}
}
else {
base[keyword] = value;
ClearPropertyDescriptors();
_knownKeywords = null;
}
}
else {
Remove(keyword);
}
}
}
[DisplayName(DbConnectionStringKeywords.Driver)]
[ResCategoryAttribute(Res.DataCategory_Source)]
[ResDescriptionAttribute(Res.DbConnectionString_Driver)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
public string Driver {
get { return _driver; }
set {
SetValue(DbConnectionStringKeywords.Driver, value);
_driver = value;
}
}
[DisplayName(DbConnectionStringKeywords.Dsn)]
[ResCategoryAttribute(Res.DataCategory_NamedConnectionString)]
[ResDescriptionAttribute(Res.DbConnectionString_DSN)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
public string Dsn {
get { return _dsn; }
set {
SetValue(DbConnectionStringKeywords.Dsn, value);
_dsn = value;
}
}
/*
[DisplayName(DbConnectionStringKeywords.NamedConnection)]
[ResCategoryAttribute(Res.DataCategory_NamedConnectionString)]
[ResDescriptionAttribute(Res.DbConnectionString_NamedConnection)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
[TypeConverter(typeof(NamedConnectionStringConverter))]
public string NamedConnection {
get { return _namedConnection; }
set {
SetValue(DbConnectionStringKeywords.NamedConnection, value);
_namedConnection = value;
}
}
*/
public override ICollection Keys {
get {
string[] knownKeywords = _knownKeywords;
if (null == knownKeywords) {
knownKeywords = _validKeywords;
int count = 0;
foreach(string keyword in base.Keys) {
bool flag = true;
foreach(string s in knownKeywords) {
if (s == keyword) {
flag = false;
break;
}
}
if (flag) {
count++;
}
}
if (0 < count) {
string[] tmp = new string[knownKeywords.Length + count];
knownKeywords.CopyTo(tmp, 0);
int index = knownKeywords.Length;
foreach(string keyword in base.Keys) {
bool flag = true;
foreach(string s in knownKeywords) {
if (s == keyword) {
flag = false;
break;
}
}
if (flag) {
tmp[index++] = keyword;
}
}
knownKeywords = tmp;
}
_knownKeywords = knownKeywords;
}
return new System.Data.Common.ReadOnlyCollection<string>(knownKeywords);
}
}
public override void Clear() {
base.Clear();
for(int i = 0; i < _validKeywords.Length; ++i) {
Reset((Keywords)i);
}
_knownKeywords = _validKeywords;
}
public override bool ContainsKey(string keyword) {
ADP.CheckArgumentNull(keyword, "keyword");
return _keywords.ContainsKey(keyword) || base.ContainsKey(keyword);
}
private static string ConvertToString(object value) {
return DbConnectionStringBuilderUtil.ConvertToString(value);
}
private object GetAt(Keywords index) {
switch(index) {
case Keywords.Driver: return Driver;
case Keywords.Dsn: return Dsn;
// case Keywords.NamedConnection: return NamedConnection;
default:
Debug.Assert(false, "unexpected keyword");
throw ADP.KeywordNotSupported(_validKeywords[(int)index]);
}
}
/*
protected override void GetProperties(Hashtable propertyDescriptors) {
object value;
if (TryGetValue(DbConnectionStringSynonyms.TRUSTEDCONNECTION, out value)) {
bool trusted = false;
if (value is bool) {
trusted = (bool)value;
}
else if ((value is string) && !Boolean.TryParse((string)value, out trusted)) {
trusted = false;
}
if (trusted) {
Attribute[] attributes = new Attribute[] {
BrowsableAttribute.Yes,
RefreshPropertiesAttribute.All,
};
DbConnectionStringBuilderDescriptor descriptor;
descriptor = new DbConnectionStringBuilderDescriptor(DbConnectionStringSynonyms.TRUSTEDCONNECTION,
this.GetType(), typeof(bool), false, attributes);
descriptor.RefreshOnChange = true;
propertyDescriptors[DbConnectionStringSynonyms.TRUSTEDCONNECTION] = descriptor;
if (ContainsKey(DbConnectionStringSynonyms.Pwd)) {
descriptor = new DbConnectionStringBuilderDescriptor(DbConnectionStringSynonyms.Pwd,
this.GetType(), typeof(string), true, attributes);
propertyDescriptors[DbConnectionStringSynonyms.Pwd] = descriptor;
}
if (ContainsKey(DbConnectionStringSynonyms.UID)) {
descriptor = new DbConnectionStringBuilderDescriptor(DbConnectionStringSynonyms.UID,
this.GetType(), typeof(string), true, attributes);
propertyDescriptors[DbConnectionStringSynonyms.UID] = descriptor;
}
}
}
base.GetProperties(propertyDescriptors);
}
*/
public override bool Remove(string keyword) {
ADP.CheckArgumentNull(keyword, "keyword");
if (base.Remove(keyword)) {
Keywords index;
if (_keywords.TryGetValue(keyword, out index)) {
Reset(index);
}
else {
ClearPropertyDescriptors();
_knownKeywords = null;
}
return true;
}
return false;
}
private void Reset(Keywords index) {
switch(index) {
case Keywords.Driver:
_driver = DbConnectionStringDefaults.Driver;
break;
case Keywords.Dsn:
_dsn = DbConnectionStringDefaults.Dsn;
break;
// case Keywords.NamedConnection:
// _namedConnection = DbConnectionStringDefaults.NamedConnection;
// break;
default:
Debug.Assert(false, "unexpected keyword");
throw ADP.KeywordNotSupported(_validKeywords[(int)index]);
}
}
private void SetValue(string keyword, string value) {
ADP.CheckArgumentNull(value, keyword);
base[keyword] = value;
}
public override bool TryGetValue(string keyword, out object value) {
ADP.CheckArgumentNull(keyword, "keyword");
Keywords index;
if (_keywords.TryGetValue(keyword, out index)) {
value = GetAt(index);
return true;
}
return base.TryGetValue(keyword, out value);
}
sealed internal class OdbcConnectionStringBuilderConverter : ExpandableObjectConverter {
// converter classes should have public ctor
public OdbcConnectionStringBuilderConverter() {
}
override public bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) {
if (typeof(System.ComponentModel.Design.Serialization.InstanceDescriptor) == destinationType) {
return true;
}
return base.CanConvertTo(context, destinationType);
}
override public object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) {
if (destinationType == null) {
throw ADP.ArgumentNull("destinationType");
}
if (typeof(System.ComponentModel.Design.Serialization.InstanceDescriptor) == destinationType) {
OdbcConnectionStringBuilder obj = (value as OdbcConnectionStringBuilder);
if (null != obj) {
return ConvertToInstanceDescriptor(obj);
}
}
return base.ConvertTo(context, culture, value, destinationType);
}
private System.ComponentModel.Design.Serialization.InstanceDescriptor ConvertToInstanceDescriptor(OdbcConnectionStringBuilder options) {
Type[] ctorParams = new Type[] { typeof(string) };
object[] ctorValues = new object[] { options.ConnectionString };
System.Reflection.ConstructorInfo ctor = typeof(OdbcConnectionStringBuilder).GetConstructor(ctorParams);
return new System.ComponentModel.Design.Serialization.InstanceDescriptor(ctor, ctorValues);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Runtime.Serialization;
using JustGestures.GestureParts;
namespace JustGestures.TypeOfAction
{
/// <summary>
/// Parent for classes which implement the specific actions
/// </summary>
[Serializable]
public class BaseActionClass : ISerializable, ICloneable
{
#region Members
protected string m_name;
public string Name { get { return m_name; } }
protected string m_details;
public string Details { get { return m_details; } set { m_details = value; } }
protected List<List<MyKey>> m_keyScript;
public List<List<MyKey>> KeyScript { get { return m_keyScript; } set { m_keyScript = value; } }
public void CheckScriptForMouse()
{
m_scriptContainsMouse = false;
if (m_keyScript == null)
return;
foreach (List<MyKey> scriptList in m_keyScript)
{
if (scriptList == null) continue;
foreach (MyKey keyscrip in scriptList)
if (keyscrip != null
&& keyscrip.KeyAction != MyKey.Action.KeyClick
&& keyscrip.KeyAction != MyKey.Action.KeyDown
&& keyscrip.KeyAction != MyKey.Action.KeyUp)
{
m_scriptContainsMouse = true;
return;
}
}
}
private bool m_scriptContainsMouse = false;
public bool ScriptContainsMouse { get { return m_scriptContainsMouse; } }
protected List<string> m_actions;
#endregion Members
#region Constructors
public BaseActionClass()
: this(string.Empty)
{
}
public BaseActionClass(string action)
{
m_name = action;
m_details = string.Empty;
m_keyScript = new List<List<MyKey>>();
}
public BaseActionClass(BaseActionClass action)
: this (action.Name)
{
this.Details = action.Details;
this.KeyScript = new List<List<MyKey>>();
foreach (List<MyKey> script in action.KeyScript)
this.KeyScript.Add(new List<MyKey>(script.ToArray()));
m_scriptContainsMouse = action.ScriptContainsMouse;
}
public virtual object Clone()
{
BaseActionClass action = new BaseActionClass(this);
return action;
}
public virtual void ControlLostFocus()
{
}
public BaseActionClass(SerializationInfo info, StreamingContext context)
{
try { m_name = info.GetString("ActionName"); }
catch { m_name = string.Empty; }
try { m_details = info.GetString("Details"); }
catch { m_details = string.Empty; }
try { m_keyScript = (List<List<MyKey>>)info.GetValue("KeyScript", typeof(List<List<MyKey>>)); }
catch { m_keyScript = new List<List<MyKey>>(); }
}
#endregion Constructors
public virtual void ExecuteAction(IntPtr activeWnd, Point location) { }
public virtual string GetDescription()
{
return Languages.Translation.GetText(this.Name);
}
public virtual Bitmap GetIcon(int size)
{
return Properties.Resources.just_gestures.ToBitmap();
}
public string[] GetValues()
{
return m_actions.ToArray();
}
public bool ContainAction(string name)
{
foreach (string str in m_actions)
if (str.Equals(name)) return true;
return false;
}
public virtual bool IsExtras()
{
return false;
}
public virtual bool IsSameType(BaseActionClass action)
{
return this.GetType().Name == action.GetType().Name;
}
/// <summary>
/// Is used whether the action might be exececuted when Form_transparent or CMS_matchedGestures is selected
/// </summary>
/// <returns></returns>
public virtual bool IsSensitiveToMySystemWindows()
{
return true;
}
public virtual void ExecuteKeyScript(MouseAction mouse, IntPtr ActiveWnd, bool selectWnd, Point location)
{
if (selectWnd)
{
Win32.SetForegroundWindow(ActiveWnd);
Win32.SetActiveWindow(ActiveWnd);
}
ExecuteKeyList(mouse, location);
//Win32.INPUT[][] inputRange = KeyInput.CreateInput(KeystrokesControl.ExtractKeyList(action, mouse));
//foreach (Win32.INPUT[] input in inputRange)
//{
// Win32.SendInput((uint)input.Length, input, (int)System.Runtime.InteropServices.Marshal.SizeOf(input[0].GetType()));
//}
}
public void ExecuteKeyList(MouseAction mouseAction, Point location)
{
Win32.INPUT[][] inputRange = Features.KeyInput.CreateInput(ExtractKeyList(mouseAction));
Point currentLocation = new Point();
foreach (Win32.INPUT[] input in inputRange)
{
foreach (Win32.INPUT one_input in input)
{
Win32.INPUT[] one = new Win32.INPUT[1];
one[0] = one_input;
if (one_input.type == Win32.INPUT_MOUSE)
{
currentLocation = Cursor.Position;
Win32.SetCursorPos(location.X, location.Y);
}
Win32.SendInput((uint)one.Length, one, (int)System.Runtime.InteropServices.Marshal.SizeOf(one[0].GetType()));
System.Threading.Thread.Sleep(1);
if (one_input.type == Win32.INPUT_MOUSE)
{
Win32.SetCursorPos(currentLocation.X, currentLocation.Y);
}
}
}
//Win32.INPUT[][] inputRange = KeyInput.CreateInput(ExtractKeyList(action, MouseAction.ModifierClick));
//foreach (Win32.INPUT[] input in inputRange)
//{
// Win32.SendInput((uint)input.Length, input, (int)System.Runtime.InteropServices.Marshal.SizeOf(input[0].GetType()));
//}
}
public enum MouseAction
{
TriggerDown,
TriggerUp,
WheelDown,
WheelUp,
ModifierClick
}
public List<MyKey> ExtractKeyList(MouseAction mouse)
{
List<MyKey> keyScript = new List<MyKey>();
if (this.KeyScript != null && this.KeyScript.Count == 4) //ModifierClick
keyScript = this.KeyScript[0];
else
return keyScript;
switch (mouse)
{
case MouseAction.TriggerDown:
keyScript = this.KeyScript[0];
break;
case MouseAction.WheelDown:
keyScript = this.KeyScript[1];
break;
case MouseAction.WheelUp:
keyScript = this.KeyScript[2];
break;
case MouseAction.TriggerUp:
keyScript = this.KeyScript[3];
break;
}
return keyScript;
}
#region ISerializable Members
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("ActionName", m_name);
info.AddValue("Details", m_details);
info.AddValue("KeyScript", m_keyScript, typeof(List<List<MyKey>>));
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Xml;
using System.Security;
using System.Collections;
using System.IO;
using System.Reflection.Emit;
/*
* Limitations:
* The ExceptionDataContract utilizes the ClassDataConract class in order to deserialize Exceptions with the ability to fill private fields.
* For the ClassDataContract to deserialize private fields, the name of the private field must exactly match the name of the field in xml.
* However the thick framework does not serialize exceptions using private field names. The thick framework is able to bypass using private field names because it has a mapping for each Exception
* made possible by implementing ISerializable. The mapping of every single .Net Exception Private Field to the Thick Framework serialized name is too much data for the ExceptionDataContract
* to hold.
* This class creates a mapping for the System.Exception private fields, which are considered the most important fields for an Exception.
* Therefore the only private fields that are supported for serialization/deserialization are those declared in System.Exception.
*
* For the serialization of classes derived from System.Exception all public properties are included into the xml out.
* There is no support for private properties other than those in System.Exception.
* In order for the property to be reset on deserialization it must implement a setter.
* Author: t-jicamp
*/
namespace System.Runtime.Serialization
{
internal sealed class ExceptionDataContract : DataContract
{
private XmlDictionaryString[] _contractNamespaces;
private XmlDictionaryString[] _memberNames;
private XmlDictionaryString[] _memberNamespaces;
[SecurityCritical]
private ExceptionDataContractCriticalHelper _helper;
[SecuritySafeCritical]
public ExceptionDataContract() : base(new ExceptionDataContractCriticalHelper())
{
_helper = base.Helper as ExceptionDataContractCriticalHelper;
_contractNamespaces = _helper.ContractNamespaces;
_memberNames = _helper.MemberNames;
_memberNamespaces = _helper.MemberNamespaces;
}
[SecuritySafeCritical]
public ExceptionDataContract(Type type) : base(new ExceptionDataContractCriticalHelper(type))
{
_helper = base.Helper as ExceptionDataContractCriticalHelper;
_contractNamespaces = _helper.ContractNamespaces;
_memberNames = _helper.MemberNames;
_memberNamespaces = _helper.MemberNamespaces;
}
public List<DataMember> Members
{
[SecuritySafeCritical]
get
{ return _helper.Members; }
}
internal override bool CanContainReferences //inherited as internal
{
get { return true; }
}
public static Dictionary<string, string> EssentialExceptionFields
{
[SecuritySafeCritical]
get
{ return ExceptionDataContractCriticalHelper.EssentialExceptionFields; }
}
public override Dictionary<XmlQualifiedName, DataContract> KnownDataContracts //inherited as internal
{
[SecuritySafeCritical]
get
{ return _helper.KnownDataContracts; }
[SecurityCritical]
set
{ _helper.KnownDataContracts = value; }
}
public XmlDictionaryString[] ContractNamespaces
{
get { return _contractNamespaces; }
set { _contractNamespaces = value; }
}
public XmlDictionaryString[] MemberNames
{
get { return _memberNames; }
set { _memberNames = value; }
}
public XmlDictionaryString[] MemberNamespaces
{
get { return _memberNamespaces; }
set { _memberNamespaces = value; }
}
[SecurityCritical]
private class ExceptionDataContractCriticalHelper : DataContract.DataContractCriticalHelper
{
private XmlDictionaryString[] _contractNamespaces;
private XmlDictionaryString[] _memberNames;
private XmlDictionaryString[] _memberNamespaces;
private ExceptionDataContract _baseContract;
private List<DataMember> _members;
private bool _hasDataContract;
private Dictionary<XmlQualifiedName, DataContract> _knownDataContracts;
private static readonly Dictionary<string, string> s_essentialExceptionFields; //Contains the essential fields to serialize an Exception. Not all fields are serialized in an Exception. Some private fields
//need to be serialized, but then again some need to be left out. This will keep track of which ones need to be serialized
//And also their display name for serialization which differs from their declared name.
/*
* The ordering of this dictionary is important due to the nature of the ClassDataContract that ExceptionDataContract depends on.
* In order for the ClassDataContract to correctly set the values for the members of the underlying class, it must have a list
* of members in the same order as the xml document it is reading. These members are created in the ImportDataMembers() method,
* and their ordering comes from this dictionary.
*
* This dictionary is in the order that the Full Framework declares System.Exceptions members. This order is established
* in the Full Framework version of System.Exception's Iserializable interface.
*/
static ExceptionDataContractCriticalHelper()
{
s_essentialExceptionFields = new Dictionary<string, string>();
s_essentialExceptionFields.Add("_className", "ClassName");
s_essentialExceptionFields.Add("_message", "Message");
s_essentialExceptionFields.Add("_data", "Data");
s_essentialExceptionFields.Add("_innerException", "InnerException");
s_essentialExceptionFields.Add("_helpURL", "HelpURL");
s_essentialExceptionFields.Add("_stackTraceString", "StackTraceString");
s_essentialExceptionFields.Add("_remoteStackTraceString", "RemoteStackTraceString");
s_essentialExceptionFields.Add("_remoteStackIndex", "RemoteStackIndex");
s_essentialExceptionFields.Add("_exceptionMethodString", "ExceptionMethod");
s_essentialExceptionFields.Add("_HResult", "HResult");
s_essentialExceptionFields.Add("_source", "Source");
s_essentialExceptionFields.Add("_watsonBuckets", "WatsonBuckets");
}
public ExceptionDataContractCriticalHelper()
{
IsValueType = false;
}
public ExceptionDataContractCriticalHelper(Type type)
: base(type)
{
this.StableName = DataContract.GetStableName(type, out _hasDataContract);
Type baseType = Globals.TypeOfException;
this.IsValueType = type.GetTypeInfo().IsValueType;
if (baseType != null && baseType != Globals.TypeOfObject && type != Globals.TypeOfException)
{
DataContract baseContract = DataContract.GetDataContract(baseType);
this.BaseContract = baseContract as ExceptionDataContract;
}
else
{
this.BaseContract = null;
}
ImportDataMembers();
ImportKnownTypes();
XmlDictionary dictionary = new XmlDictionary(2 + Members.Count);
Name = dictionary.Add(StableName.Name);
Namespace = dictionary.Add(StableName.Namespace);
int baseContractCount = 0;
if (BaseContract == null)
{
_memberNames = new XmlDictionaryString[Members.Count];
_memberNamespaces = new XmlDictionaryString[Members.Count];
_contractNamespaces = new XmlDictionaryString[1];
}
else
{
_memberNames = new XmlDictionaryString[Members.Count];
_memberNamespaces = new XmlDictionaryString[Members.Count];
baseContractCount = BaseContract._contractNamespaces.Length;
_contractNamespaces = new XmlDictionaryString[1 + baseContractCount];
Array.Copy(BaseContract._contractNamespaces, 0, _contractNamespaces, 0, baseContractCount);
}
_contractNamespaces[baseContractCount] = Namespace;
for (int i = 0; i < Members.Count; i++)
{
_memberNames[i] = dictionary.Add(Members[i].Name);
_memberNamespaces[i] = Namespace;
}
}
public ExceptionDataContract BaseContract
{
get { return _baseContract; }
set { _baseContract = value; }
}
public static Dictionary<string, string> EssentialExceptionFields
{
get { return s_essentialExceptionFields; }
}
internal override Dictionary<XmlQualifiedName, DataContract> KnownDataContracts // inherited as internal
{
[SecurityCritical]
get
{
if (_knownDataContracts == null)
_knownDataContracts = new Dictionary<XmlQualifiedName, DataContract>();
return _knownDataContracts;
}
[SecurityCritical]
set
{ /* do nothing */ }
}
public List<DataMember> Members
{
get { return _members; }
}
public XmlDictionaryString[] ContractNamespaces
{
get { return _contractNamespaces; }
set { _contractNamespaces = value; }
}
public XmlDictionaryString[] MemberNames
{
get { return _memberNames; }
set { _memberNames = value; }
}
public XmlDictionaryString[] MemberNamespaces
{
get { return _memberNamespaces; }
set { _memberNamespaces = value; }
}
private void ImportDataMembers()
{
/*
* DataMembers are used for the deserialization of Exceptions.
* DataMembers represent the fields and/or settable properties that the underlying Exception has.
* The DataMembers are stored and eventually passed to a ClassDataContract created from the underlying Exception.
* The ClassDataContract uses the list of DataMembers to set the fields/properties for the newly created Exception.
* If a DataMember is a property it must be settable.
*/
Type type = this.UnderlyingType;
if (type == Globals.TypeOfException)
{
ImportSystemExceptionDataMembers(); //System.Exception must be handled specially because it is the only exception that imports private fields.
return;
}
List<DataMember> tempMembers;
if (BaseContract != null)
{
tempMembers = new List<DataMember>(BaseContract.Members); //Don't set tempMembers = BaseContract.Members and then start adding, because this alters the base's reference.
}
else
{
tempMembers = new List<DataMember>();
}
Dictionary<string, DataMember> memberNamesTable = new Dictionary<string, DataMember>();
MemberInfo[] memberInfos;
memberInfos = type.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public);
for (int i = 0; i < memberInfos.Length; i++)
{
MemberInfo member = memberInfos[i];
//Public properties with set methods can be deserialized with the ClassDataContract
PropertyInfo publicProperty = member as PropertyInfo;
if (publicProperty != null && publicProperty.SetMethod != null)
{
DataMember memberContract = new DataMember(member);
memberContract.Name = DataContract.EncodeLocalName(member.Name);
memberContract.IsRequired = false;
memberContract.IsNullable = DataContract.IsTypeNullable(memberContract.MemberType);
if (HasNoConflictWithBaseMembers(memberContract))
{
CheckAndAddMember(tempMembers, memberContract, memberNamesTable);
}
}
}
Interlocked.MemoryBarrier();
_members = tempMembers;
}
private void ImportSystemExceptionDataMembers()
{
/*
* The data members imported for System.Exception are private fields. They must be treated specially.
* The EssentialExceptionFields Dictionary keeps track of which private fields needs to be imported, and also the name that they should be serialized with.
*/
Type type = this.UnderlyingType;
List<DataMember> tempMembers;
tempMembers = new List<DataMember>();
Dictionary<string, DataMember> memberNamesTable = new Dictionary<string, DataMember>();
foreach (string fieldInfoName in EssentialExceptionFields.Keys)
{
FieldInfo member = type.GetField(fieldInfoName, BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.Instance);
if (CanSerializeMember(member))
{
DataMember memberContract = new DataMember(member);
memberContract.Name = DataContract.EncodeLocalName(member.Name);
memberContract.IsRequired = false;
memberContract.IsNullable = DataContract.IsTypeNullable(memberContract.MemberType);
CheckAndAddMember(tempMembers, memberContract, memberNamesTable);
}
}
Interlocked.MemoryBarrier();
_members = tempMembers;
}
private void ImportKnownTypes()
{
DataContract dataDataContract = GetDataContract(typeof(IDictionary<object, object>));
this.KnownDataContracts.Add(dataDataContract.StableName, dataDataContract);
}
private bool HasNoConflictWithBaseMembers(DataMember memberContract)
{
//Don't add redundant members, this can happen if a property overrides it's base class implementation. Because the overriden property will appear as "declared" in that type.
foreach (DataMember dm in BaseContract.Members)
{
if (dm.Name.Equals(memberContract.Name))
{
return false;
}
}
return true;
}
}
private static bool CanSerializeMember(FieldInfo field)
{
return field != null &&
field.FieldType != Globals.TypeOfObject; // Don't really know how to serialize plain System.Object instance
}
private void WriteExceptionValue(XmlWriterDelegator writer, object value, XmlObjectSerializerWriteContext context)
{
/*
* Every private field present in System.Exception that is serialized in the thick framework is also serialized in this method.
* For classes that inherit from System.Exception all public properties are serialized.
* The reason that the Members property is not used here to get the properties to serialize is because Members contains only the properties with setters.
*/
Type type = value.GetType();
writer.WriteXmlnsAttribute("x", new XmlDictionary(1).Add(Globals.SchemaNamespace));
WriteSystemExceptionRequiredValues(writer, value, context);
PropertyInfo[] props = type.GetProperties();
foreach (PropertyInfo prop in props)
{
//Properties in System.Exception are handled in the call to WriteSystemExceptionRequiredValues, we don't want to repeat these properties.
if (PropertyIsSystemExceptionProperty(prop))
continue;
writer.WriteStartElement(prop.Name, "");
DataContract propDataContract = context.GetDataContract(prop.PropertyType);
if (prop.GetValue(value) != null && propDataContract != null && !TryCheckIfNoCountIDictionary(prop.PropertyType, prop.GetValue(value)))
{
if (!TryWritePrimitive(prop.PropertyType, prop.GetValue(value), writer, context))
{
writer.WriteAttributeString(Globals.XsiPrefix, "type", null, "a:" + propDataContract.StableName.Name);
writer.WriteXmlnsAttribute("a", new XmlDictionary(1).Add(propDataContract.StableName.Namespace));
context.SerializeWithoutXsiType(propDataContract, writer, prop.GetValue(value), prop.PropertyType.TypeHandle);
}
}
else
{
writer.WriteAttributeString(Globals.XsiPrefix, "nil", null, "true");
}
writer.WriteEndElement();
}
}
private void WriteSystemExceptionRequiredValues(XmlWriterDelegator writer, object value, XmlObjectSerializerWriteContext context)
{
Dictionary<string, object> exceptionFields = GetExceptionFieldValues((Exception)value);
object val;
foreach (string key in exceptionFields.Keys)
{
if (!exceptionFields.TryGetValue(key, out val))
continue;
Type fieldType;
FieldInfo FieldFind = Globals.TypeOfException.GetField(key, BindingFlags.Instance | BindingFlags.NonPublic);
if (FieldFind == null)
{
val = null; // need to nullify because the private fields that are necessary in Exception have changed.
fieldType = typeof(int); // can be any type, it doesn't matter. field type will be used to recover a contract, but the type won't be utilized.
}
else
fieldType = FieldFind.FieldType;
string fieldDisplayName;
if (EssentialExceptionFields.TryGetValue(key, out fieldDisplayName))
writer.WriteStartElement(fieldDisplayName, "");
else
writer.WriteStartElement(key, "");
DataContract fieldDataContract = context.GetDataContract(fieldType);
if (val != null && fieldDataContract != null && !TryCheckIfNoCountIDictionary(fieldType, val))
{
if (!TryWritePrimitive(fieldType, val, writer, context))
{
writer.WriteAttributeString(Globals.XsiPrefix, "type", null, "a:" + fieldDataContract.StableName.Name);
writer.WriteXmlnsAttribute("a", new XmlDictionary(1).Add(fieldDataContract.StableName.Namespace));
fieldDataContract.WriteXmlValue(writer, val, context);
}
}
else
{
writer.WriteAttributeString(Globals.XsiPrefix, "nil", null, "true");
}
writer.WriteEndElement();
}
}
private bool PropertyIsSystemExceptionProperty(PropertyInfo prop)
{
PropertyInfo[] props = Globals.TypeOfException.GetProperties();
foreach (PropertyInfo propInfo in props)
{
if (propInfo.Name.Equals(prop.Name))
{
return true;
}
}
return false;
}
private static void CheckAndAddMember(List<DataMember> members, DataMember memberContract, Dictionary<string, DataMember> memberNamesTable)
{
DataMember existingMemberContract;
if (memberNamesTable.TryGetValue(memberContract.Name, out existingMemberContract))
{
Type declaringType = memberContract.MemberInfo.DeclaringType;
DataContract.ThrowInvalidDataContractException(
string.Format(SRSerialization.DupMemberName,
existingMemberContract.MemberInfo.Name,
memberContract.MemberInfo.Name,
DataContract.GetClrTypeFullName(declaringType),
memberContract.Name),
declaringType);
}
memberNamesTable.Add(memberContract.Name, memberContract);
members.Add(memberContract);
}
[SecuritySafeCritical]
private Dictionary<string, object> GetExceptionFieldValues(Exception value)
{
// Obtain the unoverrided version of Message
Type exceptionType = Globals.TypeOfException;
PropertyInfo messageProperty = exceptionType.GetProperty("Message");
MethodInfo messageGetter = messageProperty.GetMethod;
#if !NET_NATIVE
DynamicMethod baseMessageImpl = new DynamicMethod("NonVirtual_Message", typeof(string), new Type[] { Globals.TypeOfException }, Globals.TypeOfException);
ILGenerator gen = baseMessageImpl.GetILGenerator();
gen.Emit(OpCodes.Ldarg, messageGetter.GetParameters().Length);
gen.EmitCall(OpCodes.Call, messageGetter, null);
gen.Emit(OpCodes.Ret);
string messageValue = (string)baseMessageImpl.Invoke(null, new object[] { value });
#else
string messageValue = string.Empty;
#endif
// Populate the values for the necessary System.Exception private fields.
Dictionary<string, object> fieldToValueDictionary = new Dictionary<string, object>();
fieldToValueDictionary.Add("_className", value.GetType().ToString());
fieldToValueDictionary.Add("_message", messageValue); //Thick framework retrieves the System.Exception implementation of message
fieldToValueDictionary.Add("_data", value.Data);
fieldToValueDictionary.Add("_innerException", value.InnerException);
fieldToValueDictionary.Add("_helpURL", value.HelpLink);
fieldToValueDictionary.Add("_stackTraceString", value.StackTrace);
fieldToValueDictionary.Add("_remoteStackTraceString", null);
fieldToValueDictionary.Add("_remoteStackIndex", 0);
fieldToValueDictionary.Add("_exceptionMethodString", null);
fieldToValueDictionary.Add("_HResult", value.HResult);
fieldToValueDictionary.Add("_source", null); //value.source caused transparency error on build.
fieldToValueDictionary.Add("_watsonBuckets", null);
return fieldToValueDictionary;
}
public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context)
{
Type type = obj.GetType();
if (!(typeof(Exception).IsAssignableFrom(type)))
{
throw new InvalidDataContractException("Cannot use ExceptionDataContract to serialize object with type: " + type);
}
WriteExceptionValue(xmlWriter, obj, context);
}
public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)
{
XmlReaderDelegator xmlDelegator = ParseReaderString(xmlReader);
ClassDataContract cdc = new ClassDataContract(this.UnderlyingType);
// The Class Data Contract created from the underlying exception type uses custom imported members that are
// created in this classes constructor. Here we clear out the Class Data Contract's default members and insert our own.
cdc.Members.Clear();
foreach (DataMember dm in this.Members)
{
cdc.Members.Add(dm);
}
cdc.MemberNames = _memberNames;
cdc.ContractNamespaces = _contractNamespaces;
cdc.MemberNamespaces = _memberNamespaces;
object obj = cdc.ReadXmlValue(xmlDelegator, context);
if (context != null)
context.AddNewObject(obj);
return obj;
}
private bool TryWritePrimitive(Type type, object value, XmlWriterDelegator writer, XmlObjectSerializerWriteContext context)
{
PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type);
if (primitiveContract == null || primitiveContract.UnderlyingType == Globals.TypeOfObject)
return false;
writer.WriteAttributeString(Globals.XsiPrefix, "type", null, "x:" + primitiveContract.StableName.Name);
primitiveContract.WriteXmlValue(writer, value, context);
return true;
}
private static bool TryCheckIfNoCountIDictionary(Type type, object value)
{
if (value == null)
return true;
if (type == Globals.TypeOfIDictionary)
{
IDictionary tempDictImitation = (IDictionary)value;
return (tempDictImitation.Count == 0);
}
return false;
}
/*
* The reason this function exists is to provide compatibility for ExceptionDataContract to utilize ClassDataContract for deserialization.
* In order for ExceptionDataContract to deserialize using ClassDataContract the xml elements corresponding to private fields need
* to have their name replaced with the name of the private field they map to.
* Example: Message ---replaced to--> _message
*
* Currently this method utilizes a custom created class entitled ExceptionXmlParser that sits alongside the ExceptionDataContract
* The ExceptionXmlParser reads the xml string passed to it exchanges any element names that are presented in the name map
* in its constructor.
*
* The ExceptionXmlParser also gives each nested element the proper namespace for the given exception being deserialized.
* The ClassDataContract needs an exact match on the element name and the namespace in order to deserialize the value, because not all serialization
* explicitly inserts the xmlnamespace of nested objects, the exception xml parser handles this.
*/
private XmlReaderDelegator ParseReaderString(XmlReaderDelegator xmlReader)
{
//The reference to the xmlReader passed into this method should not be modified.
//The call to ReadOuterXml advances the xmlReader to the next object if the exception being parsed is a nested object of another class.
//When the call to ReadXmlValue that called this method returns, it is possible that the 'xmlReader' will still be used by the calling datacontract.
string EntryXmlString = xmlReader.UnderlyingReader.ReadOuterXml();
string result = ExceptionXmlParser.ParseExceptionXmlForClassDataContract(ReverseDictionary(EssentialExceptionFields), this.Namespace.ToString(), EntryXmlString);
byte[] byteBuffer = Encoding.UTF8.GetBytes(result);
XmlReaderDelegator xmlDelegator = new XmlReaderDelegator(XmlDictionaryReader.CreateTextReader(byteBuffer, XmlDictionaryReaderQuotas.Max));
xmlDelegator.MoveToContent();
return xmlDelegator;
}
private static Dictionary<string, string> ReverseDictionary(Dictionary<string, string> inDict)
{
Dictionary<string, string> mapDict = new Dictionary<string, string>();
foreach (string key in inDict.Keys)
{
string valString;
valString = inDict[key];
mapDict.Add(valString, key);
}
return mapDict;
}
}
/*
* This class is necessary to create a parsed xml document to utilize the ClassDataContract.
* The ExceptionXmlParser inserts necessary xmlns declarations for exception members, the namespace is necessary for ClassDataContract to identify
* the xml members as members of the Exception object.
* This ExceptionXmlParser also performs the transformation of the serialized names of exception private fields to the actual field names.
*/
internal sealed class ExceptionXmlParser : IDisposable
{
private XmlReader _reader;
private MemoryStream _ms;
private StreamWriter _sw;
private StringBuilder _sb;
private string _exceptionNamespace;
private Dictionary<string, string> _elementNamesToMap;
private bool _disposed;
private ExceptionXmlParser(Dictionary<string, string> dictMap, string exceptionNamespace)
{
// dictMap passes in the dictionary that is used for mapping field names to their serialized representations.
if (dictMap == null)
{
throw new ArgumentNullException("dictMap");
}
if (exceptionNamespace == null)
{
throw new ArgumentNullException("exceptionNamespace");
}
_elementNamesToMap = dictMap;
_exceptionNamespace = exceptionNamespace;
_sb = new StringBuilder();
_ms = new MemoryStream();
_sw = new StreamWriter(_ms);
_disposed = false;
}
public static string ParseExceptionXmlForClassDataContract(Dictionary<string, string> dictMap, string exceptionNamespace, string stringToParse)
{
using (ExceptionXmlParser parser = new ExceptionXmlParser(dictMap, exceptionNamespace))
{
return parser.ParseExceptionXml(stringToParse);
}
}
private string ParseExceptionXml(string stringToParse)
{
_sw.Write(stringToParse);
_sw.Flush();
_ms.Position = 0;
_reader = XmlReader.Create(_ms);
return ParseRootElement();
}
public void Dispose()
{
if (!_disposed)
{
_ms.Dispose();
_ms = null;
_sw.Dispose();
_sw = null;
_reader.Dispose();
_reader = null;
_disposed = true;
}
}
private string ParseRootElement()
{
_reader.MoveToContent();
string elementName = _reader.Name;
OpenRootElement(elementName);
if (_reader.IsEmptyElement)
{
_sb.Append("/>"); // close root element.
}
else
{
HandleRootElementsContents();
CloseRootElement(elementName);
}
return _sb.ToString();
}
private void ParseChildElement()
{
string elementName = _reader.Name;
elementName = OpenChildElement(elementName);
if (_reader.IsEmptyElement)
{
InlineCloser();
}
else
{
_sb.Append(">");
HandleChildElementContent();
CloseElement(elementName);
}
}
private string WriteElementNameWithBracketAndMapping(string name)
{
_sb.Append("<");
name = SwitchElementNameIfNecessary(name);
_sb.Append(name);
return name;
}
private string WriteExactElementNameWithBracket(string name)
{
_sb.AppendFormat("<{0}", name);
return name;
}
private string SwitchElementNameIfNecessary(string name)
{
string newName;
if (_elementNamesToMap.TryGetValue(name, out newName))
{
return newName;
}
return name;
}
private void InlineCloser()
{
_sb.Append("/>");
Read();
}
private void OpenRootElement(string elementName)
{
WriteElementNameWithBracketAndMapping(elementName);
for (int i = 0; i < _reader.AttributeCount; i++)
{
_reader.MoveToNextAttribute();
WriteAttribute(_reader.Name, _reader.Value);
}
_reader.MoveToElement();
}
private void CloseRootElement(string ElementName)
{
_sb.AppendFormat("</{0}>", ElementName);
}
private void HandleRootElementsContents()
{
_sb.Append(">");
Read();
while (_reader.NodeType == XmlNodeType.Element)
{
ParseChildElement();
}
}
private string OpenChildElement(string elementName)
{
elementName = WriteElementNameWithBracketAndMapping(elementName);
// the immediate child elements must have an xmlns attribute with namespace of the parent exception.
WriteAttribute("xmlns", _exceptionNamespace);
for (int i = 0; i < _reader.AttributeCount; i++)
{
_reader.MoveToNextAttribute();
if (_reader.Name.Equals("xmlns"))
continue;
WriteAttribute(_reader.Name, _reader.Value);
}
_reader.MoveToElement();
return elementName;
}
private void CloseElement(string ElementName)
{
_sb.AppendFormat("</{0}>", ElementName);
}
private void CopyXmlFromCurrentNode()
{
string elementName = _reader.Name;
// Start with the element
OpenExactElement(elementName);
// Handle an empty element
if (_reader.IsEmptyElement)
{
InlineCloser();
return;
}
_sb.Append(">");
// Append all children elements
Read();
while (_reader.NodeType == XmlNodeType.Element)
{
CopyXmlFromCurrentNode(); // Recursive call
}
if (_reader.NodeType == XmlNodeType.Text)
{
_sb.Append(_reader.Value);
Read();
}
// Finish with the element
CloseExactElement(elementName);
}
private void OpenExactElement(string elementName)
{
WriteExactElementNameWithBracket(elementName);
for (int i = 0; i < _reader.AttributeCount; i++)
{
_reader.MoveToNextAttribute();
WriteAttribute(_reader.Name, _reader.Value);
}
_reader.MoveToElement();
}
private void CloseExactElement(string elementName)
{
_sb.AppendFormat("</{0}>", elementName);
Read();
}
private void WriteAttribute(string name, string value)
{
_sb.AppendFormat(" {0}=\"{1}\"", name, value);
}
private void HandleChildElementContent()
{
Read();
if (_reader.NodeType == XmlNodeType.Text)
{
_sb.Append(_reader.Value);
Read();
_reader.ReadEndElement();
}
else
{
while (_reader.NodeType != XmlNodeType.EndElement)
{
CopyXmlFromCurrentNode();
}
_reader.ReadEndElement();
}
}
private void Read()
{
//There is no reason the reader should return false for properly serialized xml.
if (!_reader.Read())
{
throw new InvalidOperationException();
}
}
}
}
| |
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
//---------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Threading;
using System.Windows.Data;
using System.ComponentModel;
using System.Windows.Input;
using System.Collections;
using MS.Win32;
using System.Globalization;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Markup; // for XmlLanguage
using System.Windows.Media;
using System.Text;
using System.Collections.Generic;
using MS.Internal;
using MS.Internal.Data;
namespace System.Windows.Controls
{
//
/// <summary>
/// Text Search is a feature that allows the user to quickly access items in a set by typing prefixes of the strings.
/// </summary>
public sealed class TextSearch : DependencyObject
{
/// <summary>
/// Make a new TextSearch instance attached to the given object.
/// Create the instance in the same context as the given DO.
/// </summary>
/// <param name="itemsControl"></param>
private TextSearch(ItemsControl itemsControl)
{
if (itemsControl == null)
{
throw new ArgumentNullException("itemsControl");
}
_attachedTo = itemsControl;
ResetState();
}
/// <summary>
/// Get the instance of TextSearch attached to the given ItemsControl or make one and attach it if it's not.
/// </summary>
/// <param name="itemsControl"></param>
/// <returns></returns>
internal static TextSearch EnsureInstance(ItemsControl itemsControl)
{
TextSearch instance = (TextSearch)itemsControl.GetValue(TextSearchInstanceProperty);
if (instance == null)
{
instance = new TextSearch(itemsControl);
itemsControl.SetValue(TextSearchInstancePropertyKey, instance);
}
return instance;
}
#region Text and TextPath Properties
/// <summary>
/// Attached property to indicate which property on the item in the items collection to use for the "primary" text,
/// or the text against which to search.
/// </summary>
public static readonly DependencyProperty TextPathProperty
= DependencyProperty.RegisterAttached("TextPath", typeof(string), typeof(TextSearch),
new FrameworkPropertyMetadata(String.Empty /* default value */));
/// <summary>
/// Writes the attached property to the given element.
/// </summary>
/// <param name="element"></param>
/// <param name="path"></param>
public static void SetTextPath(DependencyObject element, string path)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(TextPathProperty, path);
}
/// <summary>
/// Reads the attached property from the given element.
/// </summary>
/// <param name="element"></param>
/// <returns></returns>
[AttachedPropertyBrowsableForType(typeof(DependencyObject))]
public static string GetTextPath(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return (string)element.GetValue(TextPathProperty);
}
/// <summary>
/// Attached property to indicate the value to use for the "primary" text of an element.
/// </summary>
public static readonly DependencyProperty TextProperty
= DependencyProperty.RegisterAttached("Text", typeof(string), typeof(TextSearch),
new FrameworkPropertyMetadata((string)String.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
/// <summary>
/// Writes the attached property to the given element.
/// </summary>
/// <param name="element"></param>
/// <param name="text"></param>
public static void SetText(DependencyObject element, string text)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(TextProperty, text);
}
/// <summary>
/// Reads the attached property from the given element.
/// </summary>
/// <param name="element"></param>
/// <returns></returns>
[AttachedPropertyBrowsableForType(typeof(DependencyObject))]
public static string GetText(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return (string)element.GetValue(TextProperty);
}
#endregion
#region Properties
/// <summary>
/// Prefix that is currently being used in the algorithm.
/// </summary>
private static readonly DependencyProperty CurrentPrefixProperty =
DependencyProperty.RegisterAttached("CurrentPrefix", typeof(string), typeof(TextSearch),
new FrameworkPropertyMetadata((string)null));
/// <summary>
/// If TextSearch is currently active.
/// </summary>
private static readonly DependencyProperty IsActiveProperty =
DependencyProperty.RegisterAttached("IsActive", typeof(bool), typeof(TextSearch),
new FrameworkPropertyMetadata(false));
#endregion
#region Private Properties
/// <summary>
/// The key needed set a read-only property.
/// </summary>
private static readonly DependencyPropertyKey TextSearchInstancePropertyKey =
DependencyProperty.RegisterAttachedReadOnly("TextSearchInstance", typeof(TextSearch), typeof(TextSearch),
new FrameworkPropertyMetadata((object)null /* default value */));
/// <summary>
/// Instance of TextSearch -- attached property so that the instance can be stored on the element
/// which wants the service.
/// </summary>
private static readonly DependencyProperty TextSearchInstanceProperty =
TextSearchInstancePropertyKey.DependencyProperty;
// used to retrieve the value of an item, according to the TextPath
private static readonly BindingExpressionUncommonField TextValueBindingExpression = new BindingExpressionUncommonField();
#endregion
#region Private Methods
/// <summary>
/// Called by consumers of TextSearch when a TextInput event is received
/// to kick off the algorithm.
/// </summary>
/// <param name="nextChar"></param>
/// <returns></returns>
internal bool DoSearch(string nextChar)
{
bool repeatedChar = false;
int startItemIndex = 0;
ItemCollection itemCollection = _attachedTo.Items as ItemCollection;
// If TextSearch is not active, then we should start
// the search from the beginning. If it is active, we should
// start the search from the currently-matched item.
if (IsActive)
{
// ISSUE: This falls victim to duplicate elements being in the view.
// To mitigate this, we could remember ItemUI ourselves.
startItemIndex = MatchedItemIndex;
}
// If they pressed the same character as last time, we will do the fallback search.
// Fallback search is if they type "bob" and then press "b"
// we'll look for "bobb" and when we don't find it we should
// find the next item starting with "bob".
if (_charsEntered.Count > 0
&& (String.Compare(_charsEntered[_charsEntered.Count - 1], nextChar, true, GetCulture(_attachedTo))==0))
{
repeatedChar = true;
}
// Get the primary TextPath from the ItemsControl to which we are attached.
string primaryTextPath = GetPrimaryTextPath(_attachedTo);
bool wasNewCharUsed = false;
int matchedItemIndex = FindMatchingPrefix(_attachedTo, primaryTextPath, Prefix,
nextChar, startItemIndex, repeatedChar, ref wasNewCharUsed);
// If there was an item that matched, move to that item in the collection
if (matchedItemIndex != -1)
{
// Don't have to move currency if it didn't actually move.
// startItemIndex is the index of the current item only if IsActive is true,
// So, we have to move currency when IsActive is false.
if (!IsActive || matchedItemIndex != startItemIndex)
{
object matchedItem = itemCollection[matchedItemIndex];
// Let the control decide what to do with matched-item
_attachedTo.NavigateToItem(matchedItem, matchedItemIndex, new ItemsControl.ItemNavigateArgs(Keyboard.PrimaryDevice, ModifierKeys.None));
// Store current match
MatchedItemIndex = matchedItemIndex;
}
// Update the prefix if it changed
if (wasNewCharUsed)
{
AddCharToPrefix(nextChar);
}
// User has started typing (successfully), so we're active now.
if (!IsActive)
{
IsActive = true;
}
}
// Reset the timeout and remember this character, but only if we're
// active -- this is because if we got called but the match failed
// we don't need to set up a timeout -- no state needs to be reset.
if (IsActive)
{
ResetTimeout();
}
return (matchedItemIndex != -1);
}
/// <summary>
/// Called when the user presses backspace.
/// </summary>
/// <returns></returns>
internal bool DeleteLastCharacter()
{
if (IsActive)
{
// Remove the last character from the prefix string.
// Get the last character entered and then remove a string of
// that length off the prefix string.
if (_charsEntered.Count > 0)
{
string lastChar = _charsEntered[_charsEntered.Count - 1];
string prefix = Prefix;
_charsEntered.RemoveAt(_charsEntered.Count - 1);
Prefix = prefix.Substring(0, prefix.Length - lastChar.Length);
ResetTimeout();
return true;
}
}
return false;
}
/// <summary>
/// Searches through the given itemCollection for the first item matching the given prefix.
/// </summary>
/// <remarks>
/// --------------------------------------------------------------------------
/// Incremental Type Search algorithm
/// --------------------------------------------------------------------------
///
/// Given a prefix and new character, we loop through all items in the collection
/// and look for an item that starts with the new prefix. If we find such an item,
/// select it. If the new character is repeated, we look for the next item after
/// the current one that begins with the old prefix**. We can optimize by
/// performing both of these searches in parallel.
///
/// **NOTE: Win32 will only do this if the old prefix is of length 1 - in other
/// words, first-character-only matching. The algorithm described here
/// is an extension of ITS as implemented in Win32. This variant was
/// described to me by JeffBog as what was done in AFC - but I have yet
/// to find a listbox which behaves this way.
///
/// --------------------------------------------------------------------------
/// </remarks>
/// <returns>Item that matches the given prefix</returns>
private static int FindMatchingPrefix(ItemsControl itemsControl, string primaryTextPath, string prefix,
string newChar, int startItemIndex, bool lookForFallbackMatchToo, ref bool wasNewCharUsed)
{
ItemCollection itemCollection = itemsControl.Items;
// Using indices b/c this is a better way to uniquely
// identify an element in the collection.
int matchedItemIndex = -1;
int fallbackMatchIndex = -1;
int count = itemCollection.Count;
// Return immediately with no match if there were no items in the view.
if (count == 0)
{
return -1;
}
string newPrefix = prefix + newChar;
// With an empty prefix, we'd match anything
if (String.IsNullOrEmpty(newPrefix))
{
return -1;
}
// Hook up the binding we will apply to each object. Get the
// PrimaryTextPath off of the attached instance and then make
// a binding with that path.
BindingExpression primaryTextBinding = null;
object item0 = itemsControl.Items[0];
bool useXml = SystemXmlHelper.IsXmlNode(item0);
if (useXml || !String.IsNullOrEmpty(primaryTextPath))
{
primaryTextBinding = CreateBindingExpression(itemsControl, item0, primaryTextPath);
TextValueBindingExpression.SetValue(itemsControl, primaryTextBinding);
}
bool firstItem = true;
wasNewCharUsed = false;
CultureInfo cultureInfo = GetCulture(itemsControl);
// ISSUE: what about changing the collection while this is running?
for (int currentIndex = startItemIndex; currentIndex < count; )
{
object item = itemCollection[currentIndex];
if (item != null)
{
string itemString = GetPrimaryText(item, primaryTextBinding, itemsControl);
bool isTextSearchCaseSensitive = itemsControl.IsTextSearchCaseSensitive;
// See if the current item matches the newPrefix, if so we can
// stop searching and accept this item as the match.
if (itemString != null && itemString.StartsWith(newPrefix, !isTextSearchCaseSensitive, cultureInfo))
{
// Accept the new prefix as the current prefix.
wasNewCharUsed = true;
matchedItemIndex = currentIndex;
break;
}
// Find the next string that matches the last prefix. This
// string will be used in the case that the new prefix isn't
// matched. This enables pressing the last character multiple
// times and cylcing through the set of items that match that
// prefix.
//
// Unlike the above search, this search must start *after*
// the currently selected item. This search also shouldn't
// happen if there was no previous prefix to match against
if (lookForFallbackMatchToo)
{
if (!firstItem && prefix != String.Empty)
{
if (itemString != null)
{
if (fallbackMatchIndex == -1 && itemString.StartsWith(prefix, !isTextSearchCaseSensitive, cultureInfo))
{
fallbackMatchIndex = currentIndex;
}
}
}
else
{
firstItem = false;
}
}
}
// Move next and wrap-around if we pass the end of the container.
currentIndex++;
if (currentIndex >= count)
{
currentIndex = 0;
}
// Stop where we started but only after the first pass
// through the loop -- we should process the startItem.
if (currentIndex == startItemIndex)
{
break;
}
}
if (primaryTextBinding != null)
{
// Clean up the binding for the primary text path.
TextValueBindingExpression.ClearValue(itemsControl);
}
// In the case that the new prefix didn't match anything and
// there was a fallback match that matched the old prefix, move
// to that one.
if (matchedItemIndex == -1 && fallbackMatchIndex != -1)
{
matchedItemIndex = fallbackMatchIndex;
}
return matchedItemIndex;
}
/// <summary>
/// Helper function called by Editable ComboBox to search through items.
/// </summary>
internal static int FindMatchingPrefix(ItemsControl itemsControl, string prefix)
{
bool wasNewCharUsed = false;
return FindMatchingPrefix(itemsControl, GetPrimaryTextPath(itemsControl),
prefix, String.Empty, 0, false, ref wasNewCharUsed);
}
private void ResetTimeout()
{
// Called when we get some input. Start or reset the timer.
// Queue an inactive priority work item and set its deadline.
if (_timeoutTimer == null)
{
_timeoutTimer = new DispatcherTimer(DispatcherPriority.Normal);
_timeoutTimer.Tick += new EventHandler(OnTimeout);
}
else
{
_timeoutTimer.Stop();
}
// Schedule this operation to happen a certain number of milliseconds from now.
_timeoutTimer.Interval = TimeOut;
_timeoutTimer.Start();
}
private void AddCharToPrefix(string newChar)
{
Prefix += newChar;
_charsEntered.Add(newChar);
}
private static string GetPrimaryTextPath(ItemsControl itemsControl)
{
string primaryTextPath = (string)itemsControl.GetValue(TextPathProperty);
if (String.IsNullOrEmpty(primaryTextPath))
{
primaryTextPath = itemsControl.DisplayMemberPath;
}
return primaryTextPath;
}
private static string GetPrimaryText(object item, BindingExpression primaryTextBinding, DependencyObject primaryTextBindingHome)
{
// Order of precedence for getting Primary Text is as follows:
//
// 1) PrimaryText
// 2) PrimaryTextPath (TextSearch.TextPath or ItemsControl.DisplayMemberPath)
// 3) GetPlainText()
// 4) ToString()
DependencyObject itemDO = item as DependencyObject;
if (itemDO != null)
{
string primaryText = (string)itemDO.GetValue(TextProperty);
if (!String.IsNullOrEmpty(primaryText))
{
return primaryText;
}
}
// Here hopefully they've supplied a path into their object which we can use.
if (primaryTextBinding != null && primaryTextBindingHome != null)
{
// Take the binding that we hooked up at the beginning of the search
// and apply it to the current item. Then, read the value of the
// ItemPrimaryText property (where the binding actually lives).
// Try to convert the resulting object to a string.
primaryTextBinding.Activate(item);
object primaryText = primaryTextBinding.Value;
return ConvertToPlainText(primaryText);
}
return ConvertToPlainText(item);
}
private static string ConvertToPlainText(object o)
{
FrameworkElement fe = o as FrameworkElement;
// Try to return FrameworkElement.GetPlainText()
if (fe != null)
{
string text = fe.GetPlainText();
if (text != null)
{
return text;
}
}
// Try to convert the item to a string
return (o != null) ? o.ToString() : String.Empty;
}
/// <summary>
/// Internal helper method that uses the same primary text lookup steps but doesn't require
/// the user passing in all of the bindings that we need.
/// </summary>
/// <param name="itemsControl"></param>
/// <param name="item"></param>
/// <returns></returns>
internal static string GetPrimaryTextFromItem(ItemsControl itemsControl, object item)
{
if (item == null)
return String.Empty;
BindingExpression primaryTextBinding = CreateBindingExpression(itemsControl, item, GetPrimaryTextPath(itemsControl));
TextValueBindingExpression.SetValue(itemsControl, primaryTextBinding);
string primaryText = GetPrimaryText(item, primaryTextBinding, itemsControl);
TextValueBindingExpression.ClearValue(itemsControl);
return primaryText;
}
private static BindingExpression CreateBindingExpression(ItemsControl itemsControl, object item, string primaryTextPath)
{
Binding binding = new Binding();
// Use xpath for xmlnodes (See Selector.PrepareItemValueBinding)
if (SystemXmlHelper.IsXmlNode(item))
{
binding.XPath = primaryTextPath;
binding.Path = new PropertyPath("/InnerText");
}
else
{
binding.Path = new PropertyPath(primaryTextPath);
}
binding.Mode = BindingMode.OneWay;
binding.Source = null;
return (BindingExpression)BindingExpression.CreateUntargetedBindingExpression(itemsControl, binding);
}
private void OnTimeout(object sender, EventArgs e)
{
ResetState();
}
private void ResetState()
{
// Reset the prefix string back to empty.
IsActive = false;
Prefix = String.Empty;
MatchedItemIndex = -1;
if (_charsEntered == null)
{
_charsEntered = new List<string>(10);
}
else
{
_charsEntered.Clear();
}
if(_timeoutTimer != null)
{
_timeoutTimer.Stop();
}
_timeoutTimer = null;
}
/// <summary>
/// Time until the search engine resets.
/// </summary>
private TimeSpan TimeOut
{
get
{
// NOTE: NtUser does the following (file: windows/ntuser/kernel/sysmet.c)
// gpsi->dtLBSearch = dtTime * 4; // dtLBSearch = 4 * gdtDblClk
// gpsi->dtScroll = gpsi->dtLBSearch / 5; // dtScroll = 4/5 * gdtDblClk
//
// 4 * DoubleClickSpeed seems too slow for the search
// So for now we'll do 2 * DoubleClickSpeed
return TimeSpan.FromMilliseconds(SafeNativeMethods.GetDoubleClickTime() * 2);
}
}
#endregion
#region Testing API
// Being that this is a time-sensitive operation, it's difficult
// to get the timing right in a DRT. I'll leave input testing up to BVTs here
// but this internal API is for the DRT to do basic coverage.
private static TextSearch GetInstance(DependencyObject d)
{
return EnsureInstance(d as ItemsControl);
}
private void TypeAKey(string c)
{
DoSearch(c);
}
private void CauseTimeOut()
{
if (_timeoutTimer != null)
{
_timeoutTimer.Stop();
OnTimeout(_timeoutTimer, EventArgs.Empty);
}
}
internal string GetCurrentPrefix()
{
return Prefix;
}
#endregion
#region Internal Accessibility API
internal static string GetPrimaryText(FrameworkElement element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
string text = (string)element.GetValue(TextProperty);
if (text != null && text != String.Empty)
{
return text;
}
return element.GetPlainText();
}
#endregion
#region Private Fields
private string Prefix
{
get { return _prefix; }
set
{
_prefix = value;
#if DEBUG
// Also need to invalidate the property CurrentPrefixProperty on the instance to which we are attached.
Debug.Assert(_attachedTo != null);
_attachedTo.SetValue(CurrentPrefixProperty, _prefix);
#endif
}
}
private bool IsActive
{
get { return _isActive; }
set
{
_isActive = value;
#if DEBUG
Debug.Assert(_attachedTo != null);
_attachedTo.SetValue(IsActiveProperty, _isActive);
#endif
}
}
private int MatchedItemIndex
{
get { return _matchedItemIndex; }
set
{
_matchedItemIndex = value;
}
}
private static CultureInfo GetCulture(DependencyObject element)
{
object o = element.GetValue(FrameworkElement.LanguageProperty);
CultureInfo culture = null;
if (o != null)
{
XmlLanguage language = (XmlLanguage) o;
try
{
culture = language.GetSpecificCulture();
}
catch (InvalidOperationException)
{
}
}
return culture;
}
// Element to which this TextSearch instance is attached.
private ItemsControl _attachedTo;
// String of characters matched so far.
private string _prefix;
private List<string> _charsEntered;
private bool _isActive;
private int _matchedItemIndex;
private DispatcherTimer _timeoutTimer;
#endregion
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Unmanaged
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using Apache.Ignite.Core.Common;
using JNI = IgniteJniNativeMethods;
/// <summary>
/// Unmanaged utility classes.
/// </summary>
internal static unsafe class UnmanagedUtils
{
/** Interop factory ID for .Net. */
private const int InteropFactoryId = 1;
/// <summary>
/// Initializer.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
static UnmanagedUtils()
{
var path = IgniteUtils.UnpackEmbeddedResource(IgniteUtils.FileIgniteJniDll);
var ptr = NativeMethods.LoadLibrary(path);
if (ptr == IntPtr.Zero)
throw new IgniteException(string.Format("Failed to load {0}: {1}",
IgniteUtils.FileIgniteJniDll, Marshal.GetLastWin32Error()));
}
/// <summary>
/// No-op initializer used to force type loading and static constructor call.
/// </summary>
internal static void Initialize()
{
// No-op.
}
#region NATIVE METHODS: PROCESSOR
internal static void IgnitionStart(UnmanagedContext ctx, string cfgPath, string gridName,
bool clientMode)
{
using (var mem = IgniteManager.Memory.Allocate().GetStream())
{
mem.WriteBool(clientMode);
sbyte* cfgPath0 = IgniteUtils.StringToUtf8Unmanaged(cfgPath);
sbyte* gridName0 = IgniteUtils.StringToUtf8Unmanaged(gridName);
try
{
// OnStart receives the same InteropProcessor as here (just as another GlobalRef) and stores it.
// Release current reference immediately.
void* res = JNI.IgnitionStart(ctx.NativeContext, cfgPath0, gridName0, InteropFactoryId,
mem.SynchronizeOutput());
JNI.Release(res);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(cfgPath0));
Marshal.FreeHGlobal(new IntPtr(gridName0));
}
}
}
internal static bool IgnitionStop(void* ctx, string gridName, bool cancel)
{
sbyte* gridName0 = IgniteUtils.StringToUtf8Unmanaged(gridName);
try
{
return JNI.IgnitionStop(ctx, gridName0, cancel);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(gridName0));
}
}
internal static void IgnitionStopAll(void* ctx, bool cancel)
{
JNI.IgnitionStopAll(ctx, cancel);
}
internal static void ProcessorReleaseStart(IUnmanagedTarget target)
{
JNI.ProcessorReleaseStart(target.Context, target.Target);
}
internal static IUnmanagedTarget ProcessorProjection(IUnmanagedTarget target)
{
void* res = JNI.ProcessorProjection(target.Context, target.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget ProcessorCache(IUnmanagedTarget target, string name)
{
sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name);
try
{
void* res = JNI.ProcessorCache(target.Context, target.Target, name0);
return target.ChangeTarget(res);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(name0));
}
}
internal static IUnmanagedTarget ProcessorCreateCache(IUnmanagedTarget target, string name)
{
sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name);
try
{
void* res = JNI.ProcessorCreateCache(target.Context, target.Target, name0);
return target.ChangeTarget(res);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(name0));
}
}
internal static IUnmanagedTarget ProcessorCreateCache(IUnmanagedTarget target, long memPtr)
{
void* res = JNI.ProcessorCreateCacheFromConfig(target.Context, target.Target, memPtr);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget ProcessorGetOrCreateCache(IUnmanagedTarget target, string name)
{
sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name);
try
{
void* res = JNI.ProcessorGetOrCreateCache(target.Context, target.Target, name0);
return target.ChangeTarget(res);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(name0));
}
}
internal static IUnmanagedTarget ProcessorGetOrCreateCache(IUnmanagedTarget target, long memPtr)
{
void* res = JNI.ProcessorGetOrCreateCacheFromConfig(target.Context, target.Target, memPtr);
return target.ChangeTarget(res);
}
internal static void ProcessorDestroyCache(IUnmanagedTarget target, string name)
{
sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name);
try
{
JNI.ProcessorDestroyCache(target.Context, target.Target, name0);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(name0));
}
}
internal static IUnmanagedTarget ProcessorAffinity(IUnmanagedTarget target, string name)
{
sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name);
try
{
void* res = JNI.ProcessorAffinity(target.Context, target.Target, name0);
return target.ChangeTarget(res);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(name0));
}
}
internal static IUnmanagedTarget ProcessorDataStreamer(IUnmanagedTarget target, string name, bool keepBinary)
{
sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name);
try
{
void* res = JNI.ProcessorDataStreamer(target.Context, target.Target, name0, keepBinary);
return target.ChangeTarget(res);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(name0));
}
}
internal static IUnmanagedTarget ProcessorTransactions(IUnmanagedTarget target)
{
void* res = JNI.ProcessorTransactions(target.Context, target.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget ProcessorCompute(IUnmanagedTarget target, IUnmanagedTarget prj)
{
void* res = JNI.ProcessorCompute(target.Context, target.Target, prj.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget ProcessorMessage(IUnmanagedTarget target, IUnmanagedTarget prj)
{
void* res = JNI.ProcessorMessage(target.Context, target.Target, prj.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget ProcessorEvents(IUnmanagedTarget target, IUnmanagedTarget prj)
{
void* res = JNI.ProcessorEvents(target.Context, target.Target, prj.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget ProcessorServices(IUnmanagedTarget target, IUnmanagedTarget prj)
{
void* res = JNI.ProcessorServices(target.Context, target.Target, prj.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget ProcessorExtensions(IUnmanagedTarget target)
{
void* res = JNI.ProcessorExtensions(target.Context, target.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget ProcessorAtomicLong(IUnmanagedTarget target, string name, long initialValue,
bool create)
{
var name0 = IgniteUtils.StringToUtf8Unmanaged(name);
try
{
var res = JNI.ProcessorAtomicLong(target.Context, target.Target, name0, initialValue, create);
return res == null ? null : target.ChangeTarget(res);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(name0));
}
}
internal static IUnmanagedTarget ProcessorAtomicSequence(IUnmanagedTarget target, string name, long initialValue,
bool create)
{
var name0 = IgniteUtils.StringToUtf8Unmanaged(name);
try
{
var res = JNI.ProcessorAtomicSequence(target.Context, target.Target, name0, initialValue, create);
return res == null ? null : target.ChangeTarget(res);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(name0));
}
}
internal static IUnmanagedTarget ProcessorAtomicReference(IUnmanagedTarget target, string name, long memPtr,
bool create)
{
var name0 = IgniteUtils.StringToUtf8Unmanaged(name);
try
{
var res = JNI.ProcessorAtomicReference(target.Context, target.Target, name0, memPtr, create);
return res == null ? null : target.ChangeTarget(res);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(name0));
}
}
internal static void ProcessorGetIgniteConfiguration(IUnmanagedTarget target, long memPtr)
{
JNI.ProcessorGetIgniteConfiguration(target.Context, target.Target, memPtr);
}
#endregion
#region NATIVE METHODS: TARGET
internal static long TargetInStreamOutLong(IUnmanagedTarget target, int opType, long memPtr)
{
return JNI.TargetInStreamOutLong(target.Context, target.Target, opType, memPtr);
}
internal static void TargetInStreamOutStream(IUnmanagedTarget target, int opType, long inMemPtr, long outMemPtr)
{
JNI.TargetInStreamOutStream(target.Context, target.Target, opType, inMemPtr, outMemPtr);
}
internal static IUnmanagedTarget TargetInStreamOutObject(IUnmanagedTarget target, int opType, long inMemPtr)
{
void* res = JNI.TargetInStreanOutObject(target.Context, target.Target, opType, inMemPtr);
return target.ChangeTarget(res);
}
internal static void TargetInObjectStreamOutStream(IUnmanagedTarget target, int opType, void* arg, long inMemPtr, long outMemPtr)
{
JNI.TargetInObjectStreamOutStream(target.Context, target.Target, opType, arg, inMemPtr, outMemPtr);
}
internal static long TargetOutLong(IUnmanagedTarget target, int opType)
{
return JNI.TargetOutLong(target.Context, target.Target, opType);
}
internal static void TargetOutStream(IUnmanagedTarget target, int opType, long memPtr)
{
JNI.TargetOutStream(target.Context, target.Target, opType, memPtr);
}
internal static IUnmanagedTarget TargetOutObject(IUnmanagedTarget target, int opType)
{
void* res = JNI.TargetOutObject(target.Context, target.Target, opType);
return target.ChangeTarget(res);
}
internal static void TargetListenFuture(IUnmanagedTarget target, long futId, int typ)
{
JNI.TargetListenFut(target.Context, target.Target, futId, typ);
}
internal static void TargetListenFutureForOperation(IUnmanagedTarget target, long futId, int typ, int opId)
{
JNI.TargetListenFutForOp(target.Context, target.Target, futId, typ, opId);
}
internal static IUnmanagedTarget TargetListenFutureAndGet(IUnmanagedTarget target, long futId, int typ)
{
var res = JNI.TargetListenFutAndGet(target.Context, target.Target, futId, typ);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget TargetListenFutureForOperationAndGet(IUnmanagedTarget target, long futId,
int typ, int opId)
{
var res = JNI.TargetListenFutForOpAndGet(target.Context, target.Target, futId, typ, opId);
return target.ChangeTarget(res);
}
#endregion
#region NATIVE METHODS: AFFINITY
internal static int AffinityPartitions(IUnmanagedTarget target)
{
return JNI.AffinityParts(target.Context, target.Target);
}
#endregion
#region NATIVE METHODS: CACHE
internal static IUnmanagedTarget CacheWithSkipStore(IUnmanagedTarget target)
{
void* res = JNI.CacheWithSkipStore(target.Context, target.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget CacheWithNoRetries(IUnmanagedTarget target)
{
void* res = JNI.CacheWithNoRetries(target.Context, target.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget CacheWithExpiryPolicy(IUnmanagedTarget target, long create, long update, long access)
{
void* res = JNI.CacheWithExpiryPolicy(target.Context, target.Target, create, update, access);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget CacheWithAsync(IUnmanagedTarget target)
{
void* res = JNI.CacheWithAsync(target.Context, target.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget CacheWithKeepBinary(IUnmanagedTarget target)
{
void* res = JNI.CacheWithKeepBinary(target.Context, target.Target);
return target.ChangeTarget(res);
}
internal static void CacheClear(IUnmanagedTarget target)
{
JNI.CacheClear(target.Context, target.Target);
}
internal static void CacheRemoveAll(IUnmanagedTarget target)
{
JNI.CacheRemoveAll(target.Context, target.Target);
}
internal static IUnmanagedTarget CacheOutOpQueryCursor(IUnmanagedTarget target, int type, long memPtr)
{
void* res = JNI.CacheOutOpQueryCursor(target.Context, target.Target, type, memPtr);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget CacheOutOpContinuousQuery(IUnmanagedTarget target, int type, long memPtr)
{
void* res = JNI.CacheOutOpContinuousQuery(target.Context, target.Target, type, memPtr);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget CacheIterator(IUnmanagedTarget target)
{
void* res = JNI.CacheIterator(target.Context, target.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget CacheLocalIterator(IUnmanagedTarget target, int peekModes)
{
void* res = JNI.CacheLocalIterator(target.Context, target.Target, peekModes);
return target.ChangeTarget(res);
}
internal static void CacheEnterLock(IUnmanagedTarget target, long id)
{
JNI.CacheEnterLock(target.Context, target.Target, id);
}
internal static void CacheExitLock(IUnmanagedTarget target, long id)
{
JNI.CacheExitLock(target.Context, target.Target, id);
}
internal static bool CacheTryEnterLock(IUnmanagedTarget target, long id, long timeout)
{
return JNI.CacheTryEnterLock(target.Context, target.Target, id, timeout);
}
internal static void CacheCloseLock(IUnmanagedTarget target, long id)
{
JNI.CacheCloseLock(target.Context, target.Target, id);
}
internal static void CacheRebalance(IUnmanagedTarget target, long futId)
{
JNI.CacheRebalance(target.Context, target.Target, futId);
}
internal static void CacheStoreCallbackInvoke(IUnmanagedTarget target, long memPtr)
{
JNI.CacheStoreCallbackInvoke(target.Context, target.Target, memPtr);
}
internal static int CacheSize(IUnmanagedTarget target, int modes, bool loc)
{
return JNI.CacheSize(target.Context, target.Target, modes, loc);
}
#endregion
#region NATIVE METHODS: COMPUTE
internal static void ComputeWithNoFailover(IUnmanagedTarget target)
{
JNI.ComputeWithNoFailover(target.Context, target.Target);
}
internal static void ComputeWithTimeout(IUnmanagedTarget target, long timeout)
{
JNI.ComputeWithTimeout(target.Context, target.Target, timeout);
}
internal static IUnmanagedTarget ComputeExecuteNative(IUnmanagedTarget target, long taskPtr, long topVer)
{
void* res = JNI.ComputeExecuteNative(target.Context, target.Target, taskPtr, topVer);
return target.ChangeTarget(res);
}
#endregion
#region NATIVE METHODS: CONTINUOUS QUERY
internal static void ContinuousQueryClose(IUnmanagedTarget target)
{
JNI.ContinuousQryClose(target.Context, target.Target);
}
internal static IUnmanagedTarget ContinuousQueryGetInitialQueryCursor(IUnmanagedTarget target)
{
void* res = JNI.ContinuousQryGetInitialQueryCursor(target.Context, target.Target);
return res == null ? null : target.ChangeTarget(res);
}
#endregion
#region NATIVE METHODS: DATA STREAMER
internal static void DataStreamerListenTopology(IUnmanagedTarget target, long ptr)
{
JNI.DataStreamerListenTop(target.Context, target.Target, ptr);
}
internal static bool DataStreamerAllowOverwriteGet(IUnmanagedTarget target)
{
return JNI.DataStreamerAllowOverwriteGet(target.Context, target.Target);
}
internal static void DataStreamerAllowOverwriteSet(IUnmanagedTarget target, bool val)
{
JNI.DataStreamerAllowOverwriteSet(target.Context, target.Target, val);
}
internal static bool DataStreamerSkipStoreGet(IUnmanagedTarget target)
{
return JNI.DataStreamerSkipStoreGet(target.Context, target.Target);
}
internal static void DataStreamerSkipStoreSet(IUnmanagedTarget target, bool val)
{
JNI.DataStreamerSkipStoreSet(target.Context, target.Target, val);
}
internal static int DataStreamerPerNodeBufferSizeGet(IUnmanagedTarget target)
{
return JNI.DataStreamerPerNodeBufferSizeGet(target.Context, target.Target);
}
internal static void DataStreamerPerNodeBufferSizeSet(IUnmanagedTarget target, int val)
{
JNI.DataStreamerPerNodeBufferSizeSet(target.Context, target.Target, val);
}
internal static int DataStreamerPerNodeParallelOperationsGet(IUnmanagedTarget target)
{
return JNI.DataStreamerPerNodeParallelOpsGet(target.Context, target.Target);
}
internal static void DataStreamerPerNodeParallelOperationsSet(IUnmanagedTarget target, int val)
{
JNI.DataStreamerPerNodeParallelOpsSet(target.Context, target.Target, val);
}
#endregion
#region NATIVE METHODS: MESSAGING
internal static IUnmanagedTarget MessagingWithASync(IUnmanagedTarget target)
{
void* res = JNI.MessagingWithAsync(target.Context, target.Target);
return target.ChangeTarget(res);
}
#endregion
#region NATIVE METHODS: PROJECTION
internal static IUnmanagedTarget ProjectionForOthers(IUnmanagedTarget target, IUnmanagedTarget prj)
{
void* res = JNI.ProjectionForOthers(target.Context, target.Target, prj.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget ProjectionForRemotes(IUnmanagedTarget target)
{
void* res = JNI.ProjectionForRemotes(target.Context, target.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget ProjectionForDaemons(IUnmanagedTarget target)
{
void* res = JNI.ProjectionForDaemons(target.Context, target.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget ProjectionForRandom(IUnmanagedTarget target)
{
void* res = JNI.ProjectionForRandom(target.Context, target.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget ProjectionForOldest(IUnmanagedTarget target)
{
void* res = JNI.ProjectionForOldest(target.Context, target.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget ProjectionForYoungest(IUnmanagedTarget target)
{
void* res = JNI.ProjectionForYoungest(target.Context, target.Target);
return target.ChangeTarget(res);
}
internal static void ProjectionResetMetrics(IUnmanagedTarget target)
{
JNI.ProjectionResetMetrics(target.Context, target.Target);
}
internal static IUnmanagedTarget ProjectionOutOpRet(IUnmanagedTarget target, int type, long memPtr)
{
void* res = JNI.ProjectionOutOpRet(target.Context, target.Target, type, memPtr);
return target.ChangeTarget(res);
}
#endregion
#region NATIVE METHODS: QUERY CURSOR
internal static void QueryCursorIterator(IUnmanagedTarget target)
{
JNI.QryCursorIterator(target.Context, target.Target);
}
internal static void QueryCursorClose(IUnmanagedTarget target)
{
JNI.QryCursorClose(target.Context, target.Target);
}
#endregion
#region NATIVE METHODS: TRANSACTIONS
internal static long TransactionsStart(IUnmanagedTarget target, int concurrency, int isolation, long timeout, int txSize)
{
return JNI.TxStart(target.Context, target.Target, concurrency, isolation, timeout, txSize);
}
internal static int TransactionsCommit(IUnmanagedTarget target, long id)
{
return JNI.TxCommit(target.Context, target.Target, id);
}
internal static void TransactionsCommitAsync(IUnmanagedTarget target, long id, long futId)
{
JNI.TxCommitAsync(target.Context, target.Target, id, futId);
}
internal static int TransactionsRollback(IUnmanagedTarget target, long id)
{
return JNI.TxRollback(target.Context, target.Target, id);
}
internal static void TransactionsRollbackAsync(IUnmanagedTarget target, long id, long futId)
{
JNI.TxRollbackAsync(target.Context, target.Target, id, futId);
}
internal static int TransactionsClose(IUnmanagedTarget target, long id)
{
return JNI.TxClose(target.Context, target.Target, id);
}
internal static int TransactionsState(IUnmanagedTarget target, long id)
{
return JNI.TxState(target.Context, target.Target, id);
}
internal static bool TransactionsSetRollbackOnly(IUnmanagedTarget target, long id)
{
return JNI.TxSetRollbackOnly(target.Context, target.Target, id);
}
internal static void TransactionsResetMetrics(IUnmanagedTarget target)
{
JNI.TxResetMetrics(target.Context, target.Target);
}
#endregion
#region NATIVE METHODS: MISCELANNEOUS
internal static void Reallocate(long memPtr, int cap)
{
int res = JNI.Reallocate(memPtr, cap);
if (res != 0)
throw new IgniteException("Failed to reallocate external memory [ptr=" + memPtr +
", capacity=" + cap + ']');
}
internal static IUnmanagedTarget Acquire(UnmanagedContext ctx, void* target)
{
void* target0 = JNI.Acquire(ctx.NativeContext, target);
return new UnmanagedTarget(ctx, target0);
}
internal static void Release(IUnmanagedTarget target)
{
JNI.Release(target.Target);
}
internal static void ThrowToJava(void* ctx, Exception e)
{
char* msgChars = (char*)IgniteUtils.StringToUtf8Unmanaged(e.Message);
try
{
JNI.ThrowToJava(ctx, msgChars);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(msgChars));
}
}
internal static int HandlersSize()
{
return JNI.HandlersSize();
}
internal static void* CreateContext(void* opts, int optsLen, void* cbs)
{
return JNI.CreateContext(opts, optsLen, cbs);
}
internal static void DeleteContext(void* ctx)
{
JNI.DeleteContext(ctx);
}
internal static void DestroyJvm(void* ctx)
{
JNI.DestroyJvm(ctx);
}
#endregion
#region NATIVE METHODS: EVENTS
internal static IUnmanagedTarget EventsWithAsync(IUnmanagedTarget target)
{
return target.ChangeTarget(JNI.EventsWithAsync(target.Context, target.Target));
}
internal static bool EventsStopLocalListen(IUnmanagedTarget target, long handle)
{
return JNI.EventsStopLocalListen(target.Context, target.Target, handle);
}
internal static bool EventsIsEnabled(IUnmanagedTarget target, int type)
{
return JNI.EventsIsEnabled(target.Context, target.Target, type);
}
internal static void EventsLocalListen(IUnmanagedTarget target, long handle, int type)
{
JNI.EventsLocalListen(target.Context, target.Target, handle, type);
}
#endregion
#region NATIVE METHODS: SERVICES
internal static IUnmanagedTarget ServicesWithAsync(IUnmanagedTarget target)
{
return target.ChangeTarget(JNI.ServicesWithAsync(target.Context, target.Target));
}
internal static IUnmanagedTarget ServicesWithServerKeepBinary(IUnmanagedTarget target)
{
return target.ChangeTarget(JNI.ServicesWithServerKeepBinary(target.Context, target.Target));
}
internal static void ServicesCancel(IUnmanagedTarget target, string name)
{
var nameChars = (char*)IgniteUtils.StringToUtf8Unmanaged(name);
try
{
JNI.ServicesCancel(target.Context, target.Target, nameChars);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(nameChars));
}
}
internal static void ServicesCancelAll(IUnmanagedTarget target)
{
JNI.ServicesCancelAll(target.Context, target.Target);
}
internal static IUnmanagedTarget ServicesGetServiceProxy(IUnmanagedTarget target, string name, bool sticky)
{
var nameChars = (char*)IgniteUtils.StringToUtf8Unmanaged(name);
try
{
return target.ChangeTarget(JNI.ServicesGetServiceProxy(target.Context, target.Target, nameChars, sticky));
}
finally
{
Marshal.FreeHGlobal(new IntPtr(nameChars));
}
}
#endregion
#region NATIVE METHODS: DATA STRUCTURES
internal static long AtomicLongGet(IUnmanagedTarget target)
{
return JNI.AtomicLongGet(target.Context, target.Target);
}
internal static long AtomicLongIncrementAndGet(IUnmanagedTarget target)
{
return JNI.AtomicLongIncrementAndGet(target.Context, target.Target);
}
internal static long AtomicLongAddAndGet(IUnmanagedTarget target, long value)
{
return JNI.AtomicLongAddAndGet(target.Context, target.Target, value);
}
internal static long AtomicLongDecrementAndGet(IUnmanagedTarget target)
{
return JNI.AtomicLongDecrementAndGet(target.Context, target.Target);
}
internal static long AtomicLongGetAndSet(IUnmanagedTarget target, long value)
{
return JNI.AtomicLongGetAndSet(target.Context, target.Target, value);
}
internal static long AtomicLongCompareAndSetAndGet(IUnmanagedTarget target, long expVal, long newVal)
{
return JNI.AtomicLongCompareAndSetAndGet(target.Context, target.Target, expVal, newVal);
}
internal static bool AtomicLongIsClosed(IUnmanagedTarget target)
{
return JNI.AtomicLongIsClosed(target.Context, target.Target);
}
internal static void AtomicLongClose(IUnmanagedTarget target)
{
JNI.AtomicLongClose(target.Context, target.Target);
}
internal static long AtomicSequenceGet(IUnmanagedTarget target)
{
return JNI.AtomicSequenceGet(target.Context, target.Target);
}
internal static long AtomicSequenceIncrementAndGet(IUnmanagedTarget target)
{
return JNI.AtomicSequenceIncrementAndGet(target.Context, target.Target);
}
internal static long AtomicSequenceAddAndGet(IUnmanagedTarget target, long value)
{
return JNI.AtomicSequenceAddAndGet(target.Context, target.Target, value);
}
internal static int AtomicSequenceGetBatchSize(IUnmanagedTarget target)
{
return JNI.AtomicSequenceGetBatchSize(target.Context, target.Target);
}
internal static void AtomicSequenceSetBatchSize(IUnmanagedTarget target, int size)
{
JNI.AtomicSequenceSetBatchSize(target.Context, target.Target, size);
}
internal static bool AtomicSequenceIsClosed(IUnmanagedTarget target)
{
return JNI.AtomicSequenceIsClosed(target.Context, target.Target);
}
internal static void AtomicSequenceClose(IUnmanagedTarget target)
{
JNI.AtomicSequenceClose(target.Context, target.Target);
}
internal static bool AtomicReferenceIsClosed(IUnmanagedTarget target)
{
return JNI.AtomicReferenceIsClosed(target.Context, target.Target);
}
internal static void AtomicReferenceClose(IUnmanagedTarget target)
{
JNI.AtomicReferenceClose(target.Context, target.Target);
}
internal static bool ListenableCancel(IUnmanagedTarget target)
{
return JNI.ListenableCancel(target.Context, target.Target);
}
internal static bool ListenableIsCancelled(IUnmanagedTarget target)
{
return JNI.ListenableIsCancelled(target.Context, target.Target);
}
#endregion
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.dll Alpha
// Description: A library module for the DotSpatial geospatial framework for .Net.
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 11/12/2008 1:58:22 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Windows.Forms;
namespace DotSpatial.Data.Forms
{
/// <summary>
/// DirectoryView
/// </summary>
public class DirectoryView : ScrollingControl
{
#region Private Variables
/// <summary>
/// Designer variable
/// </summary>
//private IContainer components = null; // the members to be contained
private string _directory;
private bool _ignoreSelectChanged;
private List<DirectoryItem> _items;
private DirectoryItem _selectedItem; // the most recently selected
private DirectoryItem _selectionStart;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of DirectoryView
/// </summary>
public DirectoryView()
{
_items = new List<DirectoryItem>();
InitializeComponent();
}
#endregion
#region Methods
#endregion
#region Properties
/// <summary>
/// Gets or sets the selected item. In cases of a multiple select, this is the
/// last member added to the selection.
/// </summary>
public DirectoryItem SelectedItem
{
get { return _selectedItem; }
set
{
_selectedItem = value;
Invalidate();
}
}
/// <summary>
/// Gets or sets the string path that should be itemized in the view.
/// </summary>
public string Directory
{
get { return _directory; }
set
{
_directory = value;
UpdateContent();
}
}
/// <summary>
/// Gets or sets the collection of DirectoryItems to draw in this control
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public List<DirectoryItem> Items
{
get { return _items; }
set { _items = value; }
}
/// <summary>
/// Draws
/// </summary>
/// <param name="e"></param>
protected override void OnInitialize(PaintEventArgs e)
{
UpdateContent();
// translate into document coordinates
Matrix oldMat = e.Graphics.Transform;
Matrix mat = new Matrix();
e.Graphics.Transform = mat;
foreach (DirectoryItem item in _items)
{
if (ControlRectangle.IntersectsWith(item.Bounds))
{
item.Draw(e);
}
}
e.Graphics.Transform = oldMat;
base.OnInitialize(e);
}
#endregion
#region Protected Methods
/// <summary>
/// Gets or sets the Font to be used for all of the items in this view.
/// </summary>
[Category("Appearance"), Description("Gets or sets the Font to be used for all of the items in this view.")]
public override Font Font
{
get
{
return base.Font;
}
set
{
base.Font = value;
UpdateContent();
}
}
/// <summary>
/// Handles the situation where the mouse has been pressed down.
/// </summary>
/// <param name="e"></param>
protected override void OnMouseDown(MouseEventArgs e)
{
foreach (DirectoryItem di in _items)
{
if (di.Bounds.Contains(e.Location))
{
di.IsSelected = true;
RefreshItem(di);
Invalidate(DocumentToClient(di.Bounds));
}
}
base.OnMouseDown(e);
}
/// <summary>
/// Updates the buffer in order to correctly re-draw this item, if it is on the page, and then invalidates
/// the area where this will be drawn.
/// </summary>
/// <param name="item">The directory item to invalidate</param>
public void RefreshItem(DirectoryItem item)
{
Graphics g = Graphics.FromImage(Page);
Brush b = new SolidBrush(item.BackColor);
g.FillRectangle(b, DocumentToClient(item.Bounds));
b.Dispose();
// first translate into document coordinates
Matrix mat = new Matrix();
mat.Translate(ClientRectangle.X, ClientRectangle.Y);
g.Transform = mat;
item.Draw(new PaintEventArgs(g, item.Bounds));
g.Dispose();
}
///// <summary>
///// This handles drawing but extends the
///// </summary>
///// <param name="e"></param>
//protected override void OnDraw(PaintEventArgs e)
//{
// base.OnDraw(e);
// foreach (DirectoryItem item in _items)
// {
// item.Draw(e);
// }
//}
#endregion
private void InitializeComponent()
{
}
/// <summary>
/// Removes the existing Directory Items from the control
/// </summary>
public virtual void Clear()
{
if (_items != null) _items.Clear();
}
/// <summary>
/// Causes the control to refresh the current content.
/// </summary>
public void UpdateContent()
{
if (Controls == null) return;
SuspendLayout();
int tp = 1;
Clear();
Graphics g = CreateGraphics();
SizeF fontSize = g.MeasureString("TEST", Font);
int fontHeight = (int)(fontSize.Height + 4);
if (fontHeight < 20) fontHeight = 20;
AddFolders(ref tp, fontHeight);
AddFiles(ref tp, fontHeight);
if (tp < fontHeight * _items.Count) tp = fontHeight * _items.Count;
DocumentRectangle = new Rectangle(DocumentRectangle.X, DocumentRectangle.Y, ClientRectangle.Width, tp);
ResetScroll();
ResumeLayout(false);
}
private void AddFiles(ref int tp, int fontHeight)
{
if (_directory == null) return;
string[] files = System.IO.Directory.GetFiles(_directory);
foreach (string file in files)
{
FileItem fi = new FileItem(file);
if (fi.ItemType == ItemType.Custom) continue;
fi.Top = tp;
fi.Font = Font;
fi.Height = fontHeight;
_items.Add(fi);
tp += fontHeight;
}
}
private void item_SelectChanged(object sender, SelectEventArgs e)
{
if (_ignoreSelectChanged) return;
DirectoryItem di = sender as DirectoryItem;
if (di == null) return;
if ((e.Modifiers & Keys.Control) == Keys.Control && (e.Modifiers & Keys.Shift) != Keys.Shift)
{
if (_selectedItem != null)
{
_selectedItem.IsOutlined = false;
}
_selectionStart = di;
_selectedItem = di;
_selectedItem.IsOutlined = true;
Invalidate();
return;
}
_ignoreSelectChanged = true;
if (((e.Modifiers & Keys.Shift) == Keys.Shift) && ((e.Modifiers & Keys.Control) != Keys.Control))
{
ClearSelection();
_selectedItem.IsOutlined = false;
int iOld;
if (_selectionStart != null)
{
iOld = _items.IndexOf(_selectionStart);
}
else
{
_selectionStart = _items[0];
iOld = 0;
}
int iNew = _items.IndexOf(di);
int start = Math.Min(iOld, iNew);
int end = Math.Max(iOld, iNew);
for (int i = start; i <= end; i++)
{
_items[i].IsSelected = true;
}
_selectionStart.IsOutlined = false;
}
// With no control keys or both.
if ((((e.Modifiers & Keys.Shift) == Keys.Shift) && ((e.Modifiers & Keys.Control) == Keys.Control)) ||
(((e.Modifiers & Keys.Shift) != Keys.Shift) && ((e.Modifiers & Keys.Control) != Keys.Control)))
{
if (_selectedItem != null)
{
_selectedItem.IsOutlined = false;
}
ClearSelection();
di.IsSelected = true;
_selectionStart = di;
di.IsOutlined = true;
}
_selectedItem = di;
di.IsOutlined = true;
Invalidate();
_ignoreSelectChanged = false;
}
/// <summary>
/// Systematically clears any currently selected items.
/// </summary>
public void ClearSelection()
{
foreach (DirectoryItem di in _items)
{
di.IsSelected = false;
}
}
private void AddFolders(ref int tp, int fontHeight)
{
if (_directory == null) return;
string temp = _directory.Trim(Path.DirectorySeparatorChar);
string[] currentDirectoryParts = temp.Split(Path.DirectorySeparatorChar);
if (currentDirectoryParts.Length > 1)
{
if (_directory != null)
{
DirectoryInfo parent = System.IO.Directory.GetParent(_directory);
if (parent != null)
{
FolderItem up = new FolderItem(parent.FullName);
up.Text = "..";
up.Font = this.Font;
up.Top = tp;
up.Height = fontHeight;
_items.Add(up);
}
}
tp += fontHeight;
}
if (_directory != null)
{
string[] subDirs = System.IO.Directory.GetDirectories(_directory);
if (_items == null) _items = new List<DirectoryItem>();
foreach (string dir in subDirs)
{
FolderItem di = new FolderItem(dir);
di.Font = this.Font;
di.Top = tp;
di.Height = fontHeight;
//di.Navigate += new EventHandler<NavigateEventArgs>(item_Navigate);
//di.SelectChanged += new EventHandler<SelectEventArgs>(item_SelectChanged);
_items.Add(di);
tp += fontHeight;
}
}
}
private void item_Navigate(object sender, NavigateEventArgs e)
{
_directory = e.Path;
UpdateContent();
Invalidate();
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Net;
using System.Reflection;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Services.Connectors.SimianGrid
{
/// <summary>
/// Connects region registration and neighbor lookups to the SimianGrid
/// backend
/// </summary>
public class SimianGridServiceConnector : IGridService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private string m_ServerURI = String.Empty;
// private bool m_Enabled = false;
public SimianGridServiceConnector()
{
}
public SimianGridServiceConnector(string serverURI)
{
m_ServerURI = serverURI.TrimEnd('/');
}
public SimianGridServiceConnector(IConfigSource source)
{
CommonInit(source);
}
public void Initialise(IConfigSource source)
{
CommonInit(source);
}
private void CommonInit(IConfigSource source)
{
IConfig gridConfig = source.Configs["GridService"];
if (gridConfig == null)
{
m_log.Error("[SIMIAN GRID CONNECTOR]: GridService missing from OpenSim.ini");
throw new Exception("Grid connector init error");
}
string serviceUrl = gridConfig.GetString("GridServerURI");
if (String.IsNullOrEmpty(serviceUrl))
{
m_log.Error("[SIMIAN GRID CONNECTOR]: No Server URI named in section GridService");
throw new Exception("Grid connector init error");
}
if (!serviceUrl.EndsWith("/") && !serviceUrl.EndsWith("="))
serviceUrl = serviceUrl + '/';
m_ServerURI = serviceUrl;
// m_Enabled = true;
}
#region IGridService
public bool DeregisterRegion(UUID regionID)
{
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "AddScene" },
{ "SceneID", regionID.ToString() },
{ "Enabled", "0" }
};
OSDMap response = SimianGrid.PostToService(m_ServerURI, requestArgs);
bool success = response["Success"].AsBoolean();
if (!success)
m_log.Warn("[SIMIAN GRID CONNECTOR]: Region deregistration for " + regionID + " failed: " + response["Message"].AsString());
return success;
}
public List<GridRegion> GetDefaultHypergridRegions(UUID scopeID)
{
// TODO: Allow specifying the default grid location
return GetDefaultRegions(scopeID);
}
public List<GridRegion> GetDefaultRegions(UUID scopeID)
{
// TODO: Allow specifying the default grid location
const int DEFAULT_X = 1000 * 256;
const int DEFAULT_Y = 1000 * 256;
GridRegion defRegion = GetNearestRegion(new Vector3d(DEFAULT_X, DEFAULT_Y, 0.0), true);
if (defRegion != null)
return new List<GridRegion>(1) { defRegion };
else
return new List<GridRegion>(0);
}
public List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y)
{
GridRegion defRegion = GetNearestRegion(new Vector3d(x, y, 0.0), true);
if (defRegion != null)
return new List<GridRegion>(1) { defRegion };
else
return new List<GridRegion>(0);
}
public List<GridRegion> GetHyperlinks(UUID scopeID)
{
List<GridRegion> foundRegions = new List<GridRegion>();
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetScenes" },
{ "HyperGrid", "true" },
{ "Enabled", "1" }
};
OSDMap response = SimianGrid.PostToService(m_ServerURI, requestArgs);
if (response["Success"].AsBoolean())
{
// m_log.DebugFormat("[SIMIAN GRID CONNECTOR] found regions with name {0}",name);
OSDArray array = response["Scenes"] as OSDArray;
if (array != null)
{
for (int i = 0; i < array.Count; i++)
{
GridRegion region = ResponseToGridRegion(array[i] as OSDMap);
if (region != null)
foundRegions.Add(region);
}
}
}
return foundRegions;
}
public List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID)
{
GridRegion region = GetRegionByUUID(scopeID, regionID);
int NEIGHBOR_RADIUS = Math.Max(region.RegionSizeX, region.RegionSizeY) / 2;
if (region != null)
{
List<GridRegion> regions = GetRegionRange(scopeID,
region.RegionLocX - NEIGHBOR_RADIUS, region.RegionLocX + region.RegionSizeX + NEIGHBOR_RADIUS,
region.RegionLocY - NEIGHBOR_RADIUS, region.RegionLocY + region.RegionSizeY + NEIGHBOR_RADIUS);
for (int i = 0; i < regions.Count; i++)
{
if (regions[i].RegionID == regionID)
{
regions.RemoveAt(i);
break;
}
}
// m_log.Debug("[SIMIAN GRID CONNECTOR]: Found " + regions.Count + " neighbors for region " + regionID);
return regions;
}
return new List<GridRegion>(0);
}
public GridRegion GetRegionByName(UUID scopeID, string regionName)
{
List<GridRegion> regions = GetRegionsByName(scopeID, regionName, 1);
m_log.Debug("[SIMIAN GRID CONNECTOR]: Got " + regions.Count + " matches for region name " + regionName);
if (regions.Count > 0)
return regions[0];
return null;
}
public GridRegion GetRegionByPosition(UUID scopeID, int x, int y)
{
// Go one meter in from the requested x/y coords to avoid requesting a position
// that falls on the border of two sims
Vector3d position = new Vector3d(x + 1, y + 1, 0.0);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetScene" },
{ "Position", position.ToString() },
{ "Enabled", "1" }
};
// m_log.DebugFormat("[SIMIAN GRID CONNECTOR] request grid at {0}",position.ToString());
OSDMap response = SimianGrid.PostToService(m_ServerURI, requestArgs);
if (response["Success"].AsBoolean())
{
// m_log.DebugFormat("[SIMIAN GRID CONNECTOR] position request successful {0}",response["Name"].AsString());
return ResponseToGridRegion(response);
}
else
{
// m_log.InfoFormat("[SIMIAN GRID CONNECTOR]: Grid service did not find a match for region at {0},{1}",
// Util.WorldToRegionLoc(x), Util.WorldToRegionLoc(y));
return null;
}
}
public GridRegion GetRegionByUUID(UUID scopeID, UUID regionID)
{
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetScene" },
{ "SceneID", regionID.ToString() }
};
// m_log.DebugFormat("[SIMIAN GRID CONNECTOR] request region with uuid {0}",regionID.ToString());
OSDMap response = SimianGrid.PostToService(m_ServerURI, requestArgs);
if (response["Success"].AsBoolean())
{
// m_log.DebugFormat("[SIMIAN GRID CONNECTOR] uuid request successful {0}",response["Name"].AsString());
return ResponseToGridRegion(response);
}
else
{
m_log.Warn("[SIMIAN GRID CONNECTOR]: Grid service did not find a match for region " + regionID);
return null;
}
}
public int GetRegionFlags(UUID scopeID, UUID regionID)
{
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetScene" },
{ "SceneID", regionID.ToString() }
};
m_log.DebugFormat("[SIMIAN GRID CONNECTOR] request region flags for {0}", regionID.ToString());
OSDMap response = SimianGrid.PostToService(m_ServerURI, requestArgs);
if (response["Success"].AsBoolean())
{
OSDMap extraData = response["ExtraData"] as OSDMap;
int enabled = response["Enabled"].AsBoolean() ? (int)OpenSim.Framework.RegionFlags.RegionOnline : 0;
int hypergrid = extraData["HyperGrid"].AsBoolean() ? (int)OpenSim.Framework.RegionFlags.Hyperlink : 0;
int flags = enabled | hypergrid;
m_log.DebugFormat("[SGGC] enabled - {0} hg - {1} flags - {2}", enabled, hypergrid, flags);
return flags;
}
else
{
m_log.Warn("[SIMIAN GRID CONNECTOR]: Grid service did not find a match for region " + regionID + " during region flags check");
return -1;
}
}
public List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax)
{
List<GridRegion> foundRegions = new List<GridRegion>();
Vector3d minPosition = new Vector3d(xmin, ymin, 0.0);
Vector3d maxPosition = new Vector3d(xmax, ymax, Constants.RegionHeight);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetScenes" },
{ "MinPosition", minPosition.ToString() },
{ "MaxPosition", maxPosition.ToString() },
{ "Enabled", "1" }
};
//m_log.DebugFormat("[SIMIAN GRID CONNECTOR] request regions by range {0} to {1}",minPosition.ToString(),maxPosition.ToString());
OSDMap response = SimianGrid.PostToService(m_ServerURI, requestArgs);
if (response["Success"].AsBoolean())
{
OSDArray array = response["Scenes"] as OSDArray;
if (array != null)
{
for (int i = 0; i < array.Count; i++)
{
GridRegion region = ResponseToGridRegion(array[i] as OSDMap);
if (region != null)
foundRegions.Add(region);
}
}
}
return foundRegions;
}
public List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber)
{
List<GridRegion> foundRegions = new List<GridRegion>();
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetScenes" },
{ "NameQuery", name },
{ "Enabled", "1" }
};
if (maxNumber > 0)
requestArgs["MaxNumber"] = maxNumber.ToString();
// m_log.DebugFormat("[SIMIAN GRID CONNECTOR] request regions with name {0}",name);
OSDMap response = SimianGrid.PostToService(m_ServerURI, requestArgs);
if (response["Success"].AsBoolean())
{
// m_log.DebugFormat("[SIMIAN GRID CONNECTOR] found regions with name {0}",name);
OSDArray array = response["Scenes"] as OSDArray;
if (array != null)
{
for (int i = 0; i < array.Count; i++)
{
GridRegion region = ResponseToGridRegion(array[i] as OSDMap);
if (region != null)
foundRegions.Add(region);
}
}
}
return foundRegions;
}
public string RegisterRegion(UUID scopeID, GridRegion regionInfo)
{
Vector3d minPosition = new Vector3d(regionInfo.RegionLocX, regionInfo.RegionLocY, 0.0);
Vector3d maxPosition = minPosition + new Vector3d(regionInfo.RegionSizeX, regionInfo.RegionSizeY, Constants.RegionHeight);
OSDMap extraData = new OSDMap
{
{ "ServerURI", OSD.FromString(regionInfo.ServerURI) },
{ "InternalAddress", OSD.FromString(regionInfo.InternalEndPoint.Address.ToString()) },
{ "InternalPort", OSD.FromInteger(regionInfo.InternalEndPoint.Port) },
{ "ExternalAddress", OSD.FromString(regionInfo.ExternalEndPoint.Address.ToString()) },
{ "ExternalPort", OSD.FromInteger(regionInfo.ExternalEndPoint.Port) },
{ "MapTexture", OSD.FromUUID(regionInfo.TerrainImage) },
{ "Access", OSD.FromInteger(regionInfo.Access) },
{ "RegionSecret", OSD.FromString(regionInfo.RegionSecret) },
{ "EstateOwner", OSD.FromUUID(regionInfo.EstateOwner) },
{ "Token", OSD.FromString(regionInfo.Token) }
};
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "AddScene" },
{ "SceneID", regionInfo.RegionID.ToString() },
{ "Name", regionInfo.RegionName },
{ "MinPosition", minPosition.ToString() },
{ "MaxPosition", maxPosition.ToString() },
{ "Address", regionInfo.ServerURI },
{ "Enabled", "1" },
{ "ExtraData", OSDParser.SerializeJsonString(extraData) }
};
OSDMap response = SimianGrid.PostToService(m_ServerURI, requestArgs);
if (response["Success"].AsBoolean())
return String.Empty;
else
return "Region registration for " + regionInfo.RegionName + " failed: " + response["Message"].AsString();
}
#endregion IGridService
private GridRegion GetNearestRegion(Vector3d position, bool onlyEnabled)
{
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetScene" },
{ "Position", position.ToString() },
{ "FindClosest", "1" }
};
if (onlyEnabled)
requestArgs["Enabled"] = "1";
OSDMap response = SimianGrid.PostToService(m_ServerURI, requestArgs);
if (response["Success"].AsBoolean())
{
return ResponseToGridRegion(response);
}
else
{
m_log.Warn("[SIMIAN GRID CONNECTOR]: Grid service did not find a match for region at " + position);
return null;
}
}
private GridRegion ResponseToGridRegion(OSDMap response)
{
if (response == null)
return null;
OSDMap extraData = response["ExtraData"] as OSDMap;
if (extraData == null)
return null;
GridRegion region = new GridRegion();
region.RegionID = response["SceneID"].AsUUID();
region.RegionName = response["Name"].AsString();
Vector3d minPosition = response["MinPosition"].AsVector3d();
Vector3d maxPosition = response["MaxPosition"].AsVector3d();
region.RegionLocX = (int)minPosition.X;
region.RegionLocY = (int)minPosition.Y;
region.RegionSizeX = (int)maxPosition.X - (int)minPosition.X;
region.RegionSizeY = (int)maxPosition.Y - (int)minPosition.Y;
if (!extraData["HyperGrid"])
{
Uri httpAddress = response["Address"].AsUri();
region.ExternalHostName = httpAddress.Host;
region.HttpPort = (uint)httpAddress.Port;
IPAddress internalAddress;
IPAddress.TryParse(extraData["InternalAddress"].AsString(), out internalAddress);
if (internalAddress == null)
internalAddress = IPAddress.Any;
region.InternalEndPoint = new IPEndPoint(internalAddress, extraData["InternalPort"].AsInteger());
region.TerrainImage = extraData["MapTexture"].AsUUID();
region.Access = (byte)extraData["Access"].AsInteger();
region.RegionSecret = extraData["RegionSecret"].AsString();
region.EstateOwner = extraData["EstateOwner"].AsUUID();
region.Token = extraData["Token"].AsString();
region.ServerURI = extraData["ServerURI"].AsString();
}
else
{
region.ServerURI = response["Address"];
}
return region;
}
}
}
| |
using System;
using System.Globalization;
using System.IO;
using System.Net;
using System.Threading;
using Microsoft.Extensions.Logging;
using Orleans.Logging;
using System.Threading.Tasks;
using Orleans.Runtime.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Orleans.Configuration;
using Orleans.Hosting;
using Orleans.Runtime.Startup;
namespace Orleans.Runtime.Host
{
/// <summary>
/// Allows programmatically hosting an Orleans silo in the curent app domain.
/// </summary>
public class SiloHost :
MarshalByRefObject,
IDisposable
{
/// <summary> Name of this silo. </summary>
public string Name { get; set; }
/// <summary> Type of this silo - either <c>Primary</c> or <c>Secondary</c>. </summary>
public Silo.SiloType Type { get; set; }
/// <summary>
/// Configuration file used for this silo.
/// Changing this after the silo has started (when <c>ConfigLoaded == true</c>) will have no effect.
/// </summary>
public string ConfigFileName { get; set; }
/// <summary> Configuration data for the Orleans system. </summary>
public ClusterConfiguration Config { get; set; }
/// <summary> Configuration data for this silo. </summary>
public NodeConfiguration NodeConfig { get; private set; }
/// <summary>delegate to add some configuration to the client</summary>
public Action<ISiloHostBuilder> ConfigureSiloHostDelegate { get; set; }
/// <summary>
/// Whether the silo config has been loaded and initializing it's runtime config.
/// </summary>
/// <remarks>
/// Changes to silo config properties will be ignored after <c>ConfigLoaded == true</c>.
/// </remarks>
public bool ConfigLoaded { get; private set; }
/// <summary> Cluster Id (if any) for the cluster this silo is running in. </summary>
public string DeploymentId { get; set; }
/// <summary> Whether this silo started successfully and is currently running. </summary>
public bool IsStarted { get; private set; }
private ILoggerProvider loggerProvider;
private ILogger logger;
private Silo orleans;
private EventWaitHandle startupEvent;
private EventWaitHandle shutdownEvent;
private bool disposed;
private const string DateFormat = "yyyy-MM-dd-HH.mm.ss.fffZ";
/// <summary>
/// Constructor
/// </summary>
/// <param name="siloName">Name of this silo.</param>
public SiloHost(string siloName)
{
this.Name = siloName;
this.loggerProvider =
new FileLoggerProvider($"SiloHost-{siloName}-{DateTime.UtcNow.ToString(DateFormat)}.log");
this.logger = this.loggerProvider.CreateLogger(this.GetType().FullName);
this.Type = Silo.SiloType.Secondary; // Default
this.IsStarted = false;
}
/// <summary> Constructor </summary>
/// <param name="siloName">Name of this silo.</param>
/// <param name="config">Silo config that will be used to initialize this silo.</param>
public SiloHost(string siloName, ClusterConfiguration config) : this(siloName)
{
SetSiloConfig(config);
}
/// <summary> Constructor </summary>
/// <param name="siloName">Name of this silo.</param>
/// <param name="configFile">Silo config file that will be used to initialize this silo.</param>
public SiloHost(string siloName, FileInfo configFile)
: this(siloName)
{
this.ConfigFileName = configFile.FullName;
var config = new ClusterConfiguration();
config.LoadFromFile(this.ConfigFileName);
SetSiloConfig(config);
}
/// <summary>
/// Initialize this silo.
/// </summary>
public void InitializeOrleansSilo()
{
try
{
if (!this.ConfigLoaded) LoadOrleansConfig();
var builder = new SiloHostBuilder()
.Configure<SiloOptions>(options => options.SiloName = this.Name)
.UseConfiguration(this.Config);
if (!string.IsNullOrWhiteSpace(this.Config.Defaults.StartupTypeName))
{
builder.UseServiceProviderFactory(services =>
StartupBuilder.ConfigureStartup(this.Config.Defaults.StartupTypeName, services));
}
ConfigureSiloHostDelegate?.Invoke(builder);
var host = builder.Build();
this.orleans = host.Services.GetRequiredService<Silo>();
var localConfig = host.Services.GetRequiredService<NodeConfiguration>();
this.logger.Info(ErrorCode.Runtime_Error_100288, "Successfully initialized Orleans silo '{0}'.", this.orleans.Name);
}
catch (Exception exc)
{
ReportStartupError(exc);
this.orleans = null;
}
}
/// <summary>
/// Uninitialize this silo.
/// </summary>
public void UnInitializeOrleansSilo()
{
//currently an empty method, keep this method for backward-compatibility
}
/// <summary>
/// Start this silo.
/// </summary>
/// <returns></returns>
public bool StartOrleansSilo(bool catchExceptions = true)
{
try
{
if (string.IsNullOrEmpty(Thread.CurrentThread.Name))
Thread.CurrentThread.Name = this.GetType().Name;
if (this.orleans != null)
{
var shutdownEventName = this.Config.Defaults.SiloShutdownEventName ?? this.Name + "-Shutdown";
bool createdNew;
try
{
this.logger.Info(ErrorCode.SiloShutdownEventName, "Silo shutdown event name: {0}", shutdownEventName);
this.shutdownEvent = new EventWaitHandle(false, EventResetMode.ManualReset, shutdownEventName, out createdNew);
if (!createdNew)
{
this.logger.Info(ErrorCode.SiloShutdownEventOpened, "Opened existing shutdown event. Setting the event {0}", shutdownEventName);
}
else
{
this.logger.Info(ErrorCode.SiloShutdownEventCreated, "Created and set shutdown event {0}", shutdownEventName);
}
}
catch (PlatformNotSupportedException exc)
{
this.logger.Info(ErrorCode.SiloShutdownEventFailure, "Unable to create SiloShutdownEvent: {0}", exc.ToString());
}
// Start silo
this.orleans.Start();
// Wait for the shutdown event, and trigger a graceful shutdown if we receive it.
if (this.shutdownEvent != null)
{
var shutdownThread = new Thread(o =>
{
this.shutdownEvent.WaitOne();
this.logger.Info(ErrorCode.SiloShutdownEventReceived, "Received a shutdown event. Starting graceful shutdown.");
this.orleans.Shutdown();
})
{
IsBackground = true,
Name = "SiloShutdownMonitor"
};
shutdownThread.Start();
}
try
{
var startupEventName = this.Name;
this.logger.Info(ErrorCode.SiloStartupEventName, "Silo startup event name: {0}", startupEventName);
this.startupEvent = new EventWaitHandle(true, EventResetMode.ManualReset, startupEventName, out createdNew);
if (!createdNew)
{
this.logger.Info(ErrorCode.SiloStartupEventOpened, "Opened existing startup event. Setting the event {0}", startupEventName);
this.startupEvent.Set();
}
else
{
this.logger.Info(ErrorCode.SiloStartupEventCreated, "Created and set startup event {0}", startupEventName);
}
}
catch (PlatformNotSupportedException exc)
{
this.logger.Info(ErrorCode.SiloStartupEventFailure, "Unable to create SiloStartupEvent: {0}", exc.ToString());
}
this.logger.Info(ErrorCode.SiloStarted, "Silo {0} started successfully", this.Name);
this.IsStarted = true;
}
else
{
throw new InvalidOperationException("Cannot start silo " + this.Name + " due to prior initialization error");
}
}
catch (Exception exc)
{
if (catchExceptions)
{
ReportStartupError(exc);
this.orleans = null;
this.IsStarted = false;
return false;
}
else
throw;
}
return true;
}
/// <summary>
/// Stop this silo.
/// </summary>
public void StopOrleansSilo()
{
this.IsStarted = false;
if (this.orleans != null) this.orleans.Stop();
}
/// <summary>
/// Gracefully shutdown this silo.
/// </summary>
public void ShutdownOrleansSilo()
{
this.IsStarted = false;
if (this.orleans != null) this.orleans.Shutdown();
}
/// <summary>
/// Returns a task that will resolve when the silo has finished shutting down, or the cancellation token is cancelled.
/// </summary>
/// <param name="millisecondsTimeout">Timeout, or -1 for infinite.</param>
/// <param name="cancellationToken">Token that cancels waiting for shutdown.</param>
/// <returns></returns>
public Task ShutdownOrleansSiloAsync(int millisecondsTimeout, CancellationToken cancellationToken)
{
if (this.orleans == null || !this.IsStarted)
return Task.CompletedTask;
this.IsStarted = false;
var shutdownThread = new Thread(o =>
{
this.orleans.Shutdown();
})
{
IsBackground = true,
Name = nameof(ShutdownOrleansSiloAsync)
};
shutdownThread.Start();
return WaitForOrleansSiloShutdownAsync(millisecondsTimeout, cancellationToken);
}
/// <summary>
/// /// Returns a task that will resolve when the silo has finished shutting down, or the cancellation token is cancelled.
/// </summary>
/// <param name="cancellationToken">Token that cancels waiting for shutdown.</param>
/// <returns></returns>
public Task ShutdownOrleansSiloAsync(CancellationToken cancellationToken)
{
return ShutdownOrleansSiloAsync(Timeout.Infinite, cancellationToken);
}
/// <summary>
/// Wait for this silo to shutdown.
/// </summary>
/// <remarks>
/// Note: This method call will block execution of current thread,
/// and will not return control back to the caller until the silo is shutdown.
/// </remarks>
public void WaitForOrleansSiloShutdown()
{
WaitForOrleansSiloShutdownImpl();
}
/// <summary>
/// Wait for this silo to shutdown or to be stopped with provided cancellation token.
/// </summary>
/// <param name="cancellationToken">Cancellation token.</param>
/// <remarks>
/// Note: This method call will block execution of current thread,
/// and will not return control back to the caller until the silo is shutdown or
/// an external request for cancellation has been issued.
/// </remarks>
public void WaitForOrleansSiloShutdown(CancellationToken cancellationToken)
{
WaitForOrleansSiloShutdownImpl(cancellationToken);
}
/// <summary>
/// Waits for the SiloTerminatedEvent to fire or cancellation token to be cancelled.
/// </summary>
/// <param name="millisecondsTimeout">Timeout, or -1 for infinite.</param>
/// <param name="cancellationToken">Token that cancels waiting for shutdown.</param>
/// <remarks>
/// This is essentially an async version of WaitForOrleansSiloShutdown.
/// </remarks>
public async Task<bool> WaitForOrleansSiloShutdownAsync(int millisecondsTimeout, CancellationToken cancellationToken)
{
RegisteredWaitHandle registeredHandle = null;
CancellationTokenRegistration tokenRegistration = default(CancellationTokenRegistration);
try
{
var tcs = new TaskCompletionSource<bool>();
registeredHandle = ThreadPool.RegisterWaitForSingleObject(
this.orleans.SiloTerminatedEvent,
(state, timedOut) => ((TaskCompletionSource<bool>)state).TrySetResult(!timedOut),
tcs,
millisecondsTimeout,
true);
tokenRegistration = cancellationToken.Register(
state => ((TaskCompletionSource<bool>)state).TrySetCanceled(),
tcs);
return await tcs.Task;
}
finally
{
if (registeredHandle != null)
registeredHandle.Unregister(null);
tokenRegistration.Dispose();
}
}
/// <summary>
/// Set the ClusterId for this silo,
/// as well as the connection string to use the silo system data,
/// such as the cluster membership table..
/// </summary>
/// <param name="clusterId">ClusterId this silo is part of.</param>
/// <param name="connectionString">Azure connection string to use the silo system data.</param>
public void SetDeploymentId(string clusterId, string connectionString)
{
this.logger.Info(ErrorCode.SiloSetDeploymentId, "Setting Deployment Id to {0} and data connection string to {1}",
clusterId, ConfigUtilities.RedactConnectionStringInfo(connectionString));
this.Config.Globals.ClusterId = clusterId;
this.Config.Globals.DataConnectionString = connectionString;
}
/// <summary>
/// Set the main endpoint address for this silo,
/// plus the silo generation value to be used to distinguish this silo instance
/// from any previous silo instances previously running on this endpoint.
/// </summary>
/// <param name="endpoint">IP address and port of the main inter-silo socket connection.</param>
/// <param name="generation">Generation number for this silo.</param>
public void SetSiloEndpoint(IPEndPoint endpoint, int generation)
{
this.logger.Info(ErrorCode.SiloSetSiloEndpoint, "Setting silo endpoint address to {0}:{1}", endpoint, generation);
this.NodeConfig.HostNameOrIPAddress = endpoint.Address.ToString();
this.NodeConfig.Port = endpoint.Port;
this.NodeConfig.Generation = generation;
}
/// <summary>
/// Set the gateway proxy endpoint address for this silo.
/// </summary>
/// <param name="endpoint">IP address of the gateway socket connection.</param>
public void SetProxyEndpoint(IPEndPoint endpoint)
{
this.logger.Info(ErrorCode.SiloSetProxyEndpoint, "Setting silo proxy endpoint address to {0}", endpoint);
this.NodeConfig.ProxyGatewayEndpoint = endpoint;
}
/// <summary>
/// Set the seed node endpoint address to be used by silo.
/// </summary>
/// <param name="endpoint">IP address of the inter-silo connection socket on the seed node silo.</param>
public void SetSeedNodeEndpoint(IPEndPoint endpoint)
{
this.logger.Info(ErrorCode.SiloSetSeedNode, "Adding seed node address={0} port={1}", endpoint.Address, endpoint.Port);
this.Config.Globals.SeedNodes.Clear();
this.Config.Globals.SeedNodes.Add(endpoint);
}
/// <summary>
/// Set the set of seed node endpoint addresses to be used by silo.
/// </summary>
/// <param name="endpoints">IP addresses of the inter-silo connection socket on the seed node silos.</param>
public void SetSeedNodeEndpoints(IPEndPoint[] endpoints)
{
// Add all silos as seed nodes
this.Config.Globals.SeedNodes.Clear();
foreach (IPEndPoint endpoint in endpoints)
{
this.logger.Info(ErrorCode.SiloAddSeedNode, "Adding seed node address={0} port={1}", endpoint.Address, endpoint.Port);
this.Config.Globals.SeedNodes.Add(endpoint);
}
}
/// <summary>
/// Set the endpoint addresses for the Primary silo (if any).
/// This silo may be Primary, in which case this address should match
/// this silo's inter-silo connection socket address.
/// </summary>
/// <param name="endpoint">The IP address for the inter-silo connection socket on the Primary silo.</param>
public void SetPrimaryNodeEndpoint(IPEndPoint endpoint)
{
this.logger.Info(ErrorCode.SiloSetPrimaryNode, "Setting primary node address={0} port={1}", endpoint.Address, endpoint.Port);
this.Config.PrimaryNode = endpoint;
}
/// <summary>
/// Set the type of this silo. Default is Secondary.
/// </summary>
/// <param name="siloType">Type of this silo.</param>
public void SetSiloType(Silo.SiloType siloType)
{
this.logger.Info(ErrorCode.SiloSetSiloType, "Setting silo type {0}", siloType);
this.Type = siloType;
}
/// <summary>
/// Set the membership liveness type to be used by this silo.
/// </summary>
/// <param name="livenessType">Liveness type for this silo</param>
public void SetSiloLivenessType(GlobalConfiguration.LivenessProviderType livenessType)
{
this.logger.Info(ErrorCode.SetSiloLivenessType, "Setting silo Liveness Provider Type={0}", livenessType);
this.Config.Globals.LivenessType = livenessType;
}
/// <summary>
/// Set the reminder service type to be used by this silo.
/// </summary>
/// <param name="reminderType">Reminder service type for this silo</param>
public void SetReminderServiceType(GlobalConfiguration.ReminderServiceProviderType reminderType)
{
this.logger.Info(ErrorCode.SetSiloLivenessType, "Setting silo Reminder Service Provider Type={0}", reminderType);
this.Config.Globals.SetReminderServiceType(reminderType);
}
/// <summary>
/// Set expected deployment size.
/// </summary>
/// <param name="size">The expected deployment size.</param>
public void SetExpectedClusterSize(int size)
{
this.logger.Info(ErrorCode.SetSiloLivenessType, "Setting Expected Cluster Size to={0}", size);
this.Config.Globals.ExpectedClusterSize = size;
}
/// <summary>
/// Report an error during silo startup.
/// </summary>
/// <remarks>
/// Information on the silo startup issue will be logged to any attached Loggers,
/// then a timestamped StartupError text file will be written to
/// the current working directory (if possible).
/// </remarks>
/// <param name="exc">Exception which caused the silo startup issue.</param>
public void ReportStartupError(Exception exc)
{
if (string.IsNullOrWhiteSpace(this.Name))
this.Name = "Silo";
var errMsg = "ERROR starting Orleans silo name=" + this.Name + " Exception=" + LogFormatter.PrintException(exc);
if (this.logger != null) this.logger.Error(ErrorCode.Runtime_Error_100105, errMsg, exc);
// Dump Startup error to a log file
var now = DateTime.UtcNow;
var dateString = now.ToString(DateFormat, CultureInfo.InvariantCulture);
var startupLog = this.Name + "-StartupError-" + dateString + ".txt";
try
{
File.AppendAllText(startupLog, dateString + "Z" + Environment.NewLine + errMsg);
}
catch (Exception exc2)
{
if (this.logger != null) this.logger.Error(ErrorCode.Runtime_Error_100106, "Error writing log file " + startupLog, exc2);
}
}
/// <summary>
/// Search for and load the config file for this silo.
/// </summary>
public void LoadOrleansConfig()
{
if (this.ConfigLoaded) return;
var config = this.Config ?? new ClusterConfiguration();
try
{
if (this.ConfigFileName == null)
config.StandardLoad();
else
config.LoadFromFile(this.ConfigFileName);
}
catch (Exception ex)
{
throw new AggregateException("Error loading Config file: " + ex.Message, ex);
}
SetSiloConfig(config);
}
/// <summary>
/// Allows silo config to be programmatically set.
/// </summary>
/// <param name="config">Configuration data for this silo and cluster.</param>
private void SetSiloConfig(ClusterConfiguration config)
{
this.Config = config;
if (!string.IsNullOrEmpty(this.DeploymentId))
this.Config.Globals.ClusterId = this.DeploymentId;
if (string.IsNullOrWhiteSpace(this.Name))
throw new ArgumentException("SiloName not defined - cannot initialize config");
this.NodeConfig = this.Config.GetOrCreateNodeConfigurationForSilo(this.Name);
this.Type = this.NodeConfig.IsPrimaryNode ? Silo.SiloType.Primary : Silo.SiloType.Secondary;
this.ConfigLoaded = true;
}
/// <summary>
/// Helper to wait for this silo to shutdown or to be stopped via a cancellation token.
/// </summary>
/// <param name="cancellationToken">Optional cancellation token.</param>
/// <remarks>
/// Note: This method call will block execution of current thread,
/// and will not return control back to the caller until the silo is shutdown or
/// an external request for cancellation has been issued.
/// </remarks>
private void WaitForOrleansSiloShutdownImpl(CancellationToken? cancellationToken = null)
{
if (!this.IsStarted)
throw new InvalidOperationException("Cannot wait for silo " + this.Name + " since it was not started successfully previously.");
if (this.startupEvent != null)
this.startupEvent.Reset();
if (this.orleans != null)
{
// Intercept cancellation to initiate silo stop
if (cancellationToken.HasValue)
cancellationToken.Value.Register(this.HandleExternalCancellation);
this.orleans.SiloTerminatedEvent.WaitOne();
}
else
throw new InvalidOperationException("Cannot wait for silo " + this.Name + " due to prior initialization error");
}
/// <summary>
/// Handle the silo stop request coming from an external cancellation token.
/// </summary>
private void HandleExternalCancellation()
{
// Try to perform gracefull shutdown of Silo when we a cancellation request has been made
this.logger.Info(ErrorCode.SiloStopping, "External cancellation triggered, starting to shutdown silo.");
ShutdownOrleansSilo();
}
/// <summary>
/// Called when this silo is being Disposed by .NET runtime.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary> Perform the Dispose / cleanup operation. </summary>
/// <param name="disposing"></param>
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
this.loggerProvider?.Dispose();
this.loggerProvider = null;
if (this.startupEvent != null)
{
this.startupEvent.Dispose();
this.startupEvent = null;
}
this.IsStarted = false;
}
}
this.disposed = true;
}
}
}
| |
// Copyright (C) 2005-2013, Andriy Kozachuk
// Copyright (C) 2014 Extesla, LLC.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using OpenGamingLibrary.Numerics.Multipliers;
using OpenGamingLibrary.Numerics.OpHelpers;
using OpenGamingLibrary.Numerics.Utils;
namespace OpenGamingLibrary.Numerics.Parsers
{
/// <summary>
/// Fast parsing algorithm using divide-by-two (O[n*{log n}^2]).
/// </summary>
sealed internal class FastParser : ParserBase
{
#region Private fields
IParser _classicParser; // classic parser
#endregion Private fields
#region Constructor
/// <summary>
/// Creates new <see cref="FastParser" /> instance.
/// </summary>
/// <param name="pow2Parser">Parser for pow2 case.</param>
/// <param name="classicParser">Classic parser.</param>
public FastParser(IParser pow2Parser, IParser classicParser) : base(pow2Parser)
{
_classicParser = classicParser;
}
#endregion Constructor
/// <summary>
/// Parses provided string representation of <see cref="BigInteger" /> object.
/// </summary>
/// <param name="value">Number as string.</param>
/// <param name="startIndex">Index inside string from which to start.</param>
/// <param name="endIndex">Index inside string on which to end.</param>
/// <param name="numberBase">Number base.</param>
/// <param name="charToDigits">Char->digit dictionary.</param>
/// <param name="digitsRes">Resulting digits.</param>
/// <returns>Parsed integer length.</returns>
override unsafe public uint Parse(string value, int startIndex, int endIndex, uint numberBase, IDictionary<char, uint> charToDigits, uint[] digitsRes)
{
uint newLength = base.Parse(value, startIndex, endIndex, numberBase, charToDigits, digitsRes);
// Maybe base method already parsed this number
if (newLength != 0) return newLength;
// Check length - maybe use classic parser instead
uint initialLength = (uint)digitsRes.LongLength;
if (initialLength < Constants.FastParseLengthLowerBound || initialLength > Constants.FastParseLengthUpperBound)
{
return _classicParser.Parse(value, startIndex, endIndex, numberBase, charToDigits, digitsRes);
}
uint valueLength = (uint)(endIndex - startIndex + 1);
uint digitsLength = 1U << Bits.CeilLog2(valueLength);
// Prepare array for digits in other base
uint[] valueDigits = ArrayPool<uint>.Instance.GetArray(digitsLength);
// This second array will store integer lengths initially
uint[] valueDigits2 = ArrayPool<uint>.Instance.GetArray(digitsLength);
fixed (uint* valueDigitsStartPtr = valueDigits, valueDigitsStartPtr2 = valueDigits2)
{
// In the string first digit means last in digits array
uint* valueDigitsPtr = valueDigitsStartPtr + valueLength - 1;
uint* valueDigitsPtr2 = valueDigitsStartPtr2 + valueLength - 1;
// Reverse copy characters into digits
fixed (char* valueStartPtr = value)
{
char* valuePtr = valueStartPtr + startIndex;
char* valueEndPtr = valuePtr + valueLength;
for (; valuePtr < valueEndPtr; ++valuePtr, --valueDigitsPtr, --valueDigitsPtr2)
{
// Get digit itself - this call will throw an exception if char is invalid
*valueDigitsPtr = StrRepHelper.GetDigit(charToDigits, *valuePtr, numberBase);
// Set length of this digit (zero for zero)
*valueDigitsPtr2 = *valueDigitsPtr == 0U ? 0U : 1U;
}
}
// We have retrieved lengths array from pool - it needs to be cleared before using
DigitHelper.SetBlockDigits(valueDigitsStartPtr2 + valueLength, digitsLength - valueLength, 0);
// Now start from the digit arrays beginning
valueDigitsPtr = valueDigitsStartPtr;
valueDigitsPtr2 = valueDigitsStartPtr2;
// Current multiplier (classic or fast) will be used
IMultiplier multiplier = MultiplyManager.GetCurrentMultiplier();
// Here base in needed power will be stored
BigInteger baseInt = null;
// Temporary variables used on swapping
uint[] tempDigits;
uint* tempPtr;
// Variables used in cycle
uint* ptr1, ptr2, valueDigitsPtrEnd;
uint loLength, hiLength;
// Outer cycle instead of recursion
for (uint innerStep = 1, outerStep = 2; innerStep < digitsLength; innerStep <<= 1, outerStep <<= 1)
{
// Maybe baseInt must be multiplied by itself
baseInt = baseInt == null ? numberBase : baseInt * baseInt;
// Using unsafe here
fixed (uint* baseDigitsPtr = baseInt._digits)
{
// Start from arrays beginning
ptr1 = valueDigitsPtr;
ptr2 = valueDigitsPtr2;
// vauleDigits array end
valueDigitsPtrEnd = valueDigitsPtr + digitsLength;
// Cycle thru all digits and their lengths
for (; ptr1 < valueDigitsPtrEnd; ptr1 += outerStep, ptr2 += outerStep)
{
// Get lengths of "lower" and "higher" value parts
loLength = *ptr2;
hiLength = *(ptr2 + innerStep);
if (hiLength != 0)
{
// We always must clear an array before multiply
DigitHelper.SetBlockDigits(ptr2, outerStep, 0U);
// Multiply per baseInt
hiLength = multiplier.Multiply(
baseDigitsPtr,
baseInt._length,
ptr1 + innerStep,
hiLength,
ptr2);
}
// Sum results
if (hiLength != 0 || loLength != 0)
{
*ptr1 = DigitOpHelper.Add(
ptr2,
hiLength,
ptr1,
loLength,
ptr2);
}
else
{
*ptr1 = 0U;
}
}
}
// After inner cycle valueDigits will contain lengths and valueDigits2 will contain actual values
// so we need to swap them here
tempDigits = valueDigits;
valueDigits = valueDigits2;
valueDigits2 = tempDigits;
tempPtr = valueDigitsPtr;
valueDigitsPtr = valueDigitsPtr2;
valueDigitsPtr2 = tempPtr;
}
}
// Determine real length of converted number
uint realLength = valueDigits2[0];
// Copy to result
Array.Copy(valueDigits, digitsRes, realLength);
// Return arrays to pool
ArrayPool<uint>.Instance.AddArray(valueDigits);
ArrayPool<uint>.Instance.AddArray(valueDigits2);
return realLength;
}
}
}
| |
using Microsoft.Azure.Commands.Compute.Common;
using Microsoft.Azure.Common.Authentication.Models;
using Microsoft.WindowsAzure.Commands.Common.Extensions.DSC;
using Microsoft.WindowsAzure.Commands.Common.Extensions.DSC.Publish;
using Microsoft.WindowsAzure.Storage.Auth;
using System;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Compute.Extension.DSC
{
/// <summary>
/// Uploads a Desired State Configuration script to Azure blob storage, which
/// later can be applied to Azure Virtual Machines using the
/// Set-AzureRMVMDscExtension cmdlet.
/// </summary>
[Cmdlet(
VerbsData.Publish,
ProfileNouns.VirtualMachineDscConfiguration,
SupportsShouldProcess = true,
DefaultParameterSetName = UploadArchiveParameterSetName),
OutputType(
typeof(String))]
public class PublishAzureVMDscConfigurationCommand : DscExtensionPublishCmdletCommonBase
{
private const string CreateArchiveParameterSetName = "CreateArchive";
private const string UploadArchiveParameterSetName = "UploadArchive";
[Parameter(
Mandatory = true,
Position = 2,
ParameterSetName = UploadArchiveParameterSetName,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The name of the resource group that contains the storage account.")]
[ValidateNotNullOrEmpty]
public string ResourceGroupName { get; set; }
/// <summary>
/// Path to a file containing one or more configurations; the file can be a
/// PowerShell script (*.ps1) or MOF interface (*.mof).
/// </summary>
[Parameter(
Mandatory = true,
Position = 1,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
HelpMessage = "Path to a file containing one or more configurations")]
[ValidateNotNullOrEmpty]
public string ConfigurationPath { get; set; }
/// <summary>
/// Name of the Azure Storage Container the configuration is uploaded to.
/// </summary>
[Parameter(
ValueFromPipelineByPropertyName = true,
Position = 4,
ParameterSetName = UploadArchiveParameterSetName,
HelpMessage = "Name of the Azure Storage Container the configuration is uploaded to")]
[ValidateNotNullOrEmpty]
public string ContainerName { get; set; }
/// <summary>
/// The Azure Storage Account name used to upload the configuration script to the container specified by ContainerName.
/// </summary>
[Parameter(
Mandatory = true,
Position = 3,
ValueFromPipelineByPropertyName = true,
ParameterSetName = UploadArchiveParameterSetName,
HelpMessage = "The Azure Storage Account name used to upload the configuration script to the container " +
"specified by ContainerName ")]
[ValidateNotNullOrEmpty]
public String StorageAccountName { get; set; }
/// <summary>
/// Path to a local ZIP file to write the configuration archive to.
/// When using this parameter, Publish-AzureRMVMDscConfiguration creates a
/// local ZIP archive instead of uploading it to blob storage..
/// </summary>
[Alias("ConfigurationArchivePath")]
[Parameter(
Position = 2,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CreateArchiveParameterSetName,
HelpMessage = "Path to a local ZIP file to write the configuration archive to.")]
[ValidateNotNullOrEmpty]
public string OutputArchivePath { get; set; }
/// <summary>
/// Suffix for the storage end point, e.g. core.windows.net
/// </summary>
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = UploadArchiveParameterSetName,
HelpMessage = "Suffix for the storage end point, e.g. core.windows.net")]
[ValidateNotNullOrEmpty]
public string StorageEndpointSuffix { get; set; }
/// <summary>
/// By default Publish-AzureRMVMDscConfiguration will not overwrite any existing blobs.
/// Use -Force to overwrite them.
/// </summary>
[Parameter(HelpMessage = "By default Publish-AzureRMVMDscConfiguration will not overwrite any existing blobs")]
public SwitchParameter Force { get; set; }
/// <summary>
/// Excludes DSC resource dependencies from the configuration archive
/// </summary>
[Parameter(HelpMessage = "Excludes DSC resource dependencies from the configuration archive")]
public SwitchParameter SkipDependencyDetection { get; set; }
/// <summary>
///Path to a .psd1 file that specifies the data for the Configuration. This
/// file must contain a hashtable with the items described in
/// http://technet.microsoft.com/en-us/library/dn249925.aspx.
/// </summary>
[Parameter(
ValueFromPipelineByPropertyName = true,
HelpMessage = "Path to a .psd1 file that specifies the data for the Configuration. This is added to the configuration " +
"archive and then passed to the configuration function. It gets overwritten by the configuration data path " +
"provided through the Set-AzureRMVMDscExtension cmdlet")]
[ValidateNotNullOrEmpty]
public string ConfigurationDataPath { get; set; }
/// <summary>
/// Path to a file or a directory to include in the configuration archive
/// </summary>
[Parameter(
ValueFromPipelineByPropertyName = true,
HelpMessage = "Path to a file or a directory to include in the configuration archive. It gets downloaded to the " +
"VM along with the configuration")]
[ValidateNotNullOrEmpty]
public String[] AdditionalPath { get; set; }
//Private Variables
/// <summary>
/// Credentials used to access Azure Storage
/// </summary>
private StorageCredentials _storageCredentials;
protected override void ProcessRecord()
{
base.ProcessRecord();
try
{
ValidatePsVersion();
//validate cmdlet params
ConfigurationPath = GetUnresolvedProviderPathFromPSPath(ConfigurationPath);
ValidateConfigurationPath(ConfigurationPath, ParameterSetName);
if (ConfigurationDataPath != null)
{
ConfigurationDataPath = GetUnresolvedProviderPathFromPSPath(ConfigurationDataPath);
ValidateConfigurationDataPath(ConfigurationDataPath);
}
if (AdditionalPath != null && AdditionalPath.Length > 0)
{
for (var count = 0; count < AdditionalPath.Length; count++)
{
AdditionalPath[count] = GetUnresolvedProviderPathFromPSPath(AdditionalPath[count]);
}
}
switch (ParameterSetName)
{
case CreateArchiveParameterSetName:
OutputArchivePath = GetUnresolvedProviderPathFromPSPath(OutputArchivePath);
break;
case UploadArchiveParameterSetName:
_storageCredentials = this.GetStorageCredentials(ResourceGroupName,StorageAccountName);
if (ContainerName == null)
{
ContainerName = DscExtensionCmdletConstants.DefaultContainerName;
}
if (StorageEndpointSuffix == null)
{
StorageEndpointSuffix =
DefaultProfile.Context.Environment.GetEndpoint(AzureEnvironment.Endpoint.StorageEndpointSuffix);
}
break;
}
PublishConfiguration(
ConfigurationPath,
ConfigurationDataPath,
AdditionalPath,
OutputArchivePath,
StorageEndpointSuffix,
ContainerName,
ParameterSetName,
Force.IsPresent,
SkipDependencyDetection.IsPresent,
_storageCredentials);
}
finally
{
DeleteTemporaryFiles();
}
}
}
}
| |
using UnityEngine;
using UnityEngine.UI; //add unity engine UI to make text work
using System.Collections;
public class TextController : MonoBehaviour {
// make new variable available to all methods
public Text text;
// enumerate stes#
private enum States {bedroom_0, table_0, bathroom_0, living_0, wardrove_0, street_0, airport_0, police_0, acme_0, living_1, bedroom_1, street_1, sign_0, sign_1, guard_0, car_0, house_0, end, badend};
private States myState;
// Use this for initialization
void Start () {
myState = States.bedroom_0;
}
// Update is called once per frame
void Update () {
print (myState);
if (myState == States.bedroom_0) {bedroom_0();}
else if (myState == States.table_0) {table_0();}
else if (myState == States.bathroom_0) {bathroom_0();}
else if (myState == States.living_0) {living_0();}
else if (myState == States.wardrove_0) {wardrove_0();}
else if (myState == States.street_0) {street_0();}
else if (myState == States.airport_0) {airport_0();}
else if (myState == States.police_0) {police_0();}
else if (myState == States.acme_0) {acme_0();}
else if (myState == States.living_1) {living_1();}
else if (myState == States.bedroom_1) {bedroom_1();}
else if (myState == States.sign_0) {sign_0();}
else if (myState == States.sign_1) {sign_1();}
else if (myState == States.guard_0) {guard_0();}
else if (myState == States.car_0) {car_0();}
else if (myState == States.house_0) {house_0();}
else if (myState == States.badend) {badend();}
else if (myState == States.end) {end();}
}
// START: BEDROOM
void bedroom_0 () {
text.text = "You wake up to find your life-long partner Carmen gone. She was there when " +
"you both went to sleep, but now her side of the bed is undone and the house is silent. " +
"You call for her twice, but there's no response. Not again, you almost say out loud. \n\n" +
"Press T to inspect her bedside table, W to open her wardrove, B to check the bathroom " +
"or L to leave the bedroom and go into the living-room.";
if (Input.GetKeyDown(KeyCode.T)) {myState = States.table_0;}
else if (Input.GetKeyDown(KeyCode.B)) {myState = States.bathroom_0;}
else if (Input.GetKeyDown(KeyCode.W)) {myState = States.wardrove_0;}
else if (Input.GetKeyDown(KeyCode.L)) {myState = States.living_0;}
}
// BEDSIDE TABLE
void table_0 () {
text.text = "You open the top drawer of the bedside table. Inside, there's only a bundle of " +
"old postcards tied with a string. Budapest, Moscow, Paris, Reykjavik... " +
"places you had both seen, Carmen on the run, you chasing her. \n\n" +
"Press R to Return to inspecting the bedroom";
if (Input.GetKeyDown(KeyCode.R)) {myState = States.bedroom_0;}
}
// WARDROVE
void wardrove_0 () {
text.text = "You walks towards the wardrove but need not touching it. " +
"Through the ajar door, you see Carmen's red dresses hanging perfectly aligned. " +
"Her hat is obviously gone. \n\n" +
"Press R to Return to inspecting the bedroom.";
if (Input.GetKeyDown(KeyCode.R)) {myState = States.bedroom_0;}
}
// BATHROOM
void bathroom_0 () {
text.text = "The bathroom looks undisturbed, yet something feels out of place. " +
"You try to push your thoughts away, Carmen wouldn't leave again. " +
"You open the bathroom cabinet and, as expected, your herat sinks. Her brown gloves are gone. \n\n" +
"Press R to Return to the bedroom";
if (Input.GetKeyDown(KeyCode.R)) {myState = States.bedroom_0;}
}
// LIVING 0
void living_0 () {
text.text = "The photos on the walls are a heavy reminder of Carmen's proclivity for adventure. " +
"You had long suspected a new one in the making, but failed to anticipate its timing. \n\n" +
"Press R to Return to the bedroom, or L to leave the house.";
if (Input.GetKeyDown(KeyCode.R)) {myState = States.bedroom_0;}
else if (Input.GetKeyDown(KeyCode.L)) {myState = States.street_0;}
}
// STREET
void street_0 () {
text.text = "You step out of the house and into your awfully quiet suburban street. " +
"At least she didn't take the car, you think to yourself. " +
"You can think of three places to start searching for your beloved spy. \n\n" +
"Press A to travel to the airport, P to go to the police, A to visit the ACME Detective Agency " +
"or R to Return inside the house.";
if (Input.GetKeyDown(KeyCode.A)) {myState = States.airport_0;}
else if (Input.GetKeyDown(KeyCode.P)) {myState = States.police_0;}
else if (Input.GetKeyDown(KeyCode.D)) {myState = States.acme_0;}
else if (Input.GetKeyDown(KeyCode.R)) {myState = States.living_1;}
}
// LIVING 1 (returning)
void living_1 () {
text.text = "Nothing has changed inside the house, Carmen is still gone and " +
"you have no clue where or why she's run off. \n\n" +
"Press R to Return to the bedroom, or C to get inside your car again.";
if (Input.GetKeyDown(KeyCode.R)) {myState = States.bedroom_1;}
else if (Input.GetKeyDown(KeyCode.C)) {myState = States.car_0;}
}
// BEDROOM 1 (returning)
void bedroom_1 () {
text.text = "You are back in the bedroom. \n\n" +
"Press T to inspect Carmen's bedside table, W to open her wardrove, B to check the bathroom " +
"or L to leave the bedroom and go into the living-room.";
if (Input.GetKeyDown(KeyCode.T)) {myState = States.table_0;}
else if (Input.GetKeyDown(KeyCode.B)) {myState = States.bathroom_0;}
else if (Input.GetKeyDown(KeyCode.W)) {myState = States.wardrove_0;}
else if (Input.GetKeyDown(KeyCode.L)) {myState = States.living_0;}
}
// STREET 1 (returning)
void street_1 () {
text.text = "Where shall we head first? You ask yourself and this time cannot hold a tiny smile. \n\n" +
"Press A to travel to the Airport, P to go to the police, D to visit the ACME Detective Agency " +
"or R to Return to the house, again.";
if (Input.GetKeyDown(KeyCode.A)) {myState = States.airport_0;}
else if (Input.GetKeyDown(KeyCode.P)) {myState = States.police_0;}
else if (Input.GetKeyDown(KeyCode.D)) {myState = States.acme_0;}
else if (Input.GetKeyDown(KeyCode.R)) {myState = States.living_1;}
}
// ACME
void acme_0 () {
text.text = "The former Agency is now a laundry service. The Chief is fighting over small change. " +
"What do you want? He asks, as you reply that you are looking for Carmen." +
"His belly shakes as he laughs, walking away from you.\n\n" +
"Press R to Return to your car.";
if (Input.GetKeyDown(KeyCode.R)) {myState = States.car_0;}
}
// POLICE
void police_0 () {
text.text = "Three policemen in uniform see you approaching and stand in front of the door, arms crossed. " +
"Go away! says the talest one. You never needed us before, you don't need us now.\n\n" +
"Press R to Return to your car.";
if (Input.GetKeyDown(KeyCode.R)) {myState = States.car_0;}
}
// AIRPORT
void airport_0 () {
text.text = "Ah, the airport! How many days, months, spent looking at that departures sign " +
"and jumping into planes with strange flags attached to them. \n\n" +
"Press S to check the departures sign, G to talk to a guard of R to Return to your car.";
if (Input.GetKeyDown(KeyCode.S)) {myState = States.sign_0;}
else if (Input.GetKeyDown(KeyCode.G)) {myState = States.guard_0;}
else if (Input.GetKeyDown(KeyCode.R)) {myState = States.car_0;}
}
// SIGN
void sign_0 () {
text.text = "The destinations have changed, but the feeling remains. " +
"A deadly mixture of fear and passion, an intensity that only Carmen can cause. " +
"It would be pointless to pick a city without more clues, but not impossible. \n\n" +
"Press P for Paris, M for Mexico City, R for Reykjavic, S for San Francisco, " +
"B for Bangkok, K for Kigali or H to return to your house for once and all.";
if (Input.GetKeyDown(KeyCode.R)) {myState = States.end;}
else if (Input.GetKeyDown(KeyCode.H)) {myState = States.house_0;}
else if (Input.GetKeyDown(KeyCode.P)) {myState = States.badend;}
else if (Input.GetKeyDown(KeyCode.M)) {myState = States.badend;}
else if (Input.GetKeyDown(KeyCode.S)) {myState = States.badend;}
else if (Input.GetKeyDown(KeyCode.B)) {myState = States.badend;}
else if (Input.GetKeyDown(KeyCode.K)) {myState = States.badend;}
}
// GUARD
void guard_0 () {
text.text = "You show the guard Carmen's photo. He stares at you for a bit, laughs and then says: " +
"I saw the person you're looking for and she left in a plane with a " +
"blue, white and red flag. Then, he turns aroudn and leaves, shaking his head. \n\n" +
"Press S to check the departures sign again, or R to Return to your car.";
if (Input.GetKeyDown(KeyCode.S)) {myState = States.sign_1;}
else if (Input.GetKeyDown(KeyCode.R)) {myState = States.car_0;}
}
// CAR_0
void car_0 () {
text.text = "You are back in the car. Where to next? \n\n" +
"Press P to go to the police, A to go back into the airport, " +
"S to visit the ACME Detective Agency or R to Return to your house.";
if (Input.GetKeyDown(KeyCode.P)) {myState = States.police_0;}
else if (Input.GetKeyDown(KeyCode.S)) {myState = States.acme_0;}
else if (Input.GetKeyDown(KeyCode.A)) {myState = States.airport_0;}
else if (Input.GetKeyDown(KeyCode.R)) {myState = States.living_1;}
}
// SIGN 1 (return - pre final!)
void sign_1 () {
text.text = "And here we are again. The guard mentioned a red, blue and white flag. " +
"This is it. Make your pick, you tell yourself. Pick Carmen, or not. \n\n" +
"Press P for Paris, M for Mexico City, R for Reykjavic, S for San Francisco, " +
"B for Bangkok, K for Kigali or H to return to your house for once and all.";
if (Input.GetKeyDown(KeyCode.R)) {myState = States.end;}
else if (Input.GetKeyDown(KeyCode.H)) {myState = States.house_0;}
else if (Input.GetKeyDown(KeyCode.P)) {myState = States.badend;}
else if (Input.GetKeyDown(KeyCode.M)) {myState = States.badend;}
else if (Input.GetKeyDown(KeyCode.S)) {myState = States.badend;}
else if (Input.GetKeyDown(KeyCode.B)) {myState = States.badend;}
else if (Input.GetKeyDown(KeyCode.K)) {myState = States.badend;}
}
// REYKJAVIK (ending)
void end () {
text.text = "You got it, it gotta be Reykjavik, of course. You buy a ticket and are soon on your way " +
"to adventure. You know that by the time you land Carmen will be long gone again, but " +
"isn't that exactly what you wanted? The pursue, the chase, the certainty that " +
"no matter how old you are, or how old Carmen is, there will always be a puzzle " +
"you don't really EVER want to solve. THE END! \n\n" +
"Press R to Restart";
if (Input.GetKeyDown(KeyCode.R)) {myState = States.bedroom_0;}
}
// ALL OTHER ENDINGS (ending)
void badend () {
text.text = "After flying for hours, you spend most of the evening asking around " +
"but it seems like you have picked the wrong departure. Don't worry! " +
"It's not too late! \n\n" +
"Press A to fly back to the airport.";
if (Input.GetKeyDown(KeyCode.A)) {myState = States.sign_1;}
}
// HOUSE (alternative ending)
void house_0 () {
text.text = "You return to your house. Carmen has chosen to go, and you to let her. " +
"You have finally grown out of your late eighties obsession. " +
"About time! You tell yourself. You lie on the queen size bed like a starfish. " +
"What's that noise now, coming from the kitchen? Is she... is it... " +
"Yes. The existential angst is now here to stay. \n\n" +
"Enjoy growing up.";
}
}
| |
#region Disclaimer/Info
///////////////////////////////////////////////////////////////////////////////////////////////////
// Subtext WebLog
//
// Subtext is an open source weblog system that is a fork of the .TEXT
// weblog system.
//
// For updated news and information please visit http://subtextproject.com/
// Subtext is hosted at Google Code at http://code.google.com/p/subtext/
// The development mailing list is at subtext@googlegroups.com
//
// This project is licensed under the BSD license. See the License.txt file for more information.
///////////////////////////////////////////////////////////////////////////////////////////////////
#endregion
using System;
using System.Data;
using System.Data.SqlClient;
namespace Subtext.Framework.Data
{
public partial class StoredProcedures
{
public IDataReader GetRecentImages(string host, int? groupId, int rowCount)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@Host", host),
DataHelper.MakeInParam("@GroupID", groupId),
DataHelper.MakeInParam("@rowCount", rowCount),
};
return GetReader("DNW_GetRecentImages", p);
}
public IDataReader GetRecentPosts(string host, int? groupId, DateTime currentDateTime, int? rowCount)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@Host", host),
DataHelper.MakeInParam("@GroupID", groupId),
DataHelper.MakeInParam("@CurrentDateTime", currentDateTime),
DataHelper.MakeInParam("@RowCount", rowCount),
};
return GetReader("DNW_GetRecentPosts", p);
}
public IDataReader Stats(string host, int? groupId)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@Host", host),
DataHelper.MakeInParam("@GroupID", groupId),
};
return GetReader("DNW_Stats", p);
}
public IDataReader TotalStats(string host, int? groupId)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@Host", host),
DataHelper.MakeInParam("@GroupID", groupId),
};
return GetReader("DNW_Total_Stats", p);
}
public bool AddLogEntry(DateTime date, int? blogId, string thread, string context, string level, string logger,
string message, string exception, string url)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@Date", date),
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@Thread", thread),
DataHelper.MakeInParam("@Context", context),
DataHelper.MakeInParam("@Level", level),
DataHelper.MakeInParam("@Logger", logger),
DataHelper.MakeInParam("@Message", message),
DataHelper.MakeInParam("@Exception", exception),
DataHelper.MakeInParam("@Url", url),
};
return NonQueryBool("subtext_AddLogEntry", p);
}
public bool ClearBlogContent(int blogId)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@BlogId", blogId),
};
return NonQueryBool("subtext_ClearBlogContent", p);
}
public int CreateDomainAlias(int blogId, string host, string application, bool? active)
{
SqlParameter outParam0 = DataHelper.MakeOutParam("@Id", SqlDbType.Int, 4);
SqlParameter[] p = {
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@Host", host),
DataHelper.MakeInParam("@Application", application),
DataHelper.MakeInParam("@Active", active),
outParam0,
};
NonQueryInt("subtext_CreateDomainAlias", p);
return (int)outParam0.Value;
}
public bool DeleteBlogGroup(int id)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@Id", id),
};
return NonQueryBool("subtext_DeleteBlogGroup", p);
}
public bool DeleteCategory(int categoryId, int blogId)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@CategoryId", categoryId),
DataHelper.MakeInParam("@BlogId", blogId),
};
return NonQueryBool("subtext_DeleteCategory", p);
}
public bool DeleteDomainAlias(int id)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@Id", id),
};
return NonQueryBool("subtext_DeleteDomainAlias", p);
}
public bool DeleteEnclosure(int id)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@Id", id),
};
return NonQueryBool("subtext_DeleteEnclosure", p);
}
public bool DeleteFeedback(int id, DateTime currentDateTime)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@Id", id),
DataHelper.MakeInParam("@CurrentDateTime", currentDateTime),
};
return NonQueryBool("subtext_DeleteFeedback", p);
}
public bool DeleteFeedbackByStatus(int blogId, int statusFlag)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@StatusFlag", statusFlag),
};
return NonQueryBool("subtext_DeleteFeedbackByStatus", p);
}
public bool DeleteImage(int blogId, int imageId)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@ImageId", imageId),
};
return NonQueryBool("subtext_DeleteImage", p);
}
public bool DeleteImageCategory(int categoryId, int blogId)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@CategoryId", categoryId),
DataHelper.MakeInParam("@BlogId", blogId),
};
return NonQueryBool("subtext_DeleteImageCategory", p);
}
public bool DeleteKeyWord(int keyWordId, int blogId)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@KeyWordID", keyWordId),
DataHelper.MakeInParam("@BlogId", blogId),
};
return NonQueryBool("subtext_DeleteKeyWord", p);
}
public bool DeleteLink(int linkId, int blogId)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@LinkID", linkId),
DataHelper.MakeInParam("@BlogId", blogId),
};
return NonQueryBool("subtext_DeleteLink", p);
}
public bool DeleteLinksByPostID(int postId, int blogId)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@PostId", postId),
DataHelper.MakeInParam("@BlogId", blogId),
};
return NonQueryBool("subtext_DeleteLinksByPostID", p);
}
public bool DeleteMetaTag(int id)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@Id", id),
};
return NonQueryBool("subtext_DeleteMetaTag", p);
}
public bool DeletePost(int id, DateTime currentDateTime)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@ID", id),
DataHelper.MakeInParam("@CurrentDateTime", currentDateTime),
};
return NonQueryBool("subtext_DeletePost", p);
}
public IDataReader GetActiveCategoriesWithLinkCollection(int? blogId)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@BlogId", blogId),
};
return GetReader("subtext_GetActiveCategoriesWithLinkCollection", p);
}
public IDataReader GetBlogByDomainAlias(string host, string application, bool? strict)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@Host", host),
DataHelper.MakeInParam("@Application", application),
DataHelper.MakeInParam("@Strict", strict),
};
return GetReader("subtext_GetBlogByDomainAlias", p);
}
public IDataReader GetBlogById(int blogId)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@BlogId", blogId),
};
return GetReader("subtext_GetBlogById", p);
}
public IDataReader GetBlogGroup(int id, bool active)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@Id", id),
DataHelper.MakeInParam("@Active", active),
};
return GetReader("subtext_GetBlogGroup", p);
}
public IDataReader GetBlogKeyWords(int blogId)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@BlogId", blogId),
};
return GetReader("subtext_GetBlogKeyWords", p);
}
public IDataReader GetBlogStats(int blogId)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@BlogId", blogId),
};
return GetReader("subtext_GetBlogStats", p);
}
public IDataReader GetCategory(string categoryName, int? categoryId, bool isActive, int? blogId,
int? categoryType)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@CategoryName", categoryName),
DataHelper.MakeInParam("@CategoryId", categoryId),
DataHelper.MakeInParam("@IsActive", isActive),
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@CategoryType", categoryType),
};
return GetReader("subtext_GetCategory", p);
}
public IDataReader GetCommentByChecksumHash(string feedbackChecksumHash, int blogId)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@FeedbackChecksumHash", feedbackChecksumHash),
DataHelper.MakeInParam("@BlogId", blogId),
};
return GetReader("subtext_GetCommentByChecksumHash", p);
}
public IDataReader GetConditionalEntries(int itemCount, int postType, int postConfig, int? blogId,
bool includeCategories, DateTime currentDateTime)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@ItemCount", itemCount),
DataHelper.MakeInParam("@PostType", postType),
DataHelper.MakeInParam("@PostConfig", postConfig),
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@IncludeCategories", includeCategories),
DataHelper.MakeInParam("@CurrentDateTime", currentDateTime),
};
return GetReader("subtext_GetConditionalEntries", p);
}
public IDataReader GetConfig(string host, string application)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@Host", host),
DataHelper.MakeInParam("@Application", application),
};
return GetReader("subtext_GetConfig", p);
}
public IDataReader GetDomainAliasById(int id)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@Id", id),
};
return GetReader("subtext_GetDomainAliasById", p);
}
public IDataReader GetEntriesByDayRange(DateTime startDate, DateTime stopDate, int postType, bool isActive,
int blogId, DateTime currentDateTime)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@StartDate", startDate),
DataHelper.MakeInParam("@StopDate", stopDate),
DataHelper.MakeInParam("@PostType", postType),
DataHelper.MakeInParam("@IsActive", isActive),
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@CurrentDateTime", currentDateTime),
};
return GetReader("subtext_GetEntriesByDayRange", p);
}
public IDataReader GetEntriesForExport(int blogId, int pageIndex, int pageSize)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@PageIndex", pageIndex),
DataHelper.MakeInParam("@PageSize", pageSize),
};
return GetReader("subtext_GetEntriesForExport", p);
}
public IDataReader GetEntryPreviousNext(int id, int postType, int blogId, DateTime currentDateTime)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@ID", id),
DataHelper.MakeInParam("@PostType", postType),
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@CurrentDateTime", currentDateTime),
};
return GetReader("subtext_GetEntry_PreviousNext", p);
}
public IDataReader GetFeedback(int id)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@Id", id),
};
return GetReader("subtext_GetFeedback", p);
}
public IDataReader GetFeedbackCollection(int entryId)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@EntryId", entryId),
};
return GetReader("subtext_GetFeedbackCollection", p);
}
public void GetFeedbackCountsByStatus(int blogId, out int approvedCount, out int needsModerationCount,
out int flaggedSpam, out int deleted)
{
SqlParameter outParam0 = DataHelper.MakeOutParam("@ApprovedCount", SqlDbType.Int, 4);
SqlParameter outParam1 = DataHelper.MakeOutParam("@NeedsModerationCount", SqlDbType.Int, 4);
SqlParameter outParam2 = DataHelper.MakeOutParam("@FlaggedSpam", SqlDbType.Int, 4);
SqlParameter outParam3 = DataHelper.MakeOutParam("@Deleted", SqlDbType.Int, 4);
SqlParameter[] p = {
DataHelper.MakeInParam("@BlogId", blogId),
outParam0,
outParam1,
outParam2,
outParam3,
};
NonQueryBool("subtext_GetFeedbackCountsByStatus", p);
approvedCount = (int)outParam0.Value;
needsModerationCount = (int)outParam1.Value;
flaggedSpam = (int)outParam2.Value;
deleted = (int)outParam3.Value;
}
public IDataReader GetHost()
{
return GetReader("subtext_GetHost");
}
public IDataReader GetImageCategory(int categoryId, bool isActive, int blogId)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@CategoryId", categoryId),
DataHelper.MakeInParam("@IsActive", isActive),
DataHelper.MakeInParam("@BlogId", blogId),
};
return GetReader("subtext_GetImageCategory", p);
}
public IDataReader GetKeyWord(int keyWordId, int blogId)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@KeyWordID", keyWordId),
DataHelper.MakeInParam("@BlogId", blogId),
};
return GetReader("subtext_GetKeyWord", p);
}
public IDataReader GetLinkCollectionByPostID(int? postId, int blogId)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@PostId", postId),
DataHelper.MakeInParam("@BlogId", blogId),
};
return GetReader("subtext_GetLinkCollectionByPostID", p);
}
public IDataReader GetLinksByCategoryID(int categoryId, int blogId)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@CategoryId", categoryId),
DataHelper.MakeInParam("@BlogId", blogId),
};
return GetReader("subtext_GetLinksByCategoryID", p);
}
public IDataReader GetMetaTags(int blogId, int? entryId, int pageIndex, int pageSize)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@EntryId", entryId),
DataHelper.MakeInParam("@PageIndex", pageIndex),
DataHelper.MakeInParam("@PageSize", pageSize),
};
return GetReader("subtext_GetMetaTags", p);
}
public IDataReader GetPageableBlogs(int pageIndex, int pageSize, string host, int configurationFlags)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@PageIndex", pageIndex),
DataHelper.MakeInParam("@PageSize", pageSize),
DataHelper.MakeInParam("@Host", host),
DataHelper.MakeInParam("@ConfigurationFlags", configurationFlags),
};
return GetReader("subtext_GetPageableBlogs", p);
}
public IDataReader GetPageableDomainAliases(int pageIndex, int pageSize, int blogId)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@PageIndex", pageIndex),
DataHelper.MakeInParam("@PageSize", pageSize),
DataHelper.MakeInParam("@BlogId", blogId),
};
return GetReader("subtext_GetPageableDomainAliases", p);
}
public IDataReader GetEntries(int blogId, int? categoryId, int pageIndex, int pageSize,
int postType)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@CategoryId", categoryId),
DataHelper.MakeInParam("@PageIndex", pageIndex),
DataHelper.MakeInParam("@PageSize", pageSize),
DataHelper.MakeInParam("@PostType", postType),
};
return GetReader("subtext_GetEntries", p);
}
public IDataReader GetPageableFeedback(int blogId, int pageIndex, int pageSize, int statusFlag,
int? excludeFeedbackStatusMask, int? feedbackType)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@PageIndex", pageIndex),
DataHelper.MakeInParam("@PageSize", pageSize),
DataHelper.MakeInParam("@StatusFlag", statusFlag),
DataHelper.MakeInParam("@ExcludeFeedbackStatusMask", excludeFeedbackStatusMask),
DataHelper.MakeInParam("@FeedbackType", feedbackType),
};
return GetReader("subtext_GetPageableFeedback", p);
}
public IDataReader GetPageableKeyWords(int blogId, int pageIndex, int pageSize)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@PageIndex", pageIndex),
DataHelper.MakeInParam("@PageSize", pageSize),
};
return GetReader("subtext_GetPageableKeyWords", p);
}
public IDataReader GetPageableLinks(int blogId, int? categoryId, int pageIndex, int pageSize)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@CategoryId", categoryId),
DataHelper.MakeInParam("@PageIndex", pageIndex),
DataHelper.MakeInParam("@PageSize", pageSize),
};
return GetReader("subtext_GetPageableLinks", p);
}
public bool GetPageableLinksByCategoryID(int blogId, int? categoryId, int pageIndex, int pageSize, bool sortDesc)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@CategoryId", categoryId),
DataHelper.MakeInParam("@PageIndex", pageIndex),
DataHelper.MakeInParam("@PageSize", pageSize),
DataHelper.MakeInParam("@SortDesc", sortDesc),
};
return NonQueryBool("subtext_GetPageableLinksByCategoryID", p);
}
public IDataReader GetPageableLogEntries(int? blogId, int pageIndex, int pageSize)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@PageIndex", pageIndex),
DataHelper.MakeInParam("@PageSize", pageSize),
};
return GetReader("subtext_GetPageableLogEntries", p);
}
public IDataReader GetPageableReferrers(int blogId, int? entryId, int pageIndex, int pageSize)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@EntryId", entryId),
DataHelper.MakeInParam("@PageIndex", pageIndex),
DataHelper.MakeInParam("@PageSize", pageSize),
};
return GetReader("subtext_GetPageableReferrers", p);
}
public IDataReader GetPopularPosts(int blogId, DateTime? minDate)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@MinDate", minDate),
};
return GetReader("subtext_GetPopularPosts", p);
}
public IDataReader GetPostsByCategoriesArchive(int? blogId)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@BlogId", blogId),
};
return GetReader("subtext_GetPostsByCategoriesArchive", p);
}
public IDataReader GetPostsByCategoryID(int itemCount, int categoryId, bool isActive, int blogId,
DateTime currentDateTime)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@ItemCount", itemCount),
DataHelper.MakeInParam("@CategoryId", categoryId),
DataHelper.MakeInParam("@IsActive", isActive),
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@CurrentDateTime", currentDateTime),
};
return GetReader("subtext_GetPostsByCategoryID", p);
}
public IDataReader GetPostsByDayRange(DateTime startDate, DateTime stopDate, int blogId)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@StartDate", startDate),
DataHelper.MakeInParam("@StopDate", stopDate),
DataHelper.MakeInParam("@BlogId", blogId),
};
return GetReader("subtext_GetPostsByDayRange", p);
}
public IDataReader GetPostsByMonth(int month, int year, int? blogId, DateTime currentDateTime)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@Month", month),
DataHelper.MakeInParam("@Year", year),
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@CurrentDateTime", currentDateTime),
};
return GetReader("subtext_GetPostsByMonth", p);
}
public IDataReader GetPostsByMonthArchive(int? blogId, DateTime currentDateTime)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@CurrentDateTime", currentDateTime),
};
return GetReader("subtext_GetPostsByMonthArchive", p);
}
public IDataReader GetPostsByTag(int itemCount, string tag, int blogId, bool? isActive, DateTime currentDateTime)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@ItemCount", itemCount),
DataHelper.MakeInParam("@Tag", tag),
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@IsActive", isActive),
DataHelper.MakeInParam("@CurrentDateTime", currentDateTime),
};
return GetReader("subtext_GetPostsByTag", p);
}
public IDataReader GetPostsByYearArchive(int blogId, DateTime currentDateTime)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@CurrentDateTime", currentDateTime),
};
return GetReader("subtext_GetPostsByYearArchive", p);
}
public IDataReader GetRelatedEntries(int blogId, int entryId, int rowCount)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@EntryId", entryId),
DataHelper.MakeInParam("@RowCount", rowCount),
};
return GetReader("subtext_GetRelatedEntries", p);
}
public IDataReader GetSingleEntry(int? id, string entryName, bool isActive, int? blogId, bool includeCategories)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@ID", id),
DataHelper.MakeInParam("@EntryName", entryName),
DataHelper.MakeInParam("@IsActive", isActive),
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@IncludeCategories", includeCategories),
};
return GetReader("subtext_GetSingleEntry", p);
}
public IDataReader GetSingleImage(int imageId, bool isActive, int blogId)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@ImageId", imageId),
DataHelper.MakeInParam("@IsActive", isActive),
DataHelper.MakeInParam("@BlogId", blogId),
};
return GetReader("subtext_GetSingleImage", p);
}
public IDataReader GetSingleLink(int linkId, int blogId)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@LinkID", linkId),
DataHelper.MakeInParam("@BlogId", blogId),
};
return GetReader("subtext_GetSingleLink", p);
}
public IDataReader GetTopEntries(int blogId, int rowCount)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@RowCount", rowCount),
};
return GetReader("subtext_GetTopEntries", p);
}
public IDataReader GetTopTags(int itemCount, int blogId)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@ItemCount", itemCount),
DataHelper.MakeInParam("@BlogId", blogId),
};
return GetReader("subtext_GetTopTags", p);
}
public int GetUrlID(string url)
{
SqlParameter outParam0 = DataHelper.MakeOutParam("@UrlID", SqlDbType.Int, 4);
SqlParameter[] p = {
DataHelper.MakeInParam("@Url", url),
outParam0,
};
NonQueryInt("subtext_GetUrlID", p);
return (int)outParam0.Value;
}
public int InsertBlogGroup(string title, bool active, int? displayOrder, string description)
{
SqlParameter outParam0 = DataHelper.MakeOutParam("@Id", SqlDbType.Int, 4);
SqlParameter[] p = {
DataHelper.MakeInParam("@Title", title),
DataHelper.MakeInParam("@Active", active),
DataHelper.MakeInParam("@DisplayOrder", displayOrder),
DataHelper.MakeInParam("@Description", description),
outParam0,
};
NonQueryInt("subtext_InsertBlogGroup", p);
return (int)outParam0.Value;
}
public int InsertCategory(string title, bool active, int blogId, int categoryType, string description)
{
SqlParameter outParam0 = DataHelper.MakeOutParam("@CategoryId", SqlDbType.Int, 4);
SqlParameter[] p = {
DataHelper.MakeInParam("@Title", title),
DataHelper.MakeInParam("@Active", active),
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@CategoryType", categoryType),
DataHelper.MakeInParam("@Description", description),
outParam0,
};
NonQueryInt("subtext_InsertCategory", p);
return (int)outParam0.Value;
}
public int InsertEnclosure(string title, string url, string mimeType, long size, bool addToFeed,
bool showWithPost, int entryId)
{
SqlParameter outParam0 = DataHelper.MakeOutParam("@Id", SqlDbType.Int, 4);
SqlParameter[] p = {
DataHelper.MakeInParam("@Title", title),
DataHelper.MakeInParam("@Url", url),
DataHelper.MakeInParam("@MimeType", mimeType),
DataHelper.MakeInParam("@Size", size),
DataHelper.MakeInParam("@AddToFeed", addToFeed),
DataHelper.MakeInParam("@ShowWithPost", showWithPost),
DataHelper.MakeInParam("@EntryId", entryId),
outParam0,
};
NonQueryInt("subtext_InsertEnclosure", p);
return (int)outParam0.Value;
}
public int InsertEntry(string title, string text, int postType, string author, string email, string description,
int blogId, DateTime dateCreated, int postConfig, string entryName,
DateTime? dateSyndicated, DateTime currentDateTime)
{
SqlParameter outParam0 = DataHelper.MakeOutParam("@ID", SqlDbType.Int, 4);
SqlParameter[] p = {
DataHelper.MakeInParam("@Title", title),
DataHelper.MakeInParam("@Text", text),
DataHelper.MakeInParam("@PostType", postType),
DataHelper.MakeInParam("@Author", author),
DataHelper.MakeInParam("@Email", email),
DataHelper.MakeInParam("@Description", description),
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@DateCreated", dateCreated),
DataHelper.MakeInParam("@PostConfig", postConfig),
DataHelper.MakeInParam("@EntryName", entryName),
DataHelper.MakeInParam("@DateSyndicated", dateSyndicated),
DataHelper.MakeInParam("@CurrentDateTime", currentDateTime),
outParam0,
};
NonQueryInt("subtext_InsertEntry", p);
return (int)outParam0.Value;
}
public bool InsertEntryTagList(int entryId, int blogId, string tagList)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@EntryId", entryId),
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@TagList", tagList),
};
return NonQueryBool("subtext_InsertEntryTagList", p);
}
public int InsertFeedback(string title, string body, int blogId, int? entryId, string author, bool isBlogAuthor,
string email, string url, int feedbackType, int statusFlag, bool commentAPI,
string referrer, string ipAddress, string userAgent, string feedbackChecksumHash,
DateTime dateCreated, DateTime? dateModified, DateTime currentDateTime)
{
SqlParameter outParam0 = DataHelper.MakeOutParam("@Id", SqlDbType.Int, 4);
SqlParameter[] p = {
DataHelper.MakeInParam("@Title", title),
DataHelper.MakeInParam("@Body", body),
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@EntryId", entryId),
DataHelper.MakeInParam("@Author", author),
DataHelper.MakeInParam("@IsBlogAuthor", isBlogAuthor),
DataHelper.MakeInParam("@Email", email),
DataHelper.MakeInParam("@Url", url),
DataHelper.MakeInParam("@FeedbackType", feedbackType),
DataHelper.MakeInParam("@StatusFlag", statusFlag),
DataHelper.MakeInParam("@CommentAPI", commentAPI),
DataHelper.MakeInParam("@Referrer", referrer),
DataHelper.MakeInParam("@IpAddress", ipAddress),
DataHelper.MakeInParam("@UserAgent", userAgent),
DataHelper.MakeInParam("@FeedbackChecksumHash", feedbackChecksumHash),
DataHelper.MakeInParam("@DateCreated", dateCreated),
DataHelper.MakeInParam("@DateModified", dateModified),
DataHelper.MakeInParam("@CurrentDateTime", currentDateTime),
outParam0,
};
NonQueryInt("subtext_InsertFeedback", p);
return (int)outParam0.Value;
}
public int InsertImage(string title, int categoryId, int width, int height, string file, bool active, int blogId,
string url)
{
SqlParameter outParam0 = DataHelper.MakeOutParam("@ImageId", SqlDbType.Int, 4);
SqlParameter[] p = {
DataHelper.MakeInParam("@Title", title),
DataHelper.MakeInParam("@CategoryId", categoryId),
DataHelper.MakeInParam("@Width", width),
DataHelper.MakeInParam("@Height", height),
DataHelper.MakeInParam("@File", file),
DataHelper.MakeInParam("@Active", active),
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@Url", url),
outParam0,
};
NonQueryInt("subtext_InsertImage", p);
return (int)outParam0.Value;
}
public int InsertKeyWord(string word, string rel, string text, bool replaceFirstTimeOnly, bool openInNewWindow,
bool caseSensitive, string url, string title, int blogId)
{
SqlParameter outParam0 = DataHelper.MakeOutParam("@KeyWordID", SqlDbType.Int, 4);
SqlParameter[] p = {
DataHelper.MakeInParam("@Word", word),
DataHelper.MakeInParam("@Rel", rel),
DataHelper.MakeInParam("@Text", text),
DataHelper.MakeInParam("@ReplaceFirstTimeOnly", replaceFirstTimeOnly),
DataHelper.MakeInParam("@OpenInNewWindow", openInNewWindow),
DataHelper.MakeInParam("@CaseSensitive", caseSensitive),
DataHelper.MakeInParam("@Url", url),
DataHelper.MakeInParam("@Title", title),
DataHelper.MakeInParam("@BlogId", blogId),
outParam0,
};
NonQueryInt("subtext_InsertKeyWord", p);
return (int)outParam0.Value;
}
public int InsertLink(string title, string url, string rss, bool active, bool newWindow, int categoryId,
int? postId, int blogId, string rel)
{
SqlParameter outParam0 = DataHelper.MakeOutParam("@LinkID", SqlDbType.Int, 4);
SqlParameter[] p = {
DataHelper.MakeInParam("@Title", title),
DataHelper.MakeInParam("@Url", url),
DataHelper.MakeInParam("@Rss", rss),
DataHelper.MakeInParam("@Active", active),
DataHelper.MakeInParam("@NewWindow", newWindow),
DataHelper.MakeInParam("@CategoryId", categoryId),
DataHelper.MakeInParam("@PostId", postId),
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@Rel", rel),
outParam0,
};
NonQueryInt("subtext_InsertLink", p);
return (int)outParam0.Value;
}
public bool InsertLinkCategoryList(string categoryList, int postId, int blogId)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@CategoryList", categoryList),
DataHelper.MakeInParam("@PostId", postId),
DataHelper.MakeInParam("@BlogId", blogId),
};
return NonQueryBool("subtext_InsertLinkCategoryList", p);
}
public int InsertMetaTag(string content, string name, string httpEquiv, int blogId, int? entryId,
DateTime? dateCreated)
{
SqlParameter outParam0 = DataHelper.MakeOutParam("@Id", SqlDbType.Int, 4);
SqlParameter[] p = {
DataHelper.MakeInParam("@Content", content),
DataHelper.MakeInParam("@Name", name),
DataHelper.MakeInParam("@HttpEquiv", httpEquiv),
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@EntryId", entryId),
DataHelper.MakeInParam("@DateCreated", dateCreated),
outParam0,
};
NonQueryInt("subtext_InsertMetaTag", p);
return (int)outParam0.Value;
}
public int InsertPingTrackEntry(string title, string titleUrl, string text, string sourceUrl, int postType,
string author, string email, string sourceName, string description, int blogId,
DateTime dateAdded, int? parentId, int postConfig, string entryName,
string contentChecksumHash)
{
SqlParameter outParam0 = DataHelper.MakeOutParam("@ID", SqlDbType.Int, 4);
SqlParameter[] p = {
DataHelper.MakeInParam("@Title", title),
DataHelper.MakeInParam("@TitleUrl", titleUrl),
DataHelper.MakeInParam("@Text", text),
DataHelper.MakeInParam("@SourceUrl", sourceUrl),
DataHelper.MakeInParam("@PostType", postType),
DataHelper.MakeInParam("@Author", author),
DataHelper.MakeInParam("@Email", email),
DataHelper.MakeInParam("@SourceName", sourceName),
DataHelper.MakeInParam("@Description", description),
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@DateAdded", dateAdded),
DataHelper.MakeInParam("@ParentID", parentId),
DataHelper.MakeInParam("@PostConfig", postConfig),
DataHelper.MakeInParam("@EntryName", entryName),
DataHelper.MakeInParam("@ContentChecksumHash", contentChecksumHash),
outParam0,
};
NonQueryInt("subtext_InsertPingTrackEntry", p);
return (int)outParam0.Value;
}
public bool InsertReferral(int entryId, int blogId, string url)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@EntryId", entryId),
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@Url", url),
};
return NonQueryBool("subtext_InsertReferral", p);
}
public IDataReader InsertViewStats(int blogId, int pageType, int postId, DateTime day, string url)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@PageType", pageType),
DataHelper.MakeInParam("@PostId", postId),
DataHelper.MakeInParam("@Day", day),
DataHelper.MakeInParam("@Url", url),
};
return GetReader("subtext_InsertViewStats", p);
}
public IDataReader ListBlogGroups(bool active)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@Active", active),
};
return GetReader("subtext_ListBlogGroups", p);
}
public bool LogClear(int? blogId)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@BlogId", blogId),
};
return NonQueryBool("subtext_LogClear", p);
}
public bool Maintenance()
{
return NonQueryBool("subtext_Maintenance", null);
}
public bool RefererCleanup()
{
return NonQueryBool("subtext_RefererCleanup", null);
}
public IDataReader SearchEntries(int blogId, string searchStr, DateTime currentDateTime)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@SearchStr", searchStr),
DataHelper.MakeInParam("@CurrentDateTime", currentDateTime),
};
return GetReader("subtext_SearchEntries", p);
}
public IDataReader StatsSummary(int blogId)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@BlogId", blogId),
};
return GetReader("subtext_StatsSummary", p);
}
public bool TrackEntry(int entryId, int blogId, string url, bool isWeb)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@EntryId", entryId),
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@Url", url),
DataHelper.MakeInParam("@IsWeb", isWeb),
};
return NonQueryBool("subtext_TrackEntry", p);
}
public bool UpdateBlogGroup(int id, string title, bool active, string description, int? displayOrder)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@Id", id),
DataHelper.MakeInParam("@Title", title),
DataHelper.MakeInParam("@Active", active),
DataHelper.MakeInParam("@Description", description),
DataHelper.MakeInParam("@DisplayOrder", displayOrder),
};
return NonQueryBool("subtext_UpdateBlogGroup", p);
}
public bool UpdateBlogStats(int blogId, DateTime currentDateTime)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@CurrentDateTime", currentDateTime),
};
return NonQueryBool("subtext_UpdateBlogStats", p);
}
public bool UpdateCategory(int categoryId, string title, bool active, int categoryType, string description,
int blogId)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@CategoryId", categoryId),
DataHelper.MakeInParam("@Title", title),
DataHelper.MakeInParam("@Active", active),
DataHelper.MakeInParam("@CategoryType", categoryType),
DataHelper.MakeInParam("@Description", description),
DataHelper.MakeInParam("@BlogId", blogId),
};
return NonQueryBool("subtext_UpdateCategory", p);
}
public bool UpdateConfig(string userName, string password, string email, string title, string subTitle,
string skin, string application, string host, string author, string language,
string timeZoneId, int itemCount, int categoryListPostCount, string news,
string trackingCode, DateTime? lastUpdated, string secondaryCss, string skinCssFile,
int? flag, int blogId, string licenseUrl, int? daysTillCommentsClose,
int? commentDelayInMinutes, int? numberOfRecentComments, int? recentCommentsLength,
string akismetAPIKey, string feedBurnerName, int blogGroupId, string mobileSkin,
string mobileSkinCssFile, string openIDUrl, string cardSpaceHash, string openIDServer,
string openIDDelegate)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@UserName", userName),
DataHelper.MakeInParam("@Password", password),
DataHelper.MakeInParam("@Email", email),
DataHelper.MakeInParam("@Title", title),
DataHelper.MakeInParam("@SubTitle", subTitle),
DataHelper.MakeInParam("@Skin", skin),
DataHelper.MakeInParam("@Application", application),
DataHelper.MakeInParam("@Host", host),
DataHelper.MakeInParam("@Author", author),
DataHelper.MakeInParam("@Language", language),
DataHelper.MakeInParam("@TimeZoneId", timeZoneId),
DataHelper.MakeInParam("@ItemCount", itemCount),
DataHelper.MakeInParam("@CategoryListPostCount", categoryListPostCount),
DataHelper.MakeInParam("@News", news),
DataHelper.MakeInParam("@TrackingCode", trackingCode),
DataHelper.MakeInParam("@LastUpdated", lastUpdated),
DataHelper.MakeInParam("@SecondaryCss", secondaryCss),
DataHelper.MakeInParam("@SkinCssFile", skinCssFile),
DataHelper.MakeInParam("@Flag", flag),
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@LicenseUrl", licenseUrl),
DataHelper.MakeInParam("@DaysTillCommentsClose", daysTillCommentsClose),
DataHelper.MakeInParam("@CommentDelayInMinutes", commentDelayInMinutes),
DataHelper.MakeInParam("@NumberOfRecentComments", numberOfRecentComments),
DataHelper.MakeInParam("@RecentCommentsLength", recentCommentsLength),
DataHelper.MakeInParam("@AkismetAPIKey", akismetAPIKey),
DataHelper.MakeInParam("@FeedBurnerName", feedBurnerName),
DataHelper.MakeInParam("@BlogGroupId", blogGroupId),
DataHelper.MakeInParam("@MobileSkin", mobileSkin),
DataHelper.MakeInParam("@MobileSkinCssFile", mobileSkinCssFile),
DataHelper.MakeInParam("@OpenIdUrl", openIDUrl),
DataHelper.MakeInParam("@CardSpaceHash", cardSpaceHash),
DataHelper.MakeInParam("@OpenIdServer", openIDServer),
DataHelper.MakeInParam("@OpenIdDelegate", openIDDelegate),
};
return NonQueryBool("subtext_UpdateConfig", p);
}
public bool UpdateConfigUpdateTime(int blogId, DateTime lastUpdated)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@LastUpdated", lastUpdated),
};
return NonQueryBool("subtext_UpdateConfigUpdateTime", p);
}
public bool UpdateDomainAlias(int id, int blogId, string host, string application, bool? active)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@Id", id),
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@Host", host),
DataHelper.MakeInParam("@Application", application),
DataHelper.MakeInParam("@Active", active),
};
return NonQueryBool("subtext_UpdateDomainAlias", p);
}
public bool UpdateEnclosure(string title, string url, string mimeType, long size, bool addToFeed,
bool showWithPost, int entryId, int id)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@Title", title),
DataHelper.MakeInParam("@Url", url),
DataHelper.MakeInParam("@MimeType", mimeType),
DataHelper.MakeInParam("@Size", size),
DataHelper.MakeInParam("@AddToFeed", addToFeed),
DataHelper.MakeInParam("@ShowWithPost", showWithPost),
DataHelper.MakeInParam("@EntryId", entryId),
DataHelper.MakeInParam("@Id", id),
};
return NonQueryBool("subtext_UpdateEnclosure", p);
}
public bool UpdateEntry(int id, string title, string text, int postType, string author, string email,
string description, DateTime? dateUpdated, int postConfig, string entryName,
DateTime? dateSyndicated, int blogId, DateTime currentDateTime)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@ID", id),
DataHelper.MakeInParam("@Title", title),
DataHelper.MakeInParam("@Text", text),
DataHelper.MakeInParam("@PostType", postType),
DataHelper.MakeInParam("@Author", author),
DataHelper.MakeInParam("@Email", email),
DataHelper.MakeInParam("@Description", description),
DataHelper.MakeInParam("@DateUpdated", dateUpdated),
DataHelper.MakeInParam("@PostConfig", postConfig),
DataHelper.MakeInParam("@EntryName", entryName),
DataHelper.MakeInParam("@DateSyndicated", dateSyndicated),
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@CurrentDateTime", currentDateTime),
};
return NonQueryBool("subtext_UpdateEntry", p);
}
public bool UpdateFeedback(int id, string title, string body, string author, string email, string url,
int statusFlag, string feedbackChecksumHash, DateTime dateModified,
DateTime currentDateTime)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@ID", id),
DataHelper.MakeInParam("@Title", title),
DataHelper.MakeInParam("@Body", body),
DataHelper.MakeInParam("@Author", author),
DataHelper.MakeInParam("@Email", email),
DataHelper.MakeInParam("@Url", url),
DataHelper.MakeInParam("@StatusFlag", statusFlag),
DataHelper.MakeInParam("@FeedbackChecksumHash", feedbackChecksumHash),
DataHelper.MakeInParam("@DateModified", dateModified),
DataHelper.MakeInParam("@CurrentDateTime", currentDateTime),
};
return NonQueryBool("subtext_UpdateFeedback", p);
}
public bool UpdateFeedbackCount(int blogId, int entryId, DateTime currentDateTime)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@EntryId", entryId),
DataHelper.MakeInParam("@CurrentDateTime", currentDateTime),
};
return NonQueryBool("subtext_UpdateFeedbackCount", p);
}
public bool UpdateFeedbackStats(int blogId, DateTime currentDateTime)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@CurrentDateTime", currentDateTime),
};
return NonQueryBool("subtext_UpdateFeedbackStats", p);
}
public bool UpdateHost(string hostUserName, string password, string salt, string email)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@HostUserName", hostUserName),
DataHelper.MakeInParam("@Password", password),
DataHelper.MakeInParam("@Salt", salt),
DataHelper.MakeInParam("@Email", email),
};
return NonQueryBool("subtext_UpdateHost", p);
}
public bool UpdateImage(string title, int categoryId, int width, int height, string file, bool active,
int blogId, int imageId, string url)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@Title", title),
DataHelper.MakeInParam("@CategoryId", categoryId),
DataHelper.MakeInParam("@Width", width),
DataHelper.MakeInParam("@Height", height),
DataHelper.MakeInParam("@File", file),
DataHelper.MakeInParam("@Active", active),
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@Url", url),
DataHelper.MakeInParam("@ImageId", imageId),
};
return NonQueryBool("subtext_UpdateImage", p);
}
public bool UpdateKeyWord(int keyWordId, string word, string rel, string text, bool replaceFirstTimeOnly,
bool openInNewWindow, bool caseSensitive, string url, string title, int blogId)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@KeyWordID", keyWordId),
DataHelper.MakeInParam("@Word", word),
DataHelper.MakeInParam("@Rel", rel),
DataHelper.MakeInParam("@Text", text),
DataHelper.MakeInParam("@ReplaceFirstTimeOnly", replaceFirstTimeOnly),
DataHelper.MakeInParam("@OpenInNewWindow", openInNewWindow),
DataHelper.MakeInParam("@CaseSensitive", caseSensitive),
DataHelper.MakeInParam("@Url", url),
DataHelper.MakeInParam("@Title", title),
DataHelper.MakeInParam("@BlogId", blogId),
};
return NonQueryBool("subtext_UpdateKeyWord", p);
}
public bool UpdateLink(int linkId, string title, string url, string rss, bool active, bool newWindow,
int categoryId, string rel, int blogId)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@LinkID", linkId),
DataHelper.MakeInParam("@Title", title),
DataHelper.MakeInParam("@Url", url),
DataHelper.MakeInParam("@Rss", rss),
DataHelper.MakeInParam("@Active", active),
DataHelper.MakeInParam("@NewWindow", newWindow),
DataHelper.MakeInParam("@CategoryId", categoryId),
DataHelper.MakeInParam("@Rel", rel),
DataHelper.MakeInParam("@BlogId", blogId),
};
return NonQueryBool("subtext_UpdateLink", p);
}
public bool UpdateMetaTag(int id, string content, string name, string httpEquiv, int blogId, int? entryId)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@Id", id),
DataHelper.MakeInParam("@Content", content),
DataHelper.MakeInParam("@Name", name),
DataHelper.MakeInParam("@HttpEquiv", httpEquiv),
DataHelper.MakeInParam("@BlogId", blogId),
DataHelper.MakeInParam("@EntryId", entryId),
};
return NonQueryBool("subtext_UpdateMetaTag", p);
}
public int UTILITYAddBlog(string title, string userName, string password, string email, string host,
string application, int flag, int blogGroupId)
{
SqlParameter outParam0 = DataHelper.MakeOutParam("@Id", SqlDbType.Int, 4);
SqlParameter[] p = {
DataHelper.MakeInParam("@Title", title),
DataHelper.MakeInParam("@UserName", userName),
DataHelper.MakeInParam("@Password", password),
DataHelper.MakeInParam("@Email", email),
DataHelper.MakeInParam("@Host", host),
DataHelper.MakeInParam("@Application", application),
DataHelper.MakeInParam("@Flag", flag),
DataHelper.MakeInParam("@BlogGroupId", blogGroupId),
outParam0,
};
NonQueryInt("subtext_UTILITY_AddBlog", p);
return (int)outParam0.Value;
}
public IDataReader UtilityGetUnHashedPasswords()
{
return GetReader("subtext_Utility_GetUnHashedPasswords");
}
public bool UtilityUpdateToHashedPassword(string password, int blogId)
{
SqlParameter[] p = {
DataHelper.MakeInParam("@Password", password),
DataHelper.MakeInParam("@BlogId", blogId),
};
return NonQueryBool("subtext_Utility_UpdateToHashedPassword", p);
}
public int? VersionAdd(int major, int minor, int build, DateTime? dateCreated)
{
SqlParameter outParam0 = DataHelper.MakeOutParam("@Id", SqlDbType.Int, 4);
SqlParameter[] p = {
DataHelper.MakeInParam("@Major", major),
DataHelper.MakeInParam("@Minor", minor),
DataHelper.MakeInParam("@Build", build),
DataHelper.MakeInParam("@DateCreated", dateCreated),
outParam0,
};
NonQueryInt("subtext_VersionAdd", p);
if(outParam0.Value == null)
{
return null;
}
return (int)outParam0.Value;
}
public IDataReader VersionGetCurrent()
{
return GetReader("subtext_VersionGetCurrent");
}
}
}
| |
// 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsAzureSpecials
{
using Azure;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ApiVersionDefaultOperations operations.
/// </summary>
internal partial class ApiVersionDefaultOperations : IServiceOperations<AutoRestAzureSpecialParametersTestClient>, IApiVersionDefaultOperations
{
/// <summary>
/// Initializes a new instance of the ApiVersionDefaultOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ApiVersionDefaultOperations(AutoRestAzureSpecialParametersTestClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestAzureSpecialParametersTestClient
/// </summary>
public AutoRestAzureSpecialParametersTestClient Client { get; private set; }
/// <summary>
/// GET method with api-version modeled in global settings.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> GetMethodGlobalValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetMethodGlobalValid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/apiVersion/method/string/none/query/global/2015-07-01-preview").ToString();
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// GET method with api-version modeled in global settings.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> GetMethodGlobalNotProvidedValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetMethodGlobalNotProvidedValid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/apiVersion/method/string/none/query/globalNotProvided/2015-07-01-preview").ToString();
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// GET method with api-version modeled in global settings.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> GetPathGlobalValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetPathGlobalValid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/apiVersion/path/string/none/query/global/2015-07-01-preview").ToString();
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// GET method with api-version modeled in global settings.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> GetSwaggerGlobalValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetSwaggerGlobalValid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/apiVersion/swagger/string/none/query/global/2015-07-01-preview").ToString();
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// 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 Bridge.Test.NUnit;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace Bridge.ClientTest.IO
{
[Category(Constants.MODULE_IO)]
[TestFixture(TestNameFormat = "StreamReaderTests - {0}")]
public class StreamReaderTests
{
protected virtual Stream CreateStream()
{
return new MemoryStream();
}
protected virtual Stream GetSmallStream()
{
byte[] testData = new byte[] { 72, 69, 76, 76, 79 };
return new MemoryStream(testData);
}
protected virtual Stream GetLargeStream()
{
byte[] testData = new byte[] { 72, 69, 76, 76, 79 };
// System.Collections.Generic.
List<byte> data = new List<byte>();
for (int i = 0; i < 1000; i++)
{
data.AddRange(testData);
}
return new MemoryStream(data.ToArray());
}
protected Tuple<char[], StreamReader> GetCharArrayStream()
{
var chArr = new char[]{
char.MinValue
,char.MaxValue
,'\t'
,' '
,'$'
,'@'
,'#'
,'\0'
,'\v'
,'\''
,'\u3190'
,'\uC3A0'
,'A'
,'5'
,'\r'
,'\uFE70'
,'-'
,';'
,'\r'
,'\n'
,'T'
,'3'
,'\n'
,'K'
,'\u00E6'
};
var ms = CreateStream();
var sw = new StreamWriter(ms);
for (int i = 0; i < chArr.Length; i++)
sw.Write(chArr[i]);
sw.Flush();
ms.Position = 0;
return new Tuple<char[], StreamReader>(chArr, new StreamReader(ms));
}
[Test]
public void ObjectClosedReadLine()
{
var baseInfo = GetCharArrayStream();
StreamReader sr = baseInfo.Item2;
sr.Close();
Assert.Throws<Exception>(() => sr.ReadLine());
}
[Test]
public void ObjectClosedReadLineBaseStream()
{
Stream ms = GetLargeStream();
StreamReader sr = new StreamReader(ms);
ms.Close();
Assert.Throws<Exception>(() => sr.ReadLine());
}
[Test]
public void Synchronized_NewObject()
{
using (Stream str = GetLargeStream())
{
StreamReader reader = new StreamReader(str);
TextReader synced = TextReader.Synchronized(reader);
Assert.True(reader == synced); // different with .NET, Bridge return the same reader in Synchronized
int res1 = reader.Read();
int res2 = synced.Read();
Assert.AreNotEqual(res1, res2);
}
}
public static IEnumerable<object[]> DetectEncoding_EncodingRoundtrips_MemberData()
{
yield return new object[] { new UTF8Encoding(encoderShouldEmitUTF8Identifier: true) };
yield return new object[] { new UTF32Encoding(bigEndian: false, byteOrderMark: true) };
yield return new object[] { new UTF32Encoding(bigEndian: true, byteOrderMark: true) };
yield return new object[] { new UnicodeEncoding(bigEndian: false, byteOrderMark: true) };
yield return new object[] { new UnicodeEncoding(bigEndian: true, byteOrderMark: true) };
}
[Test]
public void EndOfStream()
{
var sw = new StreamReader(GetSmallStream());
var result = sw.ReadToEnd();
Assert.AreEqual("HELLO", result);
Assert.True(sw.EndOfStream, "End of Stream was not true after ReadToEnd");
}
[Test]
public void EndOfStreamSmallDataLargeBuffer()
{
var sw = new StreamReader(GetSmallStream(), Encoding.UTF8, true, 1024);
var result = sw.ReadToEnd();
Assert.AreEqual("HELLO", result);
Assert.True(sw.EndOfStream, "End of Stream was not true after ReadToEnd");
}
[Test]
public void EndOfStreamLargeDataSmallBuffer()
{
var sw = new StreamReader(GetLargeStream(), Encoding.UTF8, true, 1);
var result = sw.ReadToEnd();
Assert.AreEqual(5000, result.Length);
Assert.True(sw.EndOfStream, "End of Stream was not true after ReadToEnd");
}
[Test]
public void EndOfStreamLargeDataLargeBuffer()
{
var sw = new StreamReader(GetLargeStream(), Encoding.UTF8, true, 1 << 16);
var result = sw.ReadToEnd();
Assert.AreEqual(5000, result.Length);
Assert.True(sw.EndOfStream, "End of Stream was not true after ReadToEnd");
}
[Test]
public void ReadToEnd()
{
var sw = new StreamReader(GetLargeStream());
var result = sw.ReadToEnd();
Assert.AreEqual(5000, result.Length);
}
[Test]
public void GetBaseStream()
{
var ms = GetSmallStream();
var sw = new StreamReader(ms);
Assert.AreStrictEqual(sw.BaseStream, ms);
}
[Test]
public void TestRead()
{
var baseInfo = GetCharArrayStream();
var sr = baseInfo.Item2;
for (int i = 0; i < baseInfo.Item1.Length; i++)
{
int tmp = sr.Read();
Assert.AreEqual((int)baseInfo.Item1[i], tmp);
}
sr.Dispose();
}
[Test]
public void TestPeek()
{
var baseInfo = GetCharArrayStream();
var sr = baseInfo.Item2;
for (int i = 0; i < baseInfo.Item1.Length; i++)
{
var peek = sr.Peek();
Assert.AreEqual((int)baseInfo.Item1[i], peek);
sr.Read();
}
}
[Test]
public void ArgumentNullOnNullArray()
{
var baseInfo = GetCharArrayStream();
var sr = baseInfo.Item2;
Assert.Throws<ArgumentNullException>(() => sr.Read(null, 0, 0));
}
[Test]
public void ArgumentOutOfRangeOnInvalidOffset()
{
var sr = GetCharArrayStream().Item2;
Assert.Throws<ArgumentOutOfRangeException>(() => sr.Read(new char[0], -1, 0));
}
[Test]
public void ArgumentOutOfRangeOnNegativCount()
{
var sr = GetCharArrayStream().Item2;
Assert.Throws<ArgumentException>(() => sr.Read(new char[0], 0, 1));
}
[Test]
public void ArgumentExceptionOffsetAndCount()
{
var sr = GetCharArrayStream().Item2;
Assert.Throws<ArgumentException>(() => sr.Read(new char[0], 2, 0));
}
[Test]
public void ObjectDisposedExceptionDisposedStream()
{
var sr = GetCharArrayStream().Item2;
sr.Dispose();
Assert.Throws<Exception>(() => sr.Read(new char[1], 0, 1));
}
[Test]
public void ObjectDisposedExceptionDisposedBaseStream()
{
var ms = GetSmallStream();
var sr = new StreamReader(ms);
ms.Dispose();
Assert.Throws<Exception>(() => sr.Read(new char[1], 0, 1));
}
[Test]
public void EmptyStream()
{
var ms = CreateStream();
var sr = new StreamReader(ms);
var buffer = new char[10];
int read = sr.Read(buffer, 0, 1);
Assert.AreEqual(0, read);
}
[Test]
public void VanillaReads1()
{
var baseInfo = GetCharArrayStream();
var sr = baseInfo.Item2;
var chArr = new char[baseInfo.Item1.Length];
var read = sr.Read(chArr, 0, chArr.Length);
Assert.AreEqual(chArr.Length, read);
for (int i = 0; i < baseInfo.Item1.Length; i++)
{
Assert.AreEqual(baseInfo.Item1[i], chArr[i]);
}
}
[Test]
public void VanillaReads2WithAsync()
{
var baseInfo = GetCharArrayStream();
var sr = baseInfo.Item2;
var chArr = new char[baseInfo.Item1.Length];
var read = sr.Read(chArr, 4, 3);
Assert.AreEqual(read, 3);
for (int i = 0; i < 3; i++)
{
Assert.AreEqual(baseInfo.Item1[i], chArr[i + 4]);
}
}
[Test]
public void ObjectDisposedReadLine()
{
var baseInfo = GetCharArrayStream();
var sr = baseInfo.Item2;
sr.Dispose();
Assert.Throws<Exception>(() => sr.ReadLine());
}
[Test]
public void ObjectDisposedReadLineBaseStream()
{
var ms = GetLargeStream();
var sr = new StreamReader(ms);
ms.Dispose();
Assert.Throws<Exception>(() => sr.ReadLine());
}
[Test]
public void VanillaReadLines()
{
var baseInfo = GetCharArrayStream();
var sr = baseInfo.Item2;
string valueString = new string(baseInfo.Item1);
var data = sr.ReadLine();
Assert.AreEqual(valueString.Substring(0, valueString.IndexOf('\r')), data);
data = sr.ReadLine();
Assert.AreEqual(valueString.Substring(valueString.IndexOf('\r') + 1, 3), data);
data = sr.ReadLine();
Assert.AreEqual(valueString.Substring(valueString.IndexOf('\n') + 1, 2), data);
data = sr.ReadLine();
Assert.AreEqual((valueString.Substring(valueString.LastIndexOf('\n') + 1)), data);
}
[Test]
public void VanillaReadLines2()
{
var baseInfo = GetCharArrayStream();
var sr = baseInfo.Item2;
string valueString = new string(baseInfo.Item1);
var temp = new char[10];
sr.Read(temp, 0, 1);
var data = sr.ReadLine();
Assert.AreEqual(valueString.Substring(1, valueString.IndexOf('\r') - 1), data);
}
[Test]
public void ContinuousNewLinesAndTabsAsync()
{
var ms = CreateStream();
var sw = new StreamWriter(ms);
sw.Write("\n\n\r\r\n");
sw.Flush();
ms.Position = 0;
var sr = new StreamReader(ms);
for (int i = 0; i < 4; i++)
{
var data = sr.ReadLine();
Assert.AreEqual(string.Empty, data);
}
var eol = sr.ReadLine();
Assert.Null(eol);
}
[Test]
public void CurrentEncoding()
{
var ms = CreateStream();
var sr = new StreamReader(ms);
Assert.AreEqual(Encoding.UTF8, sr.CurrentEncoding);
sr = new StreamReader(ms, Encoding.Unicode);
Assert.AreEqual(Encoding.Unicode, sr.CurrentEncoding);
}
}
}
| |
/**
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace Facebook.CSSLayout
{
/**
* Should measure the given node and put the result in the given MeasureOutput.
*/
public delegate MeasureOutput MeasureFunction(CSSNode node, float width);
/**
* A CSS Node. It has a style object you can manipulate at {@link #style}. After calling
* {@link #calculateLayout()}, {@link #layout} will be filled with the results of the layout.
*/
public class CSSNode
{
const int POSITION_LEFT = CSSLayout.POSITION_LEFT;
const int POSITION_TOP = CSSLayout.POSITION_TOP;
const int POSITION_RIGHT = CSSLayout.POSITION_RIGHT;
const int POSITION_BOTTOM = CSSLayout.POSITION_BOTTOM;
const int DIMENSION_WIDTH = CSSLayout.DIMENSION_WIDTH;
const int DIMENSION_HEIGHT = CSSLayout.DIMENSION_HEIGHT;
enum LayoutState
{
/**
* Some property of this node or its children has changes and the current values in
* {@link #layout} are not valid.
*/
DIRTY,
/**
* This node has a new layout relative to the last time {@link #MarkLayoutSeen()} was called.
*/
HAS_NEW_LAYOUT,
/**
* {@link #layout} is valid for the node's properties and this layout has been marked as
* having been seen.
*/
UP_TO_DATE,
}
internal readonly CSSStyle style = new CSSStyle();
internal readonly CSSLayout layout = new CSSLayout();
internal readonly CachedCSSLayout lastLayout = new CachedCSSLayout();
internal int lineIndex = 0;
internal /*package*/ CSSNode nextAbsoluteChild;
internal /*package*/ CSSNode nextFlexChild;
// 4 is kinda arbitrary, but the default of 10 seems really high for an average View.
readonly List<CSSNode> mChildren = new List<CSSNode>(4);
[Nullable] CSSNode mParent;
[Nullable] MeasureFunction mMeasureFunction = null;
LayoutState mLayoutState = LayoutState.DIRTY;
public int ChildCount
{
get { return mChildren.Count; }
}
public CSSNode this[int i]
{
get { return mChildren[i]; }
}
public IEnumerable<CSSNode> Children
{
get { return mChildren; }
}
public void AddChild(CSSNode child)
{
InsertChild(ChildCount, child);
}
public void InsertChild(int i, CSSNode child)
{
if (child.mParent != null)
{
throw new InvalidOperationException("Child already has a parent, it must be removed first.");
}
mChildren.Insert(i, child);
child.mParent = this;
dirty();
}
public void RemoveChildAt(int i)
{
mChildren[i].mParent = null;
mChildren.RemoveAt(i);
dirty();
}
public CSSNode Parent
{
[return: Nullable]
get
{ return mParent; }
}
/**
* @return the index of the given child, or -1 if the child doesn't exist in this node.
*/
public int IndexOf(CSSNode child)
{
return mChildren.IndexOf(child);
}
public MeasureFunction MeasureFunction
{
get { return mMeasureFunction; }
set
{
if (!valuesEqual(mMeasureFunction, value))
{
mMeasureFunction = value;
dirty();
}
}
}
public bool IsMeasureDefined
{
get { return mMeasureFunction != null; }
}
internal MeasureOutput measure(MeasureOutput measureOutput, float width)
{
if (!IsMeasureDefined)
{
throw new Exception("Measure function isn't defined!");
}
return Assertions.assertNotNull(mMeasureFunction)(this, width);
}
/**
* Performs the actual layout and saves the results in {@link #layout}
*/
public void CalculateLayout()
{
layout.resetResult();
LayoutEngine.layoutNode(DummyLayoutContext, this, CSSConstants.Undefined, null);
}
static readonly CSSLayoutContext DummyLayoutContext = new CSSLayoutContext();
/**
* See {@link LayoutState#DIRTY}.
*/
public bool IsDirty
{
get { return mLayoutState == LayoutState.DIRTY; }
}
/**
* See {@link LayoutState#HAS_NEW_LAYOUT}.
*/
public bool HasNewLayout
{
get { return mLayoutState == LayoutState.HAS_NEW_LAYOUT; }
}
internal protected void dirty()
{
if (mLayoutState == LayoutState.DIRTY)
{
return;
}
else if (mLayoutState == LayoutState.HAS_NEW_LAYOUT)
{
throw new InvalidOperationException("Previous layout was ignored! MarkLayoutSeen() never called");
}
mLayoutState = LayoutState.DIRTY;
if (mParent != null)
{
mParent.dirty();
}
}
internal void markHasNewLayout()
{
mLayoutState = LayoutState.HAS_NEW_LAYOUT;
}
/**
* Tells the node that the current values in {@link #layout} have been seen. Subsequent calls
* to {@link #hasNewLayout()} will return false until this node is laid out with new parameters.
* You must call this each time the layout is generated if the node has a new layout.
*/
public void MarkLayoutSeen()
{
if (!HasNewLayout)
{
throw new InvalidOperationException("Expected node to have a new layout to be seen!");
}
mLayoutState = LayoutState.UP_TO_DATE;
}
void toStringWithIndentation(StringBuilder result, int level)
{
// Spaces and tabs are dropped by IntelliJ logcat integration, so rely on __ instead.
StringBuilder indentation = new StringBuilder();
for (int i = 0; i < level; ++i)
{
indentation.Append("__");
}
result.Append(indentation.ToString());
result.Append(layout.ToString());
if (ChildCount == 0)
{
return;
}
result.Append(", children: [\n");
for (var i = 0; i < ChildCount; i++)
{
this[i].toStringWithIndentation(result, level + 1);
result.Append("\n");
}
result.Append(indentation + "]");
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
this.toStringWithIndentation(sb, 0);
return sb.ToString();
}
protected bool valuesEqual(float f1, float f2)
{
return FloatUtil.floatsEqual(f1, f2);
}
protected bool valuesEqual<T>([Nullable] T o1, [Nullable] T o2)
{
if (o1 == null)
{
return o2 == null;
}
return o1.Equals(o2);
}
public CSSDirection Direction
{
get { return style.direction; }
set { updateDiscreteValue(ref style.direction, value); }
}
public CSSFlexDirection FlexDirection
{
get { return style.flexDirection; }
set { updateDiscreteValue(ref style.flexDirection, value); }
}
public CSSJustify JustifyContent
{
get { return style.justifyContent; }
set { updateDiscreteValue(ref style.justifyContent, value); }
}
public CSSAlign AlignContent
{
get { return style.alignContent; }
set { updateDiscreteValue(ref style.alignContent, value); }
}
public CSSAlign AlignItems
{
get { return style.alignItems; }
set { updateDiscreteValue(ref style.alignItems, value); }
}
public CSSAlign AlignSelf
{
get { return style.alignSelf; }
set { updateDiscreteValue(ref style.alignSelf, value); }
}
public CSSPositionType PositionType
{
get { return style.positionType; }
set { updateDiscreteValue(ref style.positionType, value); }
}
public CSSWrap Wrap
{
get { return style.flexWrap; }
set { updateDiscreteValue(ref style.flexWrap, value); }
}
public float Flex
{
get { return style.flex; }
set { updateFloatValue(ref style.flex, value); }
}
public void SetMargin(CSSSpacingType spacingType, float margin)
{
if (style.margin.set((int)spacingType, margin))
dirty();
}
public float GetMargin(CSSSpacingType spacingType)
{
return style.margin.getRaw((int)spacingType);
}
public void SetPadding(CSSSpacingType spacingType, float padding)
{
if (style.padding.set((int)spacingType, padding))
dirty();
}
public float GetPadding(CSSSpacingType spacingType)
{
return style.padding.getRaw((int)spacingType);
}
public void SetBorder(CSSSpacingType spacingType, float border)
{
if (style.border.set((int)spacingType, border))
dirty();
}
public float GetBorder(CSSSpacingType spacingType)
{
return style.border.getRaw((int)spacingType);
}
public float PositionTop
{
get { return style.position[POSITION_TOP]; }
set { updateFloatValue(ref style.position[POSITION_TOP], value); }
}
public float PositionBottom
{
get { return style.position[POSITION_BOTTOM]; }
set { updateFloatValue(ref style.position[POSITION_BOTTOM], value); }
}
public float PositionLeft
{
get { return style.position[POSITION_LEFT]; }
set { updateFloatValue(ref style.position[POSITION_LEFT], value); }
}
public float PositionRight
{
get { return style.position[POSITION_RIGHT]; }
set { updateFloatValue(ref style.position[POSITION_RIGHT], value); }
}
public float Width
{
get { return style.dimensions[DIMENSION_WIDTH]; }
set { updateFloatValue(ref style.dimensions[DIMENSION_WIDTH], value); }
}
public float Height
{
get { return style.dimensions[DIMENSION_HEIGHT]; }
set { updateFloatValue(ref style.dimensions[DIMENSION_HEIGHT], value); }
}
public float MinWidth
{
get { return style.minWidth; }
set { updateFloatValue(ref style.minWidth, value); }
}
public float MinHeight
{
get { return style.minHeight; }
set { updateFloatValue(ref style.minHeight, value); }
}
public float MaxWidth
{
get { return style.maxWidth; }
set { updateFloatValue(ref style.maxWidth, value); }
}
public float MaxHeight
{
get { return style.maxHeight; }
set { updateFloatValue(ref style.maxHeight, value); }
}
public float LayoutX
{
get { return layout.position[POSITION_LEFT]; }
}
public float LayoutY
{
get { return layout.position[POSITION_TOP]; }
}
public float LayoutWidth
{
get { return layout.dimensions[DIMENSION_WIDTH]; }
}
public float LayoutHeight
{
get { return layout.dimensions[DIMENSION_HEIGHT]; }
}
public CSSDirection LayoutDirection
{
get { return layout.direction; }
}
/**
* Set a default padding (left/top/right/bottom) for this node.
*/
public void SetDefaultPadding(CSSSpacingType spacingType, float padding)
{
if (style.padding.setDefault((int)spacingType, padding))
dirty();
}
void updateDiscreteValue<ValueT>(ref ValueT valueRef, ValueT newValue)
{
if (valuesEqual(valueRef, newValue))
return;
valueRef = newValue;
dirty();
}
void updateFloatValue(ref float valueRef, float newValue)
{
if (valuesEqual(valueRef, newValue))
return;
valueRef = newValue;
dirty();
}
}
public static class CSSNodeExtensions
{
/*
Explicitly mark this node as dirty.
Calling this function is required when the measure function points to the same instance,
but changes its behavior.
For all other property changes, the node is automatically marked dirty.
*/
public static void MarkDirty(this CSSNode node)
{
node.dirty();
}
}
internal static class CSSNodeExtensionsInternal
{
public static CSSNode getParent(this CSSNode node)
{
return node.Parent;
}
public static int getChildCount(this CSSNode node)
{
return node.ChildCount;
}
public static CSSNode getChildAt(this CSSNode node, int i)
{
return node[i];
}
public static void addChildAt(this CSSNode node, CSSNode child, int i)
{
node.InsertChild(i, child);
}
public static void removeChildAt(this CSSNode node, int i)
{
node.RemoveChildAt(i);
}
public static void setMeasureFunction(this CSSNode node, MeasureFunction measureFunction)
{
node.MeasureFunction = measureFunction;
}
public static void calculateLayout(this CSSNode node)
{
node.CalculateLayout();
}
public static bool isDirty(this CSSNode node)
{
return node.IsDirty;
}
public static void setMargin(this CSSNode node, int spacingType, float margin)
{
node.SetMargin((CSSSpacingType)spacingType, margin);
}
public static void setPadding(this CSSNode node, int spacingType, float padding)
{
node.SetPadding((CSSSpacingType)spacingType, padding);
}
public static void setBorder(this CSSNode node, int spacingType, float border)
{
node.SetBorder((CSSSpacingType)spacingType, border);
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.Runtime.Serialization
{
using System;
using System.Text;
using System.IO;
using System.Xml;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Security;
// NOTE: XmlReader methods that are not needed have been left un-implemented
class ExtensionDataReader : XmlReader
{
enum ExtensionDataNodeType
{
None,
Element,
EndElement,
Text,
Xml,
ReferencedElement,
NullElement,
}
Hashtable cache = new Hashtable();
ElementData[] elements;
ElementData element;
ElementData nextElement;
ReadState readState = ReadState.Initial;
ExtensionDataNodeType internalNodeType;
XmlNodeType nodeType;
int depth;
string localName;
string ns;
string prefix;
string value;
int attributeCount;
int attributeIndex;
XmlNodeReader xmlNodeReader;
Queue<IDataNode> deserializedDataNodes;
XmlObjectSerializerReadContext context;
[Fx.Tag.SecurityNote(Critical = "Holds static mappings from namespaces to prefixes."
+ " Static fields are marked SecurityCritical or readonly to prevent data from being modified or leaked to other components in appdomain.")]
[SecurityCritical]
static Dictionary<string, string> nsToPrefixTable;
[Fx.Tag.SecurityNote(Critical = "Holds static mappings from prefixes to namespaces."
+ " Static fields are marked SecurityCritical or readonly to prevent data from being modified or leaked to other components in appdomain.")]
[SecurityCritical]
static Dictionary<string, string> prefixToNsTable;
[Fx.Tag.SecurityNote(Critical = "Initializes information in critical static cache.",
Safe = "Cache is initialized with well-known namespace, prefix mappings.")]
[SecuritySafeCritical]
static ExtensionDataReader()
{
nsToPrefixTable = new Dictionary<string, string>();
prefixToNsTable = new Dictionary<string, string>();
AddPrefix(Globals.XsiPrefix, Globals.SchemaInstanceNamespace);
AddPrefix(Globals.SerPrefix, Globals.SerializationNamespace);
AddPrefix(String.Empty, String.Empty);
}
internal ExtensionDataReader(XmlObjectSerializerReadContext context)
{
this.attributeIndex = -1;
this.context = context;
}
internal void SetDeserializedValue(object obj)
{
IDataNode deserializedDataNode = (deserializedDataNodes == null || deserializedDataNodes.Count == 0) ? null : deserializedDataNodes.Dequeue();
if (deserializedDataNode != null && !(obj is IDataNode))
{
deserializedDataNode.Value = obj;
deserializedDataNode.IsFinalValue = true;
}
}
internal IDataNode GetCurrentNode()
{
IDataNode retVal = element.dataNode;
Skip();
return retVal;
}
internal void SetDataNode(IDataNode dataNode, string name, string ns)
{
SetNextElement(dataNode, name, ns, null);
this.element = nextElement;
this.nextElement = null;
SetElement();
}
internal void Reset()
{
this.localName = null;
this.ns = null;
this.prefix = null;
this.value = null;
this.attributeCount = 0;
this.attributeIndex = -1;
this.depth = 0;
this.element = null;
this.nextElement = null;
this.elements = null;
this.deserializedDataNodes = null;
}
bool IsXmlDataNode { get { return (internalNodeType == ExtensionDataNodeType.Xml); } }
public override XmlNodeType NodeType { get { return IsXmlDataNode ? xmlNodeReader.NodeType : nodeType; } }
public override string LocalName { get { return IsXmlDataNode ? xmlNodeReader.LocalName : localName; } }
public override string NamespaceURI { get { return IsXmlDataNode ? xmlNodeReader.NamespaceURI : ns; } }
public override string Prefix { get { return IsXmlDataNode ? xmlNodeReader.Prefix : prefix; } }
public override string Value { get { return IsXmlDataNode ? xmlNodeReader.Value : value; } }
public override int Depth { get { return IsXmlDataNode ? xmlNodeReader.Depth : depth; } }
public override int AttributeCount { get { return IsXmlDataNode ? xmlNodeReader.AttributeCount : attributeCount; } }
public override bool EOF { get { return IsXmlDataNode ? xmlNodeReader.EOF : (readState == ReadState.EndOfFile); } }
public override ReadState ReadState { get { return IsXmlDataNode ? xmlNodeReader.ReadState : readState; } }
public override bool IsEmptyElement { get { return IsXmlDataNode ? xmlNodeReader.IsEmptyElement : false; } }
public override bool IsDefault { get { return IsXmlDataNode ? xmlNodeReader.IsDefault : base.IsDefault; } }
public override char QuoteChar { get { return IsXmlDataNode ? xmlNodeReader.QuoteChar : base.QuoteChar; } }
public override XmlSpace XmlSpace { get { return IsXmlDataNode ? xmlNodeReader.XmlSpace : base.XmlSpace; } }
public override string XmlLang { get { return IsXmlDataNode ? xmlNodeReader.XmlLang : base.XmlLang; } }
public override string this[int i] { get { return IsXmlDataNode ? xmlNodeReader[i] : GetAttribute(i); } }
public override string this[string name] { get { return IsXmlDataNode ? xmlNodeReader[name] : GetAttribute(name); } }
public override string this[string name, string namespaceURI] { get { return IsXmlDataNode ? xmlNodeReader[name, namespaceURI] : GetAttribute(name, namespaceURI); } }
public override bool MoveToFirstAttribute()
{
if (IsXmlDataNode)
return xmlNodeReader.MoveToFirstAttribute();
if (attributeCount == 0)
return false;
MoveToAttribute(0);
return true;
}
public override bool MoveToNextAttribute()
{
if (IsXmlDataNode)
return xmlNodeReader.MoveToNextAttribute();
if (attributeIndex + 1 >= attributeCount)
return false;
MoveToAttribute(attributeIndex + 1);
return true;
}
public override void MoveToAttribute(int index)
{
if (IsXmlDataNode)
xmlNodeReader.MoveToAttribute(index);
else
{
if (index < 0 || index >= attributeCount)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.InvalidXmlDeserializingExtensionData)));
this.nodeType = XmlNodeType.Attribute;
AttributeData attribute = element.attributes[index];
this.localName = attribute.localName;
this.ns = attribute.ns;
this.prefix = attribute.prefix;
this.value = attribute.value;
this.attributeIndex = index;
}
}
public override string GetAttribute(string name, string namespaceURI)
{
if (IsXmlDataNode)
return xmlNodeReader.GetAttribute(name, namespaceURI);
for (int i = 0; i < element.attributeCount; i++)
{
AttributeData attribute = element.attributes[i];
if (attribute.localName == name && attribute.ns == namespaceURI)
return attribute.value;
}
return null;
}
public override bool MoveToAttribute(string name, string namespaceURI)
{
if (IsXmlDataNode)
return xmlNodeReader.MoveToAttribute(name, ns);
for (int i = 0; i < element.attributeCount; i++)
{
AttributeData attribute = element.attributes[i];
if (attribute.localName == name && attribute.ns == namespaceURI)
{
MoveToAttribute(i);
return true;
}
}
return false;
}
public override bool MoveToElement()
{
if (IsXmlDataNode)
return xmlNodeReader.MoveToElement();
if (this.nodeType != XmlNodeType.Attribute)
return false;
SetElement();
return true;
}
void SetElement()
{
this.nodeType = XmlNodeType.Element;
this.localName = element.localName;
this.ns = element.ns;
this.prefix = element.prefix;
this.value = String.Empty;
this.attributeCount = element.attributeCount;
this.attributeIndex = -1;
}
[Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical static cache to look up namespace given a prefix.",
Safe = "Read only access.")]
[SecuritySafeCritical]
public override string LookupNamespace(string prefix)
{
if (IsXmlDataNode)
return xmlNodeReader.LookupNamespace(prefix);
string ns;
if (!prefixToNsTable.TryGetValue(prefix, out ns))
return null;
return ns;
}
public override void Skip()
{
if (IsXmlDataNode)
xmlNodeReader.Skip();
else
{
if (ReadState != ReadState.Interactive)
return;
MoveToElement();
if (IsElementNode(this.internalNodeType))
{
int depth = 1;
while (depth != 0)
{
if (!Read())
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.InvalidXmlDeserializingExtensionData)));
if (IsElementNode(this.internalNodeType))
depth++;
else if (this.internalNodeType == ExtensionDataNodeType.EndElement)
{
ReadEndElement();
depth--;
}
}
}
else
Read();
}
}
bool IsElementNode(ExtensionDataNodeType nodeType)
{
return (nodeType == ExtensionDataNodeType.Element ||
nodeType == ExtensionDataNodeType.ReferencedElement ||
nodeType == ExtensionDataNodeType.NullElement);
}
public override void Close()
{
if (IsXmlDataNode)
xmlNodeReader.Close();
else
{
Reset();
this.readState = ReadState.Closed;
}
}
public override bool Read()
{
if (nodeType == XmlNodeType.Attribute && MoveToNextAttribute())
return true;
MoveNext(element.dataNode);
switch (internalNodeType)
{
case ExtensionDataNodeType.Element:
case ExtensionDataNodeType.ReferencedElement:
case ExtensionDataNodeType.NullElement:
PushElement();
SetElement();
break;
case ExtensionDataNodeType.Text:
this.nodeType = XmlNodeType.Text;
this.prefix = String.Empty;
this.ns = String.Empty;
this.localName = String.Empty;
this.attributeCount = 0;
this.attributeIndex = -1;
break;
case ExtensionDataNodeType.EndElement:
this.nodeType = XmlNodeType.EndElement;
this.prefix = String.Empty;
this.ns = String.Empty;
this.localName = String.Empty;
this.value = String.Empty;
this.attributeCount = 0;
this.attributeIndex = -1;
PopElement();
break;
case ExtensionDataNodeType.None:
if (depth != 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.InvalidXmlDeserializingExtensionData)));
this.nodeType = XmlNodeType.None;
this.prefix = String.Empty;
this.ns = String.Empty;
this.localName = String.Empty;
this.value = String.Empty;
this.attributeCount = 0;
readState = ReadState.EndOfFile;
return false;
case ExtensionDataNodeType.Xml:
// do nothing
break;
default:
Fx.Assert("ExtensionDataReader in invalid state");
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.GetString(SR.InvalidStateInExtensionDataReader)));
}
readState = ReadState.Interactive;
return true;
}
public override string Name
{
get
{
if (IsXmlDataNode)
{
return xmlNodeReader.Name;
}
Fx.Assert("ExtensionDataReader Name property should only be called for IXmlSerializable");
return string.Empty;
}
}
public override bool HasValue
{
get
{
if (IsXmlDataNode)
{
return xmlNodeReader.HasValue;
}
Fx.Assert("ExtensionDataReader HasValue property should only be called for IXmlSerializable");
return false;
}
}
public override string BaseURI
{
get
{
if (IsXmlDataNode)
{
return xmlNodeReader.BaseURI;
}
Fx.Assert("ExtensionDataReader BaseURI property should only be called for IXmlSerializable");
return string.Empty;
}
}
public override XmlNameTable NameTable
{
get
{
if (IsXmlDataNode)
{
return xmlNodeReader.NameTable;
}
Fx.Assert("ExtensionDataReader NameTable property should only be called for IXmlSerializable");
return null;
}
}
public override string GetAttribute(string name)
{
if (IsXmlDataNode)
{
return xmlNodeReader.GetAttribute(name);
}
Fx.Assert("ExtensionDataReader GetAttribute method should only be called for IXmlSerializable");
return null;
}
public override string GetAttribute(int i)
{
if (IsXmlDataNode)
{
return xmlNodeReader.GetAttribute(i);
}
Fx.Assert("ExtensionDataReader GetAttribute method should only be called for IXmlSerializable");
return null;
}
public override bool MoveToAttribute(string name)
{
if (IsXmlDataNode)
{
return xmlNodeReader.MoveToAttribute(name);
}
Fx.Assert("ExtensionDataReader MoveToAttribute method should only be called for IXmlSerializable");
return false;
}
public override void ResolveEntity()
{
if (IsXmlDataNode)
{
xmlNodeReader.ResolveEntity();
}
else
{
Fx.Assert("ExtensionDataReader ResolveEntity method should only be called for IXmlSerializable");
}
}
public override bool ReadAttributeValue()
{
if (IsXmlDataNode)
{
return xmlNodeReader.ReadAttributeValue();
}
Fx.Assert("ExtensionDataReader ReadAttributeValue method should only be called for IXmlSerializable");
return false;
}
void MoveNext(IDataNode dataNode)
{
switch (this.internalNodeType)
{
case ExtensionDataNodeType.Text:
case ExtensionDataNodeType.ReferencedElement:
case ExtensionDataNodeType.NullElement:
this.internalNodeType = ExtensionDataNodeType.EndElement;
return;
default:
Type dataNodeType = dataNode.DataType;
if (dataNodeType == Globals.TypeOfClassDataNode)
MoveNextInClass((ClassDataNode)dataNode);
else if (dataNodeType == Globals.TypeOfCollectionDataNode)
MoveNextInCollection((CollectionDataNode)dataNode);
else if (dataNodeType == Globals.TypeOfISerializableDataNode)
MoveNextInISerializable((ISerializableDataNode)dataNode);
else if (dataNodeType == Globals.TypeOfXmlDataNode)
MoveNextInXml((XmlDataNode)dataNode);
else if (dataNode.Value != null)
MoveToDeserializedObject(dataNode);
else
{
Fx.Assert("Encountered invalid data node when deserializing unknown data");
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.GetString(SR.InvalidStateInExtensionDataReader)));
}
break;
}
}
void SetNextElement(IDataNode node, string name, string ns, string prefix)
{
this.internalNodeType = ExtensionDataNodeType.Element;
nextElement = GetNextElement();
nextElement.localName = name;
nextElement.ns = ns;
nextElement.prefix = prefix;
if (node == null)
{
nextElement.attributeCount = 0;
nextElement.AddAttribute(Globals.XsiPrefix, Globals.SchemaInstanceNamespace, Globals.XsiNilLocalName, Globals.True);
this.internalNodeType = ExtensionDataNodeType.NullElement;
}
else if (!CheckIfNodeHandled(node))
{
AddDeserializedDataNode(node);
node.GetData(nextElement);
if (node is XmlDataNode)
MoveNextInXml((XmlDataNode)node);
}
}
void AddDeserializedDataNode(IDataNode node)
{
if (node.Id != Globals.NewObjectId && (node.Value == null || !node.IsFinalValue))
{
if (deserializedDataNodes == null)
deserializedDataNodes = new Queue<IDataNode>();
deserializedDataNodes.Enqueue(node);
}
}
bool CheckIfNodeHandled(IDataNode node)
{
bool handled = false;
if (node.Id != Globals.NewObjectId)
{
handled = (cache[node] != null);
if (handled)
{
if (nextElement == null)
nextElement = GetNextElement();
nextElement.attributeCount = 0;
nextElement.AddAttribute(Globals.SerPrefix, Globals.SerializationNamespace, Globals.RefLocalName, node.Id.ToString(NumberFormatInfo.InvariantInfo));
nextElement.AddAttribute(Globals.XsiPrefix, Globals.SchemaInstanceNamespace, Globals.XsiNilLocalName, Globals.True);
this.internalNodeType = ExtensionDataNodeType.ReferencedElement;
}
else
{
cache.Add(node, node);
}
}
return handled;
}
void MoveNextInClass(ClassDataNode dataNode)
{
if (dataNode.Members != null && element.childElementIndex < dataNode.Members.Count)
{
if (element.childElementIndex == 0)
this.context.IncrementItemCount(-dataNode.Members.Count);
ExtensionDataMember member = dataNode.Members[element.childElementIndex++];
SetNextElement(member.Value, member.Name, member.Namespace, GetPrefix(member.Namespace));
}
else
{
this.internalNodeType = ExtensionDataNodeType.EndElement;
element.childElementIndex = 0;
}
}
void MoveNextInCollection(CollectionDataNode dataNode)
{
if (dataNode.Items != null && element.childElementIndex < dataNode.Items.Count)
{
if (element.childElementIndex == 0)
this.context.IncrementItemCount(-dataNode.Items.Count);
IDataNode item = dataNode.Items[element.childElementIndex++];
SetNextElement(item, dataNode.ItemName, dataNode.ItemNamespace, GetPrefix(dataNode.ItemNamespace));
}
else
{
this.internalNodeType = ExtensionDataNodeType.EndElement;
element.childElementIndex = 0;
}
}
void MoveNextInISerializable(ISerializableDataNode dataNode)
{
if (dataNode.Members != null && element.childElementIndex < dataNode.Members.Count)
{
if (element.childElementIndex == 0)
this.context.IncrementItemCount(-dataNode.Members.Count);
ISerializableDataMember member = dataNode.Members[element.childElementIndex++];
SetNextElement(member.Value, member.Name, String.Empty, String.Empty);
}
else
{
this.internalNodeType = ExtensionDataNodeType.EndElement;
element.childElementIndex = 0;
}
}
void MoveNextInXml(XmlDataNode dataNode)
{
if (IsXmlDataNode)
{
xmlNodeReader.Read();
if (xmlNodeReader.Depth == 0)
{
this.internalNodeType = ExtensionDataNodeType.EndElement;
xmlNodeReader = null;
}
}
else
{
internalNodeType = ExtensionDataNodeType.Xml;
if (element == null)
element = nextElement;
else
PushElement();
XmlNode wrapperElement = XmlObjectSerializerReadContext.CreateWrapperXmlElement(dataNode.OwnerDocument,
dataNode.XmlAttributes, dataNode.XmlChildNodes, element.prefix, element.localName, element.ns);
for (int i = 0; i < element.attributeCount; i++)
{
AttributeData a = element.attributes[i];
XmlAttribute xmlAttr = dataNode.OwnerDocument.CreateAttribute(a.prefix, a.localName, a.ns);
xmlAttr.Value = a.value;
wrapperElement.Attributes.Append(xmlAttr);
}
xmlNodeReader = new XmlNodeReader(wrapperElement);
xmlNodeReader.Read();
}
}
void MoveToDeserializedObject(IDataNode dataNode)
{
Type type = dataNode.DataType;
bool isTypedNode = true;
if (type == Globals.TypeOfObject)
{
type = dataNode.Value.GetType();
if (type == Globals.TypeOfObject)
{
this.internalNodeType = ExtensionDataNodeType.EndElement;
return;
}
isTypedNode = false;
}
if (!MoveToText(type, dataNode, isTypedNode))
{
if (dataNode.IsFinalValue)
{
this.internalNodeType = ExtensionDataNodeType.EndElement;
}
else
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.InvalidDataNode, DataContract.GetClrTypeFullName(type))));
}
}
}
bool MoveToText(Type type, IDataNode dataNode, bool isTypedNode)
{
bool handled = true;
switch (Type.GetTypeCode(type))
{
case TypeCode.Boolean:
this.value = XmlConvert.ToString(isTypedNode ? ((DataNode<bool>)dataNode).GetValue() : (bool)dataNode.Value);
break;
case TypeCode.Char:
this.value = XmlConvert.ToString((int)(isTypedNode ? ((DataNode<char>)dataNode).GetValue() : (char)dataNode.Value));
break;
case TypeCode.Byte:
this.value = XmlConvert.ToString(isTypedNode ? ((DataNode<byte>)dataNode).GetValue() : (byte)dataNode.Value);
break;
case TypeCode.Int16:
this.value = XmlConvert.ToString(isTypedNode ? ((DataNode<short>)dataNode).GetValue() : (short)dataNode.Value);
break;
case TypeCode.Int32:
this.value = XmlConvert.ToString(isTypedNode ? ((DataNode<int>)dataNode).GetValue() : (int)dataNode.Value);
break;
case TypeCode.Int64:
this.value = XmlConvert.ToString(isTypedNode ? ((DataNode<long>)dataNode).GetValue() : (long)dataNode.Value);
break;
case TypeCode.Single:
this.value = XmlConvert.ToString(isTypedNode ? ((DataNode<float>)dataNode).GetValue() : (float)dataNode.Value);
break;
case TypeCode.Double:
this.value = XmlConvert.ToString(isTypedNode ? ((DataNode<double>)dataNode).GetValue() : (double)dataNode.Value);
break;
case TypeCode.Decimal:
this.value = XmlConvert.ToString(isTypedNode ? ((DataNode<decimal>)dataNode).GetValue() : (decimal)dataNode.Value);
break;
case TypeCode.DateTime:
DateTime dateTime = isTypedNode ? ((DataNode<DateTime>)dataNode).GetValue() : (DateTime)dataNode.Value;
this.value = dateTime.ToString("yyyy-MM-ddTHH:mm:ss.fffffffK", DateTimeFormatInfo.InvariantInfo);
break;
case TypeCode.String:
this.value = isTypedNode ? ((DataNode<string>)dataNode).GetValue() : (string)dataNode.Value;
break;
case TypeCode.SByte:
this.value = XmlConvert.ToString(isTypedNode ? ((DataNode<sbyte>)dataNode).GetValue() : (sbyte)dataNode.Value);
break;
case TypeCode.UInt16:
this.value = XmlConvert.ToString(isTypedNode ? ((DataNode<ushort>)dataNode).GetValue() : (ushort)dataNode.Value);
break;
case TypeCode.UInt32:
this.value = XmlConvert.ToString(isTypedNode ? ((DataNode<uint>)dataNode).GetValue() : (uint)dataNode.Value);
break;
case TypeCode.UInt64:
this.value = XmlConvert.ToString(isTypedNode ? ((DataNode<ulong>)dataNode).GetValue() : (ulong)dataNode.Value);
break;
case TypeCode.Object:
default:
if (type == Globals.TypeOfByteArray)
{
byte[] bytes = isTypedNode ? ((DataNode<byte[]>)dataNode).GetValue() : (byte[])dataNode.Value;
this.value = (bytes == null) ? String.Empty : Convert.ToBase64String(bytes);
}
else if (type == Globals.TypeOfTimeSpan)
this.value = XmlConvert.ToString(isTypedNode ? ((DataNode<TimeSpan>)dataNode).GetValue() : (TimeSpan)dataNode.Value);
else if (type == Globals.TypeOfGuid)
{
Guid guid = isTypedNode ? ((DataNode<Guid>)dataNode).GetValue() : (Guid)dataNode.Value;
this.value = guid.ToString();
}
else if (type == Globals.TypeOfUri)
{
Uri uri = isTypedNode ? ((DataNode<Uri>)dataNode).GetValue() : (Uri)dataNode.Value;
this.value = uri.GetComponents(UriComponents.SerializationInfoString, UriFormat.UriEscaped);
}
else
handled = false;
break;
}
if (handled)
this.internalNodeType = ExtensionDataNodeType.Text;
return handled;
}
void PushElement()
{
GrowElementsIfNeeded();
elements[depth++] = this.element;
if (nextElement == null)
element = GetNextElement();
else
{
element = nextElement;
nextElement = null;
}
}
void PopElement()
{
this.prefix = element.prefix;
this.localName = element.localName;
this.ns = element.ns;
if (depth == 0)
return;
this.depth--;
if (elements != null)
{
this.element = elements[depth];
}
}
void GrowElementsIfNeeded()
{
if (elements == null)
elements = new ElementData[8];
else if (elements.Length == depth)
{
ElementData[] newElements = new ElementData[elements.Length * 2];
Array.Copy(elements, 0, newElements, 0, elements.Length);
elements = newElements;
}
}
ElementData GetNextElement()
{
int nextDepth = depth + 1;
return (elements == null || elements.Length <= nextDepth || elements[nextDepth] == null)
? new ElementData() : elements[nextDepth];
}
[Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical static cache to look up prefix given a namespace .",
Safe = "Read only access.")]
[SecuritySafeCritical]
internal static string GetPrefix(string ns)
{
string prefix;
ns = ns ?? String.Empty;
if (!nsToPrefixTable.TryGetValue(ns, out prefix))
{
lock (nsToPrefixTable)
{
if (!nsToPrefixTable.TryGetValue(ns, out prefix))
{
prefix = (ns == null || ns.Length == 0) ? String.Empty : "p" + nsToPrefixTable.Count;
AddPrefix(prefix, ns);
}
}
}
return prefix;
}
[Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical static cache to look up prefix given a namespace .",
Safe = "Read only access.")]
[SecuritySafeCritical]
static void AddPrefix(string prefix, string ns)
{
nsToPrefixTable.Add(ns, prefix);
prefixToNsTable.Add(prefix, ns);
}
}
#if USE_REFEMIT
public class AttributeData
#else
internal class AttributeData
#endif
{
public string prefix;
public string ns;
public string localName;
public string value;
}
#if USE_REFEMIT
public class ElementData
#else
internal class ElementData
#endif
{
public string localName;
public string ns;
public string prefix;
public int attributeCount;
public AttributeData[] attributes;
public IDataNode dataNode;
public int childElementIndex;
public void AddAttribute(string prefix, string ns, string name, string value)
{
GrowAttributesIfNeeded();
AttributeData attribute = attributes[attributeCount];
if (attribute == null)
attributes[attributeCount] = attribute = new AttributeData();
attribute.prefix = prefix;
attribute.ns = ns;
attribute.localName = name;
attribute.value = value;
attributeCount++;
}
void GrowAttributesIfNeeded()
{
if (attributes == null)
attributes = new AttributeData[4];
else if (attributes.Length == attributeCount)
{
AttributeData[] newAttributes = new AttributeData[attributes.Length * 2];
Array.Copy(attributes, 0, newAttributes, 0, attributes.Length);
attributes = newAttributes;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Globalization;
using System.IO;
using System.Runtime.Versioning;
using System.Text;
using System.Xml;
using System.Xml.XPath;
namespace System.Diagnostics
{
public class XmlWriterTraceListener : TextWriterTraceListener
{
private const string FixedHeader = "<E2ETraceEvent xmlns=\"http://schemas.microsoft.com/2004/06/E2ETraceEvent\"><System xmlns=\"http://schemas.microsoft.com/2004/06/windows/eventlog/system\">";
private readonly string _machineName = Environment.MachineName;
private StringBuilder _strBldr = null;
private XmlTextWriter _xmlBlobWriter = null;
public XmlWriterTraceListener(Stream stream)
: base(stream)
{
}
public XmlWriterTraceListener(Stream stream, string name)
: base(stream, name)
{
}
public XmlWriterTraceListener(TextWriter writer)
: base(writer)
{
}
public XmlWriterTraceListener(TextWriter writer, string name)
: base(writer, name)
{
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public XmlWriterTraceListener(string filename)
: base(filename)
{
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public XmlWriterTraceListener(string filename, string name)
: base(filename, name)
{
}
public override void Write(string message)
{
WriteLine(message);
}
public override void WriteLine(string message)
{
TraceEvent(null, SR.TraceAsTraceSource, TraceEventType.Information, 0, message);
}
public override void Fail(string message, string detailMessage)
{
int length = detailMessage != null ? message.Length + 1 + detailMessage.Length : message.Length;
TraceEvent(null, SR.TraceAsTraceSource, TraceEventType.Error, 0, string.Create(length, (message, detailMessage),
(dst, v) =>
{
ReadOnlySpan<char> prefix = v.message;
prefix.CopyTo(dst);
if (v.detailMessage != null)
{
dst[prefix.Length] = ' ';
ReadOnlySpan<char> detail = v.detailMessage;
detail.CopyTo(dst.Slice(prefix.Length + 1, detail.Length));
}
}));
}
public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args)
{
if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, format, args, null, null))
return;
WriteHeader(source, eventType, id, eventCache);
WriteEscaped(args != null && args.Length != 0 ? string.Format(CultureInfo.InvariantCulture, format, args) : format);
WriteFooter(eventCache);
}
public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message)
{
if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, message, null, null, null))
return;
WriteHeader(source, eventType, id, eventCache);
WriteEscaped(message);
WriteFooter(eventCache);
}
public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data)
{
if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, data, null))
return;
WriteHeader(source, eventType, id, eventCache);
InternalWrite("<TraceData>");
if (data != null)
{
InternalWrite("<DataItem>");
WriteData(data);
InternalWrite("</DataItem>");
}
InternalWrite("</TraceData>");
WriteFooter(eventCache);
}
public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, params object[] data)
{
if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, data))
return;
WriteHeader(source, eventType, id, eventCache);
InternalWrite("<TraceData>");
if (data != null)
{
for (int i = 0; i < data.Length; i++)
{
InternalWrite("<DataItem>");
if (data[i] != null)
WriteData(data[i]);
InternalWrite("</DataItem>");
}
}
InternalWrite("</TraceData>");
WriteFooter(eventCache);
}
// Special case XPathNavigator dataitems to write out XML blob unescaped
private void WriteData(object data)
{
if (!(data is XPathNavigator xmlBlob))
{
WriteEscaped(data.ToString());
}
else
{
if (_strBldr == null)
{
_strBldr = new StringBuilder();
_xmlBlobWriter = new XmlTextWriter(new StringWriter(_strBldr, CultureInfo.CurrentCulture));
}
else
{
_strBldr.Length = 0;
}
try
{
// Rewind the blob to point to the root, this is needed to support multiple XMLTL in one TraceData call
xmlBlob.MoveToRoot();
_xmlBlobWriter.WriteNode(xmlBlob, false);
InternalWrite(_strBldr.ToString());
}
catch (Exception)
{
InternalWrite(data.ToString());
}
}
}
public override void Close()
{
base.Close();
_xmlBlobWriter?.Close();
_xmlBlobWriter = null;
_strBldr = null;
}
public override void TraceTransfer(TraceEventCache eventCache, string source, int id, string message, Guid relatedActivityId)
{
if (Filter != null && !Filter.ShouldTrace(eventCache, source, TraceEventType.Transfer, id, message, null, null, null))
return;
WriteHeader(source, TraceEventType.Transfer, id, eventCache, relatedActivityId);
WriteEscaped(message);
WriteFooter(eventCache);
}
private void WriteHeader(string source, TraceEventType eventType, int id, TraceEventCache eventCache, Guid relatedActivityId)
{
WriteStartHeader(source, eventType, id, eventCache);
InternalWrite("\" RelatedActivityID=\"");
InternalWrite(relatedActivityId.ToString("B"));
WriteEndHeader();
}
private void WriteHeader(string source, TraceEventType eventType, int id, TraceEventCache eventCache)
{
WriteStartHeader(source, eventType, id, eventCache);
WriteEndHeader();
}
private void WriteStartHeader(string source, TraceEventType eventType, int id, TraceEventCache eventCache)
{
InternalWrite(FixedHeader);
InternalWrite("<EventID>");
InternalWrite(((uint)id).ToString(CultureInfo.InvariantCulture));
InternalWrite("</EventID>");
InternalWrite("<Type>3</Type>");
InternalWrite("<SubType Name=\"");
InternalWrite(eventType.ToString());
InternalWrite("\">0</SubType>");
InternalWrite("<Level>");
int sev = (int)eventType;
if (sev > 255)
sev = 255;
if (sev < 0)
sev = 0;
InternalWrite(sev.ToString(CultureInfo.InvariantCulture));
InternalWrite("</Level>");
InternalWrite("<TimeCreated SystemTime=\"");
if (eventCache != null)
InternalWrite(eventCache.DateTime.ToString("o", CultureInfo.InvariantCulture));
else
InternalWrite(DateTime.Now.ToString("o", CultureInfo.InvariantCulture));
InternalWrite("\" />");
InternalWrite("<Source Name=\"");
WriteEscaped(source);
InternalWrite("\" />");
InternalWrite("<Correlation ActivityID=\"");
if (eventCache != null)
InternalWrite(Trace.CorrelationManager.ActivityId.ToString("B"));
else
InternalWrite(Guid.Empty.ToString("B"));
}
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
private void WriteEndHeader()
{
InternalWrite("\" />");
InternalWrite("<Execution ProcessName=\"");
InternalWrite(TraceListenerHelpers.GetProcessName());
InternalWrite("\" ProcessID=\"");
InternalWrite(((uint)TraceListenerHelpers.GetProcessId()).ToString(CultureInfo.InvariantCulture));
InternalWrite("\" ThreadID=\"");
WriteEscaped(TraceListenerHelpers.GetThreadId().ToString(CultureInfo.InvariantCulture));
InternalWrite("\" />");
InternalWrite("<Channel/>");
InternalWrite("<Computer>");
InternalWrite(_machineName);
InternalWrite("</Computer>");
InternalWrite("</System>");
InternalWrite("<ApplicationData>");
}
private void WriteFooter(TraceEventCache eventCache)
{
bool writeLogicalOps = IsEnabled(TraceOptions.LogicalOperationStack);
bool writeCallstack = IsEnabled(TraceOptions.Callstack);
if (eventCache != null && (writeLogicalOps || writeCallstack))
{
InternalWrite("<System.Diagnostics xmlns=\"http://schemas.microsoft.com/2004/08/System.Diagnostics\">");
if (writeLogicalOps)
{
InternalWrite("<LogicalOperationStack>");
Stack s = eventCache.LogicalOperationStack;
foreach (object correlationId in s)
{
InternalWrite("<LogicalOperation>");
WriteEscaped(correlationId.ToString());
InternalWrite("</LogicalOperation>");
}
InternalWrite("</LogicalOperationStack>");
}
InternalWrite("<Timestamp>");
InternalWrite(eventCache.Timestamp.ToString(CultureInfo.InvariantCulture));
InternalWrite("</Timestamp>");
if (writeCallstack)
{
InternalWrite("<Callstack>");
WriteEscaped(eventCache.Callstack);
InternalWrite("</Callstack>");
}
InternalWrite("</System.Diagnostics>");
}
InternalWrite("</ApplicationData></E2ETraceEvent>");
}
private void WriteEscaped(string str)
{
if (string.IsNullOrEmpty(str))
return;
int lastIndex = 0;
for (int i = 0; i < str.Length; i++)
{
switch (str[i])
{
case '&':
InternalWrite(str.Substring(lastIndex, i - lastIndex));
InternalWrite("&");
lastIndex = i + 1;
break;
case '<':
InternalWrite(str.Substring(lastIndex, i - lastIndex));
InternalWrite("<");
lastIndex = i + 1;
break;
case '>':
InternalWrite(str.Substring(lastIndex, i - lastIndex));
InternalWrite(">");
lastIndex = i + 1;
break;
case '"':
InternalWrite(str.Substring(lastIndex, i - lastIndex));
InternalWrite(""");
lastIndex = i + 1;
break;
case '\'':
InternalWrite(str.Substring(lastIndex, i - lastIndex));
InternalWrite("'");
lastIndex = i + 1;
break;
case (char)0xD:
InternalWrite(str.Substring(lastIndex, i - lastIndex));
InternalWrite("
");
lastIndex = i + 1;
break;
case (char)0xA:
InternalWrite(str.Substring(lastIndex, i - lastIndex));
InternalWrite("
");
lastIndex = i + 1;
break;
}
}
InternalWrite(str.Substring(lastIndex, str.Length - lastIndex));
}
private void InternalWrite(string message)
{
EnsureWriter();
if (_writer != null)
_writer.Write(message);
}
}
}
| |
using System;
using UnityEngine;
using UnityEngine.UIElements;
using UnityEngine.UIElements.StyleSheets;
namespace UnityEditor.ShaderGraph.Drawing
{
enum ResizeDirection
{
Any,
Vertical,
Horizontal
}
enum ResizeHandleAnchor
{
Top,
TopRight,
Right,
BottomRight,
Bottom,
BottomLeft,
Left,
TopLeft
}
class ResizeSideHandle : ImmediateModeElement
{
VisualElement m_ResizeTarget;
VisualElement m_Container;
WindowDockingLayout m_WindowDockingLayout;
bool m_MaintainAspectRatio;
public bool maintainAspectRatio
{
get { return m_MaintainAspectRatio; }
set { m_MaintainAspectRatio = value; }
}
public Action OnResizeFinished;
bool m_Dragging;
Rect m_ResizeBeginLayout;
Vector2 m_ResizeBeginMousePosition;
private GUIStyle m_StyleWidget;
private GUIStyle m_StyleLabel;
private Texture image { get; set; }
public ResizeSideHandle(VisualElement resizeTarget, VisualElement container, ResizeHandleAnchor anchor)
{
m_WindowDockingLayout = new WindowDockingLayout();
m_ResizeTarget = resizeTarget;
m_Container = container;
AddToClassList("resize");
switch (anchor)
{
case ResizeHandleAnchor.Top:
{
AddToClassList("vertical");
AddToClassList("top");
RegisterCallback<MouseMoveEvent>(HandleResizeFromTop);
break;
}
case ResizeHandleAnchor.TopRight:
{
AddToClassList("diagonal");
AddToClassList("top-right");
RegisterCallback<MouseMoveEvent>(HandleResizeFromTopRight);
break;
}
case ResizeHandleAnchor.Right:
{
AddToClassList("horizontal");
AddToClassList("right");
RegisterCallback<MouseMoveEvent>(HandleResizeFromRight);
break;
}
case ResizeHandleAnchor.BottomRight:
{
AddToClassList("diagonal");
AddToClassList("bottom-right");
RegisterCallback<MouseMoveEvent>(HandleResizeFromBottomRight);
break;
}
case ResizeHandleAnchor.Bottom:
{
AddToClassList("vertical");
AddToClassList("bottom");
RegisterCallback<MouseMoveEvent>(HandleResizeFromBottom);
break;
}
case ResizeHandleAnchor.BottomLeft:
{
AddToClassList("diagonal");
AddToClassList("bottom-left");
RegisterCallback<MouseMoveEvent>(HandleResizeFromBottomLeft);
break;
}
case ResizeHandleAnchor.Left:
{
AddToClassList("horizontal");
AddToClassList("left");
RegisterCallback<MouseMoveEvent>(HandleResizeFromLeft);
break;
}
case ResizeHandleAnchor.TopLeft:
{
AddToClassList("diagonal");
AddToClassList("top-left");
RegisterCallback<MouseMoveEvent>(HandleResizeFromTopLeft);
break;
}
}
RegisterCallback<MouseDownEvent>(HandleMouseDown);
RegisterCallback<MouseUpEvent>(HandleDraggableMouseUp);
m_ResizeTarget.RegisterCallback<GeometryChangedEvent>(InitialLayoutSetup);
}
void InitialLayoutSetup(GeometryChangedEvent evt)
{
m_ResizeTarget.UnregisterCallback<GeometryChangedEvent>(InitialLayoutSetup);
}
void HandleResizeFromTop(MouseMoveEvent mouseMoveEvent)
{
if (!m_Dragging)
return;
Vector2 relativeMousePosition = mouseMoveEvent.mousePosition - m_ResizeBeginMousePosition;
// Set anchor points for positioning
m_Container.style.top = float.NaN;
m_Container.style.bottom = m_Container.parent.layout.height - m_Container.layout.yMax;
float newHeight = Mathf.Max(0f, m_ResizeBeginLayout.height - relativeMousePosition.y);
m_ResizeTarget.style.height = newHeight;
if (maintainAspectRatio)
m_ResizeTarget.style.width = newHeight;
mouseMoveEvent.StopImmediatePropagation();
}
void HandleResizeFromTopRight(MouseMoveEvent mouseMoveEvent)
{
if (!m_Dragging)
return;
Vector2 relativeMousePosition = mouseMoveEvent.mousePosition - m_ResizeBeginMousePosition;
// Set anchor points for positioning
m_Container.style.top = float.NaN;
m_Container.style.bottom = m_Container.parent.layout.height - m_Container.layout.yMax;
m_Container.style.left = m_Container.layout.xMin;
m_Container.style.right = float.NaN;
float newWidth = Mathf.Max(0f, m_ResizeBeginLayout.width + relativeMousePosition.x);
float newHeight = Mathf.Max(0f, m_ResizeBeginLayout.height - relativeMousePosition.y);
if (maintainAspectRatio)
newWidth = newHeight = Mathf.Min(newWidth, newHeight);
m_ResizeTarget.style.width = newWidth;
m_ResizeTarget.style.height = newHeight;
mouseMoveEvent.StopPropagation();
}
void HandleResizeFromRight(MouseMoveEvent mouseMoveEvent)
{
if (!m_Dragging)
return;
Vector2 relativeMousePosition = mouseMoveEvent.mousePosition - m_ResizeBeginMousePosition;
// Set anchor points for positioning
m_Container.style.left = m_Container.layout.xMin;
m_Container.style.right = float.NaN;
float newWidth = Mathf.Max(0f, m_ResizeBeginLayout.width + relativeMousePosition.x);
m_ResizeTarget.style.width = newWidth;
if (maintainAspectRatio)
{
m_ResizeTarget.style.height = newWidth;
}
mouseMoveEvent.StopPropagation();
}
void HandleResizeFromBottomRight(MouseMoveEvent mouseMoveEvent)
{
if (!m_Dragging)
return;
Vector2 relativeMousePosition = mouseMoveEvent.mousePosition - m_ResizeBeginMousePosition;
// Set anchor points for positioning
m_Container.style.top = m_Container.layout.yMin;
m_Container.style.bottom = float.NaN;
m_Container.style.left = m_Container.layout.xMin;
m_Container.style.right = float.NaN;
float newWidth = Mathf.Max(0f, m_ResizeBeginLayout.width + relativeMousePosition.x);
float newHeight = Mathf.Max(0f, m_ResizeBeginLayout.height + relativeMousePosition.y);
if (maintainAspectRatio)
newWidth = newHeight = Mathf.Min(newWidth, newHeight);
m_ResizeTarget.style.width = newWidth;
m_ResizeTarget.style.height = newHeight;
mouseMoveEvent.StopPropagation();
}
void HandleResizeFromBottom(MouseMoveEvent mouseMoveEvent)
{
if (!m_Dragging)
return;
Vector2 relativeMousePosition = mouseMoveEvent.mousePosition - m_ResizeBeginMousePosition;
// Set anchor points for positioning
m_Container.style.top = m_Container.layout.yMin;
m_Container.style.bottom = float.NaN;
float newHeight = Mathf.Max(0f, m_ResizeBeginLayout.height + relativeMousePosition.y);
m_ResizeTarget.style.height = newHeight;
if (maintainAspectRatio)
m_ResizeTarget.style.width = newHeight;
mouseMoveEvent.StopPropagation();
}
void HandleResizeFromBottomLeft(MouseMoveEvent mouseMoveEvent)
{
if (!m_Dragging)
return;
Vector2 relativeMousePosition = mouseMoveEvent.mousePosition - m_ResizeBeginMousePosition;
// Set anchor points for positioning
m_Container.style.top = m_Container.layout.yMin;
m_Container.style.bottom = float.NaN;
m_Container.style.left = float.NaN;
m_Container.style.right = m_Container.parent.layout.width - m_Container.layout.xMax;
float newWidth = Mathf.Max(0f, m_ResizeBeginLayout.width - relativeMousePosition.x);
float newHeight = Mathf.Max(0f, m_ResizeBeginLayout.height + relativeMousePosition.y);
if (maintainAspectRatio)
newWidth = newHeight = Mathf.Min(newWidth, newHeight);
m_ResizeTarget.style.width = newWidth;
m_ResizeTarget.style.height = newHeight;
mouseMoveEvent.StopPropagation();
}
void HandleResizeFromLeft(MouseMoveEvent mouseMoveEvent)
{
if (!m_Dragging)
return;
Vector2 relativeMousePosition = mouseMoveEvent.mousePosition - m_ResizeBeginMousePosition;
// Set anchor points for positioning
m_Container.style.left = float.NaN;
m_Container.style.right = m_Container.parent.layout.width - m_Container.layout.xMax;
float newWidth = Mathf.Max(0f, m_ResizeBeginLayout.width - relativeMousePosition.x);
m_ResizeTarget.style.width = newWidth;
if (maintainAspectRatio)
m_ResizeTarget.style.height = newWidth;
mouseMoveEvent.StopPropagation();
}
void HandleResizeFromTopLeft(MouseMoveEvent mouseMoveEvent)
{
if (!m_Dragging)
return;
Vector2 relativeMousePosition = mouseMoveEvent.mousePosition - m_ResizeBeginMousePosition;
// Set anchor points for positioning
m_Container.style.top = float.NaN;
m_Container.style.bottom = m_Container.parent.layout.height - m_Container.layout.yMax;
m_Container.style.left = float.NaN;
m_Container.style.right = m_Container.parent.layout.width - m_Container.layout.xMax;
float newWidth = Mathf.Max(0f, m_ResizeBeginLayout.width - relativeMousePosition.x);
float newHeight = Mathf.Max(0f, m_ResizeBeginLayout.height - relativeMousePosition.y);
if (maintainAspectRatio)
newWidth = newHeight = Mathf.Min(newWidth, newHeight);
m_ResizeTarget.style.width = newWidth;
m_ResizeTarget.style.height = newHeight;
mouseMoveEvent.StopPropagation();
}
void HandleMouseDown(MouseDownEvent mouseDownEvent)
{
// Get the docking settings for the window, as well as the
// layout and mouse position when resize begins.
m_WindowDockingLayout.CalculateDockingCornerAndOffset(m_Container.layout, m_Container.parent.layout);
m_WindowDockingLayout.ApplyPosition(m_Container);
m_ResizeBeginLayout = m_ResizeTarget.layout;
m_ResizeBeginMousePosition = mouseDownEvent.mousePosition;
m_Dragging = true;
this.CaptureMouse();
mouseDownEvent.StopPropagation();
}
void HandleDraggableMouseUp(MouseUpEvent mouseUpEvent)
{
m_Dragging = false;
if (this.HasMouseCapture())
this.ReleaseMouse();
if (OnResizeFinished != null)
OnResizeFinished();
m_WindowDockingLayout.CalculateDockingCornerAndOffset(m_Container.layout, m_Container.parent.layout);
m_WindowDockingLayout.ApplyPosition(m_Container);
}
protected override void ImmediateRepaint()
{
if (m_StyleWidget == null)
{
m_StyleWidget = new GUIStyle("WindowBottomResize") { fixedHeight = 0 };
image = m_StyleWidget.normal.background;
}
if (image == null)
{
Debug.LogWarning("null texture passed to GUI.DrawTexture");
return;
}
GUI.DrawTexture(contentRect, image, ScaleMode.ScaleAndCrop, true, 0, GUI.color, 0, 0);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Reflection;
using System.Threading;
using log4net;
namespace OpenSim.Framework.Monitoring
{
/// <summary>
/// Manages various work items in the simulator.
/// </summary>
/// <remarks>
/// Currently, here work can be started
/// * As a long-running and monitored thread.
/// * In a thread that will never timeout but where the job is expected to eventually complete.
/// * In a threadpool thread that will timeout if it takes a very long time to complete (> 10 mins).
/// * As a job which will be run in a single-threaded job engine. Such jobs must not incorporate delays (sleeps,
/// network waits, etc.).
///
/// This is an evolving approach to better manage the work that OpenSimulator is asked to do from a very diverse
/// range of sources (client actions, incoming network, outgoing network calls, etc.).
///
/// Util.FireAndForget is still available to insert jobs in the threadpool, though this is equivalent to
/// WorkManager.RunInThreadPool().
/// </remarks>
public static class WorkManager
{
private static readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public static JobEngine JobEngine { get; private set; }
static WorkManager()
{
JobEngine = new JobEngine("Non-blocking non-critical job engine", "JOB ENGINE");
StatsManager.RegisterStat(
new Stat(
"JobsWaiting",
"Number of jobs waiting for processing.",
"",
"",
"server",
"jobengine",
StatType.Pull,
MeasuresOfInterest.None,
stat => stat.Value = JobEngine.JobsWaiting,
StatVerbosity.Debug));
MainConsole.Instance.Commands.AddCommand(
"Debug",
false,
"debug jobengine",
"debug jobengine <start|stop|status|log>",
"Start, stop, get status or set logging level of the job engine.",
"If stopped then all outstanding jobs are processed immediately.",
HandleControlCommand);
}
public static void Stop()
{
JobEngine.Stop();
Watchdog.Stop();
}
/// <summary>
/// Start a new long-lived thread.
/// </summary>
/// <param name="start">The method that will be executed in a new thread</param>
/// <param name="name">A name to give to the new thread</param>
/// <param name="priority">Priority to run the thread at</param>
/// <param name="isBackground">True to run this thread as a background thread, otherwise false</param>
/// <param name="alarmIfTimeout">Trigger an alarm function is we have timed out</param>
/// <param name="log">If true then creation of thread is logged.</param>
/// <returns>The newly created Thread object</returns>
public static Thread StartThread(
ThreadStart start, string name, ThreadPriority priority, bool isBackground, bool alarmIfTimeout, bool log = true)
{
return StartThread(start, name, priority, isBackground, alarmIfTimeout, null, Watchdog.DEFAULT_WATCHDOG_TIMEOUT_MS, log);
}
/// <summary>
/// Start a new thread that is tracked by the watchdog
/// </summary>
/// <param name="start">The method that will be executed in a new thread</param>
/// <param name="name">A name to give to the new thread</param>
/// <param name="priority">Priority to run the thread at</param>
/// <param name="isBackground">True to run this thread as a background
/// thread, otherwise false</param>
/// <param name="alarmIfTimeout">Trigger an alarm function is we have timed out</param>
/// <param name="alarmMethod">
/// Alarm method to call if alarmIfTimeout is true and there is a timeout.
/// Normally, this will just return some useful debugging information.
/// </param>
/// <param name="timeout">Number of milliseconds to wait until we issue a warning about timeout.</param>
/// <param name="log">If true then creation of thread is logged.</param>
/// <returns>The newly created Thread object</returns>
public static Thread StartThread(
ThreadStart start, string name, ThreadPriority priority, bool isBackground,
bool alarmIfTimeout, Func<string> alarmMethod, int timeout, bool log = true)
{
Thread thread = new Thread(start);
thread.Priority = priority;
thread.IsBackground = isBackground;
thread.Name = name;
Watchdog.ThreadWatchdogInfo twi
= new Watchdog.ThreadWatchdogInfo(thread, timeout, name)
{ AlarmIfTimeout = alarmIfTimeout, AlarmMethod = alarmMethod };
Watchdog.AddThread(twi, name, log:log);
thread.Start();
return thread;
}
/// <summary>
/// Run the callback in a new thread immediately. If the thread exits with an exception log it but do
/// not propogate it.
/// </summary>
/// <param name="callback">Code for the thread to execute.</param>
/// <param name="obj">Object to pass to the thread.</param>
/// <param name="name">Name of the thread</param>
public static void RunInThread(WaitCallback callback, object obj, string name, bool log = false)
{
if (Util.FireAndForgetMethod == FireAndForgetMethod.RegressionTest)
{
Culture.SetCurrentCulture();
callback(obj);
return;
}
ThreadStart ts = new ThreadStart(delegate()
{
try
{
Culture.SetCurrentCulture();
callback(obj);
Watchdog.RemoveThread(log:false);
}
catch (Exception e)
{
m_log.Error(string.Format("[WATCHDOG]: Exception in thread {0}.", name), e);
}
});
StartThread(ts, name, ThreadPriority.Normal, true, false, log:log);
}
/// <summary>
/// Run the callback via a threadpool thread.
/// </summary>
/// <remarks>
/// Such jobs may run after some delay but must always complete.
/// </remarks>
/// <param name="callback"></param>
/// <param name="obj"></param>
/// <param name="name">The name of the job. This is used in monitoring and debugging.</param>
public static void RunInThreadPool(System.Threading.WaitCallback callback, object obj, string name)
{
Util.FireAndForget(callback, obj, name);
}
/// <summary>
/// Run a job.
/// </summary>
/// <remarks>
/// This differs from direct scheduling (e.g. Util.FireAndForget) in that a job can be run in the job
/// engine if it is running, where all jobs are currently performed in sequence on a single thread. This is
/// to prevent observed overload and server freeze problems when there are hundreds of connections which all attempt to
/// perform work at once (e.g. in conference situations). With lower numbers of connections, the small
/// delay in performing jobs in sequence rather than concurrently has not been notiecable in testing, though a future more
/// sophisticated implementation could perform jobs concurrently when the server is under low load.
///
/// However, be advised that some callers of this function rely on all jobs being performed in sequence if any
/// jobs are performed in sequence (i.e. if jobengine is active or not). Therefore, expanding the jobengine
/// beyond a single thread will require considerable thought.
///
/// Also, any jobs submitted must be guaranteed to complete within a reasonable timeframe (e.g. they cannot
/// incorporate a network delay with a long timeout). At the moment, work that could suffer such issues
/// should still be run directly with RunInThread(), Util.FireAndForget(), etc. This is another area where
/// the job engine could be improved and so CPU utilization improved by better management of concurrency within
/// OpenSimulator.
/// </remarks>
/// <param name="jobType">General classification for the job (e.g. "RezAttachments").</param>
/// <param name="callback">Callback for job.</param>
/// <param name="obj">Object to pass to callback when run</param>
/// <param name="name">Specific name of job (e.g. "RezAttachments for Joe Bloggs"</param>
/// <param name="canRunInThisThread">If set to true then the job may be run in ths calling thread.</param>
/// <param name="mustNotTimeout">If the true then the job must never timeout.</param>
/// <param name="log">If set to true then extra logging is performed.</param>
public static void RunJob(
string jobType, WaitCallback callback, object obj, string name,
bool canRunInThisThread = false, bool mustNotTimeout = false,
bool log = false)
{
if (Util.FireAndForgetMethod == FireAndForgetMethod.RegressionTest)
{
Culture.SetCurrentCulture();
callback(obj);
return;
}
if (JobEngine.IsRunning)
JobEngine.QueueJob(name, () => callback(obj));
else if (canRunInThisThread)
callback(obj);
else if (mustNotTimeout)
RunInThread(callback, obj, name, log);
else
Util.FireAndForget(callback, obj, name);
}
private static void HandleControlCommand(string module, string[] args)
{
// if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene)
// return;
if (args.Length < 3)
{
MainConsole.Instance.Output("Usage: debug jobengine <stop|start|status|log>");
return;
}
string subCommand = args[2];
if (subCommand == "stop")
{
JobEngine.Stop();
MainConsole.Instance.OutputFormat("Stopped job engine.");
}
else if (subCommand == "start")
{
JobEngine.Start();
MainConsole.Instance.OutputFormat("Started job engine.");
}
else if (subCommand == "status")
{
MainConsole.Instance.OutputFormat("Job engine running: {0}", JobEngine.IsRunning);
JobEngine.Job job = JobEngine.CurrentJob;
MainConsole.Instance.OutputFormat("Current job {0}", job != null ? job.Name : "none");
MainConsole.Instance.OutputFormat(
"Jobs waiting: {0}", JobEngine.IsRunning ? JobEngine.JobsWaiting.ToString() : "n/a");
MainConsole.Instance.OutputFormat("Log Level: {0}", JobEngine.LogLevel);
}
else if (subCommand == "log")
{
if (args.Length < 4)
{
MainConsole.Instance.Output("Usage: debug jobengine log <level>");
return;
}
// int logLevel;
int logLevel = int.Parse(args[3]);
// if (ConsoleUtil.TryParseConsoleInt(MainConsole.Instance, args[4], out logLevel))
// {
JobEngine.LogLevel = logLevel;
MainConsole.Instance.OutputFormat("Set debug log level to {0}", JobEngine.LogLevel);
// }
}
else
{
MainConsole.Instance.OutputFormat("Unrecognized job engine subcommand {0}", subCommand);
}
}
}
}
| |
using System;
using System.Text;
using System.Collections.Generic;
namespace duct {
/**
Base Variable types.
0x1 through 0x80 are reserved types.
*/
[Flags]
public enum VariableType : uint {
/**
#IntVariable.
*/
INTEGER=0x1,
/**
#StringVariable.
*/
STRING=0x2,
/**
#FloatVariable.
*/
FLOAT=0x4,
/**
#BoolVariable.
*/
BOOL=0x8,
/**
Reserved type 0x10.
*/
_RESERVED0=0x10,
/**
Reserved type 0x20.
*/
_RESERVED1=0x20,
/**
#Identifier.
*/
IDENTIFIER=0x40,
/**
#Node.
*/
NODE=0x80,
/**
No variable type.
Special variable type (means 'no variable type'). Alias for 0x0 (no flags).
@see ANY.
*/
NONE=0x0,
/**
Special value for variable searching.
Means "any variable type".
*/
ANY=0xFFFFFFFF,
/**
Special type for ValueVariables.
*/
VALUE=INTEGER|STRING|FLOAT|BOOL,
/**
Special type for CollectionVariables.
*/
COLLECTION=IDENTIFIER|NODE
};
/**
Variable value/name format.
Formatting flags for Variable names and ValueVariable values.
*/
[Flags]
public enum ValueFormat {
/**
Value quote-always format flag.
This flag is for any variable type. The output will always have quotes around it.
*/
VALUE_QUOTE_ALWAYS=0x01,
/**
String quote-whitespace format flag.
This format will quote a string containing whitespace or linefeed/carriage-return characters. e.g. "foo bar\\t" -> "\\"foo bar\\t\\"".
*/
STRING_QUOTE_WHITESPACE=0x10,
/**
String quote-empty format flag.
This format will quote an empty string. e.g. "" -> "\\"\\"".
*/
STRING_QUOTE_EMPTY=0x20,
/**
String quote-control format flag.
This format will quote a string containing the following characters: '{', '}', '='.
*/
STRING_QUOTE_CONTROL=0x40,
/**
String quote-always format flag.
This format will always quote any string.
*/
STRING_QUOTE_ALWAYS=0x80,
/**
String quote-bool format flag.
This format will quote a string if it equals "true" or "false" as a type safeguard. e.g. "true" -> "\\"true\\"".
*/
STRING_SAFE_BOOL=0x0100,
/**
String quote-number format flag.
This format will quote a string if it is a number as a type safeguard. e.g. "1234.5678" -> "\\"1234.5678\\"".
*/
STRING_SAFE_NUMBER=0x0200,
/**
String escape-newline format flag.
This format will replace the following characters with escape sequences, if the string is not surrounded in quotes: '\\n' '\\r'
*/
STRING_ESCAPE_NEWLINE=0x1000,
/**
String escape-control format flag.
This format will replace the following characters with escape sequences, if the string is not surrounded in quotes: '{', '}', '='.
*/
STRING_ESCAPE_CONTROL=0x2000,
/**
String escape-other format flag.
This format will replace the following characters with escape sequences: '\\t', '\\"', '\\'.
*/
STRING_ESCAPE_OTHER=0x4000,
/**
String escape-all format flag.
Consists of #STRING_ESCAPE_NEWLINE, #STRING_ESCAPE_CONTROL and #STRING_ESCAPE_OTHER.
*/
STRING_ESCAPE_ALL=STRING_ESCAPE_NEWLINE|STRING_ESCAPE_CONTROL|STRING_ESCAPE_OTHER,
/**
String safe format flag.
Consists of #STRING_SAFE_BOOL, #STRING_SAFE_NUMBER, #STRING_ESCAPE_OTHER and #STRING_QUOTE_CONTROL.
*/
STRING_SAFE=STRING_SAFE_BOOL|STRING_SAFE_NUMBER|STRING_ESCAPE_OTHER|STRING_QUOTE_CONTROL,
/**
Default string format flag.
Consists of #STRING_SAFE, #STRING_QUOTE_WHITESPACE and #STRING_QUOTE_EMPTY.
*/
STRING_DEFAULT=STRING_SAFE|STRING_QUOTE_WHITESPACE|STRING_QUOTE_EMPTY,
/**
Boolean quote format flag.
Converts the boolean value to a string ("true", "false"). e.g. false -> "false", true -> "true".
*/
BOOL_QUOTE=0x010000,
/**
Default boolean format flag.
Unset flag (no formatting).
*/
BOOL_DEFAULT=NONE,
/**
Default name format flag.
Consists of #STRING_SAFE, #STRING_QUOTE_WHITESPACE and #STRING_QUOTE_EMPTY.
*/
NAME_DEFAULT=STRING_SAFE|STRING_QUOTE_WHITESPACE|STRING_QUOTE_EMPTY,
/**
Default int format flag.
Unset flag (no formatting).
*/
INTEGER_DEFAULT=NONE,
/**
Default float format flag.
Unset flag (no formatting).
*/
FLOAT_DEFAULT=NONE,
/**
Default format flag for any variable.
Consists of all default format flags: #STRING_DEFAULT, #FLOAT_DEFAULT, #BOOL_DEFAULT and #INTEGER_DEFAULT.
*/
ALL_DEFAULT=STRING_DEFAULT|FLOAT_DEFAULT|BOOL_DEFAULT|INTEGER_DEFAULT,
/**
No-format flag.
*/
NONE=0
};
/**
Variable class.
*/
public abstract class Variable {
protected string _name=String.Empty;
public string Name {
set { _name=value; }
get { return _name; }
}
public string GetNameFormatted() {
return GetNameFormatted(ValueFormat.NAME_DEFAULT);
}
public string GetNameFormatted(ValueFormat format) {
string str;
if ((format&ValueFormat.VALUE_QUOTE_ALWAYS)!=0)
str=String.Format("\"{0}\"", _name);
else if ((format&ValueFormat.STRING_QUOTE_EMPTY)!=0 && String.IsNullOrEmpty(_name))
return "\"\"";
else if ((format&ValueFormat.STRING_QUOTE_WHITESPACE)!=0 && (!String.IsNullOrEmpty(_name) && (_name.IndexOf('\t')>-1 || _name.IndexOf(' ')>-1 || _name.IndexOf('\n')>-1)))
str=String.Format("\"{0}\"", _name);
else if ((format&ValueFormat.STRING_QUOTE_CONTROL)!=0 && (_name.IndexOf(CHAR_OPENBRACE)>-1 || _name.IndexOf(CHAR_CLOSEBRACE)>-1 || _name.IndexOf(CHAR_EQUALSIGN)>-1))
str=String.Format("\"{0}\"", _name);
else
str=_name;
return EscapeString(str, format);
}
protected CollectionVariable _parent;
public CollectionVariable Parent {
set { _parent=value; }
get { return _parent; }
}
public abstract VariableType Type {get;}
public abstract string TypeName {get;}
public abstract Variable Clone();
public static int VariableToBool(Variable source) {
if (source!=null) {
if (source.Type==VariableType.BOOL) {
return ((BoolVariable)source).Value ? 1 : 0;
} else if (source.Type==VariableType.STRING) {
string str=((StringVariable)source).Value;
if (String.Compare(str, "true", true)==0 || str.CompareTo("1")==0) {
return 1;
} else if (String.Compare(str, "false", true)==0 || str.CompareTo("0")==0) {
return 0;
}
} else if (source.Type==VariableType.INTEGER) {
int val=((IntVariable)source).Value;
if (val==1)
return 1;
else if (val==0)
return 0;
}
}
return -1;
}
public static int StringToBool(string source) {
if (source!=String.Empty) {
if (String.Compare(source, "true", true)==0 || source.CompareTo("1")==0) {
return 1;
} else if (String.Compare(source, "false", true)==0 || source.CompareTo("0")==0) {
return 0;
}
}
return -1;
}
public static ValueVariable StringToValue(string source, VariableType type) {
return StringToValue(source, "", type);
}
public static ValueVariable StringToValue(string source) {
return StringToValue(source, "");
}
public static ValueVariable StringToValue(string source, string varname) {
return StringToValue(source, varname, VariableType.NONE);
}
public static ValueVariable StringToValue(string source, string varname, VariableType type) {
if (String.IsNullOrEmpty(source))
return new StringVariable(source, varname, null);
if (type==VariableType.NONE) {
for (int i=0; i<source.Length; ++i) {
char c=source[i];
if ((c>='0' && c<='9') || c=='+' || c=='-') {
if (type==VariableType.NONE) { // Leave float and string alone
type=VariableType.INTEGER; // Integer so far..
}
} else if (c=='.') {
if (type==VariableType.INTEGER || type==VariableType.NONE) {
type=VariableType.FLOAT;
} else if (type==VariableType.FLOAT) {
type=VariableType.STRING; // Float cannot have more than one decimal point, so the source must be a string
break;
}
} else { // If the character is not numerical there is nothing else to deduce and the value is a string
type=VariableType.STRING;
break;
}
}
}
ValueVariable v;
switch (type) {
case VariableType.INTEGER:
v=new IntVariable(0, varname);
break;
case VariableType.FLOAT:
v=new FloatVariable(0.0f, varname, null);
break;
case VariableType.BOOL:
v=new BoolVariable(false, varname, null);
break;
default: // NOTE: VariableType.STRING results the same as an unrecognized variable type
int b=StringToBool(source);
if (b>-1)
return new BoolVariable(b==1, varname, null);
else
return new StringVariable(source, varname, null);
}
v.SetFromString(source);
return v;
}
public const char CHAR_EOF='\xFFFF';
public const char CHAR_NEWLINE='\n';
public const char CHAR_CARRIAGERETURN='\r';
public const char CHAR_TAB='\t';
public const char CHAR_N='n';
public const char CHAR_R='r';
public const char CHAR_T='t';
public const char CHAR_APOSTROPHE='\'';
public const char CHAR_QUOTE='\"';
public const char CHAR_BACKSLASH='\\';
public const char CHAR_OPENBRACE='{';
public const char CHAR_CLOSEBRACE='}';
public const char CHAR_EQUALSIGN='=';
public static char GetEscapeChar(char c) {
switch (c) {
case CHAR_N:
return CHAR_NEWLINE;
case CHAR_R:
return CHAR_CARRIAGERETURN;
case CHAR_T:
return CHAR_TAB;
case CHAR_APOSTROPHE:
case CHAR_QUOTE:
case CHAR_BACKSLASH:
case CHAR_OPENBRACE:
case CHAR_CLOSEBRACE:
case CHAR_EQUALSIGN:
return c;
default:
return CHAR_EOF;
}
}
public static string EscapeString(string str) {
return EscapeString(str, ValueFormat.STRING_ESCAPE_OTHER);
}
public static string EscapeString(string str, ValueFormat format) {
if (String.IsNullOrEmpty(str)
|| ((format&ValueFormat.STRING_ESCAPE_OTHER)==0
&& (format&ValueFormat.STRING_ESCAPE_CONTROL)==0
&& (format&ValueFormat.STRING_ESCAPE_NEWLINE)==0)) {
return str;
}
bool isquoted=(str.Length>=2 && str[0]=='\"' && str[str.Length-1]=='\"' && !str.EndsWith("\\\""));
StringBuilder builder=new StringBuilder(str.Length+32);
for (int i=0; i<str.Length; ++i) {
char c=str[i];
if ((format&ValueFormat.STRING_ESCAPE_OTHER)!=0) {
switch (c) {
case CHAR_TAB:
if (!isquoted)
builder.Append("\\t");
else
builder.Append(c);
continue;
case CHAR_QUOTE:
if (/*!isquoted && */(i>0 && i<(str.Length-1)))
builder.Append("\\\"");
else
builder.Append(CHAR_QUOTE);
continue;
case CHAR_BACKSLASH:
if ((i+1)!=str.Length) {
char c2=GetEscapeChar(str[i+1]);
switch (c2) {
case CHAR_BACKSLASH:
i++; // we don't want to see the slash again; the continue below makes the i-uppage 2
goto case CHAR_EOF;
case CHAR_EOF:
builder.Append("\\\\");
break;
default:
builder.Append('\\'+c2);
i++; // already a valid escape sequence
break;
}
} else {
builder.Append("\\\\");
}
continue;
}
}
if ((format&ValueFormat.STRING_ESCAPE_CONTROL)!=0 && !isquoted) {
switch (c) {
case CHAR_OPENBRACE:
builder.Append("\\{");
continue;
case CHAR_CLOSEBRACE:
builder.Append("\\}");
continue;
case CHAR_EQUALSIGN:
builder.Append("\\=");
continue;
}
}
if ((format&ValueFormat.STRING_ESCAPE_NEWLINE)!=0 && !isquoted) {
switch (c) {
case CHAR_NEWLINE:
builder.Append("\\n");
continue;
case CHAR_CARRIAGERETURN:
builder.Append("\\r");
continue;
}
}
builder.Append(c);
}
return builder.ToString();
}
}
public abstract class ValueVariable : Variable {
public abstract void SetFromString(string source);
public virtual string GetValueFormatted() {
return GetValueFormatted(ValueFormat.ALL_DEFAULT);
}
public abstract string GetValueFormatted(ValueFormat format);
public abstract string ValueAsString();
}
public abstract class CollectionVariable : Variable {
protected List<Variable> _children=new List<Variable>();
public List<Variable> Children {
get { return _children; }
}
public int Count {
get { return _children.Count; }
}
public List<Variable>.Enumerator GetEnumerator() {
return _children.GetEnumerator();
}
public void Clear() {
_children.Clear();
}
public bool Add(Variable variable) {
if (variable!=null) {
_children.Add(variable);
variable.Parent=this;
return true;
}
return false;
}
public bool Insert(int index, Variable variable) {
try {
_children.Insert(index, variable);
variable.Parent=this;
return true;
} catch (ArgumentOutOfRangeException) {
}
return false;
}
public bool InsertAfter(Variable variable, Variable after) {
int index=_children.IndexOf(after);
if (index!=-1) {
return Insert(index, variable);
}
return false;
}
public bool Remove(int i) {
try {
Variable variable=_children[i];
return Remove(variable);
} catch (ArgumentOutOfRangeException) {
return false;
}
}
public bool Remove(Variable variable) {
if (_children.Remove(variable)) {
variable.Parent=null;
return true;
}
return false;
}
public bool Remove(VariableType type) {
foreach (Variable v in _children) {
if ((v.Type&type)==v.Type) {
return Remove(v);
}
}
return false;
}
public bool Remove(string name) {
return Remove(name, true);
}
public bool Remove(string name, bool casesens) {
return Remove(name, casesens, VariableType.ANY);
}
public bool Remove(string name, bool casesens, VariableType type) {
foreach (Variable v in _children) {
if (String.Compare(v.Name, name, !casesens)==0 && (type&v.Type)==v.Type) {
return Remove(v);
}
}
return false;
}
public Variable Get(string name) {
return Get(name, true);
}
public Variable Get(string name, bool casesens) {
return Get(name, casesens, VariableType.ANY);
}
public Variable Get(string name, bool casesens, VariableType type) {
foreach (Variable v in _children) {
if (String.Compare(v.Name, name, !casesens)==0 && (type&v.Type)==v.Type)
return v;
}
return null;
}
public Variable Get(int index) {
if (index>-1 && index<_children.Count) {
try {
return _children[index];
} catch {
return null;
}
}
return null;
}
public IntVariable GetInt(string name) {
return GetInt(name, true);
}
public IntVariable GetInt(string name, bool casesens) {
Variable v=Get(name, casesens, VariableType.INTEGER);
return (IntVariable)v;
}
public IntVariable GetInt(int index) {
Variable variable=Get(index);
if (variable is IntVariable)
return (IntVariable)variable;
return null;
}
public StringVariable GetString(string name) {
return GetString(name, true);
}
public StringVariable GetString(string name, bool casesens) {
Variable v=Get(name, casesens, VariableType.STRING);
return (StringVariable)v;
}
public StringVariable GetString(int index) {
Variable variable=Get(index);
if (variable is StringVariable)
return (StringVariable)variable;
return null;
}
public FloatVariable GetFloat(string name) {
return GetFloat(name, true);
}
public FloatVariable GetFloat(string name, bool casesens) {
Variable v=Get(name, casesens, VariableType.FLOAT);
return (FloatVariable)v;
}
public FloatVariable GetFloat(int index) {
Variable variable=Get(index);
if (variable is FloatVariable)
return (FloatVariable)variable;
return null;
}
public BoolVariable GetBool(string name) {
return GetBool(name, true);
}
public BoolVariable GetBool(string name, bool casesens) {
Variable v=Get(name, casesens, VariableType.BOOL);
return (BoolVariable)v;
}
public BoolVariable GetBool(int index) {
Variable variable=Get(index);
if (variable is BoolVariable)
return (BoolVariable)variable;
return null;
}
public string GetAsString(int index) {
Variable variable=Get(index);
if (variable is ValueVariable)
return ((ValueVariable)variable).ValueAsString();
return null; // TODO: return null?
}
public Identifier GetIdentifier(string name) {
return GetIdentifier(name, true);
}
public Identifier GetIdentifier(string name, bool casesens) {
Variable v=Get(name, casesens, VariableType.IDENTIFIER);
return (Identifier)v;
}
public Identifier GetIdentifier(int index) {
Variable variable=Get(index);
if (variable is Identifier)
return (Identifier)variable;
return null;
}
public Node GetNode(string name) {
return GetNode(name, true);
}
public Node GetNode(string name, bool casesens) {
Variable v=Get(name, casesens, VariableType.NODE);
return (Node)v;
}
public Node GetNode(int index) {
Variable variable=Get(index);
if (variable is Node)
return (Node)variable;
return null;
}
}
public class IntVariable : ValueVariable {
int _value;
public int Value {
set { _value=value; }
get { return _value; }
}
public IntVariable() : this(0) {
}
public IntVariable(int val) : this(val, String.Empty) {
}
public IntVariable(int val, string name) : this(val, name, null) {
}
public IntVariable(int val, string name, CollectionVariable parent) {
_value=val;
_name=name;
_parent=parent;
}
public IntVariable(int val, CollectionVariable parent) : this(val, String.Empty, parent) {
}
public override void SetFromString(string source) {
if (!Int32.TryParse(source, out _value))
_value=0;
}
public override string GetValueFormatted(ValueFormat format) {
if ((format&ValueFormat.VALUE_QUOTE_ALWAYS)!=0) {
return String.Format("\"{0}\"", _value);
}
return _value.ToString();
}
public override string ValueAsString() {
return _value.ToString();
}
public override VariableType Type {
get { return VariableType.INTEGER; }
}
public override string TypeName {
get { return "int"; }
}
public override Variable Clone() {
return new IntVariable(_value, _name);
}
}
public class StringVariable : ValueVariable {
string _value;
public string Value {
set { _value=value; }
get { return _value; }
}
public StringVariable() : this(String.Empty) {
}
public StringVariable(string val) : this(val, String.Empty) {
}
public StringVariable(string val, string name) : this(val, name, null) {
}
public StringVariable(string val, string name, CollectionVariable parent) {
_value=val;
_name=name;
_parent=parent;
}
public StringVariable(string val, CollectionVariable parent) : this(val, String.Empty, parent) {
}
public bool isNumeric() {
return isNumeric(true);
}
public bool isNumeric(bool allowdecimal) {
if (allowdecimal) {
double tmp;
return Double.TryParse(_value, out tmp);
} else {
long tmp;
return Int64.TryParse(_value, out tmp);
}
}
public override void SetFromString(string source) {
_value=source;
}
public override string GetValueFormatted(ValueFormat format) {
string str;
if ((format&ValueFormat.VALUE_QUOTE_ALWAYS)!=0 || (format&ValueFormat.STRING_QUOTE_ALWAYS)!=0)
str=String.Format("\"{0}\"", _value);
else if ((format&ValueFormat.STRING_QUOTE_EMPTY)!=0 && String.IsNullOrEmpty(_value))
return "\"\"";
else if ((format&ValueFormat.STRING_QUOTE_WHITESPACE)!=0 && (!String.IsNullOrEmpty(_value) && (_value.IndexOf('\t')>-1 || _value.IndexOf(' ')>-1 || _value.IndexOf('\n')>-1)))
str=String.Format("\"{0}\"", _value);
else if ((format&ValueFormat.STRING_SAFE_BOOL)!=0 && Variable.VariableToBool(this)!=-1)
str=String.Format("\"{0}\"", _value);
else if ((format&ValueFormat.STRING_SAFE_NUMBER)!=0 && isNumeric(true))
str=String.Format("\"{0}\"", _value);
else if ((format&ValueFormat.STRING_QUOTE_CONTROL)!=0 && (_value.IndexOf(CHAR_OPENBRACE)>-1 || _value.IndexOf(CHAR_CLOSEBRACE)>-1 || _value.IndexOf(CHAR_EQUALSIGN)>-1))
str=String.Format("\"{0}\"", _value);
else
str=_value;
return Variable.EscapeString(str, format);
}
public override string ValueAsString() {
return _value;
}
public override VariableType Type {
get { return VariableType.STRING; }
}
public override string TypeName {
get { return "string"; }
}
public override Variable Clone() {
return new StringVariable(_value, _name);
}
}
public class FloatVariable : ValueVariable {
float _value;
public float Value {
set { _value=value; }
get { return _value; }
}
public FloatVariable() : this(0.0f) {
}
public FloatVariable(float val) : this(val, String.Empty) {
}
public FloatVariable(float val, string name) : this(val, name, null) {
}
public FloatVariable(float val, string name, CollectionVariable parent) {
_value=val;
_name=name;
_parent=parent;
}
public FloatVariable(float val, CollectionVariable parent) : this(val, String.Empty, parent) {
}
public override void SetFromString(string source) {
if (!Single.TryParse(source, out _value))
_value=0.0f;
}
public override string GetValueFormatted(ValueFormat format) {
if ((format&ValueFormat.VALUE_QUOTE_ALWAYS)!=0)
return String.Format("\"{0:0.0###}\"", _value);
return _value.ToString("0.0###");
}
public override string ValueAsString() {
return _value.ToString("0.0###");
}
public override VariableType Type {
get { return VariableType.FLOAT; }
}
public override string TypeName {
get { return "float"; }
}
public override Variable Clone() {
return new FloatVariable(_value, _name);
}
}
public class BoolVariable : ValueVariable {
bool _value;
public bool Value {
set { _value=value; }
get { return _value; }
}
public BoolVariable() : this(false) {
}
public BoolVariable(bool val) : this(val, String.Empty) {
}
public BoolVariable(bool val, string name) : this(val, name, null) {
}
public BoolVariable(bool val, string name, CollectionVariable parent) {
_value=val;
_name=name;
_parent=parent;
}
public BoolVariable(bool val, CollectionVariable parent) : this(val, String.Empty, parent) {
}
public override void SetFromString(string source) {
if (String.Compare(source, "true", true)==0 || source.CompareTo("1")==0)
_value=true;
else
_value=false;
}
public override string GetValueFormatted(ValueFormat format) {
if ((format&ValueFormat.VALUE_QUOTE_ALWAYS)!=0 || (format&ValueFormat.BOOL_QUOTE)!=0)
return _value ? "\"true\"" : "\"false\"";
return _value ? "true" : "false";
}
public override string ValueAsString() {
return _value ? "true" : "false";
}
public override VariableType Type {
get { return VariableType.BOOL; }
}
public override string TypeName {
get { return "bool"; }
}
public override Variable Clone() {
return new BoolVariable(_value, _name);
}
}
public class Identifier : CollectionVariable {
public Identifier() : this("") {
}
public Identifier(string name) : this(name, null) {
}
public Identifier(string name, CollectionVariable parent) {
_name=name;
_parent=parent;
}
public Identifier(CollectionVariable parent) : this("", parent) {
}
public override VariableType Type {
get { return VariableType.IDENTIFIER; }
}
public override string TypeName {
get { return "identifier"; }
}
public override Variable Clone() {
Identifier clone=new Identifier(_name);
foreach (Variable v in _children)
clone.Add(v.Clone());
return clone;
}
}
public class Node : CollectionVariable {
public Node() : this(String.Empty) {
}
public Node(string name) : this(name, null) {
}
public Node(string name, CollectionVariable parent) {
_name=name;
_parent=parent;
}
public Node(CollectionVariable parent) : this(String.Empty, parent) {
}
public override VariableType Type {
get { return VariableType.NODE; }
}
public override string TypeName {
get { return "node"; }
}
public override Variable Clone() {
Node clone=new Node(_name);
foreach (Variable v in _children)
clone.Add(v.Clone());
return clone;
}
}
} // namespace duct
| |
// 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;
class r8NaNdiv
{
//user-defined class that overloads operator /
public class numHolder
{
double d_num;
public numHolder(double d_num)
{
this.d_num = Convert.ToDouble(d_num);
}
public static double operator /(numHolder a, double b)
{
return a.d_num / b;
}
public static double operator /(numHolder a, numHolder b)
{
return a.d_num / b.d_num;
}
}
static double d_s_test1_op1 = Double.NaN;
static double d_s_test1_op2 = Double.NaN;
static double d_s_test2_op1 = 5.12345678F;
static double d_s_test2_op2 = Double.NaN;
static double d_s_test3_op1 = Double.NaN;
static double d_s_test3_op2 = 0;
public static double d_test1_f(String s)
{
if (s == "test1_op1")
return Double.NaN;
else
return Double.NaN;
}
public static double d_test2_f(String s)
{
if (s == "test2_op1")
return 5.12345678F;
else
return Double.NaN;
}
public static double d_test3_f(String s)
{
if (s == "test3_op1")
return Double.NaN;
else
return 0;
}
class CL
{
public double d_cl_test1_op1 = Double.NaN;
public double d_cl_test1_op2 = Double.NaN;
public double d_cl_test2_op1 = 5.12345678F;
public double d_cl_test2_op2 = Double.NaN;
public double d_cl_test3_op1 = Double.NaN;
public double d_cl_test3_op2 = 0;
}
struct VT
{
public double d_vt_test1_op1;
public double d_vt_test1_op2;
public double d_vt_test2_op1;
public double d_vt_test2_op2;
public double d_vt_test3_op1;
public double d_vt_test3_op2;
}
public static int Main()
{
bool passed = true;
//initialize class
CL cl1 = new CL();
//initialize struct
VT vt1;
vt1.d_vt_test1_op1 = Double.NaN;
vt1.d_vt_test1_op2 = Double.NaN;
vt1.d_vt_test2_op1 = 5.12345678F;
vt1.d_vt_test2_op2 = Double.NaN;
vt1.d_vt_test3_op1 = Double.NaN;
vt1.d_vt_test3_op2 = 0;
double[] d_arr1d_test1_op1 = { 0, Double.NaN };
double[,] d_arr2d_test1_op1 = { { 0, Double.NaN }, { 1, 1 } };
double[, ,] d_arr3d_test1_op1 = { { { 0, Double.NaN }, { 1, 1 } } };
double[] d_arr1d_test1_op2 = { Double.NaN, 0, 1 };
double[,] d_arr2d_test1_op2 = { { 0, Double.NaN }, { 1, 1 } };
double[, ,] d_arr3d_test1_op2 = { { { 0, Double.NaN }, { 1, 1 } } };
double[] d_arr1d_test2_op1 = { 0, 5.12345678F };
double[,] d_arr2d_test2_op1 = { { 0, 5.12345678F }, { 1, 1 } };
double[, ,] d_arr3d_test2_op1 = { { { 0, 5.12345678F }, { 1, 1 } } };
double[] d_arr1d_test2_op2 = { Double.NaN, 0, 1 };
double[,] d_arr2d_test2_op2 = { { 0, Double.NaN }, { 1, 1 } };
double[, ,] d_arr3d_test2_op2 = { { { 0, Double.NaN }, { 1, 1 } } };
double[] d_arr1d_test3_op1 = { 0, Double.NaN };
double[,] d_arr2d_test3_op1 = { { 0, Double.NaN }, { 1, 1 } };
double[, ,] d_arr3d_test3_op1 = { { { 0, Double.NaN }, { 1, 1 } } };
double[] d_arr1d_test3_op2 = { 0, 0, 1 };
double[,] d_arr2d_test3_op2 = { { 0, 0 }, { 1, 1 } };
double[, ,] d_arr3d_test3_op2 = { { { 0, 0 }, { 1, 1 } } };
int[,] index = { { 0, 0 }, { 1, 1 } };
{
double d_l_test1_op1 = Double.NaN;
double d_l_test1_op2 = Double.NaN;
if (!Double.IsNaN(d_l_test1_op1 / d_l_test1_op2))
{
Console.WriteLine("Test1_testcase 1 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test1_op1 / d_s_test1_op2))
{
Console.WriteLine("Test1_testcase 2 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test1_op1 / d_test1_f("test1_op2")))
{
Console.WriteLine("Test1_testcase 3 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test1_op1 / cl1.d_cl_test1_op2))
{
Console.WriteLine("Test1_testcase 4 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test1_op1 / vt1.d_vt_test1_op2))
{
Console.WriteLine("Test1_testcase 5 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test1_op1 / d_arr1d_test1_op2[0]))
{
Console.WriteLine("Test1_testcase 6 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test1_op1 / d_arr2d_test1_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test1_testcase 7 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test1_op1 / d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test1_testcase 8 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test1_op1 / d_l_test1_op2))
{
Console.WriteLine("Test1_testcase 9 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test1_op1 / d_s_test1_op2))
{
Console.WriteLine("Test1_testcase 10 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test1_op1 / d_test1_f("test1_op2")))
{
Console.WriteLine("Test1_testcase 11 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test1_op1 / cl1.d_cl_test1_op2))
{
Console.WriteLine("Test1_testcase 12 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test1_op1 / vt1.d_vt_test1_op2))
{
Console.WriteLine("Test1_testcase 13 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test1_op1 / d_arr1d_test1_op2[0]))
{
Console.WriteLine("Test1_testcase 14 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test1_op1 / d_arr2d_test1_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test1_testcase 15 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test1_op1 / d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test1_testcase 16 failed");
passed = false;
}
if (!Double.IsNaN(d_test1_f("test1_op1") / d_l_test1_op2))
{
Console.WriteLine("Test1_testcase 17 failed");
passed = false;
}
if (!Double.IsNaN(d_test1_f("test1_op1") / d_s_test1_op2))
{
Console.WriteLine("Test1_testcase 18 failed");
passed = false;
}
if (!Double.IsNaN(d_test1_f("test1_op1") / d_test1_f("test1_op2")))
{
Console.WriteLine("Test1_testcase 19 failed");
passed = false;
}
if (!Double.IsNaN(d_test1_f("test1_op1") / cl1.d_cl_test1_op2))
{
Console.WriteLine("Test1_testcase 20 failed");
passed = false;
}
if (!Double.IsNaN(d_test1_f("test1_op1") / vt1.d_vt_test1_op2))
{
Console.WriteLine("Test1_testcase 21 failed");
passed = false;
}
if (!Double.IsNaN(d_test1_f("test1_op1") / d_arr1d_test1_op2[0]))
{
Console.WriteLine("Test1_testcase 22 failed");
passed = false;
}
if (!Double.IsNaN(d_test1_f("test1_op1") / d_arr2d_test1_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test1_testcase 23 failed");
passed = false;
}
if (!Double.IsNaN(d_test1_f("test1_op1") / d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test1_testcase 24 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test1_op1 / d_l_test1_op2))
{
Console.WriteLine("Test1_testcase 25 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test1_op1 / d_s_test1_op2))
{
Console.WriteLine("Test1_testcase 26 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test1_op1 / d_test1_f("test1_op2")))
{
Console.WriteLine("Test1_testcase 27 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test1_op1 / cl1.d_cl_test1_op2))
{
Console.WriteLine("Test1_testcase 28 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test1_op1 / vt1.d_vt_test1_op2))
{
Console.WriteLine("Test1_testcase 29 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test1_op1 / d_arr1d_test1_op2[0]))
{
Console.WriteLine("Test1_testcase 30 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test1_op1 / d_arr2d_test1_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test1_testcase 31 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test1_op1 / d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test1_testcase 32 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test1_op1 / d_l_test1_op2))
{
Console.WriteLine("Test1_testcase 33 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test1_op1 / d_s_test1_op2))
{
Console.WriteLine("Test1_testcase 34 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test1_op1 / d_test1_f("test1_op2")))
{
Console.WriteLine("Test1_testcase 35 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test1_op1 / cl1.d_cl_test1_op2))
{
Console.WriteLine("Test1_testcase 36 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test1_op1 / vt1.d_vt_test1_op2))
{
Console.WriteLine("Test1_testcase 37 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test1_op1 / d_arr1d_test1_op2[0]))
{
Console.WriteLine("Test1_testcase 38 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test1_op1 / d_arr2d_test1_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test1_testcase 39 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test1_op1 / d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test1_testcase 40 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test1_op1[1] / d_l_test1_op2))
{
Console.WriteLine("Test1_testcase 41 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test1_op1[1] / d_s_test1_op2))
{
Console.WriteLine("Test1_testcase 42 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test1_op1[1] / d_test1_f("test1_op2")))
{
Console.WriteLine("Test1_testcase 43 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test1_op1[1] / cl1.d_cl_test1_op2))
{
Console.WriteLine("Test1_testcase 44 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test1_op1[1] / vt1.d_vt_test1_op2))
{
Console.WriteLine("Test1_testcase 45 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test1_op1[1] / d_arr1d_test1_op2[0]))
{
Console.WriteLine("Test1_testcase 46 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test1_op1[1] / d_arr2d_test1_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test1_testcase 47 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test1_op1[1] / d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test1_testcase 48 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] / d_l_test1_op2))
{
Console.WriteLine("Test1_testcase 49 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] / d_s_test1_op2))
{
Console.WriteLine("Test1_testcase 50 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] / d_test1_f("test1_op2")))
{
Console.WriteLine("Test1_testcase 51 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] / cl1.d_cl_test1_op2))
{
Console.WriteLine("Test1_testcase 52 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] / vt1.d_vt_test1_op2))
{
Console.WriteLine("Test1_testcase 53 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] / d_arr1d_test1_op2[0]))
{
Console.WriteLine("Test1_testcase 54 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] / d_arr2d_test1_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test1_testcase 55 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] / d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test1_testcase 56 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] / d_l_test1_op2))
{
Console.WriteLine("Test1_testcase 57 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] / d_s_test1_op2))
{
Console.WriteLine("Test1_testcase 58 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] / d_test1_f("test1_op2")))
{
Console.WriteLine("Test1_testcase 59 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] / cl1.d_cl_test1_op2))
{
Console.WriteLine("Test1_testcase 60 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] / vt1.d_vt_test1_op2))
{
Console.WriteLine("Test1_testcase 61 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] / d_arr1d_test1_op2[0]))
{
Console.WriteLine("Test1_testcase 62 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] / d_arr2d_test1_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test1_testcase 63 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] / d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test1_testcase 64 failed");
passed = false;
}
}
{
double d_l_test2_op1 = 5.12345678F;
double d_l_test2_op2 = Double.NaN;
if (!Double.IsNaN(d_l_test2_op1 / d_l_test2_op2))
{
Console.WriteLine("Test2_testcase 1 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test2_op1 / d_s_test2_op2))
{
Console.WriteLine("Test2_testcase 2 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test2_op1 / d_test2_f("test2_op2")))
{
Console.WriteLine("Test2_testcase 3 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test2_op1 / cl1.d_cl_test2_op2))
{
Console.WriteLine("Test2_testcase 4 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test2_op1 / vt1.d_vt_test2_op2))
{
Console.WriteLine("Test2_testcase 5 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test2_op1 / d_arr1d_test2_op2[0]))
{
Console.WriteLine("Test2_testcase 6 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test2_op1 / d_arr2d_test2_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test2_testcase 7 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test2_op1 / d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test2_testcase 8 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test2_op1 / d_l_test2_op2))
{
Console.WriteLine("Test2_testcase 9 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test2_op1 / d_s_test2_op2))
{
Console.WriteLine("Test2_testcase 10 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test2_op1 / d_test2_f("test2_op2")))
{
Console.WriteLine("Test2_testcase 11 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test2_op1 / cl1.d_cl_test2_op2))
{
Console.WriteLine("Test2_testcase 12 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test2_op1 / vt1.d_vt_test2_op2))
{
Console.WriteLine("Test2_testcase 13 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test2_op1 / d_arr1d_test2_op2[0]))
{
Console.WriteLine("Test2_testcase 14 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test2_op1 / d_arr2d_test2_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test2_testcase 15 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test2_op1 / d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test2_testcase 16 failed");
passed = false;
}
if (!Double.IsNaN(d_test2_f("test2_op1") / d_l_test2_op2))
{
Console.WriteLine("Test2_testcase 17 failed");
passed = false;
}
if (!Double.IsNaN(d_test2_f("test2_op1") / d_s_test2_op2))
{
Console.WriteLine("Test2_testcase 18 failed");
passed = false;
}
if (!Double.IsNaN(d_test2_f("test2_op1") / d_test2_f("test2_op2")))
{
Console.WriteLine("Test2_testcase 19 failed");
passed = false;
}
if (!Double.IsNaN(d_test2_f("test2_op1") / cl1.d_cl_test2_op2))
{
Console.WriteLine("Test2_testcase 20 failed");
passed = false;
}
if (!Double.IsNaN(d_test2_f("test2_op1") / vt1.d_vt_test2_op2))
{
Console.WriteLine("Test2_testcase 21 failed");
passed = false;
}
if (!Double.IsNaN(d_test2_f("test2_op1") / d_arr1d_test2_op2[0]))
{
Console.WriteLine("Test2_testcase 22 failed");
passed = false;
}
if (!Double.IsNaN(d_test2_f("test2_op1") / d_arr2d_test2_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test2_testcase 23 failed");
passed = false;
}
if (!Double.IsNaN(d_test2_f("test2_op1") / d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test2_testcase 24 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test2_op1 / d_l_test2_op2))
{
Console.WriteLine("Test2_testcase 25 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test2_op1 / d_s_test2_op2))
{
Console.WriteLine("Test2_testcase 26 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test2_op1 / d_test2_f("test2_op2")))
{
Console.WriteLine("Test2_testcase 27 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test2_op1 / cl1.d_cl_test2_op2))
{
Console.WriteLine("Test2_testcase 28 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test2_op1 / vt1.d_vt_test2_op2))
{
Console.WriteLine("Test2_testcase 29 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test2_op1 / d_arr1d_test2_op2[0]))
{
Console.WriteLine("Test2_testcase 30 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test2_op1 / d_arr2d_test2_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test2_testcase 31 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test2_op1 / d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test2_testcase 32 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test2_op1 / d_l_test2_op2))
{
Console.WriteLine("Test2_testcase 33 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test2_op1 / d_s_test2_op2))
{
Console.WriteLine("Test2_testcase 34 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test2_op1 / d_test2_f("test2_op2")))
{
Console.WriteLine("Test2_testcase 35 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test2_op1 / cl1.d_cl_test2_op2))
{
Console.WriteLine("Test2_testcase 36 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test2_op1 / vt1.d_vt_test2_op2))
{
Console.WriteLine("Test2_testcase 37 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test2_op1 / d_arr1d_test2_op2[0]))
{
Console.WriteLine("Test2_testcase 38 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test2_op1 / d_arr2d_test2_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test2_testcase 39 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test2_op1 / d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test2_testcase 40 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test2_op1[1] / d_l_test2_op2))
{
Console.WriteLine("Test2_testcase 41 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test2_op1[1] / d_s_test2_op2))
{
Console.WriteLine("Test2_testcase 42 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test2_op1[1] / d_test2_f("test2_op2")))
{
Console.WriteLine("Test2_testcase 43 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test2_op1[1] / cl1.d_cl_test2_op2))
{
Console.WriteLine("Test2_testcase 44 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test2_op1[1] / vt1.d_vt_test2_op2))
{
Console.WriteLine("Test2_testcase 45 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test2_op1[1] / d_arr1d_test2_op2[0]))
{
Console.WriteLine("Test2_testcase 46 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test2_op1[1] / d_arr2d_test2_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test2_testcase 47 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test2_op1[1] / d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test2_testcase 48 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] / d_l_test2_op2))
{
Console.WriteLine("Test2_testcase 49 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] / d_s_test2_op2))
{
Console.WriteLine("Test2_testcase 50 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] / d_test2_f("test2_op2")))
{
Console.WriteLine("Test2_testcase 51 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] / cl1.d_cl_test2_op2))
{
Console.WriteLine("Test2_testcase 52 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] / vt1.d_vt_test2_op2))
{
Console.WriteLine("Test2_testcase 53 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] / d_arr1d_test2_op2[0]))
{
Console.WriteLine("Test2_testcase 54 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] / d_arr2d_test2_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test2_testcase 55 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] / d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test2_testcase 56 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] / d_l_test2_op2))
{
Console.WriteLine("Test2_testcase 57 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] / d_s_test2_op2))
{
Console.WriteLine("Test2_testcase 58 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] / d_test2_f("test2_op2")))
{
Console.WriteLine("Test2_testcase 59 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] / cl1.d_cl_test2_op2))
{
Console.WriteLine("Test2_testcase 60 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] / vt1.d_vt_test2_op2))
{
Console.WriteLine("Test2_testcase 61 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] / d_arr1d_test2_op2[0]))
{
Console.WriteLine("Test2_testcase 62 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] / d_arr2d_test2_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test2_testcase 63 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] / d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test2_testcase 64 failed");
passed = false;
}
}
{
double d_l_test3_op1 = Double.NaN;
double d_l_test3_op2 = 0;
if (!Double.IsNaN(d_l_test3_op1 / d_l_test3_op2))
{
Console.WriteLine("Test3_testcase 1 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test3_op1 / d_s_test3_op2))
{
Console.WriteLine("Test3_testcase 2 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test3_op1 / d_test3_f("test3_op2")))
{
Console.WriteLine("Test3_testcase 3 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test3_op1 / cl1.d_cl_test3_op2))
{
Console.WriteLine("Test3_testcase 4 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test3_op1 / vt1.d_vt_test3_op2))
{
Console.WriteLine("Test3_testcase 5 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test3_op1 / d_arr1d_test3_op2[0]))
{
Console.WriteLine("Test3_testcase 6 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test3_op1 / d_arr2d_test3_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test3_testcase 7 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test3_op1 / d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test3_testcase 8 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test3_op1 / d_l_test3_op2))
{
Console.WriteLine("Test3_testcase 9 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test3_op1 / d_s_test3_op2))
{
Console.WriteLine("Test3_testcase 10 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test3_op1 / d_test3_f("test3_op2")))
{
Console.WriteLine("Test3_testcase 11 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test3_op1 / cl1.d_cl_test3_op2))
{
Console.WriteLine("Test3_testcase 12 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test3_op1 / vt1.d_vt_test3_op2))
{
Console.WriteLine("Test3_testcase 13 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test3_op1 / d_arr1d_test3_op2[0]))
{
Console.WriteLine("Test3_testcase 14 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test3_op1 / d_arr2d_test3_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test3_testcase 15 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test3_op1 / d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test3_testcase 16 failed");
passed = false;
}
if (!Double.IsNaN(d_test3_f("test3_op1") / d_l_test3_op2))
{
Console.WriteLine("Test3_testcase 17 failed");
passed = false;
}
if (!Double.IsNaN(d_test3_f("test3_op1") / d_s_test3_op2))
{
Console.WriteLine("Test3_testcase 18 failed");
passed = false;
}
if (!Double.IsNaN(d_test3_f("test3_op1") / d_test3_f("test3_op2")))
{
Console.WriteLine("Test3_testcase 19 failed");
passed = false;
}
if (!Double.IsNaN(d_test3_f("test3_op1") / cl1.d_cl_test3_op2))
{
Console.WriteLine("Test3_testcase 20 failed");
passed = false;
}
if (!Double.IsNaN(d_test3_f("test3_op1") / vt1.d_vt_test3_op2))
{
Console.WriteLine("Test3_testcase 21 failed");
passed = false;
}
if (!Double.IsNaN(d_test3_f("test3_op1") / d_arr1d_test3_op2[0]))
{
Console.WriteLine("Test3_testcase 22 failed");
passed = false;
}
if (!Double.IsNaN(d_test3_f("test3_op1") / d_arr2d_test3_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test3_testcase 23 failed");
passed = false;
}
if (!Double.IsNaN(d_test3_f("test3_op1") / d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test3_testcase 24 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test3_op1 / d_l_test3_op2))
{
Console.WriteLine("Test3_testcase 25 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test3_op1 / d_s_test3_op2))
{
Console.WriteLine("Test3_testcase 26 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test3_op1 / d_test3_f("test3_op2")))
{
Console.WriteLine("Test3_testcase 27 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test3_op1 / cl1.d_cl_test3_op2))
{
Console.WriteLine("Test3_testcase 28 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test3_op1 / vt1.d_vt_test3_op2))
{
Console.WriteLine("Test3_testcase 29 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test3_op1 / d_arr1d_test3_op2[0]))
{
Console.WriteLine("Test3_testcase 30 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test3_op1 / d_arr2d_test3_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test3_testcase 31 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test3_op1 / d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test3_testcase 32 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test3_op1 / d_l_test3_op2))
{
Console.WriteLine("Test3_testcase 33 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test3_op1 / d_s_test3_op2))
{
Console.WriteLine("Test3_testcase 34 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test3_op1 / d_test3_f("test3_op2")))
{
Console.WriteLine("Test3_testcase 35 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test3_op1 / cl1.d_cl_test3_op2))
{
Console.WriteLine("Test3_testcase 36 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test3_op1 / vt1.d_vt_test3_op2))
{
Console.WriteLine("Test3_testcase 37 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test3_op1 / d_arr1d_test3_op2[0]))
{
Console.WriteLine("Test3_testcase 38 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test3_op1 / d_arr2d_test3_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test3_testcase 39 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test3_op1 / d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test3_testcase 40 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test3_op1[1] / d_l_test3_op2))
{
Console.WriteLine("Test3_testcase 41 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test3_op1[1] / d_s_test3_op2))
{
Console.WriteLine("Test3_testcase 42 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test3_op1[1] / d_test3_f("test3_op2")))
{
Console.WriteLine("Test3_testcase 43 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test3_op1[1] / cl1.d_cl_test3_op2))
{
Console.WriteLine("Test3_testcase 44 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test3_op1[1] / vt1.d_vt_test3_op2))
{
Console.WriteLine("Test3_testcase 45 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test3_op1[1] / d_arr1d_test3_op2[0]))
{
Console.WriteLine("Test3_testcase 46 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test3_op1[1] / d_arr2d_test3_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test3_testcase 47 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test3_op1[1] / d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test3_testcase 48 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] / d_l_test3_op2))
{
Console.WriteLine("Test3_testcase 49 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] / d_s_test3_op2))
{
Console.WriteLine("Test3_testcase 50 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] / d_test3_f("test3_op2")))
{
Console.WriteLine("Test3_testcase 51 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] / cl1.d_cl_test3_op2))
{
Console.WriteLine("Test3_testcase 52 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] / vt1.d_vt_test3_op2))
{
Console.WriteLine("Test3_testcase 53 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] / d_arr1d_test3_op2[0]))
{
Console.WriteLine("Test3_testcase 54 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] / d_arr2d_test3_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test3_testcase 55 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] / d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test3_testcase 56 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] / d_l_test3_op2))
{
Console.WriteLine("Test3_testcase 57 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] / d_s_test3_op2))
{
Console.WriteLine("Test3_testcase 58 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] / d_test3_f("test3_op2")))
{
Console.WriteLine("Test3_testcase 59 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] / cl1.d_cl_test3_op2))
{
Console.WriteLine("Test3_testcase 60 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] / vt1.d_vt_test3_op2))
{
Console.WriteLine("Test3_testcase 61 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] / d_arr1d_test3_op2[0]))
{
Console.WriteLine("Test3_testcase 62 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] / d_arr2d_test3_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test3_testcase 63 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] / d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test3_testcase 64 failed");
passed = false;
}
}
if (!passed)
{
Console.WriteLine("FAILED");
return 1;
}
else
{
Console.WriteLine("PASSED");
return 100;
}
}
}
| |
/***************************************************************************************************************************************
* Copyright (C) 2001-2012 LearnLift USA *
* Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, support@memorylifter.com *
* *
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License *
* as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty *
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, *
* write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************************************************************************/
// The following code was generated by Microsoft Visual Studio 2005.
// The generateQuestionThread owner should check each generateQuestionThread for validity.
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Text;
using System.Collections.Generic;
using MLifter.BusinessLayer;
using MLifterTest.BusinessLayer;
using MLifter.DAL.Interfaces;
using System.Diagnostics;
using MLifter.DAL;
using MLifterTest.DAL;
using System.IO;
using MLifter.Generics;
using System.Threading;
namespace MLifterTest.BusinessLayer
{
/// <summary>
///This is a generateQuestionThread class for MLifter.BusinessLayer.LearnLogic and is intended
///to contain all MLifter.BusinessLayer.LearnLogic Unit Tests
///</summary>
[TestClass()]
public class LearnLogicTest
{
private TestContext testContextInstance;
/// <summary>
///Gets or sets the generateQuestionThread context which provides
///information about and functionality for the current generateQuestionThread run.
///</summary>
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
#region Additional generateQuestionThread attributes
////
////You can use the following additional attributes as you write your tests:
////
////Use ClassInitialize to run code before running the first generateQuestionThread in the class
////
//[ClassInitialize()]
//public static void MyClassInitialize(TestContext testContext)
//{
// DictionaryTest.MyClassInitialize(testContext);
//}
////
////Use ClassCleanup to run code after all tests in a class have run
////
[ClassCleanup()]
public static void MyClassCleanup()
{
TestInfrastructure.MyClassCleanup();
}
//
//Use TestInitialize to run code before running each generateQuestionThread
//
//[TestInitialize()]
//public void MyTestInitialize()
//{
//}
//
//Use TestCleanup to run code after each generateQuestionThread has run
//
//[TestCleanup()]
//public void MyTestCleanup()
//{
//}
//
#endregion
private static Random random
{
get { return DictionaryTest.Random; }
}
private static bool GetRandBool()
{
return DictionaryTest.GetRandBool();
}
/// <summary>
/// Test the de-/promotion of a card.
/// </summary>
/// <remarks>Documented by Dev05, 2008-09-09</remarks>
[TestMethod]
[TestProperty("BL", "ChrFin"), DataSource("TestSources")]
public void GradeCardTest()
{
if (TestInfrastructure.IsActive(TestContext))
{
ConnectionStringStruct connectionString = TestInfrastructure.GetConnectionStringWithDummyData(TestContext);
LearnLogic llogic = new LearnLogic(OpenUserProfileTests.GetUserAdmin, (DataAccessErrorDelegate)delegate { return; });
//llogic.User.Authenticate((GetLoginInformation)MLifterTest.DAL.TestInfrastructure.GetTestUser,
// connectionString, (DataAccessErrorDelegate)delegate { return; });
try
{
llogic.OpenLearningModule(new LearningModulesIndexEntry(connectionString));
}
catch (IsOdxFormatException)
{
if (TestInfrastructure.ConnectionType(TestContext) == "File")
return;
else
throw;
}
llogic.OnLearningModuleOptionsChanged();
Card card = llogic.Dictionary.Cards.GetCardByID(llogic.CurrentCardID);
int oldBox = card.BaseCard.Box = 5;
UserInputSubmitEventArgs e = new UserInputSubmitTextEventArgs(0, card.CurrentAnswer.Words.Count, card.CurrentAnswer.Words.Count, true, card.CurrentAnswer.Words.ToString());
llogic.OnUserInputSubmit(this, e);
Assert.AreEqual<int>(oldBox + 1, card.BaseCard.Box, "Card was not correctly promoted!");
card.BaseCard.Box = oldBox;
e = new UserInputSubmitTextEventArgs(5, 0, 5, false, string.Empty);
llogic.OnUserInputSubmit(this, e);
Assert.AreEqual<int>(1, card.BaseCard.Box, "Card was not demoted!");
}
}
/// <summary>
/// Tests if the learn logic selects the correct learning mode based in the card content.
/// </summary>
/// <remarks>Documented by Dev03, 2008-09-12</remarks>
[TestMethod]
[TestProperty("BL", "AleAbe"), DataSource("TestSources")]
public void LearnLogicLearnModeTest()
{
if (TestInfrastructure.IsActive(TestContext))
{
ConnectionStringStruct connectionString = TestInfrastructure.GetConnectionStringWithDummyData(TestContext);
LearnLogic learnLogic = new LearnLogic(OpenUserProfileTests.GetUserAdmin, (DataAccessErrorDelegate)delegate { return; });
//learnLogic.User.Authenticate(OpenUserProfileTests.GetUserAdmin, connectionString, (DataAccessErrorDelegate)delegate { return; });
try
{
learnLogic.OpenLearningModule(new LearningModulesIndexEntry(connectionString));
}
catch (IsOdxFormatException)
{
if (TestInfrastructure.ConnectionType(TestContext) == "File") //success
return;
else
throw;
}
learnLogic.User.Dictionary.Settings.QueryTypes.ImageRecognition = true;
learnLogic.User.Dictionary.Settings.QueryTypes.ListeningComprehension = true;
learnLogic.User.Dictionary.Settings.QueryTypes.Sentence = true;
for (int i = 0; i < TestInfrastructure.LoopCount; i++)
{
learnLogic.OnLearningModuleOptionsChanged();
Card card = learnLogic.User.Dictionary.Cards.GetCardByID(learnLogic.CurrentCardID);
switch (learnLogic.User.Dictionary.LearnMode)
{
case LearnModes.ImageRecognition:
Assert.IsTrue(card.ContainsImage(Side.Question.ToString()), "Card must contain image for ImageRecognition mode.");
break;
case LearnModes.ListeningComprehension:
Assert.IsTrue(card.ContainsAudio(Side.Question.ToString()), "Card must contain audio for ListeningComprehension mode.");
break;
case LearnModes.Sentence:
Assert.IsTrue(card.CurrentQuestionExample.Words.Count > 0, "Card must contain example for Sentence mode.");
break;
default:
continue;
}
}
}
}
/// <summary>
/// Tests the doubles login.
/// </summary>
/// <remarks>Documented by Dev05, 2008-11-24</remarks>
[TestMethod]
[TestProperty("BL/DAL", "ChrFin"), DataSource("TestSources")]
[ExpectedException(typeof(DoubleLoginException), "The supposed Error 'DoubleLoginException' hasn't occurred!")]
public void DoubleLoginTest()
{
if (TestInfrastructure.IsActive(TestContext))
{
switch (TestInfrastructure.ConnectionType(TestContext))
{
case "File":
case "sqlce":
throw new DoubleLoginException();
default:
break;
}
ConnectionStringStruct connectionString = TestInfrastructure.GetConnectionString(TestContext);
LearnLogic learnLogic = new LearnLogic(OpenUserProfileTests.GetUserAdmin, (DataAccessErrorDelegate)delegate { return; });
learnLogic.User.Authenticate((GetLoginInformation)MLifterTest.DAL.TestInfrastructure.GetTestUser,
connectionString, (DataAccessErrorDelegate)delegate { return; });
//Doesn't throw the Exception because the UserFactory logs out the previous user
LearnLogic lLogic = new LearnLogic(OpenUserProfileTests.GetUserAdmin, (DataAccessErrorDelegate)delegate { return; });
lLogic.User.Authenticate((GetLoginInformation)GetLoginErrorMethod, connectionString, (DataAccessErrorDelegate)delegate { return; });
//Check instead if old user is logged out properly
if (!learnLogic.UserSessionAlive)
throw new DoubleLoginException();
}
else
{
throw new DoubleLoginException();
}
}
private static bool userSubmitted = false;
private UserStruct? GetLoginErrorMethod(UserStruct u, ConnectionStringStruct c)
{
if (!userSubmitted)
{
userSubmitted = true;
UserStruct user = MLifterTest.DAL.TestInfrastructure.GetTestUser(u, c).Value;
user.CloseOpenSessions = false;
return user;
}
LoginError err = u.LastLoginError;
if (err == LoginError.AlreadyLoggedIn)
throw new DoubleLoginException();
else
throw new Exception("The supposed Error 'AlreadyLoggedIn' hasn't occurred!");
}
private class DoubleLoginException : Exception { };
/// <summary>
/// Tests for exception thrown when opening null argument.
/// </summary>
/// <remarks>Documented by Dev09, 2009-03-05</remarks>
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void OpenLearningModuleNullTest()
{
LearnLogic llogic = new LearnLogic((GetLoginInformation)MLifterTest.DAL.TestInfrastructure.GetTestUser, (DataAccessErrorDelegate)delegate { return; });
llogic.OpenLearningModule(null);
}
/// <summary>
/// Tests for exception thrown when opening a file that does not exist.
/// </summary>
/// <remarks>Documented by Dev09, 2009-03-05</remarks>
[TestMethod]
[ExpectedException(typeof(FileNotFoundException))]
public void OpenLearningModuleFileNotFoundTest()
{
LearnLogic llogic = new LearnLogic((GetLoginInformation)MLifterTest.DAL.TestInfrastructure.GetTestUser, (DataAccessErrorDelegate)delegate { return; });
LearningModulesIndexEntry module = new LearningModulesIndexEntry();
module.ConnectionString = new ConnectionStringStruct(DatabaseType.Xml, "invalid");
llogic.OpenLearningModule(module);
}
/// <summary>
/// Runs a test for opening file types that throw exceptions.
/// </summary>
/// <param name="ext">The ext.</param>
/// <remarks>Documented by Dev09, 2009-03-05</remarks>
private void FileExtTestHelper(String ext)
{
// create temp file with desired extension
String filename = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + "." + ext);
File.Create(filename);
LearnLogic llogic = new LearnLogic((GetLoginInformation)MLifterTest.DAL.TestInfrastructure.GetTestUser, (DataAccessErrorDelegate)delegate { return; });
LearningModulesIndexEntry module = new LearningModulesIndexEntry();
module.ConnectionString = new ConnectionStringStruct(DatabaseType.Xml, filename);
llogic.OpenLearningModule(module);
}
/// <summary>
/// Tests exception thrown for trying to open *.dip files.
/// </summary>
/// <remarks>Documented by Dev09, 2009-03-05</remarks>
[TestMethod]
[ExpectedException(typeof(DipNotSupportedException))]
public void OpenLearningModuleFileExtDipTest()
{
FileExtTestHelper("dip");
}
/// <summary>
/// Tests exception thrown for trying to open *.zip files.
/// </summary>
/// <remarks>Documented by Dev09, 2009-03-05</remarks>
[TestMethod]
[ExpectedException(typeof(NeedToUnPackException))]
public void OpenLearningModuleFileExtZipTest()
{
FileExtTestHelper("zip");
}
/// <summary>
/// Tests exception thrown for trying to open *.dzp files.
/// </summary>
/// <remarks>Documented by Dev09, 2009-03-05</remarks>
[TestMethod]
[ExpectedException(typeof(NeedToUnPackException))]
public void OpenLearningModuleFileExtDzpTest()
{
FileExtTestHelper("dzp");
}
/// <summary>
/// Tests exception thrown for trying to open *.odf files.
/// </summary>
/// <remarks>Documented by Dev09, 2009-03-05</remarks>
[TestMethod]
[ExpectedException(typeof(IsOdfFormatException))]
public void OpenLearningModuleFileExtOdfTest()
{
FileExtTestHelper("odf");
}
/// <summary>
/// Tests exception thrown for trying to open *.odx files.
/// </summary>
/// <remarks>Documented by Dev09, 2009-03-05</remarks>
[TestMethod]
[ExpectedException(typeof(IsOdxFormatException))]
public void OpenLearningModuleFileExtOdxTest()
{
FileExtTestHelper("odx");
}
/// <summary>
/// Tests exception thrown for trying to open files with a different extension than expected.
/// </summary>
/// <remarks>Documented by Dev09, 2009-03-05</remarks>
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void OpenLearningModuleFileExtOtherTest()
{
FileExtTestHelper("txt");
}
/// <summary>
/// Tests trying to close an open module to open another, when closing fails.
/// </summary>
/// <remarks>Documented by Dev09, 2009-03-05</remarks>
[TestMethod]
[TestProperty("BL/DAL", "ChrFin"), DataSource("TestSources")]
[ExpectedException(typeof(CouldNotCloseLearningModuleException))]
public void OpenLearningModuleCannotCloseTest()
{
if (TestInfrastructure.IsActive(TestContext) && TestInfrastructure.ConnectionType(TestContext).ToLower() != "file")
{
LearnLogic llogic = new LearnLogic((GetLoginInformation)MLifterTest.DAL.TestInfrastructure.GetTestUser, (DataAccessErrorDelegate)delegate { return; });
LearningModulesIndexEntry module = new LearningModulesIndexEntry();
module.ConnectionString = TestInfrastructure.GetConnectionStringWithDummyData(TestContext);
llogic.LearningModuleClosing += new LearnLogic.LearningModuleClosingEventHandler(llogic_LearningModuleClosing);
llogic.OpenLearningModule(module);
llogic.OpenLearningModule(module);
}
else
throw new CouldNotCloseLearningModuleException();
}
/// <summary>
/// Override LearningModuleClosing event to force it to fail.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="MLifter.BusinessLayer.LearningModuleClosingEventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev09, 2009-03-05</remarks>
void llogic_LearningModuleClosing(object sender, LearningModuleClosingEventArgs e)
{
e.Cancel = true;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="TemplateField.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.UI.WebControls {
using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Globalization;
/// <devdoc>
/// <para>Defines the template for controls layout within a
/// <see cref='System.Web.UI.WebControls.DataBoundControl'/>
/// field.</para>
/// </devdoc>
//
public class TemplateField : DataControlField {
private ITemplate headerTemplate;
private ITemplate footerTemplate;
private ITemplate itemTemplate;
private ITemplate editItemTemplate;
private ITemplate alternatingItemTemplate;
private ITemplate insertItemTemplate;
/// <devdoc>
/// Initializes a new instance of the <see cref='System.Web.UI.WebControls.TemplateField'/> class.
/// </devdoc>
public TemplateField() {
}
/// <devdoc>
/// <para>Specifies the <see cref='System.Web.UI.ITemplate' qualify='true'/> that defines how alternating items are rendered. </para>
/// </devdoc>
[
Browsable(false),
DefaultValue(null),
WebSysDescription(SR.TemplateField_AlternatingItemTemplate),
PersistenceMode(PersistenceMode.InnerProperty),
TemplateContainer(typeof(IDataItemContainer), BindingDirection.TwoWay)
]
public virtual ITemplate AlternatingItemTemplate {
get {
return alternatingItemTemplate;
}
set {
alternatingItemTemplate = value;
OnFieldChanged();
}
}
/// <summary>
/// Determines whether the control validates client input or not, defaults to inherit from parent.
/// </summary>
[
WebCategory("Behavior"),
WebSysDescription(SR.Control_ValidateRequestMode),
DefaultValue(ValidateRequestMode.Inherit)
]
public new ValidateRequestMode ValidateRequestMode {
get {
return base.ValidateRequestMode;
}
set {
base.ValidateRequestMode = value;
}
}
/// <devdoc>
/// <para>Gets or sets the property that determines whether the field treats empty string as
/// null when the field values are extracted.</para>
/// </devdoc>
[
WebCategory("Behavior"),
DefaultValue(true),
WebSysDescription(SR.ImageField_ConvertEmptyStringToNull)
]
public virtual bool ConvertEmptyStringToNull {
get {
object o = ViewState["ConvertEmptyStringToNull"];
if (o != null) {
return (bool)o;
}
return true;
}
set {
ViewState["ConvertEmptyStringToNull"] = value;
}
}
/// <devdoc>
/// <para>Specifies the <see cref='System.Web.UI.ITemplate' qualify='true'/> that defines how rows in edit mode are rendered. </para>
/// </devdoc>
[
Browsable(false),
DefaultValue(null),
WebSysDescription(SR.TemplateField_EditItemTemplate),
PersistenceMode(PersistenceMode.InnerProperty),
TemplateContainer(typeof(IDataItemContainer), BindingDirection.TwoWay)
]
public virtual ITemplate EditItemTemplate {
get {
return editItemTemplate;
}
set {
editItemTemplate = value;
OnFieldChanged();
}
}
/// <devdoc>
/// <para>Specifies the <see cref='System.Web.UI.ITemplate' qualify='true'/> that defines how the control footer is rendered. </para>
/// </devdoc>
[
Browsable(false),
DefaultValue(null),
WebSysDescription(SR.TemplateField_FooterTemplate),
PersistenceMode(PersistenceMode.InnerProperty),
TemplateContainer(typeof(IDataItemContainer))
]
public virtual ITemplate FooterTemplate {
get {
return footerTemplate;
}
set {
footerTemplate = value;
OnFieldChanged();
}
}
/// <devdoc>
/// <para>Specifies the <see cref='System.Web.UI.ITemplate' qualify='true'/>
/// that defines how the control header is rendered.</para>
/// </devdoc>
[
Browsable(false),
DefaultValue(null),
WebSysDescription(SR.TemplateField_HeaderTemplate),
PersistenceMode(PersistenceMode.InnerProperty),
TemplateContainer(typeof(IDataItemContainer))
]
public virtual ITemplate HeaderTemplate {
get {
return headerTemplate;
}
set {
headerTemplate = value;
OnFieldChanged();
}
}
/// <devdoc>
/// <para>Specifies the <see cref='System.Web.UI.ITemplate' qualify='true'/> that defines how rows in insert mode are rendered. </para>
/// </devdoc>
[
Browsable(false),
DefaultValue(null),
WebSysDescription(SR.TemplateField_InsertItemTemplate),
PersistenceMode(PersistenceMode.InnerProperty),
TemplateContainer(typeof(IDataItemContainer), BindingDirection.TwoWay)
]
public virtual ITemplate InsertItemTemplate {
get {
return insertItemTemplate;
}
set {
insertItemTemplate = value;
OnFieldChanged();
}
}
/// <devdoc>
/// <para> Specifies the <see cref='System.Web.UI.ITemplate' qualify='true'/> that defines how items are rendered. </para>
/// </devdoc>
[
Browsable(false),
DefaultValue(null),
WebSysDescription(SR.TemplateField_ItemTemplate),
PersistenceMode(PersistenceMode.InnerProperty),
TemplateContainer(typeof(IDataItemContainer), BindingDirection.TwoWay)
]
public virtual ITemplate ItemTemplate {
get {
return itemTemplate;
}
set {
itemTemplate = value;
OnFieldChanged();
}
}
protected override void CopyProperties(DataControlField newField) {
((TemplateField)newField).ConvertEmptyStringToNull = ConvertEmptyStringToNull;
((TemplateField)newField).AlternatingItemTemplate = AlternatingItemTemplate;
((TemplateField)newField).ItemTemplate = ItemTemplate;
((TemplateField)newField).FooterTemplate = FooterTemplate;
((TemplateField)newField).EditItemTemplate = EditItemTemplate;
((TemplateField)newField).HeaderTemplate = HeaderTemplate;
((TemplateField)newField).InsertItemTemplate = InsertItemTemplate;
base.CopyProperties(newField);
}
protected override DataControlField CreateField() {
return new TemplateField();
}
/// <devdoc>
/// Extracts the value(s) from the given cell and puts the value(s) into a dictionary. Indicate includeReadOnly
/// to have readonly fields' values inserted into the dictionary.
/// </devdoc>
public override void ExtractValuesFromCell(IOrderedDictionary dictionary, DataControlFieldCell cell, DataControlRowState rowState, bool includeReadOnly) {
DataBoundControlHelper.ExtractValuesFromBindableControls(dictionary, cell);
IBindableTemplate bindableTemplate = ItemTemplate as IBindableTemplate;
if (((rowState & DataControlRowState.Alternate) != 0) && (AlternatingItemTemplate != null)) {
bindableTemplate = AlternatingItemTemplate as IBindableTemplate;
}
if (((rowState & DataControlRowState.Edit) != 0) && EditItemTemplate != null) {
bindableTemplate = EditItemTemplate as IBindableTemplate;
}
else if ((rowState & DataControlRowState.Insert) != 0 && InsertVisible) {
if (InsertItemTemplate != null) {
bindableTemplate = InsertItemTemplate as IBindableTemplate;
}
else {
if (EditItemTemplate != null) {
bindableTemplate = EditItemTemplate as IBindableTemplate;
}
}
}
if (bindableTemplate != null) {
bool convertEmptyStringToNull = ConvertEmptyStringToNull;
foreach (DictionaryEntry entry in bindableTemplate.ExtractValues(cell.BindingContainer)) {
object value = entry.Value;
if (convertEmptyStringToNull && value is string && ((string)value).Length == 0) {
dictionary[entry.Key] = null;
}
else {
dictionary[entry.Key] = value;
}
}
}
return;
}
/// <internalonly/>
/// <devdoc>
/// </devdoc>
public override void InitializeCell(DataControlFieldCell cell, DataControlCellType cellType, DataControlRowState rowState, int rowIndex) {
base.InitializeCell(cell, cellType, rowState, rowIndex);
ITemplate contentTemplate = null;
switch (cellType) {
case DataControlCellType.Header:
contentTemplate = headerTemplate;
break;
case DataControlCellType.Footer:
contentTemplate = footerTemplate;
break;
case DataControlCellType.DataCell:
contentTemplate = itemTemplate;
if ((rowState & DataControlRowState.Edit) != 0) {
if (editItemTemplate != null) {
contentTemplate = editItemTemplate;
}
}
else if ((rowState & DataControlRowState.Insert) != 0) {
if (insertItemTemplate != null) {
contentTemplate = insertItemTemplate;
}
else {
if (editItemTemplate != null) {
contentTemplate = editItemTemplate;
}
}
}
else if ((rowState & DataControlRowState.Alternate) != 0) {
if (alternatingItemTemplate != null) {
contentTemplate = alternatingItemTemplate;
}
}
break;
}
if (contentTemplate != null) {
// The base class might have added a control or some text for some cases
// such as header text which need to be removed before
// the corresponding template is used.
// Note that setting text also has the effect of clearing out any controls.
cell.Text = String.Empty;
contentTemplate.InstantiateIn(cell);
}
else {
if (cellType == DataControlCellType.DataCell) {
cell.Text = " ";
}
}
}
/// <devdoc>
/// <para>Override with an empty body if the field's controls all support callback.
/// Otherwise, override and throw a useful error message about why the field can't support callbacks.</para>
/// </devdoc>
public override void ValidateSupportsCallback() {
throw new NotSupportedException(SR.GetString(SR.TemplateField_CallbacksNotSupported, Control.ID));
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="ByteCountingStream.cs" company="Microsoft">
// Copyright 2013 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-----------------------------------------------------------------------
namespace Microsoft.Azure.Storage.Core
{
using Microsoft.Azure.Storage.Core.Util;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Stream that will throw a <see cref="OperationCanceledException"/> if it has to wait longer than a configurable timeout to read or write more data
/// </summary>
internal class TimeoutStream : Stream
{
private readonly Stream wrappedStream;
private TimeSpan readTimeout;
private TimeSpan writeTimeout;
private CancellationTokenSource cancellationTokenSource;
public TimeoutStream(Stream wrappedStream, TimeSpan timeout)
: this(wrappedStream, timeout, timeout) { }
public TimeoutStream(Stream wrappedStream, TimeSpan readTimeout, TimeSpan writeTimeout)
{
CommonUtility.AssertNotNull("WrappedStream", wrappedStream);
CommonUtility.AssertNotNull("ReadTimeout", readTimeout);
CommonUtility.AssertNotNull("WriteTimeout", writeTimeout);
this.wrappedStream = wrappedStream;
this.readTimeout = readTimeout;
this.writeTimeout = writeTimeout;
this.UpdateReadTimeout();
this.UpdateWriteTimeout();
this.cancellationTokenSource = new CancellationTokenSource();
}
public override long Position
{
get { return this.wrappedStream.Position; }
set { this.wrappedStream.Position = value; }
}
public override long Length
{
get { return this.wrappedStream.Length; }
}
public override bool CanWrite
{
get { return this.wrappedStream.CanWrite; }
}
public override bool CanTimeout
{
get { return this.wrappedStream.CanTimeout; }
}
public override bool CanSeek
{
get { return this.wrappedStream.CanSeek; }
}
public override bool CanRead
{
get { return this.wrappedStream.CanRead; }
}
public override int ReadTimeout
{
get { return (int) this.readTimeout.TotalMilliseconds; }
set {
this.readTimeout = TimeSpan.FromMilliseconds(value);
this.UpdateReadTimeout();
}
}
public override int WriteTimeout
{
get { return (int) this.writeTimeout.TotalMilliseconds; }
set
{
this.writeTimeout = TimeSpan.FromMilliseconds(value);
this.UpdateWriteTimeout();
}
}
public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
return this.wrappedStream.CopyToAsync(destination, bufferSize, cancellationToken);
}
public override void Flush()
{
this.wrappedStream.Flush();
}
public override async Task FlushAsync(CancellationToken cancellationToken)
{
var source = StartTimeout(cancellationToken, out bool dispose);
try
{
await this.wrappedStream.FlushAsync(source.Token);
}
finally
{
StopTimeout(source, dispose);
}
}
public override int Read(byte[] buffer, int offset, int count)
{
return wrappedStream.Read(buffer, offset, count);
}
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
var source = StartTimeout(cancellationToken, out bool dispose);
try
{
return await this.wrappedStream.ReadAsync(buffer, offset, count, source.Token);
}
finally
{
StopTimeout(source, dispose);
}
}
public override int ReadByte()
{
return this.wrappedStream.ReadByte();
}
public override long Seek(long offset, SeekOrigin origin)
{
return this.wrappedStream.Seek(offset, origin);
}
public override void SetLength(long value)
{
this.wrappedStream.SetLength(value);
}
public override void Write(byte[] buffer, int offset, int count)
{
this.wrappedStream.Write(buffer, offset, count);
}
public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
var source = StartTimeout(cancellationToken, out bool dispose);
try
{
await this.wrappedStream.WriteAsync(buffer, offset, count, source.Token);
}
finally
{
StopTimeout(source, dispose);
}
}
public override void WriteByte(byte value)
{
this.wrappedStream.WriteByte(value);
}
private CancellationTokenSource StartTimeout(CancellationToken additionalToken, out bool dispose)
{
if (this.cancellationTokenSource.IsCancellationRequested)
{
this.cancellationTokenSource = new CancellationTokenSource();
}
CancellationTokenSource source;
if (additionalToken.CanBeCanceled)
{
source = CancellationTokenSource.CreateLinkedTokenSource(additionalToken, this.cancellationTokenSource.Token);
dispose = true;
}
else
{
source = this.cancellationTokenSource;
dispose = false;
}
this.cancellationTokenSource.CancelAfter(this.readTimeout);
return source;
}
private void StopTimeout(CancellationTokenSource source, bool dispose)
{
this.cancellationTokenSource.CancelAfter(Timeout.InfiniteTimeSpan);
if (dispose)
{
source.Dispose();
}
}
private void UpdateReadTimeout()
{
if (this.wrappedStream.CanTimeout && this.wrappedStream.CanRead)
{
try
{
this.wrappedStream.ReadTimeout = (int)this.readTimeout.TotalMilliseconds;
}
catch
{
// ignore
}
}
}
private void UpdateWriteTimeout()
{
if (this.wrappedStream.CanTimeout && this.wrappedStream.CanWrite)
{
try
{
this.wrappedStream.WriteTimeout = (int)this.writeTimeout.TotalMilliseconds;
}
catch
{
// ignore
}
}
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
this.cancellationTokenSource.Dispose();
this.wrappedStream.Dispose();
}
}
}
}
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
[assembly: Elmah.Scc("$Id: MemoryErrorLog.cs addb64b2f0fa 2012-03-07 18:50:16Z azizatif $")]
namespace Elmah
{
#region Imports
using System;
using ReaderWriterLock = System.Threading.ReaderWriterLock;
using Timeout = System.Threading.Timeout;
using NameObjectCollectionBase = System.Collections.Specialized.NameObjectCollectionBase;
using IList = System.Collections.IList;
using IDictionary = System.Collections.IDictionary;
using CultureInfo = System.Globalization.CultureInfo;
#endregion
/// <summary>
/// An <see cref="ErrorLog"/> implementation that uses memory as its
/// backing store.
/// </summary>
/// <remarks>
/// All <see cref="MemoryErrorLog"/> instances will share the same memory
/// store that is bound to the application (not an instance of this class).
/// </remarks>
public sealed class MemoryErrorLog : ErrorLog
{
//
// The collection that provides the actual storage for this log
// implementation and a lock to guarantee concurrency correctness.
//
private static EntryCollection _entries;
private readonly static ReaderWriterLock _lock = new ReaderWriterLock();
//
// IMPORTANT! The size must be the same for all instances
// for the entires collection to be intialized correctly.
//
private readonly int _size;
/// <summary>
/// The maximum number of errors that will ever be allowed to be stored
/// in memory.
/// </summary>
public static readonly int MaximumSize = 500;
/// <summary>
/// The maximum number of errors that will be held in memory by default
/// if no size is specified.
/// </summary>
public static readonly int DefaultSize = 15;
/// <summary>
/// Initializes a new instance of the <see cref="MemoryErrorLog"/> class
/// with a default size for maximum recordable entries.
/// </summary>
public MemoryErrorLog() : this(DefaultSize) {}
/// <summary>
/// Initializes a new instance of the <see cref="MemoryErrorLog"/> class
/// with a specific size for maximum recordable entries.
/// </summary>
public MemoryErrorLog(int size)
{
if (size < 0 || size > MaximumSize)
throw new ArgumentOutOfRangeException("size", size, string.Format("Size must be between 0 and {0}.", MaximumSize));
_size = size;
}
/// <summary>
/// Initializes a new instance of the <see cref="MemoryErrorLog"/> class
/// using a dictionary of configured settings.
/// </summary>
public MemoryErrorLog(IDictionary config)
{
if (config == null)
{
_size = DefaultSize;
}
else
{
string sizeString = Mask.NullString((string) config["size"]);
if (sizeString.Length == 0)
{
_size = DefaultSize;
}
else
{
_size = Convert.ToInt32(sizeString, CultureInfo.InvariantCulture);
_size = Math.Max(0, Math.Min(MaximumSize, _size));
}
}
}
/// <summary>
/// Gets the name of this error log implementation.
/// </summary>
public override string Name
{
get { return "In-Memory Error Log"; }
}
/// <summary>
/// Logs an error to the application memory.
/// </summary>
/// <remarks>
/// If the log is full then the oldest error entry is removed.
/// </remarks>
public override string Log(Error error)
{
if (error == null)
throw new ArgumentNullException("error");
//
// Make a copy of the error to log since the source is mutable.
// Assign a new GUID and create an entry for the error.
//
error = (Error) ((ICloneable) error).Clone();
error.ApplicationName = this.ApplicationName;
Guid newId = Guid.NewGuid();
ErrorLogEntry entry = new ErrorLogEntry(this, newId.ToString(), error);
_lock.AcquireWriterLock(Timeout.Infinite);
try
{
if (_entries == null)
_entries = new EntryCollection(_size);
_entries.Add(entry);
}
finally
{
_lock.ReleaseWriterLock();
}
return newId.ToString();
}
internal override void Delete(Guid id)
{
throw new NotImplementedException();
}
/// <summary>
/// Returns the specified error from application memory, or null
/// if it does not exist.
/// </summary>
public override ErrorLogEntry GetError(string id)
{
_lock.AcquireReaderLock(Timeout.Infinite);
ErrorLogEntry entry;
try
{
if (_entries == null)
return null;
entry = _entries[id];
}
finally
{
_lock.ReleaseReaderLock();
}
if (entry == null)
return null;
//
// Return a copy that the caller can party on.
//
Error error = (Error) ((ICloneable) entry.Error).Clone();
return new ErrorLogEntry(this, entry.Id, error);
}
public override int GetErrors(int pageIndex, int pageSize, string filter, IList errorEntryList)
{
throw new NotImplementedException();
}
/// <summary>
/// Returns a page of errors from the application memory in
/// descending order of logged time.
/// </summary>
public override int GetErrors(int pageIndex, int pageSize, IList errorEntryList)
{
if (pageIndex < 0)
throw new ArgumentOutOfRangeException("pageIndex", pageIndex, null);
if (pageSize < 0)
throw new ArgumentOutOfRangeException("pageSize", pageSize, null);
//
// To minimize the time for which we hold the lock, we'll first
// grab just references to the entries we need to return. Later,
// we'll make copies and return those to the caller. Since Error
// is mutable, we don't want to return direct references to our
// internal versions since someone could change their state.
//
ErrorLogEntry[] selectedEntries = null;
int totalCount;
_lock.AcquireReaderLock(Timeout.Infinite);
try
{
if (_entries == null)
return 0;
totalCount = _entries.Count;
int startIndex = pageIndex * pageSize;
int endIndex = Math.Min(startIndex + pageSize, totalCount);
int count = Math.Max(0, endIndex - startIndex);
if (count > 0)
{
selectedEntries = new ErrorLogEntry[count];
int sourceIndex = endIndex;
int targetIndex = 0;
while (sourceIndex > startIndex)
selectedEntries[targetIndex++] = _entries[--sourceIndex];
}
}
finally
{
_lock.ReleaseReaderLock();
}
if (errorEntryList != null && selectedEntries != null)
{
//
// Return copies of fetched entries. If the Error class would
// be immutable then this step wouldn't be necessary.
//
foreach (ErrorLogEntry entry in selectedEntries)
{
Error error = (Error)((ICloneable)entry.Error).Clone();
errorEntryList.Add(new ErrorLogEntry(this, entry.Id, error));
}
}
return totalCount;
}
private class EntryCollection : NameObjectCollectionBase
{
private readonly int _size;
public EntryCollection(int size) : base(size)
{
_size = size;
}
public ErrorLogEntry this[int index]
{
get { return (ErrorLogEntry) BaseGet(index); }
}
public ErrorLogEntry this[Guid id]
{
get { return (ErrorLogEntry) BaseGet(id.ToString()); }
}
public ErrorLogEntry this[string id]
{
get { return this[new Guid(id)]; }
}
public void Add(ErrorLogEntry entry)
{
Debug.Assert(entry != null);
Debug.AssertStringNotEmpty(entry.Id);
Debug.Assert(this.Count <= _size);
if (this.Count == _size)
BaseRemoveAt(0);
BaseAdd(entry.Id, entry);
}
}
}
}
| |
// This file was created automatically, do not modify the contents of this file.
// ReSharper disable InvalidXmlDocComment
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable MemberCanBePrivate.Global
using System;
using System.Runtime.InteropServices;
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\SkeletalMeshComponent.h:279
namespace UnrealEngine
{
[ManageType("ManageSkeletalMeshComponent")]
public partial class ManageSkeletalMeshComponent : USkeletalMeshComponent, IManageWrapper
{
public ManageSkeletalMeshComponent(IntPtr adress)
: base(adress)
{
}
#region DLLInmport
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_PrestreamTextures(IntPtr self, float seconds, bool bPrioritizeCharacterTextures, int cinematicTextureGroups);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_SetTextureForceResidentFlag(IntPtr self, bool bForceMiplevelsToBeResident);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_OnComponentCollisionSettingsChanged(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_PutAllRigidBodiesToSleep(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_SetAllMassScale(IntPtr self, float inMassScale);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_SetAllUseCCD(IntPtr self, bool inUseCCD);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_SetAngularDamping(IntPtr self, float inDamping);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_SetEnableGravity(IntPtr self, bool bGravityEnabled);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_SetLinearDamping(IntPtr self, float inDamping);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_SetNotifyRigidBodyCollision(IntPtr self, bool bNewNotifyRigidBodyCollision);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_SetSimulatePhysics(IntPtr self, bool bSimulate);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_UnWeldChildren(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_UnWeldFromParent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_UpdatePhysicsToRBChannels(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_WakeAllRigidBodies(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_DetachFromParent(IntPtr self, bool bMaintainWorldPosition, bool bCallModify);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_OnAttachmentChanged(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_OnHiddenInGameChanged(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_OnVisibilityChanged(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_PropagateLightingScenarioChange(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_UpdateBounds(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_UpdatePhysicsVolume(IntPtr self, bool bTriggerNotifiers);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_Activate(IntPtr self, bool bReset);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_BeginPlay(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_CreateRenderState_Concurrent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_Deactivate(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_DestroyComponent(IntPtr self, bool bPromoteChildren);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_DestroyRenderState_Concurrent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_InitializeComponent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_InvalidateLightingCacheDetailed(IntPtr self, bool bInvalidateBuildEnqueuedLighting, bool bTranslationOnly);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_OnActorEnableCollisionChanged(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_OnComponentCreated(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_OnComponentDestroyed(IntPtr self, bool bDestroyingHierarchy);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_OnCreatePhysicsState(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_OnDestroyPhysicsState(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_OnRegister(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_OnRep_IsActive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_OnUnregister(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_RegisterComponentTickFunctions(IntPtr self, bool bRegister);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_SendRenderDynamicData_Concurrent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_SendRenderTransform_Concurrent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_SetActive(IntPtr self, bool bNewActive, bool bReset);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_SetAutoActivate(IntPtr self, bool bNewAutoActivate);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_SetComponentTickEnabled(IntPtr self, bool bEnabled);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_SetComponentTickEnabledAsync(IntPtr self, bool bEnabled);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_ToggleActive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_UninitializeComponent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_BeginDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_FinishDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_MarkAsEditorOnlySubobject(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_PostCDOContruct(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_PostEditImport(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_PostInitProperties(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_PostLoad(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_PostNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_PostRepNotifies(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_PostSaveRoot(IntPtr self, bool bCleanupIsRequired);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_PreDestroyFromReplication(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_PreNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_ShutdownAfterError(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_CreateCluster(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USkeletalMeshComponent_OnClusterMarkedAsPendingKill(IntPtr self);
#endregion
#region Methods
/// <summary>
/// Tell the streaming system to start loading all textures with all mip-levels.
/// </summary>
/// <param name="seconds">Number of seconds to force all mip-levels to be resident</param>
/// <param name="bPrioritizeCharacterTextures">Whether character textures should be prioritized for a while by the streaming system</param>
/// <param name="cinematicTextureGroups">Bitfield indicating which texture groups that use extra high-resolution mips</param>
public override void PrestreamTextures(float seconds, bool bPrioritizeCharacterTextures, int cinematicTextureGroups)
=> E__Supper__USkeletalMeshComponent_PrestreamTextures(this, seconds, bPrioritizeCharacterTextures, cinematicTextureGroups);
/// <summary>
/// Tell the streaming system whether or not all mip levels of all textures used by this component should be loaded and remain loaded.
/// </summary>
/// <param name="bForceMiplevelsToBeResident">Whether textures should be forced to be resident or not.</param>
public override void SetTextureForceResidentFlag(bool bForceMiplevelsToBeResident)
=> E__Supper__USkeletalMeshComponent_SetTextureForceResidentFlag(this, bForceMiplevelsToBeResident);
/// <summary>
/// Called when the BodyInstance ResponseToChannels, CollisionEnabled or bNotifyRigidBodyCollision changes, in case subclasses want to use that information.
/// </summary>
protected override void OnComponentCollisionSettingsChanged()
=> E__Supper__USkeletalMeshComponent_OnComponentCollisionSettingsChanged(this);
/// <summary>
/// Force all bodies in this component to sleep.
/// </summary>
public override void PutAllRigidBodiesToSleep()
=> E__Supper__USkeletalMeshComponent_PutAllRigidBodiesToSleep(this);
/// <summary>
/// Change the mass scale used fo all bodies in this component
/// </summary>
public override void SetAllMassScale(float inMassScale)
=> E__Supper__USkeletalMeshComponent_SetAllMassScale(this, inMassScale);
/// <summary>
/// Set whether all bodies in this component should use Continuous Collision Detection
/// </summary>
public override void SetAllUseCCD(bool inUseCCD)
=> E__Supper__USkeletalMeshComponent_SetAllUseCCD(this, inUseCCD);
/// <summary>
/// Sets the angular damping of this component.
/// </summary>
public override void SetAngularDamping(float inDamping)
=> E__Supper__USkeletalMeshComponent_SetAngularDamping(this, inDamping);
/// <summary>
/// Enables/disables whether this component is affected by gravity. This applies only to components with bSimulatePhysics set to true.
/// </summary>
public override void SetEnableGravity(bool bGravityEnabled)
=> E__Supper__USkeletalMeshComponent_SetEnableGravity(this, bGravityEnabled);
/// <summary>
/// Sets the linear damping of this component.
/// </summary>
public override void SetLinearDamping(float inDamping)
=> E__Supper__USkeletalMeshComponent_SetLinearDamping(this, inDamping);
/// <summary>
/// Changes the value of bNotifyRigidBodyCollision
/// </summary>
public override void SetNotifyRigidBodyCollision(bool bNewNotifyRigidBodyCollision)
=> E__Supper__USkeletalMeshComponent_SetNotifyRigidBodyCollision(this, bNewNotifyRigidBodyCollision);
/// <summary>
/// Sets whether or not a single body should use physics simulation, or should be 'fixed' (kinematic).
/// <para>Note that if this component is currently attached to something, beginning simulation will detach it. </para>
/// </summary>
/// <param name="bSimulate">New simulation state for single body</param>
public override void SetSimulatePhysics(bool bSimulate)
=> E__Supper__USkeletalMeshComponent_SetSimulatePhysics(this, bSimulate);
/// <summary>
/// Unwelds the children of this component. Attachment is maintained
/// </summary>
public override void UnWeldChildren()
=> E__Supper__USkeletalMeshComponent_UnWeldChildren(this);
/// <summary>
/// UnWelds this component from its parent component. Attachment is maintained (DetachFromParent automatically unwelds)
/// </summary>
public override void UnWeldFromParent()
=> E__Supper__USkeletalMeshComponent_UnWeldFromParent(this);
/// <summary>
/// Internal function that updates physics objects to match the component collision settings.
/// </summary>
protected override void UpdatePhysicsToRBChannels()
=> E__Supper__USkeletalMeshComponent_UpdatePhysicsToRBChannels(this);
/// <summary>
/// Ensure simulation is running for all bodies in this component.
/// </summary>
public override void WakeAllRigidBodies()
=> E__Supper__USkeletalMeshComponent_WakeAllRigidBodies(this);
/// <summary>
/// DEPRECATED - Use DetachFromComponent() instead
/// </summary>
public override void DetachFromParentDeprecated(bool bMaintainWorldPosition, bool bCallModify)
=> E__Supper__USkeletalMeshComponent_DetachFromParent(this, bMaintainWorldPosition, bCallModify);
/// <summary>
/// Called when AttachParent changes, to allow the scene to update its attachment state.
/// </summary>
public override void OnAttachmentChanged()
=> E__Supper__USkeletalMeshComponent_OnAttachmentChanged(this);
/// <summary>
/// Overridable internal function to respond to changes in the hidden in game value of the component.
/// </summary>
protected override void OnHiddenInGameChanged()
=> E__Supper__USkeletalMeshComponent_OnHiddenInGameChanged(this);
/// <summary>
/// Overridable internal function to respond to changes in the visibility of the component.
/// </summary>
protected override void OnVisibilityChanged()
=> E__Supper__USkeletalMeshComponent_OnVisibilityChanged(this);
/// <summary>
/// Updates any visuals after the lighting has changed
/// </summary>
public override void PropagateLightingScenarioChange()
=> E__Supper__USkeletalMeshComponent_PropagateLightingScenarioChange(this);
/// <summary>
/// Update the Bounds of the component.
/// </summary>
public override void UpdateBounds()
=> E__Supper__USkeletalMeshComponent_UpdateBounds(this);
/// <summary>
/// Updates the PhysicsVolume of this SceneComponent, if bShouldUpdatePhysicsVolume is true.
/// </summary>
/// <param name="bTriggerNotifiers">if true, send zone/volume change events</param>
public override void UpdatePhysicsVolume(bool bTriggerNotifiers)
=> E__Supper__USkeletalMeshComponent_UpdatePhysicsVolume(this, bTriggerNotifiers);
/// <summary>
/// Activates the SceneComponent, should be overridden by native child classes.
/// </summary>
/// <param name="bReset">Whether the activation should happen even if ShouldActivate returns false.</param>
public override void Activate(bool bReset)
=> E__Supper__USkeletalMeshComponent_Activate(this, bReset);
/// <summary>
/// BeginsPlay for the component. Occurs at level startup or actor spawn. This is before BeginPlay (Actor or Component).
/// <para>All Components (that want initialization) in the level will be Initialized on load before any </para>
/// Actor/Component gets BeginPlay.
/// <para>Requires component to be registered and initialized. </para>
/// </summary>
public override void BeginPlay()
=> E__Supper__USkeletalMeshComponent_BeginPlay(this);
/// <summary>
/// Used to create any rendering thread information for this component
/// <para>@warning This is called concurrently on multiple threads (but never the same component concurrently) </para>
/// </summary>
protected override void CreateRenderState_Concurrent()
=> E__Supper__USkeletalMeshComponent_CreateRenderState_Concurrent(this);
/// <summary>
/// Deactivates the SceneComponent.
/// </summary>
public override void Deactivate()
=> E__Supper__USkeletalMeshComponent_Deactivate(this);
/// <summary>
/// Unregister the component, remove it from its outer Actor's Components array and mark for pending kill.
/// </summary>
public override void DestroyComponent(bool bPromoteChildren)
=> E__Supper__USkeletalMeshComponent_DestroyComponent(this, bPromoteChildren);
/// <summary>
/// Used to shut down any rendering thread structure for this component
/// <para>@warning This is called concurrently on multiple threads (but never the same component concurrently) </para>
/// </summary>
protected override void DestroyRenderState_Concurrent()
=> E__Supper__USkeletalMeshComponent_DestroyRenderState_Concurrent(this);
/// <summary>
/// Initializes the component. Occurs at level startup or actor spawn. This is before BeginPlay (Actor or Component).
/// <para>All Components in the level will be Initialized on load before any Actor/Component gets BeginPlay </para>
/// Requires component to be registered, and bWantsInitializeComponent to be true.
/// </summary>
public override void InitializeComponent()
=> E__Supper__USkeletalMeshComponent_InitializeComponent(this);
/// <summary>
/// Called when this actor component has moved, allowing it to discard statically cached lighting information.
/// </summary>
public override void InvalidateLightingCacheDetailed(bool bInvalidateBuildEnqueuedLighting, bool bTranslationOnly)
=> E__Supper__USkeletalMeshComponent_InvalidateLightingCacheDetailed(this, bInvalidateBuildEnqueuedLighting, bTranslationOnly);
/// <summary>
/// Called on each component when the Actor's bEnableCollisionChanged flag changes
/// </summary>
public override void OnActorEnableCollisionChanged()
=> E__Supper__USkeletalMeshComponent_OnActorEnableCollisionChanged(this);
/// <summary>
/// Called when a component is created (not loaded). This can happen in the editor or during gameplay
/// </summary>
public override void OnComponentCreated()
=> E__Supper__USkeletalMeshComponent_OnComponentCreated(this);
/// <summary>
/// Called when a component is destroyed
/// </summary>
/// <param name="bDestroyingHierarchy">True if the entire component hierarchy is being torn down, allows avoiding expensive operations</param>
public override void OnComponentDestroyed(bool bDestroyingHierarchy)
=> E__Supper__USkeletalMeshComponent_OnComponentDestroyed(this, bDestroyingHierarchy);
/// <summary>
/// Used to create any physics engine information for this component
/// </summary>
protected override void OnCreatePhysicsState()
=> E__Supper__USkeletalMeshComponent_OnCreatePhysicsState(this);
/// <summary>
/// Used to shut down and physics engine structure for this component
/// </summary>
protected override void OnDestroyPhysicsState()
=> E__Supper__USkeletalMeshComponent_OnDestroyPhysicsState(this);
/// <summary>
/// Called when a component is registered, after Scene is set, but before CreateRenderState_Concurrent or OnCreatePhysicsState are called.
/// </summary>
protected override void OnRegister()
=> E__Supper__USkeletalMeshComponent_OnRegister(this);
public override void OnRep_IsActive()
=> E__Supper__USkeletalMeshComponent_OnRep_IsActive(this);
/// <summary>
/// Called when a component is unregistered. Called after DestroyRenderState_Concurrent and OnDestroyPhysicsState are called.
/// </summary>
protected override void OnUnregister()
=> E__Supper__USkeletalMeshComponent_OnUnregister(this);
/// <summary>
/// Virtual call chain to register all tick functions
/// </summary>
/// <param name="bRegister">true to register, false, to unregister</param>
protected override void RegisterComponentTickFunctions(bool bRegister)
=> E__Supper__USkeletalMeshComponent_RegisterComponentTickFunctions(this, bRegister);
/// <summary>
/// Called to send dynamic data for this component to the rendering thread
/// </summary>
protected override void SendRenderDynamicData_Concurrent()
=> E__Supper__USkeletalMeshComponent_SendRenderDynamicData_Concurrent(this);
/// <summary>
/// Called to send a transform update for this component to the rendering thread
/// <para>@warning This is called concurrently on multiple threads (but never the same component concurrently) </para>
/// </summary>
protected override void SendRenderTransform_Concurrent()
=> E__Supper__USkeletalMeshComponent_SendRenderTransform_Concurrent(this);
/// <summary>
/// Sets whether the component is active or not
/// </summary>
/// <param name="bNewActive">The new active state of the component</param>
/// <param name="bReset">Whether the activation should happen even if ShouldActivate returns false.</param>
public override void SetActive(bool bNewActive, bool bReset)
=> E__Supper__USkeletalMeshComponent_SetActive(this, bNewActive, bReset);
/// <summary>
/// Sets whether the component should be auto activate or not. Only safe during construction scripts.
/// </summary>
/// <param name="bNewAutoActivate">The new auto activate state of the component</param>
public override void SetAutoActivate(bool bNewAutoActivate)
=> E__Supper__USkeletalMeshComponent_SetAutoActivate(this, bNewAutoActivate);
/// <summary>
/// Set this component's tick functions to be enabled or disabled. Only has an effect if the function is registered
/// </summary>
/// <param name="bEnabled">Whether it should be enabled or not</param>
public override void SetComponentTickEnabled(bool bEnabled)
=> E__Supper__USkeletalMeshComponent_SetComponentTickEnabled(this, bEnabled);
/// <summary>
/// Spawns a task on GameThread that will call SetComponentTickEnabled
/// </summary>
/// <param name="bEnabled">Whether it should be enabled or not</param>
public override void SetComponentTickEnabledAsync(bool bEnabled)
=> E__Supper__USkeletalMeshComponent_SetComponentTickEnabledAsync(this, bEnabled);
/// <summary>
/// Toggles the active state of the component
/// </summary>
public override void ToggleActive()
=> E__Supper__USkeletalMeshComponent_ToggleActive(this);
/// <summary>
/// Handle this component being Uninitialized.
/// <para>Called from AActor::EndPlay only if bHasBeenInitialized is true </para>
/// </summary>
public override void UninitializeComponent()
=> E__Supper__USkeletalMeshComponent_UninitializeComponent(this);
/// <summary>
/// Called before destroying the object. This is called immediately upon deciding to destroy the object, to allow the object to begin an
/// <para>asynchronous cleanup process. </para>
/// </summary>
public override void BeginDestroy()
=> E__Supper__USkeletalMeshComponent_BeginDestroy(this);
/// <summary>
/// Called to finish destroying the object. After UObject::FinishDestroy is called, the object's memory should no longer be accessed.
/// <para>@warning Because properties are destroyed here, Super::FinishDestroy() should always be called at the end of your child class's FinishDestroy() method, rather than at the beginning. </para>
/// </summary>
public override void FinishDestroy()
=> E__Supper__USkeletalMeshComponent_FinishDestroy(this);
/// <summary>
/// Called during subobject creation to mark this component as editor only, which causes it to get stripped in packaged builds
/// </summary>
public override void MarkAsEditorOnlySubobject()
=> E__Supper__USkeletalMeshComponent_MarkAsEditorOnlySubobject(this);
/// <summary>
/// Called after the C++ constructor has run on the CDO for a class. This is an obscure routine used to deal with the recursion
/// <para>in the construction of the default materials </para>
/// </summary>
public override void PostCDOContruct()
=> E__Supper__USkeletalMeshComponent_PostCDOContruct(this);
/// <summary>
/// Called after importing property values for this object (paste, duplicate or .t3d import)
/// <para>Allow the object to perform any cleanup for properties which shouldn't be duplicated or </para>
/// are unsupported by the script serialization
/// </summary>
public override void PostEditImport()
=> E__Supper__USkeletalMeshComponent_PostEditImport(this);
/// <summary>
/// Called after the C++ constructor and after the properties have been initialized, including those loaded from config.
/// <para>This is called before any serialization or other setup has happened. </para>
/// </summary>
public override void PostInitProperties()
=> E__Supper__USkeletalMeshComponent_PostInitProperties(this);
/// <summary>
/// Do any object-specific cleanup required immediately after loading an object.
/// <para>This is not called for newly-created objects, and by default will always execute on the game thread. </para>
/// </summary>
public override void PostLoad()
=> E__Supper__USkeletalMeshComponent_PostLoad(this);
/// <summary>
/// Called right after receiving a bunch
/// </summary>
public override void PostNetReceive()
=> E__Supper__USkeletalMeshComponent_PostNetReceive(this);
/// <summary>
/// Called right after calling all OnRep notifies (called even when there are no notifies)
/// </summary>
public override void PostRepNotifies()
=> E__Supper__USkeletalMeshComponent_PostRepNotifies(this);
/// <summary>
/// Called from within SavePackage on the passed in base/root object.
/// <para>This function is called after the package has been saved and can perform cleanup. </para>
/// </summary>
/// <param name="bCleanupIsRequired">Whether PreSaveRoot dirtied state that needs to be cleaned up</param>
public override void PostSaveRoot(bool bCleanupIsRequired)
=> E__Supper__USkeletalMeshComponent_PostSaveRoot(this, bCleanupIsRequired);
/// <summary>
/// Called right before being marked for destruction due to network replication
/// </summary>
public override void PreDestroyFromReplication()
=> E__Supper__USkeletalMeshComponent_PreDestroyFromReplication(this);
/// <summary>
/// Called right before receiving a bunch
/// </summary>
public override void PreNetReceive()
=> E__Supper__USkeletalMeshComponent_PreNetReceive(this);
/// <summary>
/// After a critical error, perform any mission-critical cleanup, such as restoring the video mode orreleasing hardware resources.
/// </summary>
public override void ShutdownAfterError()
=> E__Supper__USkeletalMeshComponent_ShutdownAfterError(this);
/// <summary>
/// Called after PostLoad to create UObject cluster
/// </summary>
public override void CreateCluster()
=> E__Supper__USkeletalMeshComponent_CreateCluster(this);
/// <summary>
/// Called during Garbage Collection to perform additional cleanup when the cluster is about to be destroyed due to PendingKill flag being set on it.
/// </summary>
public override void OnClusterMarkedAsPendingKill()
=> E__Supper__USkeletalMeshComponent_OnClusterMarkedAsPendingKill(this);
#endregion
public static implicit operator IntPtr(ManageSkeletalMeshComponent self)
{
return self?.NativePointer ?? IntPtr.Zero;
}
public static implicit operator ManageSkeletalMeshComponent(ObjectPointerDescription PtrDesc)
{
return NativeManager.GetWrapper<ManageSkeletalMeshComponent>(PtrDesc);
}
}
}
| |
//---------------------------------------------------------------------
// File: BizUnit.cs
//
// Summary:
//
//---------------------------------------------------------------------
// Copyright (c) 2004-2017, Kevin B. Smith. All rights reserved.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, WHETHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
// PURPOSE.
//---------------------------------------------------------------------
using System;
using System.Collections;
using System.Threading;
using System.Collections.Generic;
using BizUnit.Core.Common;
using BizUnit.Core.TestBuilder;
using BizUnit.Core.Utilites;
namespace BizUnit.Core
{
/// <summary>
/// BizUnit test framework for the rapid development of automated test cases. Test cases may be created as 'coded tests'
/// or in XAML.
/// <para>
/// Test cases have three stages:
/// <para>1. TestSetup - used to setup the conditions ready to execute the test</para>
/// <para>2. TestExecution - the main execution stage of the test</para>
/// <para>3: TestCleanup - the final stage is always executed regardless of whether the test passes
/// or fails in order to leave the system in the state prior to executing the test</para>
/// </para>
///
/// </summary>
///
/// <remarks>
/// The following example demonstrates how to create a BizUnit coded test and execute it:
///
/// <code escaped="true">
/// namespace WoodgroveBank.BVTs
/// {
/// using System;
/// using NUnit.Framework;
/// using BizUnit;
///
/// // This is an example of calling BizUnit from NUnit...
/// [TestFixture]
/// public class SmokeTests
/// {
/// // Create the test case
/// var testCase = new TestCase();
///
/// // Create test steps...
/// var delayStep = new DelayStep {DelayMilliSeconds = 500};
///
/// // Add test steps to the required test stage
/// testCase.ExecutionSteps.Add(delayStep);
///
/// // Create a new instance of BizUnit and run the test
/// var bizUnit = new TestRunner(testCase);
/// bizUnit.Run();
/// }
/// }
/// </code>
///
/// <para>
/// The following XML shows the XAML for the coded test case shown above:
/// </para>
/// <code escaped="true">
/// <TestCase
/// Description="{x:Null}"
/// ExpectedResults="{x:Null}"
/// Name="{x:Null}" Preconditions="{x:Null}"
/// Purpose="{x:Null}" Reference="{x:Null}"
/// BizUnitVersion="4.0.133.0"
/// xmlns="clr-namespace:BizUnit.Xaml;assembly=BizUnit"
/// xmlns:btt="clr-namespace:BizUnit.TestSteps.Time;assembly=BizUnit.TestSteps"
/// xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
/// <TestCase.ExecutionSteps>
/// <btt:DelayStep
/// SubSteps="{x:Null}"
/// DelayMilliSeconds="500"
/// FailOnError="True"
/// RunConcurrently="False" />
/// </TestCase.ExecutionSteps>
/// </TestCase>
/// </code>
/// </remarks>
public class TestRunner
{
string _testName = "Unknown";
Exception _executionException;
Context _context;
internal ILogger _logger;
readonly Queue _completedConcurrentSteps = new Queue();
int _inflightQueueDepth;
TestGroupPhase _testGroupPhase = TestGroupPhase.Unknown;
private TestCase _xamlTestCase;
internal const string BizUnitTestCaseStartTime = "BizUnitTestCaseStartTime";
private const string BizUnitTestCaseName = "BizUnitTestCaseName";
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'TestRunner.TestStepStartEvent'
public event EventHandler<TestStepEventArgs> TestStepStartEvent;
#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'TestRunner.TestStepStartEvent'
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'TestRunner.TestStepStopEvent'
public event EventHandler<TestStepEventArgs> TestStepStopEvent;
#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'TestRunner.TestStepStopEvent'
/// <summary>
/// BizUnit constructor, introduced in BizUnit 4.0
/// </summary>
/// <param name="testCase">The BizUnit test case object model that has been built to represent the test to be executed.</param>
///
/// <remarks>
/// From BizUnit 4.0 test case maybe programatically created by creating
/// test steps, configuring them and then adding them to a test case or
/// by loading Xaml test cases. Test cases developed programatically
/// maybe serialised to Xaml using TestCase.SaveToFile(),
/// similarly Xaml test cases maybe deserialised into a
/// TestCase using TestCase.LoadFromFile().
///
/// The exmaple below illustrates loading and running a Xaml test case:
///
/// <code escaped="true">
/// namespace WoodgroveBank.BVTs
/// {
/// using System;
/// using NUnit.Framework;
/// using BizUnit;
///
/// [TestMethod]
/// public class SampleTests
/// {
/// [Test]
/// public void ExecuteXamlTestCase()
/// {
/// // Load the Xaml test case...
/// var bu = new TestRunner(TestCase.LoadFromFile("DelayTestCaseTest.xaml"));
///
/// // Run the test...
/// bu.Run();
/// }
/// }
/// </code>
///
/// The exmaple below illustrates programtically creating a test case and subsequently running it:
///
/// <code escaped="true">
/// namespace WoodgroveBank.BVTs
/// {
/// using System;
/// using NUnit.Framework;
/// using BizUnit;
///
/// [TestMethod]
/// public class SampleTests
/// {
/// [Test]
/// public void ExecuteProgramaticallyCreatedTestCase()
/// {
/// int stepDelayDuration = 500;
/// var step = new DelayStep();
/// step.DelayMilliSeconds = stepDelayDuration;
///
/// var sw = new Stopwatch();
/// sw.Start();
///
/// var tc = new TestCase();
/// tc.ExecutionSteps.Add(step);
///
/// // If we wanted to serialise the test case:
/// // TestCase.SaveToFile(tc, "DelayTestCaseTest.xaml");
///
/// var bu = new TestRunner(tc));
///
/// sw = new Stopwatch().Start();
///
/// // Run the test case...
/// bu.Run();
///
/// var actualDuration = sw.ElapsedMilliseconds;
/// Console.WriteLine("Observed delay: {0}", actualDuration);
/// Assert.AreEqual(actualDuration, stepDelayDuration, 20);
/// }
/// }
/// </code>
///
/// </remarks>
public TestRunner(TestCase testCase)
{
ArgumentValidation.CheckForNullReference(testCase, "testCase");
_context = new Context(this);
_logger = _context.Logger;
LoadXamlTestCaseAndInit(testCase, TestGroupPhase.Unknown, _context);
}
/// <summary>
/// BizUnit constructor, introduced in BizUnit 4.0
/// </summary>
/// <param name="testCase">The BizUnit test case object model that has been built to represent the test to be executed.</param>
/// <param name="ctx">The BizUnit test context to be used. If this is not supplied a new contxt will created.</param>
///
/// <remarks>
/// From BizUnit 4.0 test case maybe programatically created by creating
/// test steps, configuring them and then adding them to a test case or
/// by loading Xaml test cases. Test cases developed programatically
/// maybe serialised to Xaml using TestCase.SaveToFile(),
/// similarly Xaml test cases maybe deserialised into a
/// TestCase using TestCase.LoadFromFile().
///
/// The exmaple below illustrates loading and running a Xaml test case:
///
/// <code escaped="true">
/// namespace WoodgroveBank.BVTs
/// {
/// using System;
/// using NUnit.Framework;
/// using BizUnit;
///
/// [TestMethod]
/// public class SampleTests
/// {
/// [Test]
/// public void ExecuteXamlTestCase()
/// {
/// // Load the Xaml test case...
/// var bu = new TestRunner(TestCase.LoadFromFile("DelayTestCaseTest.xaml"));
///
/// // Run the test...
/// bu.Run();
/// }
/// }
/// </code>
///
/// The exmaple below illustrates programtically creating a test case and subsequently running it:
///
/// <code escaped="true">
/// namespace WoodgroveBank.BVTs
/// {
/// using System;
/// using NUnit.Framework;
/// using BizUnit;
///
/// [TestMethod]
/// public class SampleTests
/// {
/// [Test]
/// public void ExecuteProgramaticallyCreatedTestCase()
/// {
/// int stepDelayDuration = 500;
/// var step = new DelayStep();
/// step.DelayMilliSeconds = stepDelayDuration;
///
/// var sw = new Stopwatch();
/// sw.Start();
///
/// var tc = new TestCase();
/// tc.ExecutionSteps.Add(step);
///
/// // If we wanted to serialise the test case:
/// // TestCase.SaveToFile(tc, "DelayTestCaseTest.xaml");
///
/// var bu = new TestRunner(tc));
///
/// sw = new Stopwatch().Start();
///
/// // Run the test case...
/// bu.Run();
///
/// var actualDuration = sw.ElapsedMilliseconds;
/// Console.WriteLine("Observed delay: {0}", actualDuration);
/// Assert.AreEqual(actualDuration, stepDelayDuration, 20);
/// }
/// }
/// </code>
///
/// </remarks>
public TestRunner(TestCase testCase, Context ctx)
{
ArgumentValidation.CheckForNullReference(testCase, "testCase");
ArgumentValidation.CheckForNullReference(ctx, "ctx");
_logger = ctx.Logger;
LoadXamlTestCaseAndInit(testCase, TestGroupPhase.Unknown, ctx);
}
private void LoadXamlTestCaseAndInit(TestCase testCase, TestGroupPhase phase, Context ctx)
{
ArgumentValidation.CheckForNullReference(testCase, "testCase");
// ctx - optional
if (null != ctx)
{
_context = ctx;
_context.Initialize(this);
}
else
{
_context = new Context(this);
_logger = _context.Logger;
}
_xamlTestCase = testCase;
_testGroupPhase = phase;
_testName = testCase.Name;
DateTime now = DateTime.Now;
// Validate test case...
testCase.Validate(_context);
if (phase == TestGroupPhase.Unknown)
{
_logger.TestStart(_testName, now, GetUserName());
_context.Add(BizUnitTestCaseStartTime, now, true);
}
else
{
_logger.TestGroupStart(testCase.Name, phase, now, GetUserName());
}
}
public Context Ctx
{
get
{
return _context;
}
}
public void Run()
{
RunTestInternal(_xamlTestCase);
}
private void RunTestInternal(TestCase xamlTestCase)
{
try
{
_context.SetTestName(xamlTestCase.Name);
Setup(xamlTestCase.SetupSteps);
Execute(xamlTestCase.ExecutionSteps);
TearDown(xamlTestCase.CleanupSteps);
}
finally
{
if (null != _logger)
{
_logger.Flush();
_logger.Close();
}
xamlTestCase.Cleanup(_context);
}
if (null != _executionException)
{
throw _executionException;
}
}
private void Setup(IEnumerable<TestStepBase> testSteps)
{
ExecuteSteps(testSteps, TestStage.Setup);
}
private void Execute(IEnumerable<TestStepBase> testSteps)
{
ExecuteSteps(testSteps, TestStage.Execution);
}
private void TearDown(IEnumerable<TestStepBase> testSteps)
{
ExecuteSteps(testSteps, TestStage.Cleanup);
}
private void ExecuteSteps(IEnumerable<TestStepBase> testSteps, TestStage stage)
{
_logger.TestStageStart(stage, DateTime.Now);
_context.SetTestStage(stage);
try
{
if (null == testSteps)
{
return;
}
foreach (var step in testSteps)
{
ExecuteXamlTestStep(step, stage);
}
FlushConcurrentQueue(true, stage);
}
catch (Exception e)
{
// If we caught an exception on the main test execution, save it, perform cleanup,
// then throw the exception...
_executionException = e;
}
_logger.TestStageEnd(stage, DateTime.Now, _executionException);
}
private void ExecuteXamlTestStep(TestStepBase testStep, TestStage stage)
{
try
{
// Should this step be executed concurrently?
if (testStep.RunConcurrently)
{
_context.LogInfo("Queuing concurrent step: {0} for execution", testStep.GetType().ToString());
Interlocked.Increment(ref _inflightQueueDepth);
ThreadPool.QueueUserWorkItem(new WaitCallback(WorkerThreadThunk), new ConcurrentTestStepWrapper(testStep, _context));
}
else
{
_logger.TestStepStart(testStep.GetType().ToString(), DateTime.Now, false, testStep.FailOnError);
if (testStep is ImportTestCaseStep)
{
ExecuteImportedTestCase(testStep as ImportTestCaseStep, _context);
}
else
{
testStep.Execute(_context);
}
}
}
catch (Exception e)
{
_logger.TestStepEnd(testStep.GetType().ToString(), DateTime.Now, e);
if (testStep.FailOnError)
{
if (e is ValidationStepExecutionException)
{
throw;
}
var tsee = new TestStepExecutionException("BizUnit encountered an error executing a test step", e, stage, _testName, testStep.GetType().ToString());
throw tsee;
}
}
if (!testStep.RunConcurrently)
{
_logger.TestStepEnd(testStep.GetType().ToString(), DateTime.Now, null);
}
FlushConcurrentQueue(false, stage);
}
private static void ExecuteImportedTestCase(ImportTestCaseStep testStep, Context context)
{
var testCase = testStep.GetTestCase();
var bu = new TestRunner(testCase, context);
bu.Run();
}
private void FlushConcurrentQueue(bool waitingToFinish, TestStage stage)
{
if (waitingToFinish && _inflightQueueDepth == 0)
{
return;
}
while ((_completedConcurrentSteps.Count > 0) || waitingToFinish)
{
object obj = null;
lock (_completedConcurrentSteps.SyncRoot)
{
if (_completedConcurrentSteps.Count > 0)
{
try
{
obj = _completedConcurrentSteps.Dequeue();
}
catch (Exception ex)
{
_logger.LogException(ex);
}
}
}
if (null != obj)
{
var step = (ConcurrentTestStepWrapper)obj;
_logger.LogBufferedText(step.Logger);
_logger.TestStepEnd(step.Name, DateTime.Now, step.FailureException);
// Check to see if the test step failed, if it did throw the exception...
if (null != step.FailureException)
{
Interlocked.Decrement(ref _inflightQueueDepth);
if (step.FailOnError)
{
if (step.FailureException is ValidationStepExecutionException)
{
throw step.FailureException;
}
else
{
var tsee = new TestStepExecutionException("BizUnit encountered an error concurrently executing a test step", step.FailureException, stage, _testName, step.StepName);
throw tsee;
}
}
}
else
{
Interlocked.Decrement(ref _inflightQueueDepth);
}
}
if (waitingToFinish && (_inflightQueueDepth > 0))
{
Thread.Sleep(250);
}
else if (waitingToFinish && (_inflightQueueDepth == 0))
{
break;
}
}
}
private void WorkerThreadThunk(Object stateInfo)
{
var step = (ConcurrentTestStepWrapper)stateInfo;
step.Execute();
// This step is completed, add to queue
lock (_completedConcurrentSteps.SyncRoot)
{
_completedConcurrentSteps.Enqueue(step);
}
}
internal static string GetNow()
{
return DateTime.Now.ToString("HH:mm:ss.fff dd/MM/yyyy");
}
internal static string GetUserName()
{
string usersDomain = Environment.UserDomainName;
string usersName = Environment.UserName;
return usersDomain + "\\" + usersName;
}
internal void OnTestStepStart(TestStepEventArgs e)
{
if(null != TestStepStartEvent)
{
EventHandler<TestStepEventArgs> testStepStartEvent = TestStepStartEvent;
testStepStartEvent(this, e);
}
}
internal void OnTestStepStop(TestStepEventArgs e)
{
if (null != TestStepStopEvent)
{
EventHandler<TestStepEventArgs> testStepStopEvent = TestStepStopEvent;
testStepStopEvent(this, e);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Bloom.Api;
using Bloom.Book;
using Bloom.TeamCollection;
using Bloom.ToPalaso;
using SIL.IO;
using SIL.Reporting;
using SIL.Windows.Forms.FileSystem;
namespace Bloom.Collection
{
public class BookCollection
{
public enum CollectionType
{
TheOneEditableCollection,
SourceCollection
}
public delegate BookCollection Factory(string path, CollectionType collectionType);//autofac uses this
public EventHandler CollectionChanged;
private readonly string _path;
private List<BookInfo> _bookInfos;
private TeamCollectionManager _tcManager;
private readonly BookSelection _bookSelection;
private Timer _folderChangeDebounceTimer;
private static HashSet<string> _changingFolders = new HashSet<string>();
private BloomWebSocketServer _webSocketServer;
public static event EventHandler CollectionCreated;
//for moq only
public BookCollection()
{
}
// For unit tests only.
internal BookCollection(List<BookInfo> state)
{
_bookInfos = state;
}
public BookCollection(string path, CollectionType collectionType,
BookSelection bookSelection, TeamCollectionManager tcm = null, BloomWebSocketServer webSocketServer = null)
{
_path = path;
_bookSelection = bookSelection;
_tcManager = tcm;
_webSocketServer = webSocketServer;
Type = collectionType;
if (collectionType == CollectionType.TheOneEditableCollection)
{
MakeCollectionCSSIfMissing();
}
CollectionCreated?.Invoke(this, new EventArgs());
if (ContainsDownloadedBooks)
{
WatchDirectory();
}
}
/// <summary>
/// Called when a file system watcher notices a new book (or some similar change) in our downloaded books folder.
/// This will happen on a thread-pool thread.
/// Since we are updating the UI in response we want to deal with it on the main thread.
/// That also has the effect of a lock, preventing multiple threads trying to respond to changes.
/// The main purpose of this method is to debounce such changes, since lots of them may
/// happen in succession while downloading a book, and also some that we don't want
/// to process may happen while we are selecting one. Debounced changes result in a websocket message
/// that acts as an event for Javascript, and also raising a C# event.
/// </summary>
private void DebounceFolderChanged(string fullPath)
{
var shell = Application.OpenForms.Cast<Form>().FirstOrDefault(f => f is Shell);
SafeInvoke.InvokeIfPossible("update downloaded books", shell, true, (Action)(() =>
{
// We may notice a change to the downloaded books directory before the other Bloom instance has finished
// copying the new book there. Finishing should not take long, because the download is done...at worst
// we have to copy the book on our own filesystem. Typically we only have to move the directory.
// As a safeguard, wait half a second before we update things.
if (_folderChangeDebounceTimer != null)
{
// Things changed again before we started the update! Forget the old update and wait until things
// are stable for the required interval.
_folderChangeDebounceTimer.Stop();
_folderChangeDebounceTimer.Dispose();
}
_folderChangeDebounceTimer = new Timer();
_folderChangeDebounceTimer.Tick += (o, args) =>
{
_folderChangeDebounceTimer.Stop();
_folderChangeDebounceTimer.Dispose();
_folderChangeDebounceTimer = null;
// Updating the books involves selecting the modified book, which might involve changing
// some files (e.g., adding a branding image, BL-4914), which could trigger this again.
// So don't allow it to be triggered by changes to a folder we're already sending
// notifications about.
// (It's PROBABLY overkill to maintain a set of these...don't expect a notification about
// one folder to trigger a change to another...but better safe than sorry.)
// (Note that we don't need synchronized access to this dictionary, because all this
// happens only on the UI thread.)
if (!_changingFolders.Contains(fullPath))
{
try
{
_changingFolders.Add(fullPath);
_webSocketServer.SendEvent("editableCollectionList", "reload:" + PathToDirectory);
if (FolderContentChanged != null)
FolderContentChanged(this, new ProjectChangedEventArgs() { Path = fullPath });
}
finally
{
// Now we need to arrange to remove it again. Not right now, because
// whatever changes might be made during event handling may get noticed slightly later.
// But we don't want to miss it if the book gets downloaded again.
RemoveFromChangingFoldersLater(fullPath);
}
}
};
_folderChangeDebounceTimer.Interval = 500;
_folderChangeDebounceTimer.Start();
}));
}
// Arrange that the specified path should be removed from changingFolders after 10s.
// This means for 10s we wont pay attention to new changes to
// this folder. Probably excessive, but this monitor is meant to catch new downloads;
// it's unlikely the same book can be downloaded again within 10 seconds.
private static void RemoveFromChangingFoldersLater(string fullPath)
{
var waitTimer = new Timer();
waitTimer.Interval = 10000;
waitTimer.Tick += (sender1, args1) =>
{
_changingFolders.Remove(fullPath);
waitTimer.Stop();
waitTimer.Dispose();
};
waitTimer.Start();
}
// We will ignore changes to this folder for 10s. This is typically because it
// has just been selected. That may result in file mods as the book is brought
// up to date, but we don't want to treat those changes like a new book or
// version of a book arriving from BL.
public static void TemporariliyIgnoreChangesToFolder(string fullPath)
{
_changingFolders.Add(fullPath);
RemoveFromChangingFoldersLater(fullPath);
}
private void MakeCollectionCSSIfMissing()
{
string path = Path.Combine(_path, "customCollectionStyles.css");
if(RobustFile.Exists(path))
return;
RobustFile.Copy(BloomFileLocator.GetBrowserFile(false, "bookLayout", "collection styles override template.css"), path);
}
public CollectionType Type { get; private set; }
private void NotifyCollectionChanged()
{
if (CollectionChanged != null)
CollectionChanged.Invoke(this, null);
}
public void DeleteBook(Book.BookInfo bookInfo)
{
var didDelete = ConfirmRecycleDialog.Recycle(bookInfo.FolderPath);
if (!didDelete)
return;
Logger.WriteEvent("After BookStorage.DeleteBook({0})", bookInfo.FolderPath);
HandleBookDeletedFromCollection(bookInfo.FolderPath);
if (_bookSelection != null)
{
_bookSelection.SelectBook(null);
}
}
/// <summary>
/// Handles side effects of deleting a book (also used when remotely deleted)
/// </summary>
/// <param name="bookInfo"></param>
public void HandleBookDeletedFromCollection(string folderPath)
{
var infoToDelete = _bookInfos.FirstOrDefault(b => b.FolderPath == folderPath);
//Debug.Assert(_bookInfos.Contains(bookInfo)); this will occur if we delete a book from the BloomLibrary section
if (infoToDelete != null) // for paranoia. We shouldn't be trying to delete a book that isn't there.
_bookInfos.Remove(infoToDelete);
if (CollectionChanged != null)
CollectionChanged.Invoke(this, null);
}
public virtual string Name
{
get
{
var dirName = Path.GetFileName(_path);
//the UI and existing Localizations want to see "templates", but on disk, "templates" is ambiguous, so the name there is "template books".
return dirName == "template books" ? "Templates" : dirName;
}
}
public string PathToDirectory
{
get { return _path; }
}
private object _bookInfoLock = new object();
// Needs to be thread-safe
public virtual IEnumerable<Book.BookInfo> GetBookInfos()
{
lock (_bookInfoLock)
{
if (_bookInfos == null)
{
_watcherIsDisabled = true;
_bookInfos = new List<Book.BookInfo>();
var bookFolders = ProjectContext.SafeGetDirectories(_path).Select(dir => new DirectoryInfo(dir))
.ToArray();
//var orderedBookFolders = bookFolders.OrderBy(f => f.Name);
var orderedBookFolders = bookFolders.OrderBy(f => f.Name, new NaturalSortComparer<string>());
foreach (var folder in orderedBookFolders)
{
if (Path.GetFileName(folder.FullName).StartsWith(".")) //as in ".hg"
continue;
// Don't want things in the templates/xmatter folder
// (even SIL-Cameroon-Mothballed, which no longer has xmatter in its filename)
// so filter on the whole path.
if (folder.FullName.ToLowerInvariant().Contains("xmatter"))
continue;
// Note: this used to be .bloom-ignore. We believe that is no longer used.
// It was changed because files starting with dot are normally invisible,
// which could make it hard to see why a book is skipped, and also because
// we were having trouble finding a way to get a file called .bloom-ignore
// included in the filesThatMightBeNeededInOutput list in gulpfile.js.
if (RobustFile.Exists(Path.Combine(folder.FullName, "BloomIgnore.txt")))
continue;
AddBookInfo(folder.FullName);
}
_watcherIsDisabled = false;
}
return _bookInfos;
}
}
public void UpdateBookInfo(BookInfo info)
{
var oldIndex = _bookInfos.FindIndex(i => i.Id == info.Id);
IComparer<string> comp = new NaturalSortComparer<string>();
var newKey = Path.GetFileName(info.FolderPath);
if (oldIndex >= 0)
{
// optimize: very often the new one will belong at the same index,
// if that's the case we could just replace.
_bookInfos.RemoveAt(oldIndex);
}
int newIndex = _bookInfos.FindIndex(x => comp.Compare(newKey, Path.GetFileName(x.FolderPath)) <= 0);
if (newIndex < 0)
newIndex = _bookInfos.Count;
_bookInfos.Insert(newIndex, info);
NotifyCollectionChanged();
}
public void AddBookInfo(BookInfo bookInfo)
{
_bookInfos.Add(bookInfo);
NotifyCollectionChanged();
}
/// <summary>
/// Insert a book into the appropriate place. If there is already a book with the same FolderPath, replace it.
/// </summary>
/// <param name="bookInfo"></param>
public void InsertBookInfo(BookInfo bookInfo)
{
IComparer<string> comparer = new NaturalSortComparer<string>();
for (int i = 0; i < _bookInfos.Count; i++)
{
var compare = comparer.Compare(_bookInfos[i].FolderPath, bookInfo.FolderPath);
if (compare == 0)
{
_bookInfos[i] = bookInfo; // Replace
return;
}
if (compare > 0)
{
_bookInfos.Insert(i, bookInfo);
return;
}
}
_bookInfos.Add(bookInfo);
}
private bool BackupFileExists(string folderPath)
{
var bakFiles = Directory.GetFiles(folderPath, BookStorage.BackupFilename);
return bakFiles.Length == 1 && RobustFile.Exists(bakFiles[0]);
}
private void AddBookInfo(string folderPath)
{
try
{
//this is handy when windows explorer won't let go of the thumbs.db file, but we want to delete the folder
if (Directory.GetFiles(folderPath, "*.htm").Length == 0 &&
Directory.GetFiles(folderPath, "*.html").Length == 0 &&
// BL-6099: don't hide the book if we at least have a valid backup file
!BackupFileExists(folderPath))
return;
var editable = Type == CollectionType.TheOneEditableCollection;
ISaveContext sc = editable ?
_tcManager?.CurrentCollectionEvenIfDisconnected ?? new AlwaysEditSaveContext() as ISaveContext
: new NoEditSaveContext() as ISaveContext;
var bookInfo = new BookInfo(folderPath, editable, sc);
_bookInfos.Add(bookInfo);
}
catch (Exception e)
{
if (e.InnerException != null)
{
e = e.InnerException;
}
var jsonPath = Path.Combine(folderPath, BookInfo.MetaDataFileName);
Logger.WriteError("Reading "+ jsonPath, e);
try
{
Logger.WriteEvent(jsonPath +" Contents: " +System.Environment.NewLine+ RobustFile.ReadAllText(jsonPath));
}
catch(Exception readError)
{
Logger.WriteError("Error reading "+ jsonPath, readError);
}
//_books.Add(new ErrorBook(e, path, Type == CollectionType.TheOneEditableCollection));
_bookInfos.Add(new ErrorBookInfo(folderPath, e){});
}
}
protected Color CoverColor
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public const string DownloadedBooksCollectionNameInEnglish = "Books From BloomLibrary.org";
public bool ContainsDownloadedBooks { get { return Name == DownloadedBooksCollectionNameInEnglish; } }
/// <summary>
/// This includes everything in "factoryCollections" (i.e. Templates folder AND Sample Shells:Vaccinations folder)
/// </summary>
public bool IsFactoryInstalled { get { return BloomFileLocator.IsInstalledFileOrDirectory(PathToDirectory); } }
private FileSystemWatcher _watcher;
/// <summary>
/// Watch for changes to your directory (currently just additions). Raise CollectionChanged if you see anything.
/// </summary>
public void WatchDirectory()
{
_watcher = new FileSystemWatcher();
_watcher.Path = PathToDirectory;
// The default filter, LastWrite|FileName|DirectoryName, is probably OK.
// Watch everything for now.
// watcher.Filter = "*.txt";
_watcher.Created += WatcherOnChange;
_watcher.Changed += WatcherOnChange;
// Begin watching.
_watcher.EnableRaisingEvents = true;
}
/// <summary>
/// This could plausibly be a Dispose(), but I don't want to make BoolCollection Disposable, as most of them don't need it.
/// </summary>
public void StopWatchingDirectory()
{
if (_watcher != null)
{
_watcher.Dispose();
_watcher = null;
}
}
public event EventHandler<ProjectChangedEventArgs> FolderContentChanged;
private bool _watcherIsDisabled = false;
private void WatcherOnChange(object sender, FileSystemEventArgs fileSystemEventArgs)
{
if (_watcherIsDisabled)
return;
_bookInfos = null; // Possibly obsolete; next request will update it.
DebounceFolderChanged(fileSystemEventArgs.FullPath);
}
}
public class ProjectChangedEventArgs : EventArgs
{
public string Path { get; set; }
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.Contracts;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Security;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Cryptography;
using System.Security.Principal;
using System.ServiceModel.Description;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Security;
using System.ServiceModel.Security.Tokens;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using SecurityUtils = System.ServiceModel.Security.SecurityUtils;
namespace System.ServiceModel.Channels
{
internal class HttpChannelFactory<TChannel>
: TransportChannelFactory<TChannel>,
IHttpTransportFactorySettings
{
private static CacheControlHeaderValue s_requestCacheHeader = new CacheControlHeaderValue { NoCache = true, MaxAge = new TimeSpan(0) };
protected readonly ClientWebSocketFactory _clientWebSocketFactory;
private bool _allowCookies;
private AuthenticationSchemes _authenticationScheme;
private HttpCookieContainerManager _httpCookieContainerManager;
// Double-checked locking pattern requires volatile for read/write synchronization
private volatile MruCache<Uri, Uri> _credentialCacheUriPrefixCache;
private volatile MruCache<string, string> _credentialHashCache;
private volatile MruCache<string, HttpClient> _httpClientCache;
private int _maxBufferSize;
private IWebProxy _proxy;
private WebProxyFactory _proxyFactory;
private SecurityCredentialsManager _channelCredentials;
private SecurityTokenManager _securityTokenManager;
private TransferMode _transferMode;
private ISecurityCapabilities _securityCapabilities;
private Func<HttpClientHandler, HttpMessageHandler> _httpMessageHandlerFactory;
private WebSocketTransportSettings _webSocketSettings;
private Lazy<string> _webSocketSoapContentType;
private SHA512 _hashAlgorithm;
private bool _keepAliveEnabled;
internal HttpChannelFactory(HttpTransportBindingElement bindingElement, BindingContext context)
: base(bindingElement, context, HttpTransportDefaults.GetDefaultMessageEncoderFactory())
{
// validate setting interactions
if (bindingElement.TransferMode == TransferMode.Buffered)
{
if (bindingElement.MaxReceivedMessageSize > int.MaxValue)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("bindingElement.MaxReceivedMessageSize",
SR.MaxReceivedMessageSizeMustBeInIntegerRange));
}
if (bindingElement.MaxBufferSize != bindingElement.MaxReceivedMessageSize)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement",
SR.MaxBufferSizeMustMatchMaxReceivedMessageSize);
}
}
else
{
if (bindingElement.MaxBufferSize > bindingElement.MaxReceivedMessageSize)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement",
SR.MaxBufferSizeMustNotExceedMaxReceivedMessageSize);
}
}
if (TransferModeHelper.IsRequestStreamed(bindingElement.TransferMode) &&
bindingElement.AuthenticationScheme != AuthenticationSchemes.Anonymous)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement",
SR.HttpAuthDoesNotSupportRequestStreaming);
}
_allowCookies = bindingElement.AllowCookies;
if (_allowCookies)
{
_httpCookieContainerManager = new HttpCookieContainerManager();
}
if (!bindingElement.AuthenticationScheme.IsSingleton())
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("value", SR.Format(SR.HttpRequiresSingleAuthScheme,
bindingElement.AuthenticationScheme));
}
_authenticationScheme = bindingElement.AuthenticationScheme;
_maxBufferSize = bindingElement.MaxBufferSize;
_transferMode = bindingElement.TransferMode;
_keepAliveEnabled = bindingElement.KeepAliveEnabled;
if (bindingElement.ProxyAddress != null)
{
if (bindingElement.UseDefaultWebProxy)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.UseDefaultWebProxyCantBeUsedWithExplicitProxyAddress));
}
if (bindingElement.ProxyAuthenticationScheme == AuthenticationSchemes.Anonymous)
{
_proxy = new WebProxy(bindingElement.ProxyAddress, bindingElement.BypassProxyOnLocal);
}
else
{
_proxy = null;
_proxyFactory =
new WebProxyFactory(bindingElement.ProxyAddress, bindingElement.BypassProxyOnLocal,
bindingElement.ProxyAuthenticationScheme);
}
}
else if (!bindingElement.UseDefaultWebProxy)
{
_proxy = new WebProxy();
}
_channelCredentials = context.BindingParameters.Find<SecurityCredentialsManager>();
_securityCapabilities = bindingElement.GetProperty<ISecurityCapabilities>(context);
_httpMessageHandlerFactory = context.BindingParameters.Find<Func<HttpClientHandler, HttpMessageHandler>>();
_webSocketSettings = WebSocketHelper.GetRuntimeWebSocketSettings(bindingElement.WebSocketSettings);
_clientWebSocketFactory = ClientWebSocketFactory.GetFactory();
_webSocketSoapContentType = new Lazy<string>(() => MessageEncoderFactory.CreateSessionEncoder().ContentType, LazyThreadSafetyMode.ExecutionAndPublication);
}
public bool AllowCookies
{
get
{
return _allowCookies;
}
}
public AuthenticationSchemes AuthenticationScheme
{
get
{
return _authenticationScheme;
}
}
public virtual bool IsChannelBindingSupportEnabled
{
get
{
return false;
}
}
public SecurityTokenManager SecurityTokenManager
{
get
{
return _securityTokenManager;
}
}
public int MaxBufferSize
{
get
{
return _maxBufferSize;
}
}
public TransferMode TransferMode
{
get
{
return _transferMode;
}
}
public override string Scheme
{
get
{
return UriEx.UriSchemeHttp;
}
}
public WebSocketTransportSettings WebSocketSettings
{
get
{
return _webSocketSettings;
}
}
internal string WebSocketSoapContentType
{
get
{
return _webSocketSoapContentType.Value;
}
}
private HashAlgorithm HashAlgorithm
{
[SecurityCritical]
get
{
if (_hashAlgorithm == null)
{
_hashAlgorithm = SHA512.Create();
}
else
{
_hashAlgorithm.Initialize();
}
return _hashAlgorithm;
}
}
protected ClientWebSocketFactory ClientWebSocketFactory
{
get
{
return _clientWebSocketFactory;
}
}
private bool AuthenticationSchemeMayRequireResend()
{
return AuthenticationScheme != AuthenticationSchemes.Anonymous;
}
public override T GetProperty<T>()
{
if (typeof(T) == typeof(ISecurityCapabilities))
{
return (T)(object)_securityCapabilities;
}
if (typeof(T) == typeof(IHttpCookieContainerManager))
{
return (T)(object)GetHttpCookieContainerManager();
}
return base.GetProperty<T>();
}
private HttpCookieContainerManager GetHttpCookieContainerManager()
{
return _httpCookieContainerManager;
}
private Uri GetCredentialCacheUriPrefix(Uri via)
{
Uri result;
if (_credentialCacheUriPrefixCache == null)
{
lock (ThisLock)
{
if (_credentialCacheUriPrefixCache == null)
{
_credentialCacheUriPrefixCache = new MruCache<Uri, Uri>(10);
}
}
}
lock (_credentialCacheUriPrefixCache)
{
if (!_credentialCacheUriPrefixCache.TryGetValue(via, out result))
{
result = new UriBuilder(via.Scheme, via.Host, via.Port).Uri;
_credentialCacheUriPrefixCache.Add(via, result);
}
}
return result;
}
internal async Task<HttpClient> GetHttpClientAsync(EndpointAddress to, Uri via,
SecurityTokenProviderContainer tokenProvider, SecurityTokenProviderContainer proxyTokenProvider,
SecurityTokenContainer clientCertificateToken, CancellationToken cancellationToken)
{
var impersonationLevelWrapper = new OutWrapper<TokenImpersonationLevel>();
var authenticationLevelWrapper = new OutWrapper<AuthenticationLevel>();
NetworkCredential credential = await HttpChannelUtilities.GetCredentialAsync(_authenticationScheme,
tokenProvider, impersonationLevelWrapper, authenticationLevelWrapper, cancellationToken);
if (_httpClientCache == null)
{
lock (ThisLock)
{
if (_httpClientCache == null)
{
_httpClientCache = new MruCache<string, HttpClient>(10);
}
}
}
HttpClient httpClient;
string connectionGroupName = GetConnectionGroupName(credential, authenticationLevelWrapper.Value,
impersonationLevelWrapper.Value,
clientCertificateToken);
X509CertificateEndpointIdentity remoteCertificateIdentity = to.Identity as X509CertificateEndpointIdentity;
if (remoteCertificateIdentity != null)
{
connectionGroupName = string.Format(CultureInfo.InvariantCulture, "{0}[{1}]", connectionGroupName,
remoteCertificateIdentity.Certificates[0].Thumbprint);
}
connectionGroupName = connectionGroupName ?? string.Empty;
bool foundHttpClient;
lock (_httpClientCache)
{
foundHttpClient = _httpClientCache.TryGetValue(connectionGroupName, out httpClient);
}
if (!foundHttpClient)
{
var clientHandler = GetHttpClientHandler(to, clientCertificateToken);
clientHandler.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
if (clientHandler.SupportsProxy)
{
if (_proxy != null)
{
clientHandler.Proxy = _proxy;
clientHandler.UseProxy = true;
}
else if (_proxyFactory != null)
{
clientHandler.Proxy = await _proxyFactory.CreateWebProxyAsync(authenticationLevelWrapper.Value,
impersonationLevelWrapper.Value, proxyTokenProvider, cancellationToken);
clientHandler.UseProxy = true;
}
}
clientHandler.UseCookies = _allowCookies;
if (_allowCookies)
{
clientHandler.CookieContainer = _httpCookieContainerManager.CookieContainer;
}
clientHandler.PreAuthenticate = true;
clientHandler.UseDefaultCredentials = false;
if (credential == CredentialCache.DefaultCredentials || credential == null)
{
clientHandler.UseDefaultCredentials = true;
}
else
{
#if !FEATURE_NETNATIVE // HttpClientHandler for uap does not support a non-NetworkCredential type.
CredentialCache credentials = new CredentialCache();
credentials.Add(GetCredentialCacheUriPrefix(via),
AuthenticationSchemesHelper.ToString(_authenticationScheme), credential);
clientHandler.Credentials = credentials;
#else
clientHandler.Credentials = credential;
#endif
}
HttpMessageHandler handler = clientHandler;
if(_httpMessageHandlerFactory!= null)
{
handler = _httpMessageHandlerFactory(clientHandler);
}
httpClient = new HttpClient(handler);
if(!_keepAliveEnabled)
httpClient.DefaultRequestHeaders.ConnectionClose = true;
#if !FEATURE_NETNATIVE // Expect continue not correctly supported on UAP
if (IsExpectContinueHeaderRequired)
{
httpClient.DefaultRequestHeaders.ExpectContinue = true;
}
#endif
// We provide our own CancellationToken for each request. Setting HttpClient.Timeout to -1
// prevents a call to CancellationToken.CancelAfter that HttpClient does internally which
// causes TimerQueue contention at high load.
httpClient.Timeout = Timeout.InfiniteTimeSpan;
lock (_httpClientCache)
{
HttpClient tempHttpClient;
if (_httpClientCache.TryGetValue(connectionGroupName, out tempHttpClient))
{
httpClient.Dispose();
httpClient = tempHttpClient;
}
else
{
_httpClientCache.Add(connectionGroupName, httpClient);
}
}
}
return httpClient;
}
internal virtual bool IsExpectContinueHeaderRequired => AuthenticationSchemeMayRequireResend();
internal virtual HttpClientHandler GetHttpClientHandler(EndpointAddress to, SecurityTokenContainer clientCertificateToken)
{
return new HttpClientHandler();
}
internal ICredentials GetCredentials()
{
ICredentials creds = null;
if (_authenticationScheme != AuthenticationSchemes.Anonymous)
{
creds = CredentialCache.DefaultCredentials;
ClientCredentials credentials = _channelCredentials as ClientCredentials;
if (credentials != null)
{
switch (_authenticationScheme)
{
case AuthenticationSchemes.Basic:
if (credentials.UserName.UserName == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("userName");
}
if (credentials.UserName.UserName == string.Empty)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.UserNameCannotBeEmpty);
}
creds = new NetworkCredential(credentials.UserName.UserName, credentials.UserName.Password);
break;
case AuthenticationSchemes.Digest:
if (credentials.HttpDigest.ClientCredential.UserName != string.Empty)
{
creds = credentials.HttpDigest.ClientCredential;
}
break;
case AuthenticationSchemes.Ntlm:
goto case AuthenticationSchemes.Negotiate;
case AuthenticationSchemes.Negotiate:
if (credentials.Windows.ClientCredential.UserName != string.Empty)
{
creds = credentials.Windows.ClientCredential;
}
break;
}
}
}
return creds;
}
internal Exception CreateToMustEqualViaException(Uri to, Uri via)
{
return new ArgumentException(SR.Format(SR.HttpToMustEqualVia, to, via));
}
public override int GetMaxBufferSize()
{
return MaxBufferSize;
}
private SecurityTokenProviderContainer CreateAndOpenTokenProvider(TimeSpan timeout, AuthenticationSchemes authenticationScheme,
EndpointAddress target, Uri via, ChannelParameterCollection channelParameters)
{
SecurityTokenProvider tokenProvider = null;
switch (authenticationScheme)
{
case AuthenticationSchemes.Anonymous:
break;
case AuthenticationSchemes.Basic:
tokenProvider = TransportSecurityHelpers.GetUserNameTokenProvider(SecurityTokenManager, target, via, Scheme, authenticationScheme, channelParameters);
break;
case AuthenticationSchemes.Negotiate:
case AuthenticationSchemes.Ntlm:
tokenProvider = TransportSecurityHelpers.GetSspiTokenProvider(SecurityTokenManager, target, via, Scheme, authenticationScheme, channelParameters);
break;
case AuthenticationSchemes.Digest:
tokenProvider = TransportSecurityHelpers.GetDigestTokenProvider(SecurityTokenManager, target, via, Scheme, authenticationScheme, channelParameters);
break;
default:
// The setter for this property should prevent this.
throw Fx.AssertAndThrow("CreateAndOpenTokenProvider: Invalid authentication scheme");
}
SecurityTokenProviderContainer result;
if (tokenProvider != null)
{
result = new SecurityTokenProviderContainer(tokenProvider);
result.Open(timeout);
}
else
{
result = null;
}
return result;
}
protected virtual void ValidateCreateChannelParameters(EndpointAddress remoteAddress, Uri via)
{
if (string.Compare(via.Scheme, "ws", StringComparison.OrdinalIgnoreCase) != 0)
{
ValidateScheme(via);
}
if (MessageVersion.Addressing == AddressingVersion.None && remoteAddress.Uri != via)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateToMustEqualViaException(remoteAddress.Uri, via));
}
}
protected override TChannel OnCreateChannel(EndpointAddress remoteAddress, Uri via)
{
if (typeof(TChannel) != typeof(IRequestChannel))
{
remoteAddress = remoteAddress != null && !WebSocketHelper.IsWebSocketUri(remoteAddress.Uri) ?
new EndpointAddress(WebSocketHelper.NormalizeHttpSchemeWithWsScheme(remoteAddress.Uri), remoteAddress) :
remoteAddress;
via = !WebSocketHelper.IsWebSocketUri(via) ? WebSocketHelper.NormalizeHttpSchemeWithWsScheme(via) : via;
}
return OnCreateChannelCore(remoteAddress, via);
}
protected virtual TChannel OnCreateChannelCore(EndpointAddress remoteAddress, Uri via)
{
ValidateCreateChannelParameters(remoteAddress, via);
ValidateWebSocketTransportUsage();
if (typeof(TChannel) == typeof(IRequestChannel))
{
return (TChannel)(object)new HttpClientRequestChannel((HttpChannelFactory<IRequestChannel>)(object)this, remoteAddress, via, ManualAddressing);
}
else
{
return (TChannel)(object)new ClientWebSocketTransportDuplexSessionChannel((HttpChannelFactory<IDuplexSessionChannel>)(object)this, _clientWebSocketFactory, remoteAddress, via);
}
}
protected void ValidateWebSocketTransportUsage()
{
Type channelType = typeof(TChannel);
if (channelType == typeof(IRequestChannel) && WebSocketSettings.TransportUsage == WebSocketTransportUsage.Always)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.Format(
SR.WebSocketCannotCreateRequestClientChannelWithCertainWebSocketTransportUsage,
typeof(TChannel),
WebSocketTransportSettings.TransportUsageMethodName,
typeof(WebSocketTransportSettings).Name,
WebSocketSettings.TransportUsage)));
}
if (channelType == typeof(IDuplexSessionChannel))
{
if (WebSocketSettings.TransportUsage == WebSocketTransportUsage.Never)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.Format(
SR.WebSocketCannotCreateRequestClientChannelWithCertainWebSocketTransportUsage,
typeof(TChannel),
WebSocketTransportSettings.TransportUsageMethodName,
typeof(WebSocketTransportSettings).Name,
WebSocketSettings.TransportUsage)));
}
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void InitializeSecurityTokenManager()
{
if (_channelCredentials == null)
{
_channelCredentials = ClientCredentials.CreateDefaultCredentials();
}
_securityTokenManager = _channelCredentials.CreateSecurityTokenManager();
}
protected virtual bool IsSecurityTokenManagerRequired()
{
return _authenticationScheme != AuthenticationSchemes.Anonymous;
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return OnOpenAsync(timeout).ToApm(callback, state);
}
protected override void OnEndOpen(IAsyncResult result)
{
result.ToApmEnd();
}
protected override void OnOpen(TimeSpan timeout)
{
if (IsSecurityTokenManagerRequired())
{
InitializeSecurityTokenManager();
}
if (AllowCookies &&
!_httpCookieContainerManager.IsInitialized) // We don't want to overwrite the CookieContainer if someone has set it already.
{
_httpCookieContainerManager.CookieContainer = new CookieContainer();
}
}
internal protected override Task OnOpenAsync(TimeSpan timeout)
{
OnOpen(timeout);
return TaskHelpers.CompletedTask();
}
protected internal override Task OnCloseAsync(TimeSpan timeout)
{
return base.OnCloseAsync(timeout);
}
protected override void OnClosed()
{
base.OnClosed();
if (_httpClientCache != null && !_httpClientCache.IsDisposed)
{
lock (_httpClientCache)
{
_httpClientCache.Dispose();
_httpClientCache = null;
}
}
}
private string AppendWindowsAuthenticationInfo(string inputString, NetworkCredential credential,
AuthenticationLevel authenticationLevel, TokenImpersonationLevel impersonationLevel)
{
return SecurityUtils.AppendWindowsAuthenticationInfo(inputString, credential, authenticationLevel, impersonationLevel);
}
protected virtual string OnGetConnectionGroupPrefix(SecurityTokenContainer clientCertificateToken)
{
return string.Empty;
}
internal static bool IsWindowsAuth(AuthenticationSchemes authScheme)
{
Contract.Assert(authScheme.IsSingleton(), "authenticationScheme used in an Http(s)ChannelFactory must be a singleton value.");
return authScheme == AuthenticationSchemes.Negotiate ||
authScheme == AuthenticationSchemes.Ntlm;
}
private string GetConnectionGroupName(NetworkCredential credential, AuthenticationLevel authenticationLevel,
TokenImpersonationLevel impersonationLevel, SecurityTokenContainer clientCertificateToken)
{
if (_credentialHashCache == null)
{
lock (ThisLock)
{
if (_credentialHashCache == null)
{
_credentialHashCache = new MruCache<string, string>(5);
}
}
}
string inputString = TransferModeHelper.IsRequestStreamed(TransferMode) ? "streamed" : string.Empty;
if (IsWindowsAuth(_authenticationScheme))
{
inputString = AppendWindowsAuthenticationInfo(inputString, credential, authenticationLevel, impersonationLevel);
}
inputString = string.Concat(OnGetConnectionGroupPrefix(clientCertificateToken), inputString);
string credentialHash = null;
// we have to lock around each call to TryGetValue since the MruCache modifies the
// contents of it's mruList in a single-threaded manner underneath TryGetValue
if (!string.IsNullOrEmpty(inputString))
{
lock (_credentialHashCache)
{
if (!_credentialHashCache.TryGetValue(inputString, out credentialHash))
{
byte[] inputBytes = new UTF8Encoding().GetBytes(inputString);
byte[] digestBytes = HashAlgorithm.ComputeHash(inputBytes);
credentialHash = Convert.ToBase64String(digestBytes);
_credentialHashCache.Add(inputString, credentialHash);
}
}
}
return credentialHash;
}
internal HttpRequestMessage GetHttpRequestMessage(Uri via)
{
Uri httpRequestUri = via;
var requestMessage = new HttpRequestMessage(HttpMethod.Post, httpRequestUri);
if (TransferModeHelper.IsRequestStreamed(TransferMode))
{
requestMessage.Headers.TransferEncodingChunked = true;
}
requestMessage.Headers.CacheControl = s_requestCacheHeader;
return requestMessage;
}
private void ApplyManualAddressing(ref EndpointAddress to, ref Uri via, Message message)
{
if (ManualAddressing)
{
Uri toHeader = message.Headers.To;
if (toHeader == null)
{
throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.ManualAddressingRequiresAddressedMessages), message);
}
to = new EndpointAddress(toHeader);
if (MessageVersion.Addressing == AddressingVersion.None)
{
via = toHeader;
}
}
// now apply query string property
object property;
if (message.Properties.TryGetValue(HttpRequestMessageProperty.Name, out property))
{
HttpRequestMessageProperty requestProperty = (HttpRequestMessageProperty)property;
if (!string.IsNullOrEmpty(requestProperty.QueryString))
{
UriBuilder uriBuilder = new UriBuilder(via);
if (requestProperty.QueryString.StartsWith("?", StringComparison.Ordinal))
{
uriBuilder.Query = requestProperty.QueryString.Substring(1);
}
else
{
uriBuilder.Query = requestProperty.QueryString;
}
via = uriBuilder.Uri;
}
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void CreateAndOpenTokenProvidersCore(EndpointAddress to, Uri via, ChannelParameterCollection channelParameters, TimeSpan timeout, out SecurityTokenProviderContainer tokenProvider, out SecurityTokenProviderContainer proxyTokenProvider)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
tokenProvider = CreateAndOpenTokenProvider(timeoutHelper.RemainingTime(), AuthenticationScheme, to, via, channelParameters);
if (_proxyFactory != null)
{
proxyTokenProvider = CreateAndOpenTokenProvider(timeoutHelper.RemainingTime(), _proxyFactory.AuthenticationScheme, to, via, channelParameters);
}
else
{
proxyTokenProvider = null;
}
}
internal void CreateAndOpenTokenProviders(EndpointAddress to, Uri via, ChannelParameterCollection channelParameters, TimeSpan timeout, out SecurityTokenProviderContainer tokenProvider, out SecurityTokenProviderContainer proxyTokenProvider)
{
if (!IsSecurityTokenManagerRequired())
{
tokenProvider = null;
proxyTokenProvider = null;
}
else
{
CreateAndOpenTokenProvidersCore(to, via, channelParameters, timeout, out tokenProvider, out proxyTokenProvider);
}
}
internal static bool MapIdentity(EndpointAddress target, AuthenticationSchemes authenticationScheme)
{
if (target.Identity == null)
{
return false;
}
return IsWindowsAuth(authenticationScheme);
}
private bool MapIdentity(EndpointAddress target)
{
return MapIdentity(target, AuthenticationScheme);
}
protected class HttpClientRequestChannel : RequestChannel
{
private HttpChannelFactory<IRequestChannel> _factory;
private SecurityTokenProviderContainer _tokenProvider;
private SecurityTokenProviderContainer _proxyTokenProvider;
private ChannelParameterCollection _channelParameters;
public HttpClientRequestChannel(HttpChannelFactory<IRequestChannel> factory, EndpointAddress to, Uri via, bool manualAddressing)
: base(factory, to, via, manualAddressing)
{
_factory = factory;
}
public HttpChannelFactory<IRequestChannel> Factory
{
get { return _factory; }
}
protected ChannelParameterCollection ChannelParameters
{
get
{
return _channelParameters;
}
}
public override T GetProperty<T>()
{
if (typeof(T) == typeof(ChannelParameterCollection))
{
if (State == CommunicationState.Created)
{
lock (ThisLock)
{
if (_channelParameters == null)
{
_channelParameters = new ChannelParameterCollection();
}
}
}
return (T)(object)_channelParameters;
}
return base.GetProperty<T>();
}
private void PrepareOpen()
{
Factory.MapIdentity(RemoteAddress);
}
private void CreateAndOpenTokenProviders(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
if (!ManualAddressing)
{
Factory.CreateAndOpenTokenProviders(RemoteAddress, Via, _channelParameters, timeoutHelper.RemainingTime(), out _tokenProvider, out _proxyTokenProvider);
}
}
private void CloseTokenProviders(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
if (_tokenProvider != null)
{
_tokenProvider.Close(timeoutHelper.RemainingTime());
}
}
private void AbortTokenProviders()
{
if (_tokenProvider != null)
{
_tokenProvider.Abort();
}
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return CommunicationObjectInternal.OnBeginOpen(this, timeout, callback, state);
}
protected override void OnEndOpen(IAsyncResult result)
{
CommunicationObjectInternal.OnEnd(result);
}
protected override void OnOpen(TimeSpan timeout)
{
CommunicationObjectInternal.OnOpen(this, timeout);
}
internal protected override Task OnOpenAsync(TimeSpan timeout)
{
PrepareOpen();
CreateAndOpenTokenProviders(timeout);
return TaskHelpers.CompletedTask();
}
private void PrepareClose(bool aborting)
{
}
protected override void OnAbort()
{
PrepareClose(true);
AbortTokenProviders();
base.OnAbort();
}
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return CommunicationObjectInternal.OnBeginClose(this, timeout, callback, state);
}
protected override void OnEndClose(IAsyncResult result)
{
CommunicationObjectInternal.OnEnd(result);
}
protected override void OnClose(TimeSpan timeout)
{
CommunicationObjectInternal.OnClose(this, timeout);
}
protected internal override async Task OnCloseAsync(TimeSpan timeout)
{
var timeoutHelper = new TimeoutHelper(timeout);
PrepareClose(false);
CloseTokenProviders(timeoutHelper.RemainingTime());
await WaitForPendingRequestsAsync(timeoutHelper.RemainingTime());
}
protected override IAsyncRequest CreateAsyncRequest(Message message)
{
return new HttpClientChannelAsyncRequest(this);
}
internal virtual Task<HttpClient> GetHttpClientAsync(EndpointAddress to, Uri via, TimeoutHelper timeoutHelper)
{
return GetHttpClientAsync(to, via, null, timeoutHelper);
}
protected async Task<HttpClient> GetHttpClientAsync(EndpointAddress to, Uri via, SecurityTokenContainer clientCertificateToken, TimeoutHelper timeoutHelper)
{
SecurityTokenProviderContainer requestTokenProvider;
SecurityTokenProviderContainer requestProxyTokenProvider;
if (ManualAddressing)
{
Factory.CreateAndOpenTokenProviders(to, via, _channelParameters, timeoutHelper.RemainingTime(),
out requestTokenProvider, out requestProxyTokenProvider);
}
else
{
requestTokenProvider = _tokenProvider;
requestProxyTokenProvider = _proxyTokenProvider;
}
try
{
return await Factory.GetHttpClientAsync(to, via, requestTokenProvider, requestProxyTokenProvider, clientCertificateToken, await timeoutHelper.GetCancellationTokenAsync());
}
finally
{
if (ManualAddressing)
{
if (requestTokenProvider != null)
{
requestTokenProvider.Abort();
}
}
}
}
internal HttpRequestMessage GetHttpRequestMessage(Uri via)
{
return Factory.GetHttpRequestMessage(via);
}
internal virtual void OnHttpRequestCompleted(HttpRequestMessage request)
{
// empty
}
internal class HttpClientChannelAsyncRequest : IAsyncRequest
{
private static readonly Action<object> s_cancelCts = state =>
{
try
{
((CancellationTokenSource)state).Cancel();
}
catch (ObjectDisposedException)
{
// ignore
}
};
private HttpClientRequestChannel _channel;
private HttpChannelFactory<IRequestChannel> _factory;
private EndpointAddress _to;
private Uri _via;
private HttpRequestMessage _httpRequestMessage;
private HttpResponseMessage _httpResponseMessage;
private HttpAbortReason _abortReason;
private TimeoutHelper _timeoutHelper;
private int _httpRequestCompleted;
private HttpClient _httpClient;
private readonly CancellationTokenSource _httpSendCts;
public HttpClientChannelAsyncRequest(HttpClientRequestChannel channel)
{
_channel = channel;
_to = channel.RemoteAddress;
_via = channel.Via;
_factory = channel.Factory;
_httpSendCts = new CancellationTokenSource();
}
public async Task SendRequestAsync(Message message, TimeoutHelper timeoutHelper)
{
_timeoutHelper = timeoutHelper;
_factory.ApplyManualAddressing(ref _to, ref _via, message);
_httpClient = await _channel.GetHttpClientAsync(_to, _via, _timeoutHelper);
// The _httpRequestMessage field will be set to null by Cleanup() due to faulting
// or aborting, so use a local copy for exception handling within this method.
HttpRequestMessage httpRequestMessage = _channel.GetHttpRequestMessage(_via);
_httpRequestMessage = httpRequestMessage;
Message request = message;
try
{
if (_channel.State != CommunicationState.Opened)
{
// if we were aborted while getting our request or doing correlation,
// we need to abort the request and bail
Cleanup();
_channel.ThrowIfDisposedOrNotOpen();
}
bool suppressEntityBody = PrepareMessageHeaders(request);
if (!suppressEntityBody)
{
httpRequestMessage.Content = MessageContent.Create(_factory, request, _timeoutHelper);
}
#if FEATURE_NETNATIVE // UAP doesn't support Expect Continue so we do a HEAD request to get authentication done before sending the real request
try
{
// There is a possibility that a HEAD pre-auth request might fail when the actual request
// will succeed. For example, when the web service refuses HEAD requests. We don't want
// to fail the actual request because of some subtlety which causes the HEAD request.
await SendPreauthenticationHeadRequestIfNeeded();
}
catch { /* ignored */ }
#endif
bool success = false;
var timeoutToken = await _timeoutHelper.GetCancellationTokenAsync();
try
{
using (timeoutToken.Register(s_cancelCts, _httpSendCts))
{
_httpResponseMessage = await _httpClient.SendAsync(httpRequestMessage, HttpCompletionOption.ResponseHeadersRead, _httpSendCts.Token);
}
// As we have the response message and no exceptions have been thrown, the request message has completed it's job.
// Calling Dispose() on the request message to free up resources in HttpContent, but keeping the object around
// as we can still query properties once dispose'd.
httpRequestMessage.Dispose();
success = true;
}
catch (HttpRequestException requestException)
{
HttpChannelUtilities.ProcessGetResponseWebException(requestException, httpRequestMessage,
_abortReason);
}
catch (OperationCanceledException)
{
if (timeoutToken.IsCancellationRequested)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(SR.Format(
SR.HttpRequestTimedOut, httpRequestMessage.RequestUri, _timeoutHelper.OriginalTimeout)));
}
else
{
// Cancellation came from somewhere other than timeoutToken and needs to be handled differently.
throw;
}
}
finally
{
if (!success)
{
Abort(_channel);
}
}
}
finally
{
if (!ReferenceEquals(request, message))
{
request.Close();
}
}
}
private void Cleanup()
{
s_cancelCts(_httpSendCts);
if (_httpRequestMessage != null)
{
var httpRequestMessageSnapshot = _httpRequestMessage;
_httpRequestMessage = null;
TryCompleteHttpRequest(httpRequestMessageSnapshot);
httpRequestMessageSnapshot.Dispose();
}
}
public void Abort(RequestChannel channel)
{
Cleanup();
_abortReason = HttpAbortReason.Aborted;
}
public void Fault(RequestChannel channel)
{
Cleanup();
}
public async Task<Message> ReceiveReplyAsync(TimeoutHelper timeoutHelper)
{
try
{
_timeoutHelper = timeoutHelper;
var responseHelper = new HttpResponseMessageHelper(_httpResponseMessage, _factory);
var replyMessage = await responseHelper.ParseIncomingResponse(timeoutHelper);
TryCompleteHttpRequest(_httpRequestMessage);
return replyMessage;
}
catch (OperationCanceledException)
{
var cancelToken = _timeoutHelper.GetCancellationToken();
if (cancelToken.IsCancellationRequested)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(SR.Format(
SR.HttpResponseTimedOut, _httpRequestMessage.RequestUri, timeoutHelper.OriginalTimeout)));
}
else
{
// Cancellation came from somewhere other than timeoutCts and needs to be handled differently.
throw;
}
}
}
private bool PrepareMessageHeaders(Message message)
{
string action = message.Headers.Action;
if (action != null)
{
action = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", UrlUtility.UrlPathEncode(action));
}
if (message.Version.Addressing == AddressingVersion.None)
{
message.Headers.Action = null;
message.Headers.To = null;
}
bool suppressEntityBody = message is NullMessage;
object property;
if (message.Properties.TryGetValue(HttpRequestMessageProperty.Name, out property))
{
HttpRequestMessageProperty requestProperty = (HttpRequestMessageProperty)property;
_httpRequestMessage.Method = new HttpMethod(requestProperty.Method);
// Query string was applied in HttpChannelFactory.ApplyManualAddressing
WebHeaderCollection requestHeaders = requestProperty.Headers;
suppressEntityBody = suppressEntityBody || requestProperty.SuppressEntityBody;
var headerKeys = requestHeaders.AllKeys;
for (int i = 0; i < headerKeys.Length; i++)
{
string name = headerKeys[i];
string value = requestHeaders[name];
if (string.Compare(name, "accept", StringComparison.OrdinalIgnoreCase) == 0)
{
_httpRequestMessage.Headers.Accept.TryParseAdd(value);
}
else if (string.Compare(name, "connection", StringComparison.OrdinalIgnoreCase) == 0)
{
if (value.IndexOf("keep-alive", StringComparison.OrdinalIgnoreCase) != -1)
{
_httpRequestMessage.Headers.ConnectionClose = false;
}
else
{
_httpRequestMessage.Headers.Connection.TryParseAdd(value);
}
}
else if (string.Compare(name, "SOAPAction", StringComparison.OrdinalIgnoreCase) == 0)
{
if (action == null)
{
action = value;
}
else
{
if (!String.IsNullOrEmpty(value) && string.Compare(value, action, StringComparison.Ordinal) != 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ProtocolException(SR.Format(SR.HttpSoapActionMismatch, action, value)));
}
}
}
else if (string.Compare(name, "content-length", StringComparison.OrdinalIgnoreCase) == 0)
{
// this will be taken care of by System.Net when we write to the content
}
else if (string.Compare(name, "content-type", StringComparison.OrdinalIgnoreCase) == 0)
{
// Handled by MessageContent
}
else if (string.Compare(name, "expect", StringComparison.OrdinalIgnoreCase) == 0)
{
if (value.ToUpperInvariant().IndexOf("100-CONTINUE", StringComparison.OrdinalIgnoreCase) != -1)
{
_httpRequestMessage.Headers.ExpectContinue = true;
}
else
{
_httpRequestMessage.Headers.Expect.TryParseAdd(value);
}
}
else if (string.Compare(name, "host", StringComparison.OrdinalIgnoreCase) == 0)
{
// this should be controlled through Via
}
else if (string.Compare(name, "referer", StringComparison.OrdinalIgnoreCase) == 0)
{
// referrer is proper spelling, but referer is the what is in the protocol.
_httpRequestMessage.Headers.Referrer = new Uri(value);
}
else if (string.Compare(name, "transfer-encoding", StringComparison.OrdinalIgnoreCase) == 0)
{
if (value.ToUpperInvariant().IndexOf("CHUNKED", StringComparison.OrdinalIgnoreCase) != -1)
{
_httpRequestMessage.Headers.TransferEncodingChunked = true;
}
else
{
_httpRequestMessage.Headers.TransferEncoding.TryParseAdd(value);
}
}
else if (string.Compare(name, "user-agent", StringComparison.OrdinalIgnoreCase) == 0)
{
_httpRequestMessage.Headers.Add(name, value);
}
else if (string.Compare(name, "if-modified-since", StringComparison.OrdinalIgnoreCase) == 0)
{
DateTimeOffset modifiedSinceDate;
if (DateTimeOffset.TryParse(value, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.AssumeLocal, out modifiedSinceDate))
{
_httpRequestMessage.Headers.IfModifiedSince = modifiedSinceDate;
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ProtocolException(SR.Format(SR.HttpIfModifiedSinceParseError, value)));
}
}
else if (string.Compare(name, "date", StringComparison.OrdinalIgnoreCase) == 0)
{
// this will be taken care of by System.Net when we make the request
}
else if (string.Compare(name, "proxy-connection", StringComparison.OrdinalIgnoreCase) == 0)
{
throw ExceptionHelper.PlatformNotSupported("proxy-connection");
}
else if (string.Compare(name, "range", StringComparison.OrdinalIgnoreCase) == 0)
{
// specifying a range doesn't make sense in the context of WCF
}
else
{
try
{
_httpRequestMessage.Headers.Add(name, value);
}
catch (Exception addHeaderException)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.Format(
SR.CopyHttpHeaderFailed,
name,
value,
HttpChannelUtilities.HttpRequestHeadersTypeName),
addHeaderException));
}
}
}
}
if (action != null)
{
if (message.Version.Envelope == EnvelopeVersion.Soap11)
{
_httpRequestMessage.Headers.TryAddWithoutValidation("SOAPAction", action);
}
else if (message.Version.Envelope == EnvelopeVersion.Soap12)
{
// Handled by MessageContent
}
else if (message.Version.Envelope != EnvelopeVersion.None)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ProtocolException(SR.Format(SR.EnvelopeVersionUnknown,
message.Version.Envelope.ToString())));
}
}
// since we don't get the output stream in send when retVal == true,
// we need to disable chunking for some verbs (DELETE/PUT)
if (suppressEntityBody)
{
_httpRequestMessage.Headers.TransferEncodingChunked = false;
}
return suppressEntityBody;
}
public void OnReleaseRequest()
{
TryCompleteHttpRequest(_httpRequestMessage);
}
private void TryCompleteHttpRequest(HttpRequestMessage request)
{
if (request == null)
{
return;
}
if (Interlocked.CompareExchange(ref _httpRequestCompleted, 1, 0) == 0)
{
_channel.OnHttpRequestCompleted(request);
}
}
private async Task SendPreauthenticationHeadRequestIfNeeded()
{
if (!_factory.AuthenticationSchemeMayRequireResend())
{
return;
}
var requestUri = _httpRequestMessage.RequestUri;
// sends a HEAD request to the specificed requestUri for authentication purposes
Contract.Assert(requestUri != null);
HttpRequestMessage headHttpRequestMessage = new HttpRequestMessage()
{
Method = HttpMethod.Head,
RequestUri = requestUri
};
var cancelToken = await _timeoutHelper.GetCancellationTokenAsync();
await _httpClient.SendAsync(headHttpRequestMessage, cancelToken);
}
}
}
class WebProxyFactory
{
Uri _address;
bool _bypassOnLocal;
AuthenticationSchemes _authenticationScheme;
public WebProxyFactory(Uri address, bool bypassOnLocal, AuthenticationSchemes authenticationScheme)
{
_address = address;
_bypassOnLocal = bypassOnLocal;
if (!authenticationScheme.IsSingleton())
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(nameof(authenticationScheme), SR.Format(SR.HttpRequiresSingleAuthScheme,
authenticationScheme));
}
_authenticationScheme = authenticationScheme;
}
internal AuthenticationSchemes AuthenticationScheme
{
get
{
return _authenticationScheme;
}
}
public async Task<IWebProxy> CreateWebProxyAsync(AuthenticationLevel requestAuthenticationLevel, TokenImpersonationLevel requestImpersonationLevel, SecurityTokenProviderContainer tokenProvider, CancellationToken token)
{
WebProxy result = new WebProxy(_address, _bypassOnLocal);
if (_authenticationScheme != AuthenticationSchemes.Anonymous)
{
var impersonationLevelWrapper = new OutWrapper<TokenImpersonationLevel>();
var authenticationLevelWrapper = new OutWrapper<AuthenticationLevel>();
NetworkCredential credential = await HttpChannelUtilities.GetCredentialAsync(_authenticationScheme,
tokenProvider, impersonationLevelWrapper, authenticationLevelWrapper, token);
// The impersonation level for target auth is also used for proxy auth (by System.Net). Therefore,
// fail if the level stipulated for proxy auth is more restrictive than that for target auth.
if (!TokenImpersonationLevelHelper.IsGreaterOrEqual(impersonationLevelWrapper.Value, requestImpersonationLevel))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(
SR.ProxyImpersonationLevelMismatch, impersonationLevelWrapper.Value, requestImpersonationLevel)));
}
// The authentication level for target auth is also used for proxy auth (by System.Net).
// Therefore, fail if proxy auth requires mutual authentication but target auth does not.
if ((authenticationLevelWrapper.Value == AuthenticationLevel.MutualAuthRequired) &&
(requestAuthenticationLevel != AuthenticationLevel.MutualAuthRequired))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(
SR.ProxyAuthenticationLevelMismatch, authenticationLevelWrapper.Value, requestAuthenticationLevel)));
}
CredentialCache credentials = new CredentialCache();
credentials.Add(_address, AuthenticationSchemesHelper.ToString(_authenticationScheme),
credential);
result.Credentials = credentials;
}
return result;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
////////////////////////////////////////////////////////////////////////////
//
//
//
// Purpose: This class represents the software preferences of a particular
// culture or community. It includes information such as the
// language, writing system, and a calendar used by the culture
// as well as methods for common operations such as printing
// dates and sorting strings.
//
//
//
// !!!! NOTE WHEN CHANGING THIS CLASS !!!!
//
// If adding or removing members to this class, please update CultureInfoBaseObject
// in ndp/clr/src/vm/object.h. Note, the "actual" layout of the class may be
// different than the order in which members are declared. For instance, all
// reference types will come first in the class before value types (like ints, bools, etc)
// regardless of the order in which they are declared. The best way to see the
// actual order of the class is to do a !dumpobj on an instance of the managed
// object inside of the debugger.
//
////////////////////////////////////////////////////////////////////////////
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
using System.Threading;
#if ENABLE_WINRT
using Internal.Runtime.Augments;
#endif
namespace System.Globalization
{
[Serializable]
public partial class CultureInfo : IFormatProvider, ICloneable
{
//--------------------------------------------------------------------//
// Internal Information //
//--------------------------------------------------------------------//
//--------------------------------------------------------------------//
// Data members to be serialized:
//--------------------------------------------------------------------//
// We use an RFC4646 type string to construct CultureInfo.
// This string is stored in m_name and is authoritative.
// We use the m_cultureData to get the data for our object
private bool _isReadOnly;
private CompareInfo _compareInfo;
private TextInfo _textInfo;
internal NumberFormatInfo numInfo;
internal DateTimeFormatInfo dateTimeInfo;
private Calendar _calendar;
//
// The CultureData instance that we are going to read data from.
// For supported culture, this will be the CultureData instance that read data from mscorlib assembly.
// For customized culture, this will be the CultureData instance that read data from user customized culture binary file.
//
internal CultureData m_cultureData;
internal bool m_isInherited;
private CultureInfo m_consoleFallbackCulture;
// Names are confusing. Here are 3 names we have:
//
// new CultureInfo() m_name _nonSortName _sortName
// en-US en-US en-US en-US
// de-de_phoneb de-DE_phoneb de-DE de-DE_phoneb
// fj-fj (custom) fj-FJ fj-FJ en-US (if specified sort is en-US)
// en en
//
// Note that in Silverlight we ask the OS for the text and sort behavior, so the
// textinfo and compareinfo names are the same as the name
// Note that the name used to be serialized for Everett; it is now serialized
// because alernate sorts can have alternate names.
// This has a de-DE, de-DE_phoneb or fj-FJ style name
internal string m_name;
// This will hold the non sorting name to be returned from CultureInfo.Name property.
// This has a de-DE style name even for de-DE_phoneb type cultures
private string _nonSortName;
// This will hold the sorting name to be returned from CultureInfo.SortName property.
// This might be completely unrelated to the culture name if a custom culture. Ie en-US for fj-FJ.
// Otherwise its the sort name, ie: de-DE or de-DE_phoneb
private string _sortName;
//--------------------------------------------------------------------//
//
// Static data members
//
//--------------------------------------------------------------------//
//Get the current user default culture. This one is almost always used, so we create it by default.
private static volatile CultureInfo s_userDefaultCulture;
//
// All of the following will be created on demand.
//
// WARNING: We allow diagnostic tools to directly inspect these three members (s_InvariantCultureInfo, s_DefaultThreadCurrentUICulture and s_DefaultThreadCurrentCulture)
// See https://github.com/dotnet/corert/blob/master/Documentation/design-docs/diagnostics/diagnostics-tools-contract.md for more details.
// Please do not change the type, the name, or the semantic usage of this member without understanding the implication for tools.
// Get in touch with the diagnostics team if you have questions.
//The Invariant culture;
private static volatile CultureInfo s_InvariantCultureInfo;
//These are defaults that we use if a thread has not opted into having an explicit culture
private static volatile CultureInfo s_DefaultThreadCurrentUICulture;
private static volatile CultureInfo s_DefaultThreadCurrentCulture;
[ThreadStatic]
private static CultureInfo s_currentThreadCulture;
[ThreadStatic]
private static CultureInfo s_currentThreadUICulture;
private static readonly Lock s_lock = new Lock();
private static volatile LowLevelDictionary<string, CultureInfo> s_NameCachedCultures;
private static volatile LowLevelDictionary<int, CultureInfo> s_LcidCachedCultures;
//The parent culture.
private CultureInfo _parent;
// LOCALE constants of interest to us internally and privately for LCID functions
// (ie: avoid using these and use names if possible)
internal const int LOCALE_NEUTRAL = 0x0000;
private const int LOCALE_USER_DEFAULT = 0x0400;
private const int LOCALE_SYSTEM_DEFAULT = 0x0800;
internal const int LOCALE_CUSTOM_UNSPECIFIED = 0x1000;
internal const int LOCALE_CUSTOM_DEFAULT = 0x0c00;
internal const int LOCALE_INVARIANT = 0x007F;
//
// The CultureData instance that reads the data provided by our CultureData class.
//
// Using a field initializer rather than a static constructor so that the whole class can be lazy
// init.
private static readonly bool s_init = Init();
private static bool Init()
{
if (s_InvariantCultureInfo == null)
{
CultureInfo temp = new CultureInfo("", false);
temp._isReadOnly = true;
s_InvariantCultureInfo = temp;
}
s_userDefaultCulture = GetUserDefaultCulture();
return true;
}
////////////////////////////////////////////////////////////////////////
//
// CultureInfo Constructors
//
////////////////////////////////////////////////////////////////////////
public CultureInfo(String name)
: this(name, true)
{
}
public CultureInfo(String name, bool useUserOverride)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name),
SR.ArgumentNull_String);
}
// Get our data providing record
this.m_cultureData = CultureData.GetCultureData(name, useUserOverride);
if (this.m_cultureData == null)
throw new CultureNotFoundException(
nameof(name), name, SR.Argument_CultureNotSupported);
this.m_name = this.m_cultureData.CultureName;
this.m_isInherited = !this.EETypePtr.FastEquals(EETypePtr.EETypePtrOf<CultureInfo>());
}
public CultureInfo(int culture) : this(culture, true)
{
}
public CultureInfo(int culture, bool useUserOverride)
{
// We don't check for other invalid LCIDS here...
if (culture < 0)
{
throw new ArgumentOutOfRangeException(nameof(culture), SR.ArgumentOutOfRange_NeedPosNum);
}
Contract.EndContractBlock();
InitializeFromCultureId(culture, useUserOverride);
}
private void InitializeFromCultureId(int culture, bool useUserOverride)
{
switch (culture)
{
case LOCALE_CUSTOM_DEFAULT:
case LOCALE_SYSTEM_DEFAULT:
case LOCALE_NEUTRAL:
case LOCALE_USER_DEFAULT:
case LOCALE_CUSTOM_UNSPECIFIED:
// Can't support unknown custom cultures and we do not support neutral or
// non-custom user locales.
throw new CultureNotFoundException(nameof(culture), culture, SR.Argument_CultureNotSupported);
default:
// Now see if this LCID is supported in the system default CultureData table.
m_cultureData = CultureData.GetCultureData(culture, useUserOverride);
break;
}
m_isInherited = (this.GetType() != typeof(System.Globalization.CultureInfo));
m_name = m_cultureData.CultureName;
}
// Constructor called by SQL Server's special munged culture - creates a culture with
// a TextInfo and CompareInfo that come from a supplied alternate source. This object
// is ALWAYS read-only.
// Note that we really cannot use an LCID version of this override as the cached
// name we create for it has to include both names, and the logic for this is in
// the GetCultureInfo override *only*.
internal CultureInfo(String cultureName, String textAndCompareCultureName)
{
if (cultureName == null)
{
throw new ArgumentNullException(nameof(cultureName), SR.ArgumentNull_String);
}
Contract.EndContractBlock();
m_cultureData = CultureData.GetCultureData(cultureName, false);
if (m_cultureData == null)
throw new CultureNotFoundException(nameof(cultureName), cultureName, SR.Argument_CultureNotSupported);
m_name = m_cultureData.CultureName;
CultureInfo altCulture = GetCultureInfo(textAndCompareCultureName);
_compareInfo = altCulture.CompareInfo;
_textInfo = altCulture.TextInfo;
}
// We do this to try to return the system UI language and the default user languages
// This method will fallback if this fails (like Invariant)
//
// TODO: It would appear that this is only ever called with userOveride = true
// and this method only has one caller. Can we fold it into the caller?
private static CultureInfo GetCultureByName(String name, bool userOverride)
{
CultureInfo ci = null;
// Try to get our culture
try
{
ci = userOverride ? new CultureInfo(name) : CultureInfo.GetCultureInfo(name);
}
catch (ArgumentException)
{
}
if (ci == null)
{
ci = InvariantCulture;
}
return ci;
}
//
// Return a specific culture. A tad irrelevent now since we always return valid data
// for neutral locales.
//
// Note that there's interesting behavior that tries to find a smaller name, ala RFC4647,
// if we can't find a bigger name. That doesn't help with things like "zh" though, so
// the approach is of questionable value
//
public static CultureInfo CreateSpecificCulture(String name)
{
Contract.Ensures(Contract.Result<CultureInfo>() != null);
CultureInfo culture;
try
{
culture = new CultureInfo(name);
}
catch (ArgumentException)
{
// When CultureInfo throws this exception, it may be because someone passed the form
// like "az-az" because it came out of an http accept lang. We should try a little
// parsing to perhaps fall back to "az" here and use *it* to create the neutral.
int idx;
culture = null;
for (idx = 0; idx < name.Length; idx++)
{
if ('-' == name[idx])
{
try
{
culture = new CultureInfo(name.Substring(0, idx));
break;
}
catch (ArgumentException)
{
// throw the original exception so the name in the string will be right
throw;
}
}
}
if (culture == null)
{
// nothing to save here; throw the original exception
throw;
}
}
// In the most common case, they've given us a specific culture, so we'll just return that.
if (!(culture.IsNeutralCulture))
{
return culture;
}
return (new CultureInfo(culture.m_cultureData.SSPECIFICCULTURE));
}
// //
// // Return a specific culture. A tad irrelevent now since we always return valid data
// // for neutral locales.
// //
// // Note that there's interesting behavior that tries to find a smaller name, ala RFC4647,
// // if we can't find a bigger name. That doesn't help with things like "zh" though, so
// // the approach is of questionable value
// //
internal static bool VerifyCultureName(String cultureName, bool throwException)
{
// This function is used by ResourceManager.GetResourceFileName().
// ResourceManager searches for resource using CultureInfo.Name,
// so we should check against CultureInfo.Name.
for (int i = 0; i < cultureName.Length; i++)
{
char c = cultureName[i];
// TODO: Names can only be RFC4646 names (ie: a-zA-Z0-9) while this allows any unicode letter/digit
if (Char.IsLetterOrDigit(c) || c == '-' || c == '_')
{
continue;
}
if (throwException)
{
throw new ArgumentException(SR.Format(SR.Argument_InvalidResourceCultureName, cultureName));
}
return false;
}
return true;
}
internal static bool VerifyCultureName(CultureInfo culture, bool throwException)
{
//If we have an instance of one of our CultureInfos, the user can't have changed the
//name and we know that all names are valid in files.
if (!culture.m_isInherited)
{
return true;
}
return VerifyCultureName(culture.Name, throwException);
}
////////////////////////////////////////////////////////////////////////
//
// CurrentCulture
//
// This instance provides methods based on the current user settings.
// These settings are volatile and may change over the lifetime of the
// thread.
//
////////////////////////////////////////////////////////////////////////
//
// We use the following order to return CurrentCulture and CurrentUICulture
// o Use WinRT to return the current user profile language
// o use current thread culture if the user already set one using CurrentCulture/CurrentUICulture
// o use thread culture if the user already set one using DefaultThreadCurrentCulture
// or DefaultThreadCurrentUICulture
// o Use NLS default user culture
// o Use NLS default system culture
// o Use Invariant culture
//
public static CultureInfo CurrentCulture
{
get
{
CultureInfo ci = GetUserDefaultCultureCacheOverride();
if (ci != null)
{
return ci;
}
if (s_currentThreadCulture != null)
{
return s_currentThreadCulture;
}
ci = s_DefaultThreadCurrentCulture;
if (ci != null)
{
return ci;
}
// if s_userDefaultCulture == null means CultureInfo statics didn't get initialized yet. this can happen if there early static
// method get executed which eventually hit the cultureInfo code while CultureInfo statics didn't get chance to initialize
if (s_userDefaultCulture == null)
{
Init();
}
Debug.Assert(s_userDefaultCulture != null);
return s_userDefaultCulture;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
#if ENABLE_WINRT
WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks;
if (callbacks != null && callbacks.IsAppxModel())
{
callbacks.SetGlobalDefaultCulture(value);
return;
}
#endif
s_currentThreadCulture = value;
}
}
public static CultureInfo CurrentUICulture
{
get
{
CultureInfo ci = GetUserDefaultCultureCacheOverride();
if (ci != null)
{
return ci;
}
if (s_currentThreadUICulture != null)
{
return s_currentThreadUICulture;
}
ci = s_DefaultThreadCurrentUICulture;
if (ci != null)
{
return ci;
}
// if s_userDefaultCulture == null means CultureInfo statics didn't get initialized yet. this can happen if there early static
// method get executed which eventually hit the cultureInfo code while CultureInfo statics didn't get chance to initialize
if (s_userDefaultCulture == null)
{
Init();
}
Debug.Assert(s_userDefaultCulture != null);
return s_userDefaultCulture;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
CultureInfo.VerifyCultureName(value, true);
#if ENABLE_WINRT
WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks;
if (callbacks != null && callbacks.IsAppxModel())
{
callbacks.SetGlobalDefaultCulture(value);
return;
}
#endif
s_currentThreadUICulture = value;
}
}
public static CultureInfo InstalledUICulture
{
get
{
Contract.Ensures(Contract.Result<CultureInfo>() != null);
if (s_userDefaultCulture == null)
{
Init();
}
Contract.Assert(s_userDefaultCulture != null, "[CultureInfo.InstalledUICulture] s_userDefaultCulture != null");
return s_userDefaultCulture;
}
}
public static CultureInfo DefaultThreadCurrentCulture
{
get { return s_DefaultThreadCurrentCulture; }
set
{
// If you add pre-conditions to this method, check to see if you also need to
// add them to Thread.CurrentCulture.set.
s_DefaultThreadCurrentCulture = value;
}
}
public static CultureInfo DefaultThreadCurrentUICulture
{
get { return s_DefaultThreadCurrentUICulture; }
set
{
//If they're trying to use a Culture with a name that we can't use in resource lookup,
//don't even let them set it on the thread.
// If you add more pre-conditions to this method, check to see if you also need to
// add them to Thread.CurrentUICulture.set.
if (value != null)
{
CultureInfo.VerifyCultureName(value, true);
}
s_DefaultThreadCurrentUICulture = value;
}
}
////////////////////////////////////////////////////////////////////////
//
// InvariantCulture
//
// This instance provides methods, for example for casing and sorting,
// that are independent of the system and current user settings. It
// should be used only by processes such as some system services that
// require such invariant results (eg. file systems). In general,
// the results are not linguistically correct and do not match any
// culture info.
//
////////////////////////////////////////////////////////////////////////
public static CultureInfo InvariantCulture
{
get
{
return (s_InvariantCultureInfo);
}
}
////////////////////////////////////////////////////////////////////////
//
// Parent
//
// Return the parent CultureInfo for the current instance.
//
////////////////////////////////////////////////////////////////////////
public virtual CultureInfo Parent
{
get
{
if (null == _parent)
{
CultureInfo culture = null;
try
{
string parentName = this.m_cultureData.SPARENT;
if (String.IsNullOrEmpty(parentName))
{
culture = InvariantCulture;
}
else
{
culture = new CultureInfo(parentName, this.m_cultureData.UseUserOverride);
}
}
catch (ArgumentException)
{
// For whatever reason our IPARENT or SPARENT wasn't correct, so use invariant
// We can't allow ourselves to fail. In case of custom cultures the parent of the
// current custom culture isn't installed.
culture = InvariantCulture;
}
Interlocked.CompareExchange<CultureInfo>(ref _parent, culture, null);
}
return _parent;
}
}
public virtual int LCID
{
get
{
return (this.m_cultureData.ILANGUAGE);
}
}
public virtual int KeyboardLayoutId
{
get
{
return m_cultureData.IINPUTLANGUAGEHANDLE;
}
}
public static CultureInfo[] GetCultures(CultureTypes types)
{
Contract.Ensures(Contract.Result<CultureInfo[]>() != null);
// internally we treat UserCustomCultures as Supplementals but v2
// treats as Supplementals and Replacements
if ((types & CultureTypes.UserCustomCulture) == CultureTypes.UserCustomCulture)
{
types |= CultureTypes.ReplacementCultures;
}
return (CultureData.GetCultures(types));
}
////////////////////////////////////////////////////////////////////////
//
// Name
//
// Returns the full name of the CultureInfo. The name is in format like
// "en-US" This version does NOT include sort information in the name.
//
////////////////////////////////////////////////////////////////////////
public virtual String Name
{
get
{
// We return non sorting name here.
if (_nonSortName == null)
{
_nonSortName = this.m_cultureData.SNAME;
if (_nonSortName == null)
{
_nonSortName = String.Empty;
}
}
return _nonSortName;
}
}
// This one has the sort information (ie: de-DE_phoneb)
internal String SortName
{
get
{
if (_sortName == null)
{
_sortName = this.m_cultureData.SCOMPAREINFO;
}
return _sortName;
}
}
public string IetfLanguageTag
{
get
{
Contract.Ensures(Contract.Result<string>() != null);
// special case the compatibility cultures
switch (this.Name)
{
case "zh-CHT":
return "zh-Hant";
case "zh-CHS":
return "zh-Hans";
default:
return this.Name;
}
}
}
////////////////////////////////////////////////////////////////////////
//
// DisplayName
//
// Returns the full name of the CultureInfo in the localized language.
// For example, if the localized language of the runtime is Spanish and the CultureInfo is
// US English, "Ingles (Estados Unidos)" will be returned.
//
////////////////////////////////////////////////////////////////////////
public virtual String DisplayName
{
get
{
Contract.Ensures(Contract.Result<String>() != null);
Debug.Assert(m_name != null, "[CultureInfo.DisplayName] Always expect m_name to be set");
return m_cultureData.SLOCALIZEDDISPLAYNAME;
}
}
////////////////////////////////////////////////////////////////////////
//
// GetNativeName
//
// Returns the full name of the CultureInfo in the native language.
// For example, if the CultureInfo is US English, "English
// (United States)" will be returned.
//
////////////////////////////////////////////////////////////////////////
public virtual String NativeName
{
get
{
Contract.Ensures(Contract.Result<String>() != null);
return (this.m_cultureData.SNATIVEDISPLAYNAME);
}
}
////////////////////////////////////////////////////////////////////////
//
// GetEnglishName
//
// Returns the full name of the CultureInfo in English.
// For example, if the CultureInfo is US English, "English
// (United States)" will be returned.
//
////////////////////////////////////////////////////////////////////////
public virtual String EnglishName
{
get
{
Contract.Ensures(Contract.Result<String>() != null);
return (this.m_cultureData.SENGDISPLAYNAME);
}
}
// ie: en
public virtual String TwoLetterISOLanguageName
{
get
{
Contract.Ensures(Contract.Result<String>() != null);
return (this.m_cultureData.SISO639LANGNAME);
}
}
// ie: eng
public virtual String ThreeLetterISOLanguageName
{
get
{
Contract.Ensures(Contract.Result<String>() != null);
return m_cultureData.SISO639LANGNAME2;
}
}
////////////////////////////////////////////////////////////////////////
//
// ThreeLetterWindowsLanguageName
//
// Returns the 3 letter windows language name for the current instance. eg: "ENU"
// The ISO names are much preferred
//
////////////////////////////////////////////////////////////////////////
public virtual String ThreeLetterWindowsLanguageName
{
get
{
Contract.Ensures(Contract.Result<String>() != null);
return m_cultureData.SABBREVLANGNAME;
}
}
////////////////////////////////////////////////////////////////////////
//
// CompareInfo Read-Only Property
//
// Gets the CompareInfo for this culture.
//
////////////////////////////////////////////////////////////////////////
public virtual CompareInfo CompareInfo
{
get
{
if (_compareInfo == null)
{
// Since CompareInfo's don't have any overrideable properties, get the CompareInfo from
// the Non-Overridden CultureInfo so that we only create one CompareInfo per culture
CompareInfo temp = UseUserOverride
? GetCultureInfo(this.m_name).CompareInfo
: new CompareInfo(this);
if (OkayToCacheClassWithCompatibilityBehavior)
{
_compareInfo = temp;
}
else
{
return temp;
}
}
return (_compareInfo);
}
}
private static bool OkayToCacheClassWithCompatibilityBehavior
{
get
{
return true;
}
}
////////////////////////////////////////////////////////////////////////
//
// TextInfo
//
// Gets the TextInfo for this culture.
//
////////////////////////////////////////////////////////////////////////
public virtual TextInfo TextInfo
{
get
{
if (_textInfo == null)
{
// Make a new textInfo
TextInfo tempTextInfo = new TextInfo(this.m_cultureData);
tempTextInfo.SetReadOnlyState(_isReadOnly);
if (OkayToCacheClassWithCompatibilityBehavior)
{
_textInfo = tempTextInfo;
}
else
{
return tempTextInfo;
}
}
return (_textInfo);
}
}
////////////////////////////////////////////////////////////////////////
//
// Equals
//
// Implements Object.Equals(). Returns a boolean indicating whether
// or not object refers to the same CultureInfo as the current instance.
//
////////////////////////////////////////////////////////////////////////
public override bool Equals(Object value)
{
if (Object.ReferenceEquals(this, value))
return true;
CultureInfo that = value as CultureInfo;
if (that != null)
{
// using CompareInfo to verify the data passed through the constructor
// CultureInfo(String cultureName, String textAndCompareCultureName)
return (this.Name.Equals(that.Name) && this.CompareInfo.Equals(that.CompareInfo));
}
return (false);
}
////////////////////////////////////////////////////////////////////////
//
// GetHashCode
//
// Implements Object.GetHashCode(). Returns the hash code for the
// CultureInfo. The hash code is guaranteed to be the same for CultureInfo A
// and B where A.Equals(B) is true.
//
////////////////////////////////////////////////////////////////////////
public override int GetHashCode()
{
return (this.Name.GetHashCode() + this.CompareInfo.GetHashCode());
}
////////////////////////////////////////////////////////////////////////
//
// ToString
//
// Implements Object.ToString(). Returns the name of the CultureInfo,
// eg. "de-DE_phoneb", "en-US", or "fj-FJ".
//
////////////////////////////////////////////////////////////////////////
public override String ToString()
{
return m_name;
}
public virtual Object GetFormat(Type formatType)
{
if (formatType == typeof(NumberFormatInfo))
return (NumberFormat);
if (formatType == typeof(DateTimeFormatInfo))
return (DateTimeFormat);
return (null);
}
public virtual bool IsNeutralCulture
{
get
{
return this.m_cultureData.IsNeutralCulture;
}
}
public CultureTypes CultureTypes
{
get
{
CultureTypes types = 0;
if (m_cultureData.IsNeutralCulture)
types |= CultureTypes.NeutralCultures;
else
types |= CultureTypes.SpecificCultures;
types |= m_cultureData.IsWin32Installed ? CultureTypes.InstalledWin32Cultures : 0;
// Disable warning 618: System.Globalization.CultureTypes.FrameworkCultures' is obsolete
#pragma warning disable 618
types |= m_cultureData.IsFramework ? CultureTypes.FrameworkCultures : 0;
#pragma warning restore 618
types |= m_cultureData.IsSupplementalCustomCulture ? CultureTypes.UserCustomCulture : 0;
types |= m_cultureData.IsReplacementCulture ? CultureTypes.ReplacementCultures | CultureTypes.UserCustomCulture : 0;
return types;
}
}
public virtual NumberFormatInfo NumberFormat
{
get
{
if (numInfo == null)
{
NumberFormatInfo temp = new NumberFormatInfo(this.m_cultureData);
temp.isReadOnly = _isReadOnly;
Interlocked.CompareExchange(ref numInfo, temp, null);
}
return (numInfo);
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value), SR.ArgumentNull_Obj);
}
VerifyWritable();
numInfo = value;
}
}
////////////////////////////////////////////////////////////////////////
//
// GetDateTimeFormatInfo
//
// Create a DateTimeFormatInfo, and fill in the properties according to
// the CultureID.
//
////////////////////////////////////////////////////////////////////////
public virtual DateTimeFormatInfo DateTimeFormat
{
get
{
if (dateTimeInfo == null)
{
// Change the calendar of DTFI to the specified calendar of this CultureInfo.
DateTimeFormatInfo temp = new DateTimeFormatInfo(this.m_cultureData, this.Calendar);
temp._isReadOnly = _isReadOnly;
Interlocked.CompareExchange(ref dateTimeInfo, temp, null);
}
return (dateTimeInfo);
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value), SR.ArgumentNull_Obj);
}
VerifyWritable();
dateTimeInfo = value;
}
}
public void ClearCachedData()
{
s_userDefaultCulture = null;
RegionInfo.s_currentRegionInfo = null;
#pragma warning disable 0618 // disable the obsolete warning
//TimeZone.ResetTimeZone();
#pragma warning restore 0618
TimeZoneInfo.ClearCachedData();
s_LcidCachedCultures = null;
s_NameCachedCultures = null;
CultureData.ClearCachedData();
}
/*=================================GetCalendarInstance==========================
**Action: Map a Win32 CALID to an instance of supported calendar.
**Returns: An instance of calendar.
**Arguments: calType The Win32 CALID
**Exceptions:
** Shouldn't throw exception since the calType value is from our data table or from Win32 registry.
** If we are in trouble (like getting a weird value from Win32 registry), just return the GregorianCalendar.
============================================================================*/
internal static Calendar GetCalendarInstance(CalendarId calType)
{
if (calType == CalendarId.GREGORIAN)
{
return (new GregorianCalendar());
}
return GetCalendarInstanceRare(calType);
}
//This function exists as a shortcut to prevent us from loading all of the non-gregorian
//calendars unless they're required.
internal static Calendar GetCalendarInstanceRare(CalendarId calType)
{
Debug.Assert(calType != CalendarId.GREGORIAN, "calType!=CalendarId.GREGORIAN");
switch (calType)
{
case CalendarId.GREGORIAN_US: // Gregorian (U.S.) calendar
case CalendarId.GREGORIAN_ME_FRENCH: // Gregorian Middle East French calendar
case CalendarId.GREGORIAN_ARABIC: // Gregorian Arabic calendar
case CalendarId.GREGORIAN_XLIT_ENGLISH: // Gregorian Transliterated English calendar
case CalendarId.GREGORIAN_XLIT_FRENCH: // Gregorian Transliterated French calendar
return (new GregorianCalendar((GregorianCalendarTypes)calType));
case CalendarId.TAIWAN: // Taiwan Era calendar
return (new TaiwanCalendar());
case CalendarId.JAPAN: // Japanese Emperor Era calendar
return (new JapaneseCalendar());
case CalendarId.KOREA: // Korean Tangun Era calendar
return (new KoreanCalendar());
case CalendarId.THAI: // Thai calendar
return (new ThaiBuddhistCalendar());
case CalendarId.HIJRI: // Hijri (Arabic Lunar) calendar
return (new HijriCalendar());
case CalendarId.HEBREW: // Hebrew (Lunar) calendar
return (new HebrewCalendar());
case CalendarId.UMALQURA:
return (new UmAlQuraCalendar());
case CalendarId.PERSIAN:
return (new PersianCalendar());
}
return (new GregorianCalendar());
}
/*=================================Calendar==========================
**Action: Return/set the default calendar used by this culture.
** This value can be overridden by regional option if this is a current culture.
**Returns:
**Arguments:
**Exceptions:
** ArgumentNull_Obj if the set value is null.
============================================================================*/
public virtual Calendar Calendar
{
get
{
if (_calendar == null)
{
Debug.Assert(this.m_cultureData.CalendarIds.Length > 0, "this.m_cultureData.CalendarIds.Length > 0");
// Get the default calendar for this culture. Note that the value can be
// from registry if this is a user default culture.
Calendar newObj = this.m_cultureData.DefaultCalendar;
System.Threading.Interlocked.MemoryBarrier();
newObj.SetReadOnlyState(_isReadOnly);
_calendar = newObj;
}
return (_calendar);
}
}
/*=================================OptionCalendars==========================
**Action: Return an array of the optional calendar for this culture.
**Returns: an array of Calendar.
**Arguments:
**Exceptions:
============================================================================*/
public virtual Calendar[] OptionalCalendars
{
get
{
Contract.Ensures(Contract.Result<Calendar[]>() != null);
//
// This property always returns a new copy of the calendar array.
//
CalendarId[] calID = this.m_cultureData.CalendarIds;
Calendar[] cals = new Calendar[calID.Length];
for (int i = 0; i < cals.Length; i++)
{
cals[i] = GetCalendarInstance(calID[i]);
}
return (cals);
}
}
public bool UseUserOverride
{
get
{
return m_cultureData.UseUserOverride;
}
}
public CultureInfo GetConsoleFallbackUICulture()
{
Contract.Ensures(Contract.Result<CultureInfo>() != null);
CultureInfo temp = m_consoleFallbackCulture;
if (temp == null)
{
temp = CreateSpecificCulture(m_cultureData.SCONSOLEFALLBACKNAME);
temp._isReadOnly = true;
m_consoleFallbackCulture = temp;
}
return (temp);
}
public virtual Object Clone()
{
CultureInfo ci = (CultureInfo)MemberwiseClone();
ci._isReadOnly = false;
//If this is exactly our type, we can make certain optimizations so that we don't allocate NumberFormatInfo or DTFI unless
//they've already been allocated. If this is a derived type, we'll take a more generic codepath.
if (!m_isInherited)
{
if (this.dateTimeInfo != null)
{
ci.dateTimeInfo = (DateTimeFormatInfo)this.dateTimeInfo.Clone();
}
if (this.numInfo != null)
{
ci.numInfo = (NumberFormatInfo)this.numInfo.Clone();
}
}
else
{
ci.DateTimeFormat = (DateTimeFormatInfo)this.DateTimeFormat.Clone();
ci.NumberFormat = (NumberFormatInfo)this.NumberFormat.Clone();
}
if (_textInfo != null)
{
ci._textInfo = (TextInfo)_textInfo.Clone();
}
if (_calendar != null)
{
ci._calendar = (Calendar)_calendar.Clone();
}
return (ci);
}
public static CultureInfo ReadOnly(CultureInfo ci)
{
if (ci == null)
{
throw new ArgumentNullException(nameof(ci));
}
Contract.Ensures(Contract.Result<CultureInfo>() != null);
Contract.EndContractBlock();
if (ci.IsReadOnly)
{
return (ci);
}
CultureInfo newInfo = (CultureInfo)(ci.MemberwiseClone());
if (!ci.IsNeutralCulture)
{
//If this is exactly our type, we can make certain optimizations so that we don't allocate NumberFormatInfo or DTFI unless
//they've already been allocated. If this is a derived type, we'll take a more generic codepath.
if (!ci.m_isInherited)
{
if (ci.dateTimeInfo != null)
{
newInfo.dateTimeInfo = DateTimeFormatInfo.ReadOnly(ci.dateTimeInfo);
}
if (ci.numInfo != null)
{
newInfo.numInfo = NumberFormatInfo.ReadOnly(ci.numInfo);
}
}
else
{
newInfo.DateTimeFormat = DateTimeFormatInfo.ReadOnly(ci.DateTimeFormat);
newInfo.NumberFormat = NumberFormatInfo.ReadOnly(ci.NumberFormat);
}
}
if (ci._textInfo != null)
{
newInfo._textInfo = TextInfo.ReadOnly(ci._textInfo);
}
if (ci._calendar != null)
{
newInfo._calendar = Calendar.ReadOnly(ci._calendar);
}
// Don't set the read-only flag too early.
// We should set the read-only flag here. Otherwise, info.DateTimeFormat will not be able to set.
newInfo._isReadOnly = true;
return (newInfo);
}
public bool IsReadOnly
{
get
{
return (_isReadOnly);
}
}
private void VerifyWritable()
{
if (_isReadOnly)
{
throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
}
}
// Helper function both both overloads of GetCachedReadOnlyCulture. If lcid is 0, we use the name.
// If lcid is -1, use the altName and create one of those special SQL cultures.
internal static CultureInfo GetCultureInfoHelper(int lcid, string name, string altName)
{
// retval is our return value.
CultureInfo retval;
// Temporary hashtable for the names.
LowLevelDictionary<string, CultureInfo> tempNameHT = s_NameCachedCultures;
if (name != null)
{
name = CultureData.AnsiToLower(name);
}
if (altName != null)
{
altName = CultureData.AnsiToLower(altName);
}
// We expect the same result for both hashtables, but will test individually for added safety.
if (tempNameHT == null)
{
tempNameHT = new LowLevelDictionary<string, CultureInfo>();
}
else
{
// If we are called by name, check if the object exists in the hashtable. If so, return it.
if (lcid == -1 || lcid == 0)
{
bool ret;
using (LockHolder.Hold(s_lock))
{
ret = tempNameHT.TryGetValue(lcid == 0 ? name : name + '\xfffd' + altName, out retval);
}
if (ret && retval != null)
{
return retval;
}
}
}
// Next, the Lcid table.
LowLevelDictionary<int, CultureInfo> tempLcidHT = s_LcidCachedCultures;
if (tempLcidHT == null)
{
// Case insensitive is not an issue here, save the constructor call.
tempLcidHT = new LowLevelDictionary<int, CultureInfo>();
}
else
{
// If we were called by Lcid, check if the object exists in the table. If so, return it.
if (lcid > 0)
{
bool ret;
using (LockHolder.Hold(s_lock))
{
ret = tempLcidHT.TryGetValue(lcid, out retval);
}
if (ret && retval != null)
{
return retval;
}
}
}
// We now have two temporary hashtables and the desired object was not found.
// We'll construct it. We catch any exceptions from the constructor call and return null.
try
{
switch (lcid)
{
case -1:
// call the private constructor
retval = new CultureInfo(name, altName);
break;
case 0:
retval = new CultureInfo(name, false);
break;
default:
retval = new CultureInfo(lcid, false);
break;
}
}
catch (ArgumentException)
{
return null;
}
// Set it to read-only
retval._isReadOnly = true;
if (lcid == -1)
{
using (LockHolder.Hold(s_lock))
{
// This new culture will be added only to the name hash table.
tempNameHT[name + '\xfffd' + altName] = retval;
}
// when lcid == -1 then TextInfo object is already get created and we need to set it as read only.
retval.TextInfo.SetReadOnlyState(true);
}
else if (lcid == 0)
{
// Remember our name (as constructed). Do NOT use alternate sort name versions because
// we have internal state representing the sort. (So someone would get the wrong cached version)
string newName = CultureData.AnsiToLower(retval.m_name);
// We add this new culture info object to both tables.
using (LockHolder.Hold(s_lock))
{
tempNameHT[newName] = retval;
}
}
else
{
using (LockHolder.Hold(s_lock))
{
tempLcidHT[lcid] = retval;
}
}
// Copy the two hashtables to the corresponding member variables. This will potentially overwrite
// new tables simultaneously created by a new thread, but maximizes thread safety.
if (-1 != lcid)
{
// Only when we modify the lcid hash table, is there a need to overwrite.
s_LcidCachedCultures = tempLcidHT;
}
s_NameCachedCultures = tempNameHT;
// Finally, return our new CultureInfo object.
return retval;
}
// Gets a cached copy of the specified culture from an internal hashtable (or creates it
// if not found). (LCID version)... use named version
public static CultureInfo GetCultureInfo(int culture)
{
// Must check for -1 now since the helper function uses the value to signal
// the altCulture code path for SQL Server.
// Also check for zero as this would fail trying to add as a key to the hash.
if (culture <= 0)
{
throw new ArgumentOutOfRangeException(nameof(culture), SR.ArgumentOutOfRange_NeedPosNum);
}
Contract.Ensures(Contract.Result<CultureInfo>() != null);
Contract.EndContractBlock();
CultureInfo retval = GetCultureInfoHelper(culture, null, null);
if (null == retval)
{
throw new CultureNotFoundException(nameof(culture), culture, SR.Argument_CultureNotSupported);
}
return retval;
}
// Gets a cached copy of the specified culture from an internal hashtable (or creates it
// if not found). (Named version)
public static CultureInfo GetCultureInfo(string name)
{
// Make sure we have a valid, non-zero length string as name
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
CultureInfo retval = GetCultureInfoHelper(0, name, null);
if (retval == null)
{
throw new CultureNotFoundException(
nameof(name), name, SR.Argument_CultureNotSupported);
}
return retval;
}
// Gets a cached copy of the specified culture from an internal hashtable (or creates it
// if not found).
public static CultureInfo GetCultureInfo(string name, string altName)
{
// Make sure we have a valid, non-zero length string as name
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (altName == null)
{
throw new ArgumentNullException(nameof(altName));
}
Contract.Ensures(Contract.Result<CultureInfo>() != null);
Contract.EndContractBlock();
CultureInfo retval = GetCultureInfoHelper(-1, name, altName);
if (retval == null)
{
throw new CultureNotFoundException("name or altName",
SR.Format(SR.Argument_OneOfCulturesNotSupported, name, altName));
}
return retval;
}
// This function is deprecated, we don't like it
public static CultureInfo GetCultureInfoByIetfLanguageTag(string name)
{
Contract.Ensures(Contract.Result<CultureInfo>() != null);
// Disallow old zh-CHT/zh-CHS names
if (name == "zh-CHT" || name == "zh-CHS")
{
throw new CultureNotFoundException(nameof(name), SR.Format(SR.Argument_CultureIetfNotSupported, name));
}
CultureInfo ci = GetCultureInfo(name);
// Disallow alt sorts and es-es_TS
if (ci.LCID > 0xffff || ci.LCID == 0x040a)
{
throw new CultureNotFoundException(nameof(name), SR.Format(SR.Argument_CultureIetfNotSupported, name));
}
return ci;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using NServiceKit.Common;
using NServiceKit.Common.Web;
using NServiceKit.Service;
using NServiceKit.ServiceClient.Web;
using NServiceKit.ServiceHost;
using NServiceKit.ServiceInterface.ServiceModel;
using NServiceKit.ServiceModel;
using NServiceKit.Text;
using NServiceKit.WebHost.Endpoints;
using NServiceKit.WebHost.Endpoints.Support;
namespace NServiceKit.ServiceInterface.Testing
{
/// <summary>A test base.</summary>
public abstract class TestBase
{
/// <summary>Gets or sets the application host.</summary>
///
/// <value>The application host.</value>
protected IAppHost AppHost { get; set; }
/// <summary>Gets or sets a value indicating whether this object has configured.</summary>
///
/// <value>true if this object has configured, false if not.</value>
protected bool HasConfigured { get; set; }
/// <summary>Initializes a new instance of the NServiceKit.ServiceInterface.Testing.TestBase class.</summary>
///
/// <param name="serviceAssemblies">The service assemblies.</param>
protected TestBase(params Assembly[] serviceAssemblies)
: this(null, serviceAssemblies) { }
/// <summary>Initializes a new instance of the NServiceKit.ServiceInterface.Testing.TestBase class.</summary>
///
/// <param name="serviceClientBaseUri">URI of the service client base.</param>
/// <param name="serviceAssemblies"> The service assemblies.</param>
protected TestBase(string serviceClientBaseUri, params Assembly[] serviceAssemblies)
{
if (serviceAssemblies.Length == 0)
serviceAssemblies = new[] { GetType().Assembly };
ServiceClientBaseUri = serviceClientBaseUri;
ServiceAssemblies = serviceAssemblies;
this.AppHost = new TestAppHost(null, serviceAssemblies);
EndpointHost.ServiceManager = this.AppHost.Config.ServiceManager;
EndpointHost.ConfigureHost(this.AppHost, "TestBase", EndpointHost.ServiceManager);
}
/// <summary>Configures the given container.</summary>
///
/// <param name="container">The container.</param>
protected abstract void Configure(Funq.Container container);
/// <summary>Gets the container.</summary>
///
/// <value>The container.</value>
protected Funq.Container Container
{
get { return EndpointHost.ServiceManager.Container; }
}
/// <summary>Gets the routes.</summary>
///
/// <value>The routes.</value>
protected IServiceRoutes Routes
{
get { return EndpointHost.ServiceManager.ServiceController.Routes; }
}
//All integration tests call the Webservices hosted at the following location:
protected string ServiceClientBaseUri { get; set; }
/// <summary>Gets or sets the service assemblies.</summary>
///
/// <value>The service assemblies.</value>
protected Assembly[] ServiceAssemblies { get; set; }
/// <summary>Executes the before test fixture action.</summary>
public virtual void OnBeforeTestFixture()
{
OnConfigure();
}
/// <summary>Executes the configure action.</summary>
protected virtual void OnConfigure()
{
if (HasConfigured) return;
HasConfigured = true;
Configure(Container);
EndpointHost.AfterInit();
}
/// <summary>Executes the before each test action.</summary>
public virtual void OnBeforeEachTest()
{
OnConfigure();
}
/// <summary>Creates new service client.</summary>
///
/// <returns>The new new service client.</returns>
protected virtual IServiceClient CreateNewServiceClient()
{
return new DirectServiceClient(this, EndpointHost.ServiceManager);
}
/// <summary>Creates new rest client.</summary>
///
/// <returns>The new new rest client.</returns>
protected virtual IRestClient CreateNewRestClient()
{
return new DirectServiceClient(this, EndpointHost.ServiceManager);
}
/// <summary>Creates new rest client asynchronous.</summary>
///
/// <returns>The new new rest client asynchronous.</returns>
protected virtual IRestClientAsync CreateNewRestClientAsync()
{
return new DirectServiceClient(this, EndpointHost.ServiceManager);
}
/// <summary>A direct service client.</summary>
public class DirectServiceClient : IServiceClient, IRestClient
{
private readonly TestBase parent;
ServiceManager ServiceManager { get; set; }
/// <summary>Initializes a new instance of the NServiceKit.ServiceInterface.Testing.TestBase.DirectServiceClient class.</summary>
///
/// <param name="parent"> The parent.</param>
/// <param name="serviceManager">Manager for service.</param>
public DirectServiceClient(TestBase parent, ServiceManager serviceManager)
{
this.parent = parent;
this.ServiceManager = serviceManager;
}
/// <summary>Sends an one way.</summary>
///
/// <param name="request">The request.</param>
public void SendOneWay(object request)
{
ServiceManager.Execute(request);
}
/// <summary>Sends an one way.</summary>
///
/// <param name="relativeOrAbsoluteUrl">URL of the relative or absolute.</param>
/// <param name="request"> The request.</param>
public void SendOneWay(string relativeOrAbsoluteUrl, object request)
{
ServiceManager.Execute(request);
}
/// <summary>Send this message.</summary>
///
/// <exception cref="WebServiceException">Thrown when a Web Service error condition occurs.</exception>
///
/// <typeparam name="TResponse">Type of the response.</typeparam>
/// <param name="request">The request.</param>
///
/// <returns>A TResponse.</returns>
public TResponse Send<TResponse>(object request)
{
var response = ServiceManager.Execute(request);
var httpResult = response as IHttpResult;
if (httpResult != null)
{
if (httpResult.StatusCode >= HttpStatusCode.BadRequest)
{
var webEx = new WebServiceException(httpResult.StatusDescription) {
ResponseDto = httpResult.Response,
StatusCode = httpResult.Status,
};
throw webEx;
}
return (TResponse) httpResult.Response;
}
return (TResponse)response;
}
/// <summary>Send this message.</summary>
///
/// <exception cref="NotImplementedException">Thrown when the requested operation is unimplemented.</exception>
///
/// <typeparam name="TResponse">Type of the response.</typeparam>
/// <param name="request">The request.</param>
///
/// <returns>A TResponse.</returns>
public TResponse Send<TResponse>(IReturn<TResponse> request)
{
throw new NotImplementedException();
}
/// <summary>Send this message.</summary>
///
/// <exception cref="NotImplementedException">Thrown when the requested operation is unimplemented.</exception>
///
/// <param name="request">The request.</param>
public void Send(IReturnVoid request)
{
throw new NotImplementedException();
}
/// <summary>Gets.</summary>
///
/// <exception cref="NotImplementedException">Thrown when the requested operation is unimplemented.</exception>
///
/// <typeparam name="TResponse">Type of the response.</typeparam>
/// <param name="request">The request.</param>
///
/// <returns>A TResponse.</returns>
public TResponse Get<TResponse>(IReturn<TResponse> request)
{
throw new NotImplementedException();
}
/// <summary>Gets the given request.</summary>
///
/// <exception cref="NotImplementedException">Thrown when the requested operation is unimplemented.</exception>
///
/// <param name="request">The request.</param>
public void Get(IReturnVoid request)
{
throw new NotImplementedException();
}
/// <summary>Gets.</summary>
///
/// <typeparam name="TResponse">Type of the response.</typeparam>
/// <param name="relativeOrAbsoluteUrl">URL of the relative or absolute.</param>
///
/// <returns>A TResponse.</returns>
public TResponse Get<TResponse>(string relativeOrAbsoluteUrl)
{
return parent.ExecutePath<TResponse>(HttpMethods.Get, new UrlParts(relativeOrAbsoluteUrl), null);
}
/// <summary>Deletes the given relativeOrAbsoluteUrl.</summary>
///
/// <exception cref="NotImplementedException">Thrown when the requested operation is unimplemented.</exception>
///
/// <typeparam name="TResponse">Type of the response.</typeparam>
/// <param name="request">The request.</param>
///
/// <returns>A TResponse.</returns>
public TResponse Delete<TResponse>(IReturn<TResponse> request)
{
throw new NotImplementedException();
}
/// <summary>Deletes the given request.</summary>
///
/// <exception cref="NotImplementedException">Thrown when the requested operation is unimplemented.</exception>
///
/// <param name="request">The request.</param>
public void Delete(IReturnVoid request)
{
throw new NotImplementedException();
}
/// <summary>Deletes the given relativeOrAbsoluteUrl.</summary>
///
/// <typeparam name="TResponse">Type of the response.</typeparam>
/// <param name="relativeOrAbsoluteUrl">URL of the relative or absolute.</param>
///
/// <returns>A TResponse.</returns>
public TResponse Delete<TResponse>(string relativeOrAbsoluteUrl)
{
return parent.ExecutePath<TResponse>(HttpMethods.Delete, new UrlParts(relativeOrAbsoluteUrl), null);
}
/// <summary>Post this message.</summary>
///
/// <exception cref="NotImplementedException">Thrown when the requested operation is unimplemented.</exception>
///
/// <typeparam name="TResponse">Type of the response.</typeparam>
/// <param name="request">The request.</param>
///
/// <returns>A TResponse.</returns>
public TResponse Post<TResponse>(IReturn<TResponse> request)
{
throw new NotImplementedException();
}
/// <summary>Post this message.</summary>
///
/// <exception cref="NotImplementedException">Thrown when the requested operation is unimplemented.</exception>
///
/// <param name="request">The request.</param>
public void Post(IReturnVoid request)
{
throw new NotImplementedException();
}
/// <summary>Post this message.</summary>
///
/// <typeparam name="TResponse">Type of the response.</typeparam>
/// <param name="relativeOrAbsoluteUrl">URL of the relative or absolute.</param>
/// <param name="request"> The request.</param>
///
/// <returns>A TResponse.</returns>
public TResponse Post<TResponse>(string relativeOrAbsoluteUrl, object request)
{
return parent.ExecutePath<TResponse>(HttpMethods.Post, new UrlParts(relativeOrAbsoluteUrl), request);
}
/// <summary>Puts.</summary>
///
/// <exception cref="NotImplementedException">Thrown when the requested operation is unimplemented.</exception>
///
/// <typeparam name="TResponse">Type of the response.</typeparam>
/// <param name="request">The request.</param>
///
/// <returns>A TResponse.</returns>
public TResponse Put<TResponse>(IReturn<TResponse> request)
{
throw new NotImplementedException();
}
/// <summary>Puts the given request.</summary>
///
/// <exception cref="NotImplementedException">Thrown when the requested operation is unimplemented.</exception>
///
/// <param name="request">The request.</param>
public void Put(IReturnVoid request)
{
throw new NotImplementedException();
}
/// <summary>Puts.</summary>
///
/// <typeparam name="TResponse">Type of the response.</typeparam>
/// <param name="relativeOrAbsoluteUrl">URL of the relative or absolute.</param>
/// <param name="request"> The request.</param>
///
/// <returns>A TResponse.</returns>
public TResponse Put<TResponse>(string relativeOrAbsoluteUrl, object request)
{
return parent.ExecutePath<TResponse>(HttpMethods.Put, new UrlParts(relativeOrAbsoluteUrl), request);
}
/// <summary>Patches.</summary>
///
/// <exception cref="NotImplementedException">Thrown when the requested operation is unimplemented.</exception>
///
/// <typeparam name="TResponse">Type of the response.</typeparam>
/// <param name="request">The request.</param>
///
/// <returns>A TResponse.</returns>
public TResponse Patch<TResponse>(IReturn<TResponse> request)
{
throw new NotImplementedException();
}
/// <summary>Patches the given request.</summary>
///
/// <exception cref="NotImplementedException">Thrown when the requested operation is unimplemented.</exception>
///
/// <param name="request">The request.</param>
public void Patch(IReturnVoid request)
{
throw new NotImplementedException();
}
/// <summary>Patches.</summary>
///
/// <typeparam name="TResponse">Type of the response.</typeparam>
/// <param name="relativeOrAbsoluteUrl">URL of the relative or absolute.</param>
/// <param name="request"> The request.</param>
///
/// <returns>A TResponse.</returns>
public TResponse Patch<TResponse>(string relativeOrAbsoluteUrl, object request)
{
return parent.ExecutePath<TResponse>(HttpMethods.Patch, new UrlParts(relativeOrAbsoluteUrl), request);
}
/// <summary>Posts a file.</summary>
///
/// <exception cref="NotImplementedException">Thrown when the requested operation is unimplemented.</exception>
///
/// <typeparam name="TResponse">Type of the response.</typeparam>
/// <param name="relativeOrAbsoluteUrl">URL of the relative or absolute.</param>
/// <param name="fileToUpload"> The file to upload.</param>
/// <param name="mimeType"> Type of the mime.</param>
///
/// <returns>A TResponse.</returns>
public TResponse PostFile<TResponse>(string relativeOrAbsoluteUrl, FileInfo fileToUpload, string mimeType)
{
throw new NotImplementedException();
}
/// <summary>Custom method.</summary>
///
/// <exception cref="NotImplementedException">Thrown when the requested operation is unimplemented.</exception>
///
/// <param name="httpVerb">The HTTP verb.</param>
/// <param name="request"> The request.</param>
public void CustomMethod(string httpVerb, IReturnVoid request)
{
throw new NotImplementedException();
}
/// <summary>Custom method.</summary>
///
/// <exception cref="NotImplementedException">Thrown when the requested operation is unimplemented.</exception>
///
/// <typeparam name="TResponse">Type of the response.</typeparam>
/// <param name="httpVerb">The HTTP verb.</param>
/// <param name="request"> The request.</param>
///
/// <returns>A TResponse.</returns>
public TResponse CustomMethod<TResponse>(string httpVerb, IReturn<TResponse> request)
{
throw new NotImplementedException();
}
/// <summary>Heads.</summary>
///
/// <exception cref="NotImplementedException">Thrown when the requested operation is unimplemented.</exception>
///
/// <param name="request">The request.</param>
///
/// <returns>A HttpWebResponse.</returns>
public HttpWebResponse Head(IReturn request)
{
throw new NotImplementedException();
}
/// <summary>Heads.</summary>
///
/// <exception cref="NotImplementedException">Thrown when the requested operation is unimplemented.</exception>
///
/// <param name="relativeOrAbsoluteUrl">URL of the relative or absolute.</param>
///
/// <returns>A HttpWebResponse.</returns>
public HttpWebResponse Head(string relativeOrAbsoluteUrl)
{
throw new NotImplementedException();
}
/// <summary>Posts a file.</summary>
///
/// <exception cref="NotImplementedException">Thrown when the requested operation is unimplemented.</exception>
///
/// <typeparam name="TResponse">Type of the response.</typeparam>
/// <param name="relativeOrAbsoluteUrl">URL of the relative or absolute.</param>
/// <param name="fileToUpload"> The file to upload.</param>
/// <param name="fileName"> Filename of the file.</param>
/// <param name="mimeType"> Type of the mime.</param>
///
/// <returns>A TResponse.</returns>
public TResponse PostFile<TResponse>(string relativeOrAbsoluteUrl, Stream fileToUpload, string fileName, string mimeType)
{
throw new NotImplementedException();
}
/// <summary>Sends the asynchronous.</summary>
///
/// <typeparam name="TResponse">Type of the response.</typeparam>
/// <param name="request"> The request.</param>
/// <param name="onSuccess">The on success.</param>
/// <param name="onError"> The on error.</param>
public void SendAsync<TResponse>(object request,
Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
try
{
var response = (TResponse)ServiceManager.Execute(request);
onSuccess(response);
}
catch (Exception ex)
{
HandleException(ex, onError);
}
}
private static void HandleException<TResponse>(Exception exception, Action<TResponse, Exception> onError)
{
var response = (TResponse)typeof(TResponse).CreateInstance();
var hasResponseStatus = response as IHasResponseStatus;
if (hasResponseStatus != null)
{
hasResponseStatus.ResponseStatus = new ResponseStatus {
ErrorCode = exception.GetType().Name,
Message = exception.Message,
StackTrace = exception.StackTrace,
};
}
var webServiceEx = new WebServiceException(exception.Message, exception);
if (onError != null) onError(response, webServiceEx);
}
/// <summary>Sets the credentials.</summary>
///
/// <exception cref="NotImplementedException">Thrown when the requested operation is unimplemented.</exception>
///
/// <param name="userName">Name of the user.</param>
/// <param name="password">The password.</param>
public void SetCredentials(string userName, string password)
{
throw new NotImplementedException();
}
/// <summary>Gets the asynchronous.</summary>
///
/// <exception cref="NotImplementedException">Thrown when the requested operation is unimplemented.</exception>
///
/// <typeparam name="TResponse">Type of the response.</typeparam>
/// <param name="request"> The request.</param>
/// <param name="onSuccess">The on success.</param>
/// <param name="onError"> The on error.</param>
public void GetAsync<TResponse>(IReturn<TResponse> request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
throw new NotImplementedException();
}
/// <summary>Gets the asynchronous.</summary>
///
/// <typeparam name="TResponse">Type of the response.</typeparam>
/// <param name="relativeOrAbsoluteUrl">URL of the relative or absolute.</param>
/// <param name="onSuccess"> The on success.</param>
/// <param name="onError"> The on error.</param>
public void GetAsync<TResponse>(string relativeOrAbsoluteUrl, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
try
{
var response = parent.ExecutePath<TResponse>(HttpMethods.Get, new UrlParts(relativeOrAbsoluteUrl), default(TResponse));
onSuccess(response);
}
catch (Exception ex)
{
HandleException(ex, onError);
}
}
/// <summary>Deletes the asynchronous.</summary>
///
/// <typeparam name="TResponse">Type of the response.</typeparam>
/// <param name="relativeOrAbsoluteUrl">URL of the relative or absolute.</param>
/// <param name="onSuccess"> The on success.</param>
/// <param name="onError"> The on error.</param>
public void DeleteAsync<TResponse>(string relativeOrAbsoluteUrl, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
try
{
var response = parent.ExecutePath<TResponse>(HttpMethods.Delete, new UrlParts(relativeOrAbsoluteUrl), default(TResponse));
onSuccess(response);
}
catch (Exception ex)
{
HandleException(ex, onError);
}
}
/// <summary>Deletes the asynchronous.</summary>
///
/// <exception cref="NotImplementedException">Thrown when the requested operation is unimplemented.</exception>
///
/// <typeparam name="TResponse">Type of the response.</typeparam>
/// <param name="request"> The request.</param>
/// <param name="onSuccess">The on success.</param>
/// <param name="onError"> The on error.</param>
public void DeleteAsync<TResponse>(IReturn<TResponse> request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
throw new NotImplementedException();
}
/// <summary>Posts the asynchronous.</summary>
///
/// <exception cref="NotImplementedException">Thrown when the requested operation is unimplemented.</exception>
///
/// <typeparam name="TResponse">Type of the response.</typeparam>
/// <param name="request"> The request.</param>
/// <param name="onSuccess">The on success.</param>
/// <param name="onError"> The on error.</param>
public void PostAsync<TResponse>(IReturn<TResponse> request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
throw new NotImplementedException();
}
/// <summary>Posts the asynchronous.</summary>
///
/// <typeparam name="TResponse">Type of the response.</typeparam>
/// <param name="relativeOrAbsoluteUrl">URL of the relative or absolute.</param>
/// <param name="request"> The request.</param>
/// <param name="onSuccess"> The on success.</param>
/// <param name="onError"> The on error.</param>
public void PostAsync<TResponse>(string relativeOrAbsoluteUrl, object request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
try
{
var response = parent.ExecutePath<TResponse>(HttpMethods.Post, new UrlParts(relativeOrAbsoluteUrl), request);
onSuccess(response);
}
catch (Exception ex)
{
HandleException(ex, onError);
}
}
/// <summary>Puts the asynchronous.</summary>
///
/// <exception cref="NotImplementedException">Thrown when the requested operation is unimplemented.</exception>
///
/// <typeparam name="TResponse">Type of the response.</typeparam>
/// <param name="request"> The request.</param>
/// <param name="onSuccess">The on success.</param>
/// <param name="onError"> The on error.</param>
public void PutAsync<TResponse>(IReturn<TResponse> request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
throw new NotImplementedException();
}
/// <summary>Puts the asynchronous.</summary>
///
/// <typeparam name="TResponse">Type of the response.</typeparam>
/// <param name="relativeOrAbsoluteUrl">URL of the relative or absolute.</param>
/// <param name="request"> The request.</param>
/// <param name="onSuccess"> The on success.</param>
/// <param name="onError"> The on error.</param>
public void PutAsync<TResponse>(string relativeOrAbsoluteUrl, object request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
try
{
var response = parent.ExecutePath<TResponse>(HttpMethods.Put, new UrlParts(relativeOrAbsoluteUrl), request);
onSuccess(response);
}
catch (Exception ex)
{
HandleException(ex, onError);
}
}
/// <summary>Custom method asynchronous.</summary>
///
/// <exception cref="NotImplementedException">Thrown when the requested operation is unimplemented.</exception>
///
/// <typeparam name="TResponse">Type of the response.</typeparam>
/// <param name="httpVerb"> The HTTP verb.</param>
/// <param name="request"> The request.</param>
/// <param name="onSuccess">The on success.</param>
/// <param name="onError"> The on error.</param>
public void CustomMethodAsync<TResponse>(string httpVerb, IReturn<TResponse> request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
throw new NotImplementedException();
}
/// <summary>Cancel asynchronous.</summary>
///
/// <exception cref="NotImplementedException">Thrown when the requested operation is unimplemented.</exception>
public void CancelAsync()
{
throw new NotImplementedException();
}
/// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
public void Dispose() { }
/// <summary>Posts a file with request.</summary>
///
/// <exception cref="NotImplementedException">Thrown when the requested operation is unimplemented.</exception>
///
/// <typeparam name="TResponse">Type of the response.</typeparam>
/// <param name="relativeOrAbsoluteUrl">URL of the relative or absolute.</param>
/// <param name="fileToUpload"> The file to upload.</param>
/// <param name="request"> The request.</param>
///
/// <returns>A TResponse.</returns>
public TResponse PostFileWithRequest<TResponse>(string relativeOrAbsoluteUrl, FileInfo fileToUpload, object request)
{
throw new NotImplementedException();
}
/// <summary>Posts a file with request.</summary>
///
/// <exception cref="NotImplementedException">Thrown when the requested operation is unimplemented.</exception>
///
/// <typeparam name="TResponse">Type of the response.</typeparam>
/// <param name="relativeOrAbsoluteUrl">URL of the relative or absolute.</param>
/// <param name="fileToUpload"> The file to upload.</param>
/// <param name="fileName"> Filename of the file.</param>
/// <param name="request"> The request.</param>
///
/// <returns>A TResponse.</returns>
public TResponse PostFileWithRequest<TResponse>(string relativeOrAbsoluteUrl, Stream fileToUpload, string fileName, object request)
{
throw new NotImplementedException();
}
}
/// <summary>Executes the path operation.</summary>
///
/// <param name="pathInfo">Information describing the path.</param>
///
/// <returns>An object.</returns>
public object ExecutePath(string pathInfo)
{
return ExecutePath(HttpMethods.Get, pathInfo);
}
private class UrlParts
{
/// <summary>Initializes a new instance of the NServiceKit.ServiceInterface.Testing.TestBase.UrlParts class.</summary>
///
/// <param name="pathInfo">Information describing the path.</param>
public UrlParts(string pathInfo)
{
this.PathInfo = pathInfo.UrlDecode();
var qsIndex = pathInfo.IndexOf("?");
if (qsIndex != -1)
{
var qs = pathInfo.Substring(qsIndex + 1);
this.PathInfo = pathInfo.Substring(0, qsIndex);
var kvps = qs.Split('&');
this.QueryString = new Dictionary<string, string>();
foreach (var kvp in kvps)
{
var parts = kvp.Split('=');
this.QueryString[parts[0]] = parts.Length > 1 ? parts[1] : null;
}
}
}
/// <summary>Gets information describing the path.</summary>
///
/// <value>Information describing the path.</value>
public string PathInfo { get; private set; }
/// <summary>Gets the query string.</summary>
///
/// <value>The query string.</value>
public Dictionary<string, string> QueryString { get; private set; }
}
/// <summary>Executes the path operation.</summary>
///
/// <param name="httpMethod">The HTTP method.</param>
/// <param name="pathInfo"> Information describing the path.</param>
///
/// <returns>An object.</returns>
public object ExecutePath(string httpMethod, string pathInfo)
{
var urlParts = new UrlParts(pathInfo);
return ExecutePath(httpMethod, urlParts.PathInfo, urlParts.QueryString, null, null);
}
private TResponse ExecutePath<TResponse>(string httpMethod, UrlParts urlParts, object requestDto)
{
return (TResponse)ExecutePath(httpMethod, urlParts.PathInfo, urlParts.QueryString, null, requestDto);
}
/// <summary>Executes the path operation.</summary>
///
/// <typeparam name="TResponse">Type of the response.</typeparam>
/// <param name="httpMethod">The HTTP method.</param>
/// <param name="pathInfo"> Information describing the path.</param>
/// <param name="requestDto">The request dto.</param>
///
/// <returns>An object.</returns>
public TResponse ExecutePath<TResponse>(string httpMethod, string pathInfo, object requestDto)
{
var urlParts = new UrlParts(pathInfo);
return (TResponse)ExecutePath(httpMethod, urlParts.PathInfo, urlParts.QueryString, null, requestDto);
}
/// <summary>Executes the path operation.</summary>
///
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="httpMethod"> The HTTP method.</param>
/// <param name="pathInfo"> Information describing the path.</param>
/// <param name="queryString">The query string.</param>
/// <param name="formData"> Information describing the form.</param>
/// <param name="requestBody">The request body.</param>
///
/// <returns>An object.</returns>
public object ExecutePath<T>(
string httpMethod,
string pathInfo,
Dictionary<string, string> queryString,
Dictionary<string, string> formData,
T requestBody)
{
var isDefault = Equals(requestBody, default(T));
var json = !isDefault ? JsonSerializer.SerializeToString(requestBody) : null;
return ExecutePath(httpMethod, pathInfo, queryString, formData, json);
}
/// <summary>Executes the path operation.</summary>
///
/// <exception cref="WebServiceException">Thrown when a Web Service error condition occurs.</exception>
///
/// <param name="httpMethod"> The HTTP method.</param>
/// <param name="pathInfo"> Information describing the path.</param>
/// <param name="queryString">The query string.</param>
/// <param name="formData"> Information describing the form.</param>
/// <param name="requestBody">The request body.</param>
///
/// <returns>An object.</returns>
public object ExecutePath(
string httpMethod,
string pathInfo,
Dictionary<string, string> queryString,
Dictionary<string, string> formData,
string requestBody)
{
var httpHandler = GetHandler(httpMethod, pathInfo);
var contentType = (formData != null && formData.Count > 0)
? ContentType.FormUrlEncoded
: requestBody != null ? ContentType.Json : null;
var httpReq = new MockHttpRequest(
httpHandler.RequestName, httpMethod, contentType,
pathInfo,
queryString.ToNameValueCollection(),
requestBody == null ? null : new MemoryStream(Encoding.UTF8.GetBytes(requestBody)),
formData.ToNameValueCollection()
);
var request = httpHandler.CreateRequest(httpReq, httpHandler.RequestName);
object response;
try
{
response = httpHandler.GetResponse(httpReq, null, request);
}
catch (Exception ex)
{
response = DtoUtils.HandleException(AppHost, request, ex);
}
var httpRes = response as IHttpResult;
if (httpRes != null)
{
var httpError = httpRes as IHttpError;
if (httpError != null)
{
throw new WebServiceException(httpError.Message) {
StatusCode = httpError.Status,
ResponseDto = httpError.Response
};
}
var hasResponseStatus = httpRes.Response as IHasResponseStatus;
if (hasResponseStatus != null)
{
var status = hasResponseStatus.ResponseStatus;
if (status != null && !status.ErrorCode.IsNullOrEmpty())
{
throw new WebServiceException(status.Message) {
StatusCode = (int)HttpStatusCode.InternalServerError,
ResponseDto = httpRes.Response,
};
}
}
return httpRes.Response;
}
return response;
}
/// <summary>Gets a request.</summary>
///
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="pathInfo">Information describing the path.</param>
///
/// <returns>The request.</returns>
public T GetRequest<T>(string pathInfo)
{
return (T) GetRequest(pathInfo);
}
/// <summary>Gets a request.</summary>
///
/// <param name="pathInfo">Information describing the path.</param>
///
/// <returns>The request.</returns>
public object GetRequest(string pathInfo)
{
var urlParts = new UrlParts(pathInfo);
return GetRequest(HttpMethods.Get, urlParts.PathInfo, urlParts.QueryString, null, null);
}
/// <summary>Gets a request.</summary>
///
/// <param name="httpMethod">The HTTP method.</param>
/// <param name="pathInfo"> Information describing the path.</param>
///
/// <returns>The request.</returns>
public object GetRequest(string httpMethod, string pathInfo)
{
var urlParts = new UrlParts(pathInfo);
return GetRequest(httpMethod, urlParts.PathInfo, urlParts.QueryString, null, null);
}
/// <summary>Gets a request.</summary>
///
/// <param name="httpMethod"> The HTTP method.</param>
/// <param name="pathInfo"> Information describing the path.</param>
/// <param name="queryString">The query string.</param>
/// <param name="formData"> Information describing the form.</param>
/// <param name="requestBody">The request body.</param>
///
/// <returns>The request.</returns>
public object GetRequest(
string httpMethod,
string pathInfo,
Dictionary<string, string> queryString,
Dictionary<string, string> formData,
string requestBody)
{
var httpHandler = GetHandler(httpMethod, pathInfo);
var contentType = (formData != null && formData.Count > 0)
? ContentType.FormUrlEncoded
: requestBody != null ? ContentType.Json : null;
var httpReq = new MockHttpRequest(
httpHandler.RequestName, httpMethod, contentType,
pathInfo,
queryString.ToNameValueCollection(),
requestBody == null ? null : new MemoryStream(Encoding.UTF8.GetBytes(requestBody)),
formData.ToNameValueCollection()
);
var request = httpHandler.CreateRequest(httpReq, httpHandler.RequestName);
return request;
}
private static EndpointHandlerBase GetHandler(string httpMethod, string pathInfo)
{
var httpHandler = NServiceKitHttpHandlerFactory.GetHandlerForPathInfo(httpMethod, pathInfo, pathInfo, null) as EndpointHandlerBase;
if (httpHandler == null)
throw new NotSupportedException(pathInfo);
return httpHandler;
}
}
}
| |
// -- FILE ------------------------------------------------------------------
// name : CalendarVisitor.cs
// project : Itenso Time Period
// created : Jani Giannoudis - 2011.03.21
// language : C# 4.0
// environment: .NET 2.0
// copyright : (c) 2011-2012 by Itenso GmbH, Switzerland
// --------------------------------------------------------------------------
using System;
namespace Itenso.TimePeriod
{
// ------------------------------------------------------------------------
public abstract class CalendarVisitor<TFilter, TContext>
where TFilter : class, ICalendarVisitorFilter
where TContext : class, ICalendarVisitorContext
{
// ------------------------------------------------------------------------
protected CalendarVisitor( TFilter filter, ITimePeriod limits,
SeekDirection seekDirection = SeekDirection.Forward, ITimeCalendar calendar = null )
{
if ( filter == null )
{
throw new ArgumentNullException( "filter" );
}
if ( limits == null )
{
throw new ArgumentNullException( "limits" );
}
this.filter = filter;
this.limits = limits;
this.seekDirection = seekDirection;
this.calendar = calendar;
} // CalendarVisitor
// ----------------------------------------------------------------------
public TFilter Filter
{
get { return filter; }
} // Filter
// ----------------------------------------------------------------------
public ITimePeriod Limits
{
get { return limits; }
} // Limits
// ----------------------------------------------------------------------
public SeekDirection SeekDirection
{
get { return seekDirection; }
} // SeekDirection
// ----------------------------------------------------------------------
public ITimeCalendar Calendar
{
get { return calendar; }
} // Calendar
// ----------------------------------------------------------------------
protected void StartPeriodVisit( TContext context = null )
{
StartPeriodVisit( limits, context );
} // StartPeriodVisit
// ----------------------------------------------------------------------
protected void StartPeriodVisit( ITimePeriod period, TContext context = null )
{
if ( period == null )
{
throw new ArgumentNullException( "period" );
}
if ( period.IsMoment )
{
return;
}
OnVisitStart();
Years years = calendar != null ?
new Years( period.Start.Year, period.End.Year - period.Start.Year + 1, calendar ) :
new Years( period.Start.Year, period.End.Year - period.Start.Year + 1 );
if ( OnVisitYears( years, context ) && EnterYears( years, context ) )
{
ITimePeriodCollection yearsToVisit = years.GetYears();
if ( seekDirection == SeekDirection.Backward )
{
yearsToVisit.SortByEnd();
}
foreach ( Year year in yearsToVisit )
{
if ( !year.OverlapsWith( period ) || OnVisitYear( year, context ) == false )
{
continue;
}
// months
if ( EnterMonths( year, context ) == false )
{
continue;
}
ITimePeriodCollection monthsToVisit = year.GetMonths();
if ( seekDirection == SeekDirection.Backward )
{
monthsToVisit.SortByEnd();
}
foreach ( Month month in monthsToVisit )
{
if ( !month.OverlapsWith( period ) || OnVisitMonth( month, context ) == false )
{
continue;
}
// days
if ( EnterDays( month, context ) == false )
{
continue;
}
ITimePeriodCollection daysToVisit = month.GetDays();
if ( seekDirection == SeekDirection.Backward )
{
daysToVisit.SortByEnd();
}
foreach ( Day day in daysToVisit )
{
if ( !day.OverlapsWith( period ) || OnVisitDay( day, context ) == false )
{
continue;
}
// hours
if ( EnterHours( day, context ) == false )
{
continue;
}
ITimePeriodCollection hoursToVisit = day.GetHours();
if ( seekDirection == SeekDirection.Backward )
{
hoursToVisit.SortByEnd();
}
foreach ( Hour hour in hoursToVisit )
{
if ( !hour.OverlapsWith( period ) || OnVisitHour( hour, context ) == false )
{
// ReSharper disable RedundantJumpStatement
continue;
// ReSharper restore RedundantJumpStatement
}
}
}
}
}
}
OnVisitEnd();
} // StartPeriodVisit
// ----------------------------------------------------------------------
protected Year StartYearVisit( Year year, TContext context = null, SeekDirection? visitDirection = null )
{
if ( year == null )
{
throw new ArgumentNullException( "year" );
}
if ( visitDirection == null )
{
visitDirection = SeekDirection;
}
OnVisitStart();
// iteration limits
Year lastVisited = null;
DateTime minStart = DateTime.MinValue;
DateTime maxEnd = DateTime.MaxValue.AddYears( -1 );
while ( year.Start > minStart && year.End < maxEnd )
{
if ( OnVisitYear( year, context ) == false )
{
lastVisited = year;
break;
}
switch ( visitDirection )
{
case SeekDirection.Forward:
year = year.GetNextYear();
break;
case SeekDirection.Backward:
year = year.GetPreviousYear();
break;
}
}
OnVisitEnd();
return lastVisited;
} // StartYearVisit
// ----------------------------------------------------------------------
protected Month StartMonthVisit( Month month, TContext context = null, SeekDirection? visitDirection = null )
{
if ( month == null )
{
throw new ArgumentNullException( "month" );
}
if ( visitDirection == null )
{
visitDirection = SeekDirection;
}
OnVisitStart();
// iteration limits
Month lastVisited = null;
DateTime minStart = DateTime.MinValue;
DateTime maxEnd = DateTime.MaxValue.AddMonths( -1 );
while ( month.Start > minStart && month.End < maxEnd )
{
if ( OnVisitMonth( month, context ) == false )
{
lastVisited = month;
break;
}
switch ( visitDirection )
{
case SeekDirection.Forward:
month = month.GetNextMonth();
break;
case SeekDirection.Backward:
month = month.GetPreviousMonth();
break;
}
}
OnVisitEnd();
return lastVisited;
} // StartMonthVisit
// ----------------------------------------------------------------------
protected Day StartDayVisit( Day day, TContext context = null, SeekDirection? visitDirection = null )
{
if ( day == null )
{
throw new ArgumentNullException( "day" );
}
if ( visitDirection == null )
{
visitDirection = SeekDirection;
}
OnVisitStart();
// iteration limits
Day lastVisited = null;
DateTime minStart = DateTime.MinValue;
DateTime maxEnd = DateTime.MaxValue.AddDays( -1 );
while ( day.Start > minStart && day.End < maxEnd )
{
if ( OnVisitDay( day, context ) == false )
{
lastVisited = day;
break;
}
switch ( visitDirection )
{
case SeekDirection.Forward:
day = day.GetNextDay();
break;
case SeekDirection.Backward:
day = day.GetPreviousDay();
break;
}
}
OnVisitEnd();
return lastVisited;
} // StartDayVisit
// ----------------------------------------------------------------------
protected Hour StartHourVisit( Hour hour, TContext context = null, SeekDirection? visitDirection = null )
{
if ( hour == null )
{
throw new ArgumentNullException( "hour" );
}
if ( visitDirection == null )
{
visitDirection = SeekDirection;
}
OnVisitStart();
// iteration limits
Hour lastVisited = null;
DateTime minStart = DateTime.MinValue;
DateTime maxEnd = DateTime.MaxValue.AddHours( -1 );
while ( hour.Start > minStart && hour.End < maxEnd )
{
if ( OnVisitHour( hour, context ) == false )
{
lastVisited = hour;
break;
}
switch ( visitDirection )
{
case SeekDirection.Forward:
hour = hour.GetNextHour();
break;
case SeekDirection.Backward:
hour = hour.GetPreviousHour();
break;
}
}
OnVisitEnd();
return lastVisited;
} // StartHourVisit
// ----------------------------------------------------------------------
protected virtual void OnVisitStart()
{
} // OnVisitStart
// ----------------------------------------------------------------------
protected virtual bool CheckLimits( ITimePeriod test )
{
return limits.HasInside( test );
} // CheckLimits
// ----------------------------------------------------------------------
protected virtual bool CheckExcludePeriods( ITimePeriod test )
{
if ( filter.ExcludePeriods.Count == 0 )
{
return true;
}
return filter.ExcludePeriods.OverlapPeriods( test ).Count == 0;
} // CheckExcludePeriods
// ----------------------------------------------------------------------
protected virtual bool EnterYears( Years years, TContext context )
{
return true;
} // EnterYears
// ----------------------------------------------------------------------
protected virtual bool EnterMonths( Year year, TContext context )
{
return true;
} // EnterMonths
// ----------------------------------------------------------------------
protected virtual bool EnterDays( Month month, TContext context )
{
return true;
} // EnterDays
// ----------------------------------------------------------------------
protected virtual bool EnterHours( Day day, TContext context )
{
return true;
} // EnterHours
// ----------------------------------------------------------------------
protected virtual bool OnVisitYears( Years years, TContext context )
{
return true;
} // OnVisitYears
// ----------------------------------------------------------------------
protected virtual bool OnVisitYear( Year year, TContext context )
{
return true;
} // OnVisitYear
// ----------------------------------------------------------------------
protected virtual bool OnVisitMonth( Month month, TContext context )
{
return true;
} // OnVisitMonth
// ----------------------------------------------------------------------
protected virtual bool OnVisitDay( Day day, TContext context )
{
return true;
} // OnVisitDay
// ----------------------------------------------------------------------
protected virtual bool OnVisitHour( Hour hour, TContext context )
{
return true;
} // OnVisitHour
// ----------------------------------------------------------------------
protected virtual bool IsMatchingYear( Year year, TContext context )
{
// year filter
if ( filter.Years.Count > 0 && !filter.Years.Contains( year.YearValue ) )
{
return false;
}
return CheckExcludePeriods( year );
} // IsMatchingYear
// ----------------------------------------------------------------------
protected virtual bool IsMatchingMonth( Month month, TContext context )
{
// year filter
if ( filter.Years.Count > 0 && !filter.Years.Contains( month.Year ) )
{
return false;
}
// month filter
if ( filter.Months.Count > 0 && !filter.Months.Contains( month.YearMonth ) )
{
return false;
}
return CheckExcludePeriods( month );
} // IsMatchingMonth
// ----------------------------------------------------------------------
protected virtual bool IsMatchingDay( Day day, TContext context )
{
// year filter
if ( filter.Years.Count > 0 && !filter.Years.Contains( day.Year ) )
{
return false;
}
// month filter
if ( filter.Months.Count > 0 && !filter.Months.Contains( (YearMonth)day.Month ) )
{
return false;
}
// day filter
if ( filter.Days.Count > 0 && !filter.Days.Contains( day.DayValue ) )
{
return false;
}
// weekday filter
if ( filter.WeekDays.Count > 0 && !filter.WeekDays.Contains( day.DayOfWeek ) )
{
return false;
}
return CheckExcludePeriods( day );
} // IsMatchingDay
// ----------------------------------------------------------------------
protected virtual bool IsMatchingHour( Hour hour, TContext context )
{
// year filter
if ( filter.Years.Count > 0 && !filter.Years.Contains( hour.Year ) )
{
return false;
}
// month filter
if ( filter.Months.Count > 0 && !filter.Months.Contains( (YearMonth)hour.Month ) )
{
return false;
}
// day filter
if ( filter.Days.Count > 0 && !filter.Days.Contains( hour.Day ) )
{
return false;
}
// weekday filter
if ( filter.WeekDays.Count > 0 && !filter.WeekDays.Contains( hour.Start.DayOfWeek ) )
{
return false;
}
// hour filter
if ( filter.Hours.Count > 0 && !filter.Hours.Contains( hour.HourValue ) )
{
return false;
}
return CheckExcludePeriods( hour );
} // IsMatchingHour
// ----------------------------------------------------------------------
protected virtual void OnVisitEnd()
{
} // OnVisitEnd
// ----------------------------------------------------------------------
// members
private readonly TFilter filter;
private readonly ITimePeriod limits;
private readonly SeekDirection seekDirection;
private readonly ITimeCalendar calendar;
} // class CalendarVisitor
} // namespace Itenso.TimePeriod
// -- EOF -------------------------------------------------------------------
| |
/****************************************************************************
Tilde
Copyright (c) 2008 Tantalus Media Pty
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.IO;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Windows.Forms;
using Tilde.Framework.Controller;
using Tilde.Framework.View;
using Tilde.Framework.Model;
using Tilde.Framework.Model.ProjectHierarchy;
using System.Threading;
using Tilde.CorePlugins.TextEditor;
using Tilde.Framework;
namespace Tilde.LuaDebugger
{
public delegate void DebuggerConnectingEventHandler(DebugManager sender, Target target);
public delegate void DebuggerConnectedEventHandler(DebugManager sender, Target target);
public delegate void DebuggerDisconnectingEventHandler(DebugManager sender, Target target);
public delegate void DebuggerDisconnectedEventHandler(DebugManager sender);
public delegate void CurrentStackFrameChangedEventHandler(DebugManager sender, LuaStackFrame frame);
public delegate void BreakpointChangedEventHandler(DebugManager sender, BreakpointDetails bkpt, bool valid);
public enum ConnectionStatus
{
NotConnected,
Connecting,
Connected,
Disconnecting
}
public class DebugManager
{
MainWindowComponents mMainWindowComponents;
bool mBuildInProgress = false;
HostInfo mHostInfo;
public DebugManager(IManager manager)
{
mManager = manager;
mPlugin = (LuaPlugin) manager.GetPlugin(typeof(LuaPlugin));
mTransports = new List<ITransport>();
mConnectionStatus = ConnectionStatus.NotConnected;
mTargetStatus = TargetState.Disconnected;
mConnectedTarget = null;
mBreakpoints = new List<BreakpointDetails>();
mWatches = new Dictionary<int, WatchDetails>();
mValueCache = new ValueCache();
mMainWindowComponents = new MainWindowComponents(this);
InitialiseTransports();
Manager.AddToMenuStrip(mMainWindowComponents.menuStrip.Items);
Manager.AddToStatusStrip(mMainWindowComponents.statusStrip.Items);
Manager.AddToolStrip(mMainWindowComponents.toolStrip, DockStyle.Top, 1);
Manager.ProjectOpened += new ProjectOpenedEventHandler(Manager_ProjectOpened);
if(Manager.MainWindow != null)
Manager.MainWindow.FormClosing += new FormClosingEventHandler(MainWindow_FormClosing);
}
void Manager_ProjectOpened(IManager sender, Project project)
{
if(Options.LuaSourceSearchPath.Length == 0)
{
Options.LuaSourceSearchPath = new string[] { project.RootDocument.BaseDirectory };
}
}
public event DebuggerConnectingEventHandler DebuggerConnecting;
public event DebuggerConnectedEventHandler DebuggerConnected;
public event DebuggerDisconnectingEventHandler DebuggerDisconnecting;
public event DebuggerDisconnectedEventHandler DebuggerDisconnected;
public event CurrentStackFrameChangedEventHandler CurrentStackFrameChanged;
public event BreakpointChangedEventHandler BreakpointChanged;
public IManager Manager
{
get { return mManager; }
}
public Form MainWindow
{
get { return mManager.MainWindow; }
}
public DebuggerOptions Options
{
get { return mPlugin.Options; }
}
public List<ITransport> Transports
{
get { return mTransports; }
}
public Target ConnectedTarget
{
get { return mConnectedTarget; }
}
public ConnectionStatus ConnectionStatus
{
get { return mConnectionStatus; }
}
public TargetState TargetStatus
{
get { return mTargetStatus; }
}
public List<BreakpointDetails> Breakpoints
{
get { return mBreakpoints; }
}
public ICollection<WatchDetails> Watches
{
get { return mWatches.Values; }
}
public LuaValue MainThread
{
get { return new LuaValue(0, LuaValueType.THREAD); }
}
public LuaValue CurrentThread
{
get { return mCurrentThread; }
set
{
if (value == null)
mCurrentThread = LuaValue.nil;
else
mCurrentThread = value;
if (mConnectedTarget != null && mCurrentStackFrame != null && !mCurrentThread.IsNil())
{
mConnectedTarget.RetrieveStatus(mCurrentThread, mCurrentStackFrame.Depth);
}
}
}
public LuaStackFrame CurrentStackFrame
{
get { return mCurrentStackFrame; }
set
{
// Broadcast a stackframe change regardless, so we can click on the active frame to return to the source line
mCurrentStackFrame = value;
OnCurrentStackFrameChanged(mCurrentStackFrame, true);
}
}
public ValueCache ValueCache
{
get { return mValueCache; }
}
public bool IsBuildInProgress
{
get { return mBuildInProgress; }
}
public void Connect(HostInfo hostInfo)
{
if (mConnectedTarget == null)
{
IConnection connection = hostInfo.Transport.Connect(hostInfo);
mHostInfo = hostInfo;
if (connection != null)
{
Target target = new Target(this, MainWindow, connection);
// mStatusMessage = new DebuggerStatusDialog("Establishing connection to " + target.HostInfo.ToString() + "...", true);
// mStatusMessage.Cancel.Click += new EventHandler(StatusMessage_Cancel_Click);
// mStatusMessage.Show(MainWindow);
mManager.SetStatusMessage("Establishing connection to " + target.HostInfo.ToString() + "...", 0);
SetNotification(Tilde.LuaDebugger.Properties.Resources.SystrayConnected, "Tilde Connecting...");
mConnectedTarget = target;
mConnectedTarget.DebugPrint += new DebugPrintEventHandler(Target_DebugPrint);
mConnectedTarget.ErrorMessage += new ErrorMessageEventHandler(Target_ErrorMessage);
mConnectedTarget.StatusMessage += new StatusMessageEventHandler(Target_StatusMessage);
mConnectedTarget.StateUpdate += new StateUpdateEventHandler(Target_StateUpdate);
mConnectedTarget.CallstackUpdate += new CallstackUpdateEventHandler(Target_CallstackUpdate);
mConnectedTarget.BreakpointUpdate += new BreakpointUpdateEventHandler(Target_BreakpointUpdate);
mConnectedTarget.ValueCached += new ValueCachedEventHandler(Target_ValueCached);
mConnectedTarget.FileUpload += new FileUploadEventHandler(Target_FileUpload);
OnDebuggerConnecting(mConnectedTarget);
}
}
}
public void Disconnect(bool silent, bool resetAutoConnect)
{
if (mConnectedTarget != null)
{
if (resetAutoConnect)
mHostInfo.Transport.DisableAutoConnect();
HideStatusMessage();
OnDebuggerDisconnecting(mConnectedTarget);
mConnectedTarget.ValueCached -= new ValueCachedEventHandler(Target_ValueCached);
mConnectedTarget.BreakpointUpdate -= new BreakpointUpdateEventHandler(Target_BreakpointUpdate);
mConnectedTarget.CallstackUpdate -= new CallstackUpdateEventHandler(Target_CallstackUpdate);
mConnectedTarget.StateUpdate -= new StateUpdateEventHandler(Target_StateUpdate);
mConnectedTarget.StatusMessage -= new StatusMessageEventHandler(Target_StatusMessage);
mConnectedTarget.ErrorMessage -= new ErrorMessageEventHandler(Target_ErrorMessage);
mConnectedTarget.DebugPrint -= new DebugPrintEventHandler(Target_DebugPrint);
mConnectedTarget.Disconnect();
mTargetStatus = TargetState.Disconnected;
// Don't send messages about changes if we're shutting down the app
if (!silent)
{
SetNotification(Tilde.LuaDebugger.Properties.Resources.SystrayDisconnected, "Tilde disconnected", "Connection to " + mConnectedTarget.HostInfo.ToString() + " has been closed.");
// Tell everyone we no longer have a stack frame
CurrentStackFrame = null;
// Reset breakpoint state
foreach (BreakpointDetails bkpt in mBreakpoints)
{
bkpt.TargetState = BreakpointState.NotSent;
OnBreakpointChanged(bkpt, true);
}
// Reset breakpoint state
foreach (WatchDetails watch in mWatches.Values)
{
watch.State = WatchState.NotSent;
}
}
mConnectedTarget = null;
mMainWindowComponents.targetStateLabel.Text = "";
mManager.SetStatusMessage("", 0);
OnDebuggerDisconnected();
}
}
public BreakpointDetails FindBreakpoint(string file, int line)
{
foreach(BreakpointDetails bkpt in mBreakpoints)
{
if (bkpt.FileName == file && bkpt.Line == line)
return bkpt;
}
return null;
}
public BreakpointDetails FindBreakpoint(int bkptid)
{
foreach (BreakpointDetails bkpt in mBreakpoints)
{
if (bkpt.ID == bkptid)
return bkpt;
}
return null;
}
public BreakpointDetails ToggleBreakpoint(string file, int line)
{
BreakpointDetails bkpt = FindBreakpoint(file, line);
if (bkpt == null)
return AddBreakpoint(file, line);
else
RemoveBreakpoint(file, line);
return null;
}
public BreakpointDetails AddBreakpoint(string file, int line)
{
BreakpointDetails bkpt = FindBreakpoint(file, line);
if (bkpt == null)
{
bkpt = new BreakpointDetails(file, line, true);
mBreakpoints.Add(bkpt);
if (mTargetStatus != TargetState.Disconnected && mConnectedTarget != null)
{
bkpt.TargetState = BreakpointState.PendingAdd;
mConnectedTarget.AddBreakpoint(file, line, bkpt.ID);
}
}
OnBreakpointChanged(bkpt, true);
return bkpt;
}
public void RemoveBreakpoint(string file, int line)
{
BreakpointDetails bkpt = FindBreakpoint(file, line);
if (bkpt != null)
{
if (mTargetStatus != TargetState.Disconnected && bkpt.Enabled && mConnectedTarget != null && bkpt.TargetState != BreakpointState.PendingRemove)
{
bkpt.TargetState = BreakpointState.PendingRemove;
mConnectedTarget.RemoveBreakpoint(bkpt.ID);
OnBreakpointChanged(bkpt, true);
}
else if(mTargetStatus == TargetState.Disconnected || mConnectedTarget == null)
{
mBreakpoints.Remove(bkpt);
OnBreakpointChanged(bkpt, false);
}
}
}
public void EnableBreakpoint(string file, int line)
{
BreakpointDetails bkpt = FindBreakpoint(file, line);
if (bkpt == null)
{
bkpt = new BreakpointDetails(file, line, true);
mBreakpoints.Add(bkpt);
}
else if (!bkpt.Enabled)
{
bkpt.Enabled = true;
}
else
{
return;
}
if (mConnectedTarget != null)
{
bkpt.TargetState = BreakpointState.PendingAdd;
mConnectedTarget.AddBreakpoint(file, line, bkpt.ID);
}
OnBreakpointChanged(bkpt, true);
}
public void DisableBreakpoint(string file, int line)
{
BreakpointDetails bkpt = FindBreakpoint(file, line);
if (bkpt == null)
{
bkpt = new BreakpointDetails(file, line, false);
mBreakpoints.Add(bkpt);
}
else if (bkpt.Enabled)
{
bkpt.Enabled = false;
if (mConnectedTarget != null)
{
bkpt.TargetState = BreakpointState.PendingDisable;
mConnectedTarget.RemoveBreakpoint(bkpt.ID);
}
}
OnBreakpointChanged(bkpt, true);
}
public WatchDetails FindWatch(int watchid)
{
WatchDetails watch;
mWatches.TryGetValue(watchid, out watch);
return watch;
}
public WatchDetails AddWatch(string expr)
{
WatchDetails watch = new WatchDetails(expr, true);
mWatches.Add(watch.ID, watch);
if (mConnectedTarget != null)
{
watch.State = WatchState.PendingAdd;
mConnectedTarget.AddWatch(watch.Expression, watch.ID);
}
return watch;
}
public void RemoveWatch(WatchDetails watch)
{
mWatches.Remove(watch.ID);
if(mConnectedTarget != null && watch.Enabled)
{
watch.State = WatchState.PendingRemove;
mConnectedTarget.RemoveWatch(watch.ID);
}
}
public string GetValueString(LuaValue luaValue)
{
if (luaValue == null)
return "";
switch (luaValue.Type)
{
case LuaValueType.NIL:
return "nil";
case LuaValueType.BOOLEAN:
return luaValue.AsBoolean().ToString();
case LuaValueType.NUMBER:
return luaValue.AsNumber().ToString("R");
case LuaValueType.TILDE_METATABLE:
return "metatable";
case LuaValueType.TILDE_ENVIRONMENT:
return "environment";
case LuaValueType.TILDE_UPVALUES:
return "upvalues";
default:
if (mValueCache.Contains(luaValue))
return mValueCache.Get(luaValue);
else
return "Unknown:" + luaValue.ToString();
}
}
public void ShowStatusMessage(string message)
{
Manager.ShowMessages("Debug");
Manager.AddMessage("Debug", message + "\r\n");
Manager.FlashMainWindow();
MessageBox.Show(Manager.MainWindow, message, "Lua Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
public string FindTargetFile(string sourceFile)
{
if (sourceFile == null)
return null;
string fileName = PathUtils.MakeCanonicalFileName(sourceFile);
foreach(string path in Options.LuaSourceSearchPath)
{
string normPath = PathUtils.MakeCanonicalFileName(path);
if (normPath.Length < fileName.Length && String.Compare(normPath, 0, fileName, 0, normPath.Length, true) == 0)
{
return fileName.Substring(path.Length + 1).Replace('\\', '/');
}
}
string hierarchy = Manager.Project.CalculateHierarchyForAbsolutePath(fileName);
if (hierarchy != null)
{
return hierarchy;
}
return sourceFile;
}
public string FindSourceFile(string targetFile)
{
if (targetFile == null)
return null;
string fileName = PathUtils.MakeCanonicalFileName(targetFile);
foreach (string path in Options.LuaSourceSearchPath)
{
string sourceFile = Path.Combine(path, fileName);
if (File.Exists(sourceFile))
return sourceFile;
}
string hierarchy = fileName.Replace('\\', '/');
DocumentItem docItem = Manager.Project.FindHierarchy(hierarchy);
if (docItem != null)
{
return docItem.AbsoluteFileName;
}
return targetFile;
}
void OnDebuggerConnecting(Target target)
{
mConnectionStatus = ConnectionStatus.Connecting;
if (DebuggerConnecting != null)
DebuggerConnecting(this, target);
}
void OnDebuggerConnected(Target target)
{
mConnectionStatus = ConnectionStatus.Connected;
if (DebuggerConnected != null)
DebuggerConnected(this, target);
}
void OnDebuggerDisconnecting(Target target)
{
mConnectionStatus = ConnectionStatus.Disconnecting;
if (DebuggerDisconnecting != null)
DebuggerDisconnecting(this, target);
}
void OnDebuggerDisconnected()
{
mConnectionStatus = ConnectionStatus.NotConnected;
if (DebuggerDisconnected != null)
DebuggerDisconnected(this);
}
void OnCurrentStackFrameChanged(LuaStackFrame frame, bool getlocals)
{
if (frame != null)
{
ShowSource(frame.File, frame.Line);
if (getlocals)
{
mConnectedTarget.RetrieveLocals(mCurrentThread, frame.Depth);
mConnectedTarget.RetrieveWatches(mCurrentThread, frame.Depth);
}
}
if (CurrentStackFrameChanged != null)
CurrentStackFrameChanged(this, frame);
}
void OnBreakpointChanged(BreakpointDetails bkpt, bool valid)
{
if (BreakpointChanged != null)
BreakpointChanged(this, bkpt, valid);
}
void StatusMessage_Cancel_Click(object sender, EventArgs e)
{
Disconnect(false, true);
}
void Target_DebugPrint(Target sender, DebugPrintEventArgs args)
{
Manager.AddMessage("Debug", args.Message);
}
void Target_ErrorMessage(Target sender, ErrorMessageEventArgs args)
{
Manager.ShowMessages("Debug");
Manager.AddMessage("Debug", "\r\n" + args.Message + "\r\n");
Manager.FlashMainWindow();
if (mTargetStatus != TargetState.Error)
MessageBox.Show(Manager.MainWindow, args.Message, "Lua Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
else
{
string result = Tilde.Framework.Controls.MessageBoxEx.Show(Manager.MainWindow, args.Message, "Lua Error", new string[] { "Break", "Continue", "Ignore" }, MessageBoxIcon.Error, "Break");
if (result == "Continue")
mConnectedTarget.Run(ExecutionMode.Continue);
else if (result == "Ignore")
{
// Skip over any C functions on the stack to get to the top-most lua function
foreach(LuaStackFrame frame in mCurrentStack)
{
if (!frame.File.StartsWith("=[C]"))
{
mConnectedTarget.IgnoreError(frame.File, frame.Line);
break;
}
}
mConnectedTarget.Run(ExecutionMode.Continue);
}
}
}
void Target_StatusMessage(Target sender, StatusMessageEventArgs args)
{
ShowStatusMessage(args.Message);
}
void Target_StateUpdate(Target sender, StateUpdateEventArgs args)
{
mTargetStatus = args.TargetState;
if(args.TargetState == TargetState.Disconnected)
{
Disconnect(false, false);
mMainWindowComponents.targetStateLabel.Text = "";
Connect(mHostInfo);
}
else if (args.TargetState == TargetState.Connected)
{
HideStatusMessage();
// Tell everyone the good news
OnDebuggerConnected(mConnectedTarget);
SetNotification(Tilde.LuaDebugger.Properties.Resources.SystrayConnected, "Tilde connected", "Connection established to " + mConnectedTarget.HostInfo.ToString());
// Send breakpoints
foreach (BreakpointDetails bkpt in mBreakpoints)
{
if (bkpt.Enabled)
{
bkpt.TargetState = BreakpointState.PendingAdd;
mConnectedTarget.AddBreakpoint(bkpt.FileName, bkpt.Line, bkpt.ID);
}
else
{
bkpt.TargetState = BreakpointState.NotSent;
}
OnBreakpointChanged(bkpt, true);
}
// Send watches
foreach (WatchDetails watch in mWatches.Values)
{
if (watch.Enabled)
{
watch.State = WatchState.PendingAdd;
mConnectedTarget.AddWatch(watch.Expression, watch.ID);
}
else
{
watch.State = WatchState.NotSent;
}
}
// Request threads
mConnectedTarget.RetrieveThreads();
mMainWindowComponents.targetStateLabel.Text = "CONNECTED";
mCurrentThread = LuaValue.nil;
}
else if (args.TargetState == TargetState.Running)
{
mMainWindowComponents.targetStateLabel.Text = "RUN";
mCurrentThread = LuaValue.nil;
CurrentStackFrame = null;
}
else if (args.TargetState == TargetState.Breaked)
{
mMainWindowComponents.targetStateLabel.Text = "BREAK";
mCurrentThread = args.Thread;
Manager.FlashMainWindow();
}
else if (args.TargetState == TargetState.Error)
{
mMainWindowComponents.targetStateLabel.Text = "ERROR";
mCurrentThread = args.Thread;
}
else if (args.TargetState == TargetState.Finished)
{
mMainWindowComponents.targetStateLabel.Text = "FINISH";
mCurrentThread = LuaValue.nil;
CurrentStackFrame = null;
}
}
private void HideStatusMessage()
{
if (mStatusMessage != null)
{
mStatusMessage.Close();
mStatusMessage.Dispose();
mStatusMessage = null;
}
}
void Target_CallstackUpdate(Target sender, CallstackUpdateEventArgs args)
{
if(args.StackFrames.Length > 0)
{
mCurrentStack = args.StackFrames;
mCurrentStackFrame = args.StackFrames[args.CurrentFrame < args.StackFrames.Length ? args.CurrentFrame : 0];
OnCurrentStackFrameChanged(mCurrentStackFrame, false);
}
}
/// <summary>
/// Triggered when the target has accepted or rejected a breakpoint.
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
void Target_BreakpointUpdate(Target sender, BreakpointUpdateEventArgs args)
{
BreakpointDetails bkpt = FindBreakpoint(args.ID);
if(bkpt != null)
{
if (args.State == BreakpointUpdateEventState.Added)
{
// Force it to be displayed as enabled, 'cos the debugger is gonna break on it anyway!
bkpt.Enabled = true;
bkpt.TargetState = BreakpointState.Accepted;
}
else if (args.State == BreakpointUpdateEventState.Invalid)
bkpt.TargetState = BreakpointState.Invalid;
else if (args.State == BreakpointUpdateEventState.Removed)
{
if (bkpt.TargetState == BreakpointState.PendingRemove)
bkpt.TargetState = BreakpointState.Removed;
else if (bkpt.TargetState == BreakpointState.PendingDisable)
bkpt.TargetState = BreakpointState.NotSent;
}
if(bkpt.TargetState == BreakpointState.Removed)
mBreakpoints.Remove(bkpt);
OnBreakpointChanged(bkpt, bkpt.TargetState != BreakpointState.Removed);
}
}
void Target_ValueCached(Target target, ValueCachedEventArgs args)
{
mValueCache.Add(args.Value, args.Description);
}
void Target_FileUpload(Target sender, FileUploadEventArgs args)
{
MemoryStream stream = new MemoryStream(args.Data);
Document doc = Manager.CreateDocument(args.FileName, null, stream);
stream.Dispose();
if(doc != null)
Manager.ShowDocument(doc);
}
public void ShowSource(string file, int line)
{
DocumentItem docItem = Manager.Project.FindHierarchy(file.Replace('\\', '/'));
if (docItem == null)
docItem = Manager.Project.FindDocument(file);
Document doc = docItem != null ? Manager.OpenDocument(docItem) : null;
if (doc == null)
{
doc = Manager.OpenDocument(file);
}
if (doc == null)
{
MessageBox.Show(Manager.MainWindow, String.Format("No source is available for \r\n\r\n{0}", file), "File not found", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
else
{
DocumentView docView = Manager.ShowDocument(doc);
TextView textView = docView as TextView;
if (textView != null)
{
textView.ShowLine(line);
}
}
}
void InitialiseTransports()
{
foreach (Type type in Manager.GetPluginImplementations(typeof(ITransport)))
{
mTransports.Add((ITransport)Activator.CreateInstance(type, new object[] { this }));
}
}
void MainWindow_FormClosing(object sender, FormClosingEventArgs e)
{
Disconnect(true, false);
mMainWindowComponents.notifyIcon.Visible = false;
}
public void SetNotification(System.Drawing.Icon icon, String title, String message)
{
mMainWindowComponents.notifyIcon.Icon = icon;
mMainWindowComponents.notifyIcon.Text = title;
mMainWindowComponents.notifyIcon.ShowBalloonTip(5000, title, message, ToolTipIcon.Info);
mMainWindowComponents.notifyIcon.Visible = true;
}
public void SetNotification(System.Drawing.Icon icon, String title)
{
mMainWindowComponents.notifyIcon.Icon = icon;
mMainWindowComponents.notifyIcon.Text = title;
mMainWindowComponents.notifyIcon.Visible = true;
}
public void RemoveNotification()
{
mMainWindowComponents.notifyIcon.Visible = false;
}
internal void Build()
{
if (mPlugin.Options.BuildCommand.Length == 0)
{
MessageBox.Show("No build command has been specified in the Options!");
}
else if (mBuildInProgress)
{
MessageBox.Show("A build is already in progress!");
}
else
{
mBuildInProgress = true;
mManager.SaveAllDocuments();
ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object state) { BuildAndRunThreadProc(true, false); }));
}
}
internal void Run()
{
if (mPlugin.Options.RunCommand.Length == 0)
{
MessageBox.Show("No run command has been specified in the Options!");
}
else if (mBuildInProgress)
{
MessageBox.Show("A build is already in progress!");
}
else
{
ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object state) { BuildAndRunThreadProc(false, true); }));
}
}
internal void BuildAndRun()
{
if (mPlugin.Options.BuildCommand.Length == 0)
{
MessageBox.Show("No build command has been specified in the Options!");
}
else if(mBuildInProgress)
{
MessageBox.Show("A build is already in progress!");
}
else
{
mBuildInProgress = true;
mManager.SaveAllDocuments();
ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object state) { BuildAndRunThreadProc(true, true); }));
}
}
internal void CancelBuild()
{
}
void BuildAndRunThreadProc(bool build, bool run)
{
try
{
mManager.ShowMessages("Build Output");
int result = 0;
if (build)
{
result = mManager.Execute("Build Output", mPlugin.Options.BuildCommand);
mBuildInProgress = false;
}
if (run && result == 0 && mPlugin.Options.RunCommand.Length > 0)
{
result = mManager.Execute("Build Output", mPlugin.Options.RunCommand);
}
}
catch (System.Exception)
{
}
}
internal void StopTarget()
{
if (mPlugin.Options.StopCommand.Length == 0)
{
MessageBox.Show("No stop command has been specified in the Options!");
}
else
{
try
{
mManager.ShowMessages("Build Output");
int result = mManager.Execute("Build Output", mPlugin.Options.StopCommand);
}
catch (System.Exception)
{
}
}
}
private IManager mManager;
private LuaPlugin mPlugin;
private List<ITransport> mTransports;
private ConnectionStatus mConnectionStatus;
private TargetState mTargetStatus;
private Target mConnectedTarget;
private LuaValue mCurrentThread = LuaValue.nil;
private LuaStackFrame[] mCurrentStack;
private LuaStackFrame mCurrentStackFrame;
private List<BreakpointDetails> mBreakpoints;
private Dictionary<int, WatchDetails> mWatches;
private ValueCache mValueCache;
private DebuggerStatusDialog mStatusMessage;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics; // for TraceInformation
using System.Threading;
using System.Runtime.CompilerServices;
namespace System.Threading
{
public enum LockRecursionPolicy
{
NoRecursion = 0,
SupportsRecursion = 1,
}
//
// ReaderWriterCount tracks how many of each kind of lock is held by each thread.
// We keep a linked list for each thread, attached to a ThreadStatic field.
// These are reused wherever possible, so that a given thread will only
// allocate N of these, where N is the maximum number of locks held simultaneously
// by that thread.
//
internal class ReaderWriterCount
{
// Which lock does this object belong to? This is a numeric ID for two reasons:
// 1) We don't want this field to keep the lock object alive, and a WeakReference would
// be too expensive.
// 2) Setting the value of a long is faster than setting the value of a reference.
// The "hot" paths in ReaderWriterLockSlim are short enough that this actually
// matters.
public long lockID;
// How many reader locks does this thread hold on this ReaderWriterLockSlim instance?
public int readercount;
// Ditto for writer/upgrader counts. These are only used if the lock allows recursion.
// But we have to have the fields on every ReaderWriterCount instance, because
// we reuse it for different locks.
public int writercount;
public int upgradecount;
// Next RWC in this thread's list.
public ReaderWriterCount next;
}
/// <summary>
/// A reader-writer lock implementation that is intended to be simple, yet very
/// efficient. In particular only 1 interlocked operation is taken for any lock
/// operation (we use spin locks to achieve this). The spin lock is never held
/// for more than a few instructions (in particular, we never call event APIs
/// or in fact any non-trivial API while holding the spin lock).
/// </summary>
public class ReaderWriterLockSlim : IDisposable
{
//Specifying if locked can be reacquired recursively.
private bool _fIsReentrant;
// Lock specification for myLock: This lock protects exactly the local fields associated with this
// instance of ReaderWriterLockSlim. It does NOT protect the memory associated with
// the events that hang off this lock (eg writeEvent, readEvent upgradeEvent).
private int _myLock;
//The variables controlling spinning behavior of Mylock(which is a spin-lock)
private const int LockSpinCycles = 20;
private const int LockSpinCount = 10;
private const int LockSleep0Count = 5;
// These variables allow use to avoid Setting events (which is expensive) if we don't have to.
private uint _numWriteWaiters; // maximum number of threads that can be doing a WaitOne on the writeEvent
private uint _numReadWaiters; // maximum number of threads that can be doing a WaitOne on the readEvent
private uint _numWriteUpgradeWaiters; // maximum number of threads that can be doing a WaitOne on the upgradeEvent (at most 1).
private uint _numUpgradeWaiters;
//Variable used for quick check when there are no waiters.
private bool _fNoWaiters;
private int _upgradeLockOwnerId;
private int _writeLockOwnerId;
// conditions we wait on.
private EventWaitHandle _writeEvent; // threads waiting to aquire a write lock go here.
private EventWaitHandle _readEvent; // threads waiting to aquire a read lock go here (will be released in bulk)
private EventWaitHandle _upgradeEvent; // thread waiting to acquire the upgrade lock
private EventWaitHandle _waitUpgradeEvent; // thread waiting to upgrade from the upgrade lock to a write lock go here (at most one)
// Every lock instance has a unique ID, which is used by ReaderWriterCount to associate itself with the lock
// without holding a reference to it.
private static long s_nextLockID;
private long _lockID;
// See comments on ReaderWriterCount.
[ThreadStatic]
private static ReaderWriterCount t_rwc;
private bool _fUpgradeThreadHoldingRead;
private const int MaxSpinCount = 20;
//The uint, that contains info like if the writer lock is held, num of
//readers etc.
private uint _owners;
//Various R/W masks
//Note:
//The Uint is divided as follows:
//
//Writer-Owned Waiting-Writers Waiting Upgraders Num-Readers
// 31 30 29 28.......0
//
//Dividing the uint, allows to vastly simplify logic for checking if a
//reader should go in etc. Setting the writer bit will automatically
//make the value of the uint much larger than the max num of readers
//allowed, thus causing the check for max_readers to fail.
private const uint WRITER_HELD = 0x80000000;
private const uint WAITING_WRITERS = 0x40000000;
private const uint WAITING_UPGRADER = 0x20000000;
//The max readers is actually one less then its theoretical max.
//This is done in order to prevent reader count overflows. If the reader
//count reaches max, other readers will wait.
private const uint MAX_READER = 0x10000000 - 2;
private const uint READER_MASK = 0x10000000 - 1;
private bool _fDisposed;
private void InitializeThreadCounts()
{
_upgradeLockOwnerId = -1;
_writeLockOwnerId = -1;
}
public ReaderWriterLockSlim()
: this(LockRecursionPolicy.NoRecursion)
{
}
public ReaderWriterLockSlim(LockRecursionPolicy recursionPolicy)
{
if (recursionPolicy == LockRecursionPolicy.SupportsRecursion)
{
_fIsReentrant = true;
}
InitializeThreadCounts();
_fNoWaiters = true;
_lockID = Interlocked.Increment(ref s_nextLockID);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool IsRWEntryEmpty(ReaderWriterCount rwc)
{
if (rwc.lockID == 0)
return true;
else if (rwc.readercount == 0 && rwc.writercount == 0 && rwc.upgradecount == 0)
return true;
else
return false;
}
private bool IsRwHashEntryChanged(ReaderWriterCount lrwc)
{
return lrwc.lockID != _lockID;
}
/// <summary>
/// This routine retrieves/sets the per-thread counts needed to enforce the
/// various rules related to acquiring the lock.
///
/// DontAllocate is set to true if the caller just wants to get an existing
/// entry for this thread, but doesn't want to add one if an existing one
/// could not be found.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private ReaderWriterCount GetThreadRWCount(bool dontAllocate)
{
ReaderWriterCount rwc = t_rwc;
ReaderWriterCount empty = null;
while (rwc != null)
{
if (rwc.lockID == _lockID)
return rwc;
if (!dontAllocate && empty == null && IsRWEntryEmpty(rwc))
empty = rwc;
rwc = rwc.next;
}
if (dontAllocate)
return null;
if (empty == null)
{
empty = new ReaderWriterCount();
empty.next = t_rwc;
t_rwc = empty;
}
empty.lockID = _lockID;
return empty;
}
public void EnterReadLock()
{
TryEnterReadLock(-1);
}
//
// Common timeout support
//
private struct TimeoutTracker
{
private int _total;
private int _start;
public TimeoutTracker(TimeSpan timeout)
{
long ltm = (long)timeout.TotalMilliseconds;
if (ltm < -1 || ltm > (long)Int32.MaxValue)
throw new ArgumentOutOfRangeException("timeout");
_total = (int)ltm;
if (_total != -1 && _total != 0)
_start = Environment.TickCount;
else
_start = 0;
}
public TimeoutTracker(int millisecondsTimeout)
{
if (millisecondsTimeout < -1)
throw new ArgumentOutOfRangeException("millisecondsTimeout");
_total = millisecondsTimeout;
if (_total != -1 && _total != 0)
_start = Environment.TickCount;
else
_start = 0;
}
public int RemainingMilliseconds
{
get
{
if (_total == -1 || _total == 0)
return _total;
int elapsed = Environment.TickCount - _start;
// elapsed may be negative if TickCount has overflowed by 2^31 milliseconds.
if (elapsed < 0 || elapsed >= _total)
return 0;
return _total - elapsed;
}
}
public bool IsExpired
{
get
{
return RemainingMilliseconds == 0;
}
}
}
public bool TryEnterReadLock(TimeSpan timeout)
{
return TryEnterReadLock(new TimeoutTracker(timeout));
}
public bool TryEnterReadLock(int millisecondsTimeout)
{
return TryEnterReadLock(new TimeoutTracker(millisecondsTimeout));
}
private bool TryEnterReadLock(TimeoutTracker timeout)
{
return TryEnterReadLockCore(timeout);
}
private bool TryEnterReadLockCore(TimeoutTracker timeout)
{
if (_fDisposed)
throw new ObjectDisposedException(null);
ReaderWriterCount lrwc = null;
int id = Environment.CurrentManagedThreadId;
if (!_fIsReentrant)
{
if (id == _writeLockOwnerId)
{
//Check for AW->AR
throw new LockRecursionException(SR.LockRecursionException_ReadAfterWriteNotAllowed);
}
EnterMyLock();
lrwc = GetThreadRWCount(false);
//Check if the reader lock is already acquired. Note, we could
//check the presence of a reader by not allocating rwc (But that
//would lead to two lookups in the common case. It's better to keep
//a count in the structure).
if (lrwc.readercount > 0)
{
ExitMyLock();
throw new LockRecursionException(SR.LockRecursionException_RecursiveReadNotAllowed);
}
else if (id == _upgradeLockOwnerId)
{
//The upgrade lock is already held.
//Update the global read counts and exit.
lrwc.readercount++;
_owners++;
ExitMyLock();
return true;
}
}
else
{
EnterMyLock();
lrwc = GetThreadRWCount(false);
if (lrwc.readercount > 0)
{
lrwc.readercount++;
ExitMyLock();
return true;
}
else if (id == _upgradeLockOwnerId)
{
//The upgrade lock is already held.
//Update the global read counts and exit.
lrwc.readercount++;
_owners++;
ExitMyLock();
_fUpgradeThreadHoldingRead = true;
return true;
}
else if (id == _writeLockOwnerId)
{
//The write lock is already held.
//Update global read counts here,
lrwc.readercount++;
_owners++;
ExitMyLock();
return true;
}
}
bool retVal = true;
int spincount = 0;
for (; ;)
{
// We can enter a read lock if there are only read-locks have been given out
// and a writer is not trying to get in.
if (_owners < MAX_READER)
{
// Good case, there is no contention, we are basically done
_owners++; // Indicate we have another reader
lrwc.readercount++;
break;
}
if (spincount < MaxSpinCount)
{
ExitMyLock();
if (timeout.IsExpired)
return false;
spincount++;
SpinWait(spincount);
EnterMyLock();
//The per-thread structure may have been recycled as the lock is acquired (due to message pumping), load again.
if (IsRwHashEntryChanged(lrwc))
lrwc = GetThreadRWCount(false);
continue;
}
// Drat, we need to wait. Mark that we have waiters and wait.
if (_readEvent == null) // Create the needed event
{
LazyCreateEvent(ref _readEvent, false);
if (IsRwHashEntryChanged(lrwc))
lrwc = GetThreadRWCount(false);
continue; // since we left the lock, start over.
}
retVal = WaitOnEvent(_readEvent, ref _numReadWaiters, timeout);
if (!retVal)
{
return false;
}
if (IsRwHashEntryChanged(lrwc))
lrwc = GetThreadRWCount(false);
}
ExitMyLock();
return retVal;
}
public void EnterWriteLock()
{
TryEnterWriteLock(-1);
}
public bool TryEnterWriteLock(TimeSpan timeout)
{
return TryEnterWriteLock(new TimeoutTracker(timeout));
}
public bool TryEnterWriteLock(int millisecondsTimeout)
{
return TryEnterWriteLock(new TimeoutTracker(millisecondsTimeout));
}
private bool TryEnterWriteLock(TimeoutTracker timeout)
{
return TryEnterWriteLockCore(timeout);
}
private bool TryEnterWriteLockCore(TimeoutTracker timeout)
{
if (_fDisposed)
throw new ObjectDisposedException(null);
int id = Environment.CurrentManagedThreadId;
ReaderWriterCount lrwc;
bool upgradingToWrite = false;
if (!_fIsReentrant)
{
if (id == _writeLockOwnerId)
{
//Check for AW->AW
throw new LockRecursionException(SR.LockRecursionException_RecursiveWriteNotAllowed);
}
else if (id == _upgradeLockOwnerId)
{
//AU->AW case is allowed once.
upgradingToWrite = true;
}
EnterMyLock();
lrwc = GetThreadRWCount(true);
//Can't acquire write lock with reader lock held.
if (lrwc != null && lrwc.readercount > 0)
{
ExitMyLock();
throw new LockRecursionException(SR.LockRecursionException_WriteAfterReadNotAllowed);
}
}
else
{
EnterMyLock();
lrwc = GetThreadRWCount(false);
if (id == _writeLockOwnerId)
{
lrwc.writercount++;
ExitMyLock();
return true;
}
else if (id == _upgradeLockOwnerId)
{
upgradingToWrite = true;
}
else if (lrwc.readercount > 0)
{
//Write locks may not be acquired if only read locks have been
//acquired.
ExitMyLock();
throw new LockRecursionException(SR.LockRecursionException_WriteAfterReadNotAllowed);
}
}
int spincount = 0;
bool retVal = true;
for (; ;)
{
if (IsWriterAcquired())
{
// Good case, there is no contention, we are basically done
SetWriterAcquired();
break;
}
//Check if there is just one upgrader, and no readers.
//Assumption: Only one thread can have the upgrade lock, so the
//following check will fail for all other threads that may sneak in
//when the upgrading thread is waiting.
if (upgradingToWrite)
{
uint readercount = GetNumReaders();
if (readercount == 1)
{
//Good case again, there is just one upgrader, and no readers.
SetWriterAcquired(); // indicate we have a writer.
break;
}
else if (readercount == 2)
{
if (lrwc != null)
{
if (IsRwHashEntryChanged(lrwc))
lrwc = GetThreadRWCount(false);
if (lrwc.readercount > 0)
{
//This check is needed for EU->ER->EW case, as the owner count will be two.
Debug.Assert(_fIsReentrant);
Debug.Assert(_fUpgradeThreadHoldingRead);
//Good case again, there is just one upgrader, and no readers.
SetWriterAcquired(); // indicate we have a writer.
break;
}
}
}
}
if (spincount < MaxSpinCount)
{
ExitMyLock();
if (timeout.IsExpired)
return false;
spincount++;
SpinWait(spincount);
EnterMyLock();
continue;
}
if (upgradingToWrite)
{
if (_waitUpgradeEvent == null) // Create the needed event
{
LazyCreateEvent(ref _waitUpgradeEvent, true);
continue; // since we left the lock, start over.
}
Debug.Assert(_numWriteUpgradeWaiters == 0, "There can be at most one thread with the upgrade lock held.");
retVal = WaitOnEvent(_waitUpgradeEvent, ref _numWriteUpgradeWaiters, timeout);
//The lock is not held in case of failure.
if (!retVal)
return false;
}
else
{
// Drat, we need to wait. Mark that we have waiters and wait.
if (_writeEvent == null) // create the needed event.
{
LazyCreateEvent(ref _writeEvent, true);
continue; // since we left the lock, start over.
}
retVal = WaitOnEvent(_writeEvent, ref _numWriteWaiters, timeout);
//The lock is not held in case of failure.
if (!retVal)
return false;
}
}
Debug.Assert((_owners & WRITER_HELD) > 0);
if (_fIsReentrant)
{
if (IsRwHashEntryChanged(lrwc))
lrwc = GetThreadRWCount(false);
lrwc.writercount++;
}
ExitMyLock();
_writeLockOwnerId = id;
return true;
}
public void EnterUpgradeableReadLock()
{
TryEnterUpgradeableReadLock(-1);
}
public bool TryEnterUpgradeableReadLock(TimeSpan timeout)
{
return TryEnterUpgradeableReadLock(new TimeoutTracker(timeout));
}
public bool TryEnterUpgradeableReadLock(int millisecondsTimeout)
{
return TryEnterUpgradeableReadLock(new TimeoutTracker(millisecondsTimeout));
}
private bool TryEnterUpgradeableReadLock(TimeoutTracker timeout)
{
return TryEnterUpgradeableReadLockCore(timeout);
}
private bool TryEnterUpgradeableReadLockCore(TimeoutTracker timeout)
{
if (_fDisposed)
throw new ObjectDisposedException(null);
int id = Environment.CurrentManagedThreadId;
ReaderWriterCount lrwc;
if (!_fIsReentrant)
{
if (id == _upgradeLockOwnerId)
{
//Check for AU->AU
throw new LockRecursionException(SR.LockRecursionException_RecursiveUpgradeNotAllowed);
}
else if (id == _writeLockOwnerId)
{
//Check for AU->AW
throw new LockRecursionException(SR.LockRecursionException_UpgradeAfterWriteNotAllowed);
}
EnterMyLock();
lrwc = GetThreadRWCount(true);
//Can't acquire upgrade lock with reader lock held.
if (lrwc != null && lrwc.readercount > 0)
{
ExitMyLock();
throw new LockRecursionException(SR.LockRecursionException_UpgradeAfterReadNotAllowed);
}
}
else
{
EnterMyLock();
lrwc = GetThreadRWCount(false);
if (id == _upgradeLockOwnerId)
{
lrwc.upgradecount++;
ExitMyLock();
return true;
}
else if (id == _writeLockOwnerId)
{
//Write lock is already held, Just update the global state
//to show presence of upgrader.
Debug.Assert((_owners & WRITER_HELD) > 0);
_owners++;
_upgradeLockOwnerId = id;
lrwc.upgradecount++;
if (lrwc.readercount > 0)
_fUpgradeThreadHoldingRead = true;
ExitMyLock();
return true;
}
else if (lrwc.readercount > 0)
{
//Upgrade locks may not be acquired if only read locks have been
//acquired.
ExitMyLock();
throw new LockRecursionException(SR.LockRecursionException_UpgradeAfterReadNotAllowed);
}
}
bool retVal = true;
int spincount = 0;
for (; ;)
{
//Once an upgrade lock is taken, it's like having a reader lock held
//until upgrade or downgrade operations are performed.
if ((_upgradeLockOwnerId == -1) && (_owners < MAX_READER))
{
_owners++;
_upgradeLockOwnerId = id;
break;
}
if (spincount < MaxSpinCount)
{
ExitMyLock();
if (timeout.IsExpired)
return false;
spincount++;
SpinWait(spincount);
EnterMyLock();
continue;
}
// Drat, we need to wait. Mark that we have waiters and wait.
if (_upgradeEvent == null) // Create the needed event
{
LazyCreateEvent(ref _upgradeEvent, true);
continue; // since we left the lock, start over.
}
//Only one thread with the upgrade lock held can proceed.
retVal = WaitOnEvent(_upgradeEvent, ref _numUpgradeWaiters, timeout);
if (!retVal)
return false;
}
if (_fIsReentrant)
{
//The lock may have been dropped getting here, so make a quick check to see whether some other
//thread did not grab the entry.
if (IsRwHashEntryChanged(lrwc))
lrwc = GetThreadRWCount(false);
lrwc.upgradecount++;
}
ExitMyLock();
return true;
}
public void ExitReadLock()
{
ReaderWriterCount lrwc = null;
EnterMyLock();
lrwc = GetThreadRWCount(true);
if (lrwc == null || lrwc.readercount < 1)
{
//You have to be holding the read lock to make this call.
ExitMyLock();
throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedRead);
}
if (_fIsReentrant)
{
if (lrwc.readercount > 1)
{
lrwc.readercount--;
ExitMyLock();
return;
}
if (Environment.CurrentManagedThreadId == _upgradeLockOwnerId)
{
_fUpgradeThreadHoldingRead = false;
}
}
Debug.Assert(_owners > 0, "ReleasingReaderLock: releasing lock and no read lock taken");
--_owners;
Debug.Assert(lrwc.readercount == 1);
lrwc.readercount--;
ExitAndWakeUpAppropriateWaiters();
}
public void ExitWriteLock()
{
ReaderWriterCount lrwc;
if (!_fIsReentrant)
{
if (Environment.CurrentManagedThreadId != _writeLockOwnerId)
{
//You have to be holding the write lock to make this call.
throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedWrite);
}
EnterMyLock();
}
else
{
EnterMyLock();
lrwc = GetThreadRWCount(false);
if (lrwc == null)
{
ExitMyLock();
throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedWrite);
}
if (lrwc.writercount < 1)
{
ExitMyLock();
throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedWrite);
}
lrwc.writercount--;
if (lrwc.writercount > 0)
{
ExitMyLock();
return;
}
}
Debug.Assert((_owners & WRITER_HELD) > 0, "Calling ReleaseWriterLock when no write lock is held");
ClearWriterAcquired();
_writeLockOwnerId = -1;
ExitAndWakeUpAppropriateWaiters();
}
public void ExitUpgradeableReadLock()
{
ReaderWriterCount lrwc;
if (!_fIsReentrant)
{
if (Environment.CurrentManagedThreadId != _upgradeLockOwnerId)
{
//You have to be holding the upgrade lock to make this call.
throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedUpgrade);
}
EnterMyLock();
}
else
{
EnterMyLock();
lrwc = GetThreadRWCount(true);
if (lrwc == null)
{
ExitMyLock();
throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedUpgrade);
}
if (lrwc.upgradecount < 1)
{
ExitMyLock();
throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedUpgrade);
}
lrwc.upgradecount--;
if (lrwc.upgradecount > 0)
{
ExitMyLock();
return;
}
_fUpgradeThreadHoldingRead = false;
}
_owners--;
_upgradeLockOwnerId = -1;
ExitAndWakeUpAppropriateWaiters();
}
/// <summary>
/// A routine for lazily creating a event outside the lock (so if errors
/// happen they are outside the lock and that we don't do much work
/// while holding a spin lock). If all goes well, reenter the lock and
/// set 'waitEvent'
/// </summary>
private void LazyCreateEvent(ref EventWaitHandle waitEvent, bool makeAutoResetEvent)
{
#if DEBUG
Debug.Assert(MyLockHeld);
Debug.Assert(waitEvent == null);
#endif
ExitMyLock();
EventWaitHandle newEvent;
if (makeAutoResetEvent)
newEvent = new AutoResetEvent(false);
else
newEvent = new ManualResetEvent(false);
EnterMyLock();
if (waitEvent == null) // maybe someone snuck in.
waitEvent = newEvent;
else
newEvent.Dispose();
}
/// <summary>
/// Waits on 'waitEvent' with a timeout
/// Before the wait 'numWaiters' is incremented and is restored before leaving this routine.
/// </summary>
private bool WaitOnEvent(EventWaitHandle waitEvent, ref uint numWaiters, TimeoutTracker timeout)
{
#if DEBUG
Debug.Assert(MyLockHeld);
#endif
waitEvent.Reset();
numWaiters++;
_fNoWaiters = false;
//Setting these bits will prevent new readers from getting in.
if (_numWriteWaiters == 1)
SetWritersWaiting();
if (_numWriteUpgradeWaiters == 1)
SetUpgraderWaiting();
bool waitSuccessful = false;
ExitMyLock(); // Do the wait outside of any lock
try
{
waitSuccessful = waitEvent.WaitOne(timeout.RemainingMilliseconds);
}
finally
{
EnterMyLock();
--numWaiters;
if (_numWriteWaiters == 0 && _numWriteUpgradeWaiters == 0 && _numUpgradeWaiters == 0 && _numReadWaiters == 0)
_fNoWaiters = true;
if (_numWriteWaiters == 0)
ClearWritersWaiting();
if (_numWriteUpgradeWaiters == 0)
ClearUpgraderWaiting();
if (!waitSuccessful) // We may also be about to throw for some reason. Exit myLock.
ExitMyLock();
}
return waitSuccessful;
}
/// <summary>
/// Determines the appropriate events to set, leaves the locks, and sets the events.
/// </summary>
private void ExitAndWakeUpAppropriateWaiters()
{
#if DEBUG
Debug.Assert(MyLockHeld);
#endif
if (_fNoWaiters)
{
ExitMyLock();
return;
}
ExitAndWakeUpAppropriateWaitersPreferringWriters();
}
private void ExitAndWakeUpAppropriateWaitersPreferringWriters()
{
bool setUpgradeEvent = false;
bool setReadEvent = false;
uint readercount = GetNumReaders();
//We need this case for EU->ER->EW case, as the read count will be 2 in
//that scenario.
if (_fIsReentrant)
{
if (_numWriteUpgradeWaiters > 0 && _fUpgradeThreadHoldingRead && readercount == 2)
{
ExitMyLock(); // Exit before signaling to improve efficiency (wakee will need the lock)
_waitUpgradeEvent.Set(); // release all upgraders (however there can be at most one).
return;
}
}
if (readercount == 1 && _numWriteUpgradeWaiters > 0)
{
//We have to be careful now, as we are droppping the lock.
//No new writes should be allowed to sneak in if an upgrade
//was pending.
ExitMyLock(); // Exit before signaling to improve efficiency (wakee will need the lock)
_waitUpgradeEvent.Set(); // release all upgraders (however there can be at most one).
}
else if (readercount == 0 && _numWriteWaiters > 0)
{
ExitMyLock(); // Exit before signaling to improve efficiency (wakee will need the lock)
_writeEvent.Set(); // release one writer.
}
else if (readercount >= 0)
{
if (_numReadWaiters != 0 || _numUpgradeWaiters != 0)
{
if (_numReadWaiters != 0)
setReadEvent = true;
if (_numUpgradeWaiters != 0 && _upgradeLockOwnerId == -1)
{
setUpgradeEvent = true;
}
ExitMyLock(); // Exit before signaling to improve efficiency (wakee will need the lock)
if (setReadEvent)
_readEvent.Set(); // release all readers.
if (setUpgradeEvent)
_upgradeEvent.Set(); //release one upgrader.
}
else
ExitMyLock();
}
else
ExitMyLock();
}
private bool IsWriterAcquired()
{
return (_owners & ~WAITING_WRITERS) == 0;
}
private void SetWriterAcquired()
{
_owners |= WRITER_HELD; // indicate we have a writer.
}
private void ClearWriterAcquired()
{
_owners &= ~WRITER_HELD;
}
private void SetWritersWaiting()
{
_owners |= WAITING_WRITERS;
}
private void ClearWritersWaiting()
{
_owners &= ~WAITING_WRITERS;
}
private void SetUpgraderWaiting()
{
_owners |= WAITING_UPGRADER;
}
private void ClearUpgraderWaiting()
{
_owners &= ~WAITING_UPGRADER;
}
private uint GetNumReaders()
{
return _owners & READER_MASK;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void EnterMyLock()
{
if (Interlocked.CompareExchange(ref _myLock, 1, 0) != 0)
EnterMyLockSpin();
}
private void EnterMyLockSpin()
{
int pc = Environment.ProcessorCount;
for (int i = 0; ; i++)
{
if (i < LockSpinCount && pc > 1)
{
Helpers.Spin(LockSpinCycles * (i + 1)); // Wait a few dozen instructions to let another processor release lock.
}
else if (i < (LockSpinCount + LockSleep0Count))
{
Helpers.Sleep(0); // Give up my quantum.
}
else
{
Helpers.Sleep(1); // Give up my quantum.
}
if (_myLock == 0 && Interlocked.CompareExchange(ref _myLock, 1, 0) == 0)
return;
}
}
private void ExitMyLock()
{
Debug.Assert(_myLock != 0, "Exiting spin lock that is not held");
Volatile.Write(ref _myLock, 0);
}
#if DEBUG
private bool MyLockHeld { get { return _myLock != 0; } }
#endif
private static void SpinWait(int SpinCount)
{
//Exponential backoff
if ((SpinCount < 5) && (Environment.ProcessorCount > 1))
{
Helpers.Spin(LockSpinCycles * SpinCount);
}
else if (SpinCount < MaxSpinCount - 3)
{
Helpers.Sleep(0);
}
else
{
Helpers.Sleep(1);
}
}
public void Dispose()
{
Dispose(true);
}
private void Dispose(bool disposing)
{
if (disposing && !_fDisposed)
{
if (WaitingReadCount > 0 || WaitingUpgradeCount > 0 || WaitingWriteCount > 0)
throw new SynchronizationLockException(SR.SynchronizationLockException_IncorrectDispose);
if (IsReadLockHeld || IsUpgradeableReadLockHeld || IsWriteLockHeld)
throw new SynchronizationLockException(SR.SynchronizationLockException_IncorrectDispose);
if (_writeEvent != null)
{
_writeEvent.Dispose();
_writeEvent = null;
}
if (_readEvent != null)
{
_readEvent.Dispose();
_readEvent = null;
}
if (_upgradeEvent != null)
{
_upgradeEvent.Dispose();
_upgradeEvent = null;
}
if (_waitUpgradeEvent != null)
{
_waitUpgradeEvent.Dispose();
_waitUpgradeEvent = null;
}
_fDisposed = true;
}
}
public bool IsReadLockHeld
{
get
{
if (RecursiveReadCount > 0)
return true;
else
return false;
}
}
public bool IsUpgradeableReadLockHeld
{
get
{
if (RecursiveUpgradeCount > 0)
return true;
else
return false;
}
}
public bool IsWriteLockHeld
{
get
{
if (RecursiveWriteCount > 0)
return true;
else
return false;
}
}
public LockRecursionPolicy RecursionPolicy
{
get
{
if (_fIsReentrant)
{
return LockRecursionPolicy.SupportsRecursion;
}
else
{
return LockRecursionPolicy.NoRecursion;
}
}
}
public int CurrentReadCount
{
get
{
int numreaders = (int)GetNumReaders();
if (_upgradeLockOwnerId != -1)
return numreaders - 1;
else
return numreaders;
}
}
public int RecursiveReadCount
{
get
{
int count = 0;
ReaderWriterCount lrwc = GetThreadRWCount(true);
if (lrwc != null)
count = lrwc.readercount;
return count;
}
}
public int RecursiveUpgradeCount
{
get
{
if (_fIsReentrant)
{
int count = 0;
ReaderWriterCount lrwc = GetThreadRWCount(true);
if (lrwc != null)
count = lrwc.upgradecount;
return count;
}
else
{
if (Environment.CurrentManagedThreadId == _upgradeLockOwnerId)
return 1;
else
return 0;
}
}
}
public int RecursiveWriteCount
{
get
{
if (_fIsReentrant)
{
int count = 0;
ReaderWriterCount lrwc = GetThreadRWCount(true);
if (lrwc != null)
count = lrwc.writercount;
return count;
}
else
{
if (Environment.CurrentManagedThreadId == _writeLockOwnerId)
return 1;
else
return 0;
}
}
}
public int WaitingReadCount
{
get
{
return (int)_numReadWaiters;
}
}
public int WaitingUpgradeCount
{
get
{
return (int)_numUpgradeWaiters;
}
}
public int WaitingWriteCount
{
get
{
return (int)_numWriteWaiters;
}
}
}
}
| |
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.ComponentModel;
using WeifenLuo.WinFormsUI.Docking;
namespace ks_admin.Customization
{
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/ClassDef/*'/>
internal class VS2003AutoHideStrip : AutoHideStripBase
{
private class TabVS2003 : Tab
{
internal TabVS2003(IDockContent content)
: base(content)
{
}
private int m_tabX = 0;
protected internal int TabX
{
get { return m_tabX; }
set { m_tabX = value; }
}
private int m_tabWidth = 0;
protected internal int TabWidth
{
get { return m_tabWidth; }
set { m_tabWidth = value; }
}
}
private const int _ImageHeight = 16;
private const int _ImageWidth = 16;
private const int _ImageGapTop = 2;
private const int _ImageGapLeft = 4;
private const int _ImageGapRight = 4;
private const int _ImageGapBottom = 2;
private const int _TextGapLeft = 4;
private const int _TextGapRight = 10;
private const int _TabGapTop = 3;
private const int _TabGapLeft = 2;
private const int _TabGapBetween = 10;
private static Matrix _matrixIdentity;
private static DockState[] _dockStates;
#region Customizable Properties
private static StringFormat _stringFormatTabHorizontal = null;
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="StringFormatTabHorizontal"]/*'/>
protected virtual StringFormat StringFormatTabHorizontal
{
get
{
if (_stringFormatTabHorizontal == null)
{
_stringFormatTabHorizontal = new StringFormat();
_stringFormatTabHorizontal.Alignment = StringAlignment.Near;
_stringFormatTabHorizontal.LineAlignment = StringAlignment.Center;
_stringFormatTabHorizontal.FormatFlags = StringFormatFlags.NoWrap;
}
return _stringFormatTabHorizontal;
}
}
private static StringFormat _stringFormatTabVertical;
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="StringFormatTabVertical"]/*'/>
protected virtual StringFormat StringFormatTabVertical
{
get
{
if (_stringFormatTabVertical == null)
{
_stringFormatTabVertical = new StringFormat();
_stringFormatTabVertical.Alignment = StringAlignment.Near;
_stringFormatTabVertical.LineAlignment = StringAlignment.Center;
_stringFormatTabVertical.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.DirectionVertical;
}
return _stringFormatTabVertical;
}
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="ImageHeight"]/*'/>
protected virtual int ImageHeight
{
get { return _ImageHeight; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="ImageWidth"]/*'/>
protected virtual int ImageWidth
{
get { return _ImageWidth; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="ImageGapTop"]/*'/>
protected virtual int ImageGapTop
{
get { return _ImageGapTop; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="ImageGapLeft"]/*'/>
protected virtual int ImageGapLeft
{
get { return _ImageGapLeft; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="ImageGapRight"]/*'/>
protected virtual int ImageGapRight
{
get { return _ImageGapRight; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="ImageGapBottom"]/*'/>
protected virtual int ImageGapBottom
{
get { return _ImageGapBottom; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="TextGapLeft"]/*'/>
protected virtual int TextGapLeft
{
get { return _TextGapLeft; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="TextGapRight"]/*'/>
protected virtual int TextGapRight
{
get { return _TextGapRight; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="TabGapTop"]/*'/>
protected virtual int TabGapTop
{
get { return _TabGapTop; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="TabGapLeft"]/*'/>
protected virtual int TabGapLeft
{
get { return _TabGapLeft; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="TabGapBetween"]/*'/>
protected virtual int TabGapBetween
{
get { return _TabGapBetween; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="BrushTabBackground"]/*'/>
protected virtual Brush BrushTabBackground
{
get { return SystemBrushes.Control; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="PenTabBorder"]/*'/>
protected virtual Pen PenTabBorder
{
get { return SystemPens.GrayText; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="BrushTabText"]/*'/>
protected virtual Brush BrushTabText
{
get { return SystemBrushes.FromSystemColor(SystemColors.ControlDarkDark); }
}
#endregion
private Matrix MatrixIdentity
{
get { return _matrixIdentity; }
}
private DockState[] DockStates
{
get { return _dockStates; }
}
static VS2003AutoHideStrip()
{
_matrixIdentity = new Matrix();
_dockStates = new DockState[4];
_dockStates[0] = DockState.DockLeftAutoHide;
_dockStates[1] = DockState.DockRightAutoHide;
_dockStates[2] = DockState.DockTopAutoHide;
_dockStates[3] = DockState.DockBottomAutoHide;
}
public VS2003AutoHideStrip(DockPanel panel) : base(panel)
{
SetStyle(ControlStyles.ResizeRedraw, true);
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
BackColor = Color.WhiteSmoke;
}
/// <exclude/>
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
DrawTabStrip(g);
}
/// <exclude/>
protected override void OnLayout(LayoutEventArgs levent)
{
CalculateTabs();
base.OnLayout (levent);
}
private void DrawTabStrip(Graphics g)
{
DrawTabStrip(g, DockState.DockTopAutoHide);
DrawTabStrip(g, DockState.DockBottomAutoHide);
DrawTabStrip(g, DockState.DockLeftAutoHide);
DrawTabStrip(g, DockState.DockRightAutoHide);
}
private void DrawTabStrip(Graphics g, DockState dockState)
{
Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState);
if (rectTabStrip.IsEmpty)
return;
Matrix matrixIdentity = g.Transform;
if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide)
{
Matrix matrixRotated = new Matrix();
matrixRotated.RotateAt(90, new PointF((float)rectTabStrip.X + (float)rectTabStrip.Height / 2,
(float)rectTabStrip.Y + (float)rectTabStrip.Height / 2));
g.Transform = matrixRotated;
}
foreach (Pane pane in GetPanes(dockState))
{
foreach (TabVS2003 tab in pane.AutoHideTabs)
DrawTab(g, tab);
}
g.Transform = matrixIdentity;
}
private void CalculateTabs()
{
CalculateTabs(DockState.DockTopAutoHide);
CalculateTabs(DockState.DockBottomAutoHide);
CalculateTabs(DockState.DockLeftAutoHide);
CalculateTabs(DockState.DockRightAutoHide);
}
private void CalculateTabs(DockState dockState)
{
Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState);
int imageHeight = rectTabStrip.Height - ImageGapTop - ImageGapBottom;
int imageWidth = ImageWidth;
if (imageHeight > ImageHeight)
imageWidth = ImageWidth * (imageHeight/ImageHeight);
using (Graphics g = CreateGraphics())
{
int x = TabGapLeft + rectTabStrip.X;
foreach (Pane pane in GetPanes(dockState))
{
int maxWidth = 0;
foreach (TabVS2003 tab in pane.AutoHideTabs)
{
int width = imageWidth + ImageGapLeft + ImageGapRight +
(int)g.MeasureString(tab.Content.DockHandler.TabText, Font).Width + 1 +
TextGapLeft + TextGapRight;
if (width > maxWidth)
maxWidth = width;
}
foreach (TabVS2003 tab in pane.AutoHideTabs)
{
tab.TabX = x;
if (tab.Content == pane.DockPane.ActiveContent)
tab.TabWidth = maxWidth;
else
tab.TabWidth = imageWidth + ImageGapLeft + ImageGapRight;
x += tab.TabWidth;
}
x += TabGapBetween;
}
}
}
private void DrawTab(Graphics g, TabVS2003 tab)
{
Rectangle rectTab = GetTabRectangle(tab);
if (rectTab.IsEmpty)
return;
DockState dockState = tab.Content.DockHandler.DockState;
IDockContent content = tab.Content;
OnBeginDrawTab(tab);
Brush brushTabBackGround = BrushTabBackground;
Pen penTabBorder = PenTabBorder;
Brush brushTabText = BrushTabText;
g.FillRectangle(brushTabBackGround, rectTab);
g.DrawLine(penTabBorder, rectTab.Left, rectTab.Top, rectTab.Left, rectTab.Bottom);
g.DrawLine(penTabBorder, rectTab.Right, rectTab.Top, rectTab.Right, rectTab.Bottom);
if (dockState == DockState.DockTopAutoHide || dockState == DockState.DockRightAutoHide)
g.DrawLine(penTabBorder, rectTab.Left, rectTab.Bottom, rectTab.Right, rectTab.Bottom);
else
g.DrawLine(penTabBorder, rectTab.Left, rectTab.Top, rectTab.Right, rectTab.Top);
// Set no rotate for drawing icon and text
Matrix matrixRotate = g.Transform;
g.Transform = MatrixIdentity;
// Draw the icon
Rectangle rectImage = rectTab;
rectImage.X += ImageGapLeft;
rectImage.Y += ImageGapTop;
int imageHeight = rectTab.Height - ImageGapTop - ImageGapBottom;
int imageWidth = ImageWidth;
if (imageHeight > ImageHeight)
imageWidth = ImageWidth * (imageHeight/ImageHeight);
rectImage.Height = imageHeight;
rectImage.Width = imageWidth;
rectImage = GetTransformedRectangle(dockState, rectImage);
g.DrawIcon(((Form)content).Icon, rectImage);
// Draw the text
if (content == content.DockHandler.Pane.ActiveContent)
{
Rectangle rectText = rectTab;
rectText.X += ImageGapLeft + imageWidth + ImageGapRight + TextGapLeft;
rectText.Width -= ImageGapLeft + imageWidth + ImageGapRight + TextGapLeft;
rectText = GetTransformedRectangle(dockState, rectText);
if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide)
g.DrawString(content.DockHandler.TabText, Font, brushTabText, rectText, StringFormatTabVertical);
else
g.DrawString(content.DockHandler.TabText, Font, brushTabText, rectText, StringFormatTabHorizontal);
}
// Set rotate back
g.Transform = matrixRotate;
OnEndDrawTab(tab);
}
private Rectangle GetLogicalTabStripRectangle(DockState dockState)
{
return GetLogicalTabStripRectangle(dockState, false);
}
private Rectangle GetLogicalTabStripRectangle(DockState dockState, bool transformed)
{
if (!DockHelper.IsDockStateAutoHide(dockState))
return Rectangle.Empty;
int leftPanes = GetPanes(DockState.DockLeftAutoHide).Count;
int rightPanes = GetPanes(DockState.DockRightAutoHide).Count;
int topPanes = GetPanes(DockState.DockTopAutoHide).Count;
int bottomPanes = GetPanes(DockState.DockBottomAutoHide).Count;
int x, y, width, height;
height = MeasureHeight();
if (dockState == DockState.DockLeftAutoHide && leftPanes > 0)
{
x = 0;
y = (topPanes == 0) ? 0 : height;
width = Height - (topPanes == 0 ? 0 : height) - (bottomPanes == 0 ? 0 :height);
}
else if (dockState == DockState.DockRightAutoHide && rightPanes > 0)
{
x = Width - height;
if (leftPanes != 0 && x < height)
x = height;
y = (topPanes == 0) ? 0 : height;
width = Height - (topPanes == 0 ? 0 : height) - (bottomPanes == 0 ? 0 :height);
}
else if (dockState == DockState.DockTopAutoHide && topPanes > 0)
{
x = leftPanes == 0 ? 0 : height;
y = 0;
width = Width - (leftPanes == 0 ? 0 : height) - (rightPanes == 0 ? 0 : height);
}
else if (dockState == DockState.DockBottomAutoHide && bottomPanes > 0)
{
x = leftPanes == 0 ? 0 : height;
y = Height - height;
if (topPanes != 0 && y < height)
y = height;
width = Width - (leftPanes == 0 ? 0 : height) - (rightPanes == 0 ? 0 : height);
}
else
return Rectangle.Empty;
if (!transformed)
return new Rectangle(x, y, width, height);
else
return GetTransformedRectangle(dockState, new Rectangle(x, y, width, height));
}
private Rectangle GetTabRectangle(TabVS2003 tab)
{
return GetTabRectangle(tab, false);
}
private Rectangle GetTabRectangle(TabVS2003 tab, bool transformed)
{
DockState dockState = tab.Content.DockHandler.DockState;
Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState);
if (rectTabStrip.IsEmpty)
return Rectangle.Empty;
int x = tab.TabX;
int y = rectTabStrip.Y +
(dockState == DockState.DockTopAutoHide || dockState == DockState.DockRightAutoHide ?
0 : TabGapTop);
int width = tab.TabWidth;
int height = rectTabStrip.Height - TabGapTop;
if (!transformed)
return new Rectangle(x, y, width, height);
else
return GetTransformedRectangle(dockState, new Rectangle(x, y, width, height));
}
private Rectangle GetTransformedRectangle(DockState dockState, Rectangle rect)
{
if (dockState != DockState.DockLeftAutoHide && dockState != DockState.DockRightAutoHide)
return rect;
PointF[] pts = new PointF[1];
// the center of the rectangle
pts[0].X = (float)rect.X + (float)rect.Width / 2;
pts[0].Y = (float)rect.Y + (float)rect.Height / 2;
Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState);
Matrix matrix = new Matrix();
matrix.RotateAt(90, new PointF((float)rectTabStrip.X + (float)rectTabStrip.Height / 2,
(float)rectTabStrip.Y + (float)rectTabStrip.Height / 2));
matrix.TransformPoints(pts);
return new Rectangle((int)(pts[0].X - (float)rect.Height / 2 + .5F),
(int)(pts[0].Y - (float)rect.Width / 2 + .5F),
rect.Height, rect.Width);
}
/// <exclude />
protected override IDockContent HitTest(Point ptMouse)
{
foreach(DockState state in DockStates)
{
Rectangle rectTabStrip = GetLogicalTabStripRectangle(state, true);
if (!rectTabStrip.Contains(ptMouse))
continue;
foreach(Pane pane in GetPanes(state))
{
foreach(TabVS2003 tab in pane.AutoHideTabs)
{
Rectangle rectTab = GetTabRectangle(tab, true);
rectTab.Intersect(rectTabStrip);
if (rectTab.Contains(ptMouse))
return tab.Content;
}
}
}
return null;
}
/// <exclude/>
protected override int MeasureHeight()
{
return Math.Max(ImageGapBottom +
ImageGapTop + ImageHeight,
Font.Height) + TabGapTop;
}
/// <exclude/>
protected override void OnRefreshChanges()
{
CalculateTabs();
Invalidate();
}
protected override AutoHideStripBase.Tab CreateTab(IDockContent content)
{
return new TabVS2003(content);
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Method[@name="OnBeginDrawTab(AutoHideTab)"]/*'/>
protected virtual void OnBeginDrawTab(Tab tab)
{
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Method[@name="OnEndDrawTab(AutoHideTab)"]/*'/>
protected virtual void OnEndDrawTab(Tab tab)
{
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Sam.Areas.HelpPage.SampleGeneration
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.PetstoreV2
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Models;
/// <summary>
/// Extension methods for SwaggerPetstoreV2.
/// </summary>
public static partial class SwaggerPetstoreV2Extensions
{
/// <summary>
/// Add a new pet to the store
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
public static Pet AddPet(this ISwaggerPetstoreV2 operations, Pet body)
{
return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).AddPetAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Add a new pet to the store
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Pet> AddPetAsync(this ISwaggerPetstoreV2 operations, Pet body, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.AddPetWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Update an existing pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
public static void UpdatePet(this ISwaggerPetstoreV2 operations, Pet body)
{
Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).UpdatePetAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Update an existing pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task UpdatePetAsync(this ISwaggerPetstoreV2 operations, Pet body, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.UpdatePetWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Finds Pets by status
/// </summary>
/// Multiple status values can be provided with comma seperated strings
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='status'>
/// Status values that need to be considered for filter
/// </param>
public static IList<Pet> FindPetsByStatus(this ISwaggerPetstoreV2 operations, IList<string> status)
{
return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).FindPetsByStatusAsync(status), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Finds Pets by status
/// </summary>
/// Multiple status values can be provided with comma seperated strings
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='status'>
/// Status values that need to be considered for filter
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IList<Pet>> FindPetsByStatusAsync(this ISwaggerPetstoreV2 operations, IList<string> status, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.FindPetsByStatusWithHttpMessagesAsync(status, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Finds Pets by tags
/// </summary>
/// Muliple tags can be provided with comma seperated strings. Use tag1, tag2,
/// tag3 for testing.
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='tags'>
/// Tags to filter by
/// </param>
public static IList<Pet> FindPetsByTags(this ISwaggerPetstoreV2 operations, IList<string> tags)
{
return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).FindPetsByTagsAsync(tags), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Finds Pets by tags
/// </summary>
/// Muliple tags can be provided with comma seperated strings. Use tag1, tag2,
/// tag3 for testing.
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='tags'>
/// Tags to filter by
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IList<Pet>> FindPetsByTagsAsync(this ISwaggerPetstoreV2 operations, IList<string> tags, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.FindPetsByTagsWithHttpMessagesAsync(tags, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Find pet by Id
/// </summary>
/// Returns a single pet
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// Id of pet to return
/// </param>
public static Pet GetPetById(this ISwaggerPetstoreV2 operations, long petId)
{
return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).GetPetByIdAsync(petId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Find pet by Id
/// </summary>
/// Returns a single pet
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// Id of pet to return
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Pet> GetPetByIdAsync(this ISwaggerPetstoreV2 operations, long petId, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetPetByIdWithHttpMessagesAsync(petId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates a pet in the store with form data
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// Id of pet that needs to be updated
/// </param>
/// <param name='fileContent'>
/// File to upload.
/// </param>
/// <param name='fileName'>
/// Updated name of the pet
/// </param>
/// <param name='status'>
/// Updated status of the pet
/// </param>
public static void UpdatePetWithForm(this ISwaggerPetstoreV2 operations, long petId, System.IO.Stream fileContent, string fileName = default(string), string status = default(string))
{
Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).UpdatePetWithFormAsync(petId, fileContent, fileName, status), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Updates a pet in the store with form data
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// Id of pet that needs to be updated
/// </param>
/// <param name='fileContent'>
/// File to upload.
/// </param>
/// <param name='fileName'>
/// Updated name of the pet
/// </param>
/// <param name='status'>
/// Updated status of the pet
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task UpdatePetWithFormAsync(this ISwaggerPetstoreV2 operations, long petId, System.IO.Stream fileContent, string fileName = default(string), string status = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.UpdatePetWithFormWithHttpMessagesAsync(petId, fileContent, fileName, status, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Deletes a pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// Pet id to delete
/// </param>
/// <param name='apiKey'>
/// </param>
public static void DeletePet(this ISwaggerPetstoreV2 operations, long petId, string apiKey = "")
{
Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).DeletePetAsync(petId, apiKey), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// Pet id to delete
/// </param>
/// <param name='apiKey'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeletePetAsync(this ISwaggerPetstoreV2 operations, long petId, string apiKey = "", CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeletePetWithHttpMessagesAsync(petId, apiKey, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Returns pet inventories by status
/// </summary>
/// Returns a map of status codes to quantities
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IDictionary<string, int?> GetInventory(this ISwaggerPetstoreV2 operations)
{
return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).GetInventoryAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns pet inventories by status
/// </summary>
/// Returns a map of status codes to quantities
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IDictionary<string, int?>> GetInventoryAsync(this ISwaggerPetstoreV2 operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetInventoryWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Place an order for a pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// order placed for purchasing the pet
/// </param>
public static Order PlaceOrder(this ISwaggerPetstoreV2 operations, Order body)
{
return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).PlaceOrderAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Place an order for a pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// order placed for purchasing the pet
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Order> PlaceOrderAsync(this ISwaggerPetstoreV2 operations, Order body, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.PlaceOrderWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Find purchase order by Id
/// </summary>
/// For valid response try integer IDs with value <= 5 or > 10. Other
/// values will generated exceptions
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='orderId'>
/// Id of pet that needs to be fetched
/// </param>
public static Order GetOrderById(this ISwaggerPetstoreV2 operations, string orderId)
{
return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).GetOrderByIdAsync(orderId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Find purchase order by Id
/// </summary>
/// For valid response try integer IDs with value <= 5 or > 10. Other
/// values will generated exceptions
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='orderId'>
/// Id of pet that needs to be fetched
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Order> GetOrderByIdAsync(this ISwaggerPetstoreV2 operations, string orderId, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetOrderByIdWithHttpMessagesAsync(orderId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Delete purchase order by Id
/// </summary>
/// For valid response try integer IDs with value < 1000. Anything above
/// 1000 or nonintegers will generate API errors
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='orderId'>
/// Id of the order that needs to be deleted
/// </param>
public static void DeleteOrder(this ISwaggerPetstoreV2 operations, string orderId)
{
Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).DeleteOrderAsync(orderId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete purchase order by Id
/// </summary>
/// For valid response try integer IDs with value < 1000. Anything above
/// 1000 or nonintegers will generate API errors
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='orderId'>
/// Id of the order that needs to be deleted
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteOrderAsync(this ISwaggerPetstoreV2 operations, string orderId, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteOrderWithHttpMessagesAsync(orderId, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Create user
/// </summary>
/// This can only be done by the logged in user.
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Created user object
/// </param>
public static void CreateUser(this ISwaggerPetstoreV2 operations, User body)
{
Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).CreateUserAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create user
/// </summary>
/// This can only be done by the logged in user.
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Created user object
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task CreateUserAsync(this ISwaggerPetstoreV2 operations, User body, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.CreateUserWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// List of user object
/// </param>
public static void CreateUsersWithArrayInput(this ISwaggerPetstoreV2 operations, IList<User> body)
{
Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).CreateUsersWithArrayInputAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// List of user object
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task CreateUsersWithArrayInputAsync(this ISwaggerPetstoreV2 operations, IList<User> body, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.CreateUsersWithArrayInputWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// List of user object
/// </param>
public static void CreateUsersWithListInput(this ISwaggerPetstoreV2 operations, IList<User> body)
{
Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).CreateUsersWithListInputAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// List of user object
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task CreateUsersWithListInputAsync(this ISwaggerPetstoreV2 operations, IList<User> body, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.CreateUsersWithListInputWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Logs user into the system
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The user name for login
/// </param>
/// <param name='password'>
/// The password for login in clear text
/// </param>
public static string LoginUser(this ISwaggerPetstoreV2 operations, string username, string password)
{
return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).LoginUserAsync(username, password), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Logs user into the system
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The user name for login
/// </param>
/// <param name='password'>
/// The password for login in clear text
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<string> LoginUserAsync(this ISwaggerPetstoreV2 operations, string username, string password, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.LoginUserWithHttpMessagesAsync(username, password, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Logs out current logged in user session
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static void LogoutUser(this ISwaggerPetstoreV2 operations)
{
Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).LogoutUserAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Logs out current logged in user session
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task LogoutUserAsync(this ISwaggerPetstoreV2 operations, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.LogoutUserWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get user by user name
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The name that needs to be fetched. Use user1 for testing.
/// </param>
public static User GetUserByName(this ISwaggerPetstoreV2 operations, string username)
{
return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).GetUserByNameAsync(username), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get user by user name
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The name that needs to be fetched. Use user1 for testing.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<User> GetUserByNameAsync(this ISwaggerPetstoreV2 operations, string username, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetUserByNameWithHttpMessagesAsync(username, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updated user
/// </summary>
/// This can only be done by the logged in user.
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// name that need to be deleted
/// </param>
/// <param name='body'>
/// Updated user object
/// </param>
public static void UpdateUser(this ISwaggerPetstoreV2 operations, string username, User body)
{
Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).UpdateUserAsync(username, body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Updated user
/// </summary>
/// This can only be done by the logged in user.
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// name that need to be deleted
/// </param>
/// <param name='body'>
/// Updated user object
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task UpdateUserAsync(this ISwaggerPetstoreV2 operations, string username, User body, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.UpdateUserWithHttpMessagesAsync(username, body, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Delete user
/// </summary>
/// This can only be done by the logged in user.
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The name that needs to be deleted
/// </param>
public static void DeleteUser(this ISwaggerPetstoreV2 operations, string username)
{
Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).DeleteUserAsync(username), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete user
/// </summary>
/// This can only be done by the logged in user.
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The name that needs to be deleted
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteUserAsync(this ISwaggerPetstoreV2 operations, string username, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteUserWithHttpMessagesAsync(username, null, cancellationToken).ConfigureAwait(false);
}
}
}
| |
/*
* Copyright (c) 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
using System;
using System.Threading.Tasks;
using System.Transactions;
using Google.Cloud.Spanner.Data;
using CommandLine;
namespace GoogleCloudSamples.Leaderboard
{
[Verb("create", HelpText = "Create a sample Cloud Spanner database "
+ "along with sample 'Players' and 'Scores' tables in your project.")]
class CreateOptions
{
[Value(0, HelpText = "The project ID of the project to use "
+ "when creating Cloud Spanner resources.", Required = true)]
public string projectId { get; set; }
[Value(1, HelpText = "The ID of the instance where the sample database "
+ "will be created.", Required = true)]
public string instanceId { get; set; }
[Value(2, HelpText = "The ID of the sample database to create.",
Required = true)]
public string databaseId { get; set; }
}
[Verb("insert", HelpText = "Insert sample 'players' records or 'scores' records "
+ "into the database.")]
class InsertOptions
{
[Value(0, HelpText = "The project ID of the project to use "
+ "when managing Cloud Spanner resources.", Required = true)]
public string projectId { get; set; }
[Value(1, HelpText = "The ID of the instance where the sample database resides.",
Required = true)]
public string instanceId { get; set; }
[Value(2, HelpText = "The ID of the database where the sample database resides.",
Required = true)]
public string databaseId { get; set; }
[Value(3, HelpText = "The type of insert to perform, 'players' or 'scores'.",
Required = true)]
public string insertType { get; set; }
}
[Verb("query", HelpText = "Query players with 'Top Ten' scores within a specific timespan "
+ "from sample Cloud Spanner database table.")]
class QueryOptions
{
[Value(0, HelpText = "The project ID of the project to use "
+ "when managing Cloud Spanner resources.", Required = true)]
public string projectId { get; set; }
[Value(1, HelpText = "The ID of the instance where the sample data resides.",
Required = true)]
public string instanceId { get; set; }
[Value(2, HelpText = "The ID of the database where the sample data resides.",
Required = true)]
public string databaseId { get; set; }
[Value(3, Default = 0, HelpText = "The timespan in hours that will be used to filter the "
+ "results based on a record's timestamp. The default will return the "
+ "'Top Ten' scores of all time.")]
public int timespan { get; set; }
}
public class Program
{
enum ExitCode : int
{
Success = 0,
InvalidParameter = 1,
}
public static object Create(string projectId,
string instanceId, string databaseId)
{
var response =
CreateAsync(projectId, instanceId, databaseId);
Console.WriteLine("Waiting for operation to complete...");
response.Wait();
Console.WriteLine($"Operation status: {response.Status}");
Console.WriteLine($"Created sample database {databaseId} on "
+ $"instance {instanceId}");
return ExitCode.Success;
}
public static async Task CreateAsync(
string projectId, string instanceId, string databaseId)
{
// Initialize request connection string for database creation.
string connectionString =
$"Data Source=projects/{projectId}/instances/{instanceId}";
using (var connection = new SpannerConnection(connectionString))
{
string createStatement = $"CREATE DATABASE `{databaseId}`";
string[] createTableStatements = new string[] {
// Define create table statement for Players table.
@"CREATE TABLE Players(
PlayerId INT64 NOT NULL,
PlayerName STRING(2048) NOT NULL
) PRIMARY KEY(PlayerId)",
// Define create table statement for Scores table.
@"CREATE TABLE Scores(
PlayerId INT64 NOT NULL,
Score INT64 NOT NULL,
Timestamp TIMESTAMP NOT NULL OPTIONS(allow_commit_timestamp=true)
) PRIMARY KEY(PlayerId, Timestamp),
INTERLEAVE IN PARENT Players ON DELETE NO ACTION" };
// Make the request.
var cmd = connection.CreateDdlCommand(
createStatement, createTableStatements);
try
{
await cmd.ExecuteNonQueryAsync();
}
catch (SpannerException e) when
(e.ErrorCode == ErrorCode.AlreadyExists)
{
// OK.
}
}
}
public static object Insert(string projectId,
string instanceId, string databaseId, string insertType)
{
if (insertType.ToLower() == "players")
{
var responseTask =
InsertPlayersAsync(projectId, instanceId, databaseId);
Console.WriteLine("Waiting for insert players operation to complete...");
responseTask.Wait();
Console.WriteLine($"Operation status: {responseTask.Status}");
}
else if (insertType.ToLower() == "scores")
{
var responseTask =
InsertScoresAsync(projectId, instanceId, databaseId);
Console.WriteLine("Waiting for insert scores operation to complete...");
responseTask.Wait();
Console.WriteLine($"Operation status: {responseTask.Status}");
}
else
{
Console.WriteLine("Invalid value for 'type of insert'. "
+ "Specify 'players' or 'scores'.");
return ExitCode.InvalidParameter;
}
Console.WriteLine($"Inserted {insertType} into sample database "
+ $"{databaseId} on instance {instanceId}");
return ExitCode.Success;
}
public static async Task InsertPlayersAsync(string projectId,
string instanceId, string databaseId)
{
string connectionString =
$"Data Source=projects/{projectId}/instances/{instanceId}"
+ $"/databases/{databaseId}";
long numberOfPlayers = 0;
using (var connection = new SpannerConnection(connectionString))
{
await connection.OpenAsync();
await connection.RunWithRetriableTransactionAsync(async (transaction) =>
{
// Execute a SQL statement to get current number of records
// in the Players table to use as an incrementing value
// for each PlayerName to be inserted.
var cmd = connection.CreateSelectCommand(
@"SELECT Count(PlayerId) as PlayerCount FROM Players");
numberOfPlayers = await cmd.ExecuteScalarAsync<long>();
// Insert 100 player records into the Players table.
SpannerBatchCommand cmdBatch = connection.CreateBatchDmlCommand();
for (int i = 0; i < 100; i++)
{
numberOfPlayers++;
SpannerCommand cmdInsert = connection.CreateDmlCommand(
"INSERT INTO Players "
+ "(PlayerId, PlayerName) "
+ "VALUES (@PlayerId, @PlayerName)",
new SpannerParameterCollection {
{"PlayerId", SpannerDbType.Int64},
{"PlayerName", SpannerDbType.String}});
cmdInsert.Parameters["PlayerId"].Value =
Math.Abs(Guid.NewGuid().GetHashCode());
cmdInsert.Parameters["PlayerName"].Value =
$"Player {numberOfPlayers}";
cmdBatch.Add(cmdInsert);
}
await cmdBatch.ExecuteNonQueryAsync();
});
}
Console.WriteLine("Done inserting player records...");
}
public static async Task InsertScoresAsync(
string projectId, string instanceId, string databaseId)
{
string connectionString =
$"Data Source=projects/{projectId}/instances/{instanceId}"
+ $"/databases/{databaseId}";
// Insert 4 score records into the Scores table for each player
// in the Players table.
using (var connection = new SpannerConnection(connectionString))
{
await connection.OpenAsync();
await connection.RunWithRetriableTransactionAsync(async (transaction) =>
{
Random r = new Random();
bool playerRecordsFound = false;
SpannerBatchCommand cmdBatch =
connection.CreateBatchDmlCommand();
var cmdLookup =
connection.CreateSelectCommand("SELECT * FROM Players");
using (var reader = await cmdLookup.ExecuteReaderAsync())
{
while (await reader.ReadAsync())
{
playerRecordsFound = true;
for (int i = 0; i < 4; i++)
{
DateTime randomTimestamp = DateTime.Now
.AddYears(r.Next(-2, 1))
.AddMonths(r.Next(-12, 1))
.AddDays(r.Next(-28, 0))
.AddHours(r.Next(-24, 0))
.AddSeconds(r.Next(-60, 0))
.AddMilliseconds(r.Next(-100000, 0));
SpannerCommand cmdInsert =
connection.CreateDmlCommand(
"INSERT INTO Scores "
+ "(PlayerId, Score, Timestamp) "
+ "VALUES (@PlayerId, @Score, @Timestamp)",
new SpannerParameterCollection {
{"PlayerId", SpannerDbType.Int64},
{"Score", SpannerDbType.Int64},
{"Timestamp",
SpannerDbType.Timestamp}});
cmdInsert.Parameters["PlayerId"].Value =
reader.GetFieldValue<int>("PlayerId");
cmdInsert.Parameters["Score"].Value =
r.Next(1000, 1000001);
cmdInsert.Parameters["Timestamp"].Value =
randomTimestamp.ToString("o");
cmdBatch.Add(cmdInsert);
}
}
if (!playerRecordsFound)
{
Console.WriteLine("Parameter 'scores' is invalid "
+ "since no player records currently exist. First "
+ "insert players then insert scores.");
Environment.Exit((int)ExitCode.InvalidParameter);
}
else
{
await cmdBatch.ExecuteNonQueryAsync();
Console.WriteLine(
"Done inserting score records..."
);
}
}
});
}
}
public static object Query(string projectId,
string instanceId, string databaseId, int timespan)
{
var response = QueryAsync(
projectId, instanceId, databaseId, timespan);
response.Wait();
return ExitCode.Success;
}
public static async Task QueryAsync(
string projectId, string instanceId, string databaseId, int timespan)
{
string connectionString =
$"Data Source=projects/{projectId}/instances/"
+ $"{instanceId}/databases/{databaseId}";
// Create connection to Cloud Spanner.
using (var connection = new SpannerConnection(connectionString))
{
string sqlCommand;
if (timespan == 0)
{
// No timespan specified. Query Top Ten scores of all time.
sqlCommand =
@"SELECT p.PlayerId, p.PlayerName, s.Score, s.Timestamp
FROM Players p
JOIN Scores s ON p.PlayerId = s.PlayerId
ORDER BY s.Score DESC LIMIT 10";
}
else
{
// Query Top Ten scores filtered by the timepan specified.
sqlCommand =
$@"SELECT p.PlayerId, p.PlayerName, s.Score, s.Timestamp
FROM Players p
JOIN Scores s ON p.PlayerId = s.PlayerId
WHERE s.Timestamp >
TIMESTAMP_SUB(CURRENT_TIMESTAMP(),
INTERVAL {timespan.ToString()} HOUR)
ORDER BY s.Score DESC LIMIT 10";
}
var cmd = connection.CreateSelectCommand(sqlCommand);
using (var reader = await cmd.ExecuteReaderAsync())
{
while (await reader.ReadAsync())
{
Console.WriteLine("PlayerId : "
+ reader.GetFieldValue<string>("PlayerId")
+ " PlayerName : "
+ reader.GetFieldValue<string>("PlayerName")
+ " Score : "
+ string.Format("{0:n0}",
Int64.Parse(reader.GetFieldValue<string>("Score")))
+ " Timestamp : "
+ reader.GetFieldValue<string>("Timestamp").Substring(0, 10));
}
}
}
}
public static int Main(string[] args)
{
var verbMap = new VerbMap<object>();
verbMap
.Add((CreateOptions opts) => Create(
opts.projectId, opts.instanceId, opts.databaseId))
.Add((InsertOptions opts) => Insert(
opts.projectId, opts.instanceId, opts.databaseId, opts.insertType))
.Add((QueryOptions opts) => Query(
opts.projectId, opts.instanceId, opts.databaseId, opts.timespan))
.NotParsedFunc = (err) => 1;
return (int)verbMap.Run(args);
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
namespace CalbucciLib
{
/// <summary>
/// HTML Element
/// </summary>
public partial class HtmlElementInfo
{
// ====================================================================
//
// STATIC FIELDS
//
// ====================================================================
/// <summary>
/// Elements that cannot contain script or any other "unsafe" content
/// </summary>
public static List<string> GlobaAttributes;
private static List<HtmlElementInfo> AllElements;
private static Dictionary<string, HtmlElementInfo> ElemsInfo;
// ====================================================================
//
// PRIVATE FIELDS
//
// ====================================================================
// ====================================================================
//
// CONSTRUCTORS
//
// ====================================================================
static HtmlElementInfo()
{
GlobaAttributes =
"accesskey;class;contenteditable;contextmenu;dir;draggable;dropzone;hidden;id;lang;spellcheck;style;tabindex;title;translate;;onabort;onblur;oncanplay;oncanplaythrough;onchange;onclick;oncontextmenu;ondblclick;ondrag;ondragend;ondragenter;ondragleave;ondragover;ondragstart;ondrop;ondurationchange;onemptied;onended;onerror;onfocus;oninput;oninvalid;onkeydown;onkeypress;onkeyup;onload;onloaddata;onloadeddata;onloadedmetadata;onloadstart;onmousedown;onmousemove;onmouseout;onmouseover;onmouseup;onmousewheel;onpause;onplay;onplaying;onprogress;onratechange;onreadystatechange;onreset;onscroll;onseekend;onseeking;onselect;onshow;onstalled;onsubmit;onsuspended;ontimeupdate;onvolumechange;onwaiting;xml:base;xml:lang;xml:space"
.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
.Distinct().OrderBy(a => a).ToList();
Initialize();
ElemsInfo = new Dictionary<string, HtmlElementInfo>();
foreach (var hei in AllElements)
{
ElemsInfo[hei.TagName] = hei;
}
}
internal HtmlElementInfo()
{
}
// ====================================================================
//
// VIRTUAL METHODS (public/protected)
//
// ====================================================================
// ====================================================================
//
// PUBLIC METHODS (instance)
//
// ====================================================================
public AttrStatus GetAttributeStatus(string attrName)
{
if (string.IsNullOrWhiteSpace(attrName))
return AttrStatus.Unknown;
attrName = attrName.ToLowerInvariant();
if (ObsoleteAttributes != null)
{
if (ObsoleteAttributes.Contains(attrName))
return AttrStatus.Deprecated;
}
if (Attributes.Contains(attrName))
return AttrStatus.Valid;
return AttrStatus.Unknown;
}
public bool IsValidParent(string parentTagName)
{
if (string.IsNullOrWhiteSpace(parentTagName))
return true; // no parent is always valid here
parentTagName = parentTagName.ToLowerInvariant();
// Check if the parent is in the not-allowed list
if (ExcludeParentTags != null)
{
if (ExcludeParentTags.Contains(parentTagName))
return false;
}
// Check if the parent is in the white list
if (ParentTags != null)
{
if (ParentTags.Contains(parentTagName))
return true;
}
// Finally, check if the content type is allowed
if (ParentContentTypes == HtmlElementType.None)
return false;
var parentInfo = GetElementInfo(parentTagName);
if (parentInfo == null)
{
if (parentTagName.IndexOf(':') >= 0)
return true; // assume it's a custom defined element
return false;
}
if ((ParentContentTypes & parentInfo.PermittedChildrenTypes) != 0)
return true;
return false;
}
// ====================================================================
//
// PRIVATE/PROTECTED METHODS
//
// ====================================================================
// ====================================================================
//
// STATIC METHODS (public)
//
// ====================================================================
/// <summary>
/// Returns the HtmlElementInfo for the tag.
/// </summary>
public static HtmlElementInfo GetElementInfo(string tagName)
{
if (string.IsNullOrWhiteSpace(tagName))
return null;
HtmlElementInfo elementInfo;
ElemsInfo.TryGetValue(tagName.ToLowerInvariant(), out elementInfo);
return elementInfo;
}
private static IList<string> ConvertSemicolonDelimited(string text)
{
List<string> strList;
if (text != null)
{
strList = text.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
.Select(t => t.ToLowerInvariant())
.Distinct()
.OrderBy(t => t).ToList();
if (strList.Count > 0)
return strList;
}
return null;
}
// ====================================================================
//
// PROPERTIES
//
// ====================================================================
public string TagName { get; private set; }
/// <summary>
/// HTML verison that introduced this tag
/// </summary>
public int HtmlVersion { get; private set; }
/// <summary>
/// Indicates if this element is obsolete
/// </summary>
public bool Obsolete { get; private set; }
public HtmlTagFormatting TagFormatting { get; private set; }
public HtmlElementType ElementType { get; private set; }
/// <summary>
/// Valid types of elements that can be nested inside this tag
/// </summary>
public HtmlElementType PermittedChildrenTypes { get; private set; }
/// <summary>
/// Valid children for this tag
/// </summary>
public IList<string> PermittedChildrenTags { get; private set; }
public IList<string> Attributes { get; private set; }
public IList<string> ObsoleteAttributes { get; private set; }
public HtmlElementType ParentContentTypes { get; private set; }
public IList<string> ParentTags { get; private set; }
public IList<string> ExcludeParentTags { get; private set; }
private string PermittedChildrenTagsString
{
set { PermittedChildrenTags = ConvertSemicolonDelimited(value); }
}
private string AttributesString
{
set
{
var additionalAttributes = ConvertSemicolonDelimited(value);
if (additionalAttributes != null)
Attributes = GlobaAttributes.Union(additionalAttributes).OrderBy(a => a).ToList();
else
Attributes = GlobaAttributes;
}
}
private string ObsoleteAttributesString
{
set { ObsoleteAttributes = ConvertSemicolonDelimited(value); }
}
private string ParentTagsString
{
set { ParentTags = ConvertSemicolonDelimited(value); }
}
private string ExcludeParentTagsString
{
set { ExcludeParentTags = ConvertSemicolonDelimited(value); }
}
}
}
| |
using System.Diagnostics;
using NUnit.Framework;
using StructureMap.Configuration.DSL;
using StructureMap.Graph;
using StructureMap.Pipeline;
using StructureMap.Testing.Widget;
using StructureMap.Testing.Widget3;
namespace StructureMap.Testing.Graph
{
[TestFixture]
public class ContainerTester : Registry
{
#region Setup/Teardown
[SetUp]
public void SetUp()
{
_container = new Container(registry => {
registry.Scan(x => x.Assembly("StructureMap.Testing.Widget"));
registry.For<Rule>();
registry.For<IWidget>();
registry.For<WidgetMaker>();
});
}
#endregion
private IContainer _container;
private void addColorInstance(string Color)
{
_container.Configure(r => {
r.For<Rule>().Use<ColorRule>().Ctor<string>("color").Is(Color).Named(Color);
r.For<IWidget>().Use<ColorWidget>().Ctor<string>("color").Is(Color).Named(
Color);
r.For<WidgetMaker>().Use<ColorWidgetMaker>().Ctor<string>("color").Is(Color).
Named(Color);
});
}
public interface IProvider
{
}
public class Provider : IProvider
{
}
public class ClassThatUsesProvider
{
private readonly IProvider _provider;
public ClassThatUsesProvider(IProvider provider)
{
_provider = provider;
}
public IProvider Provider
{
get { return _provider; }
}
}
public class DifferentProvider : IProvider
{
}
private void assertColorIs(IContainer container, string color)
{
container.GetInstance<IService>().ShouldBeOfType<ColorService>().Color.ShouldEqual(color);
}
[Test]
public void can_inject_into_a_running_container()
{
var container = new Container();
container.Inject(typeof (ISport), new ConstructorInstance(typeof (Football)));
container.GetInstance<ISport>()
.ShouldBeOfType<Football>();
}
[Test]
public void Can_set_profile_name_and_reset_defaults()
{
var container = new Container(r => {
r.For<IService>()
.Use<ColorService>().Named("Orange").Ctor<string>("color").Is(
"Orange");
r.For<IService>().AddInstances(x => {
x.Type<ColorService>().Named("Red").Ctor<string>("color").Is("Red");
x.Type<ColorService>().Named("Blue").Ctor<string>("color").Is("Blue");
x.Type<ColorService>().Named("Green").Ctor<string>("color").Is("Green");
});
r.Profile("Red", x => { x.For<IService>().Use("Red"); });
r.Profile("Blue", x => { x.For<IService>().Use("Blue"); });
});
assertColorIs(container, "Orange");
assertColorIs(container.GetProfile("Red"), "Red");
assertColorIs(container.GetProfile("Blue"), "Blue");
assertColorIs(container, "Orange");
}
[Test]
public void CanBuildConcreteTypesThatAreNotPreviouslyRegistered()
{
IContainer manager = new Container(
registry => registry.For<IProvider>().Use<Provider>());
// Now, have that same Container create a ClassThatUsesProvider. StructureMap will
// see that ClassThatUsesProvider is concrete, determine its constructor args, and build one
// for you with the default IProvider. No other configuration necessary.
var classThatUsesProvider = manager.GetInstance<ClassThatUsesProvider>();
classThatUsesProvider.Provider.ShouldBeOfType<Provider>();
}
[Test]
public void CanBuildConcreteTypesThatAreNotPreviouslyRegisteredWithArgumentsProvided()
{
IContainer manager =
new Container(
registry => registry.For<IProvider>().Use<Provider>());
var differentProvider = new DifferentProvider();
var args = new ExplicitArguments();
args.Set<IProvider>(differentProvider);
var classThatUsesProvider = manager.GetInstance<ClassThatUsesProvider>(args);
Assert.AreSame(differentProvider, classThatUsesProvider.Provider);
}
[Test]
public void can_get_the_default_instance()
{
addColorInstance("Red");
addColorInstance("Orange");
addColorInstance("Blue");
_container.Configure(x => x.For<Rule>().Use("Blue"));
_container.GetInstance<Rule>().ShouldBeOfType<ColorRule>().Color.ShouldEqual("Blue");
}
[Test]
public void GetInstanceOf3Types()
{
addColorInstance("Red");
addColorInstance("Orange");
addColorInstance("Blue");
var rule = _container.GetInstance(typeof (Rule), "Blue") as ColorRule;
Assert.IsNotNull(rule);
Assert.AreEqual("Blue", rule.Color);
var widget = _container.GetInstance(typeof (IWidget), "Red") as ColorWidget;
Assert.IsNotNull(widget);
Assert.AreEqual("Red", widget.Color);
var maker = _container.GetInstance(typeof (WidgetMaker), "Orange") as ColorWidgetMaker;
Assert.IsNotNull(maker);
Assert.AreEqual("Orange", maker.Color);
}
[Test]
public void GetMissingType()
{
var ex = Exception<StructureMapException>.ShouldBeThrownBy(() => {
_container.GetInstance(typeof(string));
});
ex.Title.ShouldContain("No default");
}
[Test]
public void InjectStub_by_name()
{
IContainer container = new Container();
var red = new ColorRule("Red");
var blue = new ColorRule("Blue");
container.Configure(x => {
x.For<Rule>().Add(red).Named("Red");
x.For<Rule>().Add(blue).Named("Blue");
});
Assert.AreSame(red, container.GetInstance<Rule>("Red"));
Assert.AreSame(blue, container.GetInstance<Rule>("Blue"));
}
[Test]
public void TryGetInstance_returns_instance_for_an_open_generic_that_it_can_close()
{
var container =
new Container(
x =>
x.For(typeof (IOpenGeneric<>)).Use(typeof (ConcreteOpenGeneric<>)));
container.TryGetInstance<IOpenGeneric<object>>().ShouldNotBeNull();
}
[Test]
public void TryGetInstance_returns_null_for_an_open_generic_that_it_cannot_close()
{
var container =
new Container(
x =>
x.For(typeof (IOpenGeneric<>)).Use(typeof (ConcreteOpenGeneric<>)));
container.TryGetInstance<IAnotherOpenGeneric<object>>().ShouldBeNull();
}
[Test]
public void TryGetInstance_ReturnsInstance_WhenTypeFound()
{
_container.Configure(c => c.For<IProvider>().Use<Provider>());
var instance = _container.TryGetInstance(typeof (IProvider));
instance.ShouldBeOfType(typeof (Provider));
}
[Test]
public void TryGetInstance_ReturnsNull_WhenTypeNotFound()
{
var instance = _container.TryGetInstance(typeof (IProvider));
instance.ShouldBeNull();
}
[Test]
public void TryGetInstanceViaGeneric_ReturnsInstance_WhenTypeFound()
{
_container.Configure(c => c.For<IProvider>().Use<Provider>());
var instance = _container.TryGetInstance<IProvider>();
instance.ShouldBeOfType(typeof (Provider));
}
[Test]
public void TryGetInstanceViaGeneric_ReturnsNull_WhenTypeNotFound()
{
var instance = _container.TryGetInstance<IProvider>();
instance.ShouldBeNull();
}
[Test]
public void TryGetInstanceViaName_ReturnsNull_WhenNotFound()
{
addColorInstance("Red");
addColorInstance("Orange");
addColorInstance("Blue");
var rule = _container.TryGetInstance(typeof (Rule), "Yellow");
rule.ShouldBeNull();
}
[Test]
public void TryGetInstanceViaName_ReturnsTheOutInstance_WhenFound()
{
addColorInstance("Red");
addColorInstance("Orange");
addColorInstance("Blue");
var rule = _container.TryGetInstance(typeof (Rule), "Orange");
rule.ShouldBeOfType(typeof (ColorRule));
}
[Test]
public void TryGetInstanceViaNameAndGeneric_ReturnsInstance_WhenTypeFound()
{
addColorInstance("Red");
addColorInstance("Orange");
addColorInstance("Blue");
// "Orange" exists, so an object should be returned
var instance = _container.TryGetInstance<Rule>("Orange");
instance.ShouldBeOfType(typeof (ColorRule));
}
[Test]
public void TryGetInstanceViaNameAndGeneric_ReturnsNull_WhenTypeNotFound()
{
addColorInstance("Red");
addColorInstance("Orange");
addColorInstance("Blue");
// "Yellow" does not exist, so return null
var instance = _container.TryGetInstance<Rule>("Yellow");
instance.ShouldBeNull();
}
}
public interface ISport
{
}
public class Football : ISport
{
}
public interface IOpenGeneric<T>
{
void Nop();
}
public interface IAnotherOpenGeneric<T>
{
}
public class ConcreteOpenGeneric<T> : IOpenGeneric<T>
{
public void Nop()
{
}
}
public class StringOpenGeneric : ConcreteOpenGeneric<string>
{
}
}
| |
/***********************************************************************************************************************
* TorrentDotNET - A BitTorrent library based on the .NET platform *
* Copyright (C) 2004, Peter Ward *
* *
* This library is free software; you can redistribute it and/or modify it under the terms of the *
* GNU Lesser General Public License as published by the Free Software Foundation; *
* either version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License along with this library; *
* if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
***********************************************************************************************************************/
using System.Collections;
using Net = System.Net;
using IO = System.IO;
using Threading = System.Threading;
using PWLib.Platform;
namespace BitTorrent
{
/// <summary>
/// For when the peer list updates
/// </summary>
/// <param name="tp">Associated tracker protocol</param>
/// <param name="numNewPeers">New number of peers</param>
public delegate void TrackerUpdateCallback(ArrayList peers, bool success, string errorMessage);
public class TrackerException : System.Exception
{
public TrackerException(string err)
: base(err)
{}
}
/// <summary>
/// Encapsulates the Tracker protocol. Provides all tracker-related communication.
/// </summary>
public class TrackerProtocol : System.IDisposable
{
private Torrent torrent;
private MetainfoFile infofile;
private DownloadFile file;
private bool autoUpdate = true, badTracker = false;
private int updateInterval = 0;
private ArrayList peerList = new ArrayList();
private Threading.Timer updateTimer = null;
/// <summary>
/// Called whenever the peer list is updated
/// </summary>
public event TrackerUpdateCallback TrackerUpdate;
/// <summary>
/// Interval in seconds at which the client should communicate with the tracker to keep
/// it up-to-date with the torrent's progress. It isn't recommended that this is changed
/// from the default, but it is possible.
/// </summary>
/// <returns>Update interval in seconds</returns>
public int UpdateInterval
{
get { return this.updateInterval; }
}
/// <summary>
/// Whether the TrackerProtocol should automatically update the tracker itself. Defaults to true.
/// </summary>
/// <returns>True if autoupdate is on, false otherwise</returns>
public bool AutoUpdate
{
get { return this.autoUpdate; }
set
{
if (this.autoUpdate != value)
{
if (value)
{
this.updateTimer = new Threading.Timer(new Threading.TimerCallback(OnUpdate), null,
this.updateInterval * 1000, this.updateInterval * 1000);
}
else
{
this.updateTimer.Dispose();
this.updateTimer = null;
}
this.autoUpdate = value;
}
}
}
/// <summary>
/// Constructs a TrackerProtocol
/// </summary>
public TrackerProtocol(Torrent torrent, MetainfoFile infofile, DownloadFile file)
{
this.torrent = torrent;
this.infofile = infofile;
this.file = file;
}
/// <summary>
/// URI escapes an array of data
/// </summary>
/// <returns>Escaped string</returns>
public static string UriEscape(byte[] data)
{
string escaped = "";
for (int i=0; i<data.Length; ++i)
{
char c = (char)data[i];
// this is a list of allowed characters in web escaping
// if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')))
//// || c == '$' || c == '-' || c == '_' ||
//// c == '.' || c == '+' || c == '!' || c == '*' || c == '\'' || c == '(' || c == ')'))
// {
escaped += System.Uri.HexEscape(c);
//}
//else
// escaped += c;
}
return escaped;
}
/// <summary>
/// Used by the auto-updater, this simply called Update()
/// </summary>
/// <param name="state">Not used</param>
private void OnUpdate(object state)
{
this.Update();
}
/// <summary>
/// Initiate the connection with the tracker, retrieve a list of peers to use.
/// </summary>
/// <param name="infofile">Metainfo file for the torrent</param>
/// <param name="file">Download file for the torrent</param>
public void Initiate()
{
this.SendWebRequest("started", Config.DefaultNumWant, true);
}
/// <summary>
/// Every now and again the tracker needs to be informed of the torrent's progress as well as knowing that we are
/// still connected. This tells the tracker how we are doing.
/// </summary>
public void Update()
{
this.SendWebRequest("", Config.DefaultNumWant, true);
}
/// <summary>
/// This tells the tracker we have finished downloading. This should *not* be called when the torrent starts with
/// a full torrent, just when it has finished downloading.
/// </summary>
public void Completed()
{
this.SendWebRequest("completed", 0, true);
}
/// <summary>
/// This is called when a torrent is stopping gracefully.
/// </summary>
public void Stop()
{
this.SendWebRequest("stopped", 0, false);
}
public void Stop(int bytesUploaded, int bytesDownloaded)
{
this.SendWebRequest("stopped", 0, false, bytesUploaded, bytesDownloaded);
}
public void SendWebRequest(string eventString, int numwant, bool compact)
{
this.SendWebRequest(eventString, numwant, compact, this.torrent.BytesUploaded, this.torrent.BytesDownloaded);
}
/// <summary>
/// Creates the WebRequest object for communicating with the tracker
/// </summary>
/// <param name="eventString">Event to report. Can be either "started", "completed", "stopped", or "" (for tracker updates)</param>
/// <param name="numwant">How many peers to request. Defaults to 50.</param>
/// <param name="compact">True if we want the tracker to respond in compact form. The tracker ignores this if it does not support it</param>
/// <returns>WebRequest object</returns>
private void SendWebRequest(string eventString, int numwant, bool compact,
int bytesUploaded, int bytesDownloaded)
{
string newUrl = infofile.AnnounceUrl;
newUrl += newUrl.IndexOf("?") >= 0 ? "&" : "?";
newUrl += "info_hash=" + UriEscape(infofile.InfoDigest.Data);
newUrl += "&peer_id=" + UriEscape(torrent.Session.LocalPeerID.Data);
newUrl += "&port=" + Config.ActiveConfig.ChosenPort;
newUrl += "&uploaded=" + bytesUploaded;
newUrl += "&downloaded=" + bytesDownloaded;
newUrl += "&left=" + this.file.NumBytesLeft;
if (Config.ActiveConfig.ServerIP != "")
newUrl += "&ip=" + Config.ActiveConfig.ServerIP;
if (numwant > 0)
newUrl += "&numwant=" + numwant;
if (compact)
{
newUrl += "&compact=1";
newUrl += "&no_peer_id=1";
}
// newUrl += "&key=54644";
if (eventString != "")
newUrl += "&event=" + eventString;
Net.HttpWebRequest request = (Net.HttpWebRequest)Net.WebRequest.Create(newUrl);
request.KeepAlive = false;
request.UserAgent = "BitTorrent/3.4.2";
request.Headers.Add("Cache-Control", "no-cache");
request.ProtocolVersion = new System.Version(1, 0);
if (eventString == "stopped" && badTracker)
return;
else
request.BeginGetResponse(new System.AsyncCallback(OnResponse), request);
}
private void OnResponse(System.IAsyncResult result)
{
try
{
Net.HttpWebRequest request = (Net.HttpWebRequest)result.AsyncState;
Net.WebResponse response = request.EndGetResponse(result);
this.ParseTrackerResponse(response.GetResponseStream());
response.Close();
if (this.TrackerUpdate != null)
this.TrackerUpdate(this.peerList, true, string.Empty);
if (this.autoUpdate && this.updateTimer == null)
{
this.updateTimer = new Threading.Timer(new Threading.TimerCallback(OnUpdate), null,
this.updateInterval * 1000, this.updateInterval * 1000);
}
}
catch (System.Exception e)
{
if (this.TrackerUpdate != null)
this.TrackerUpdate(null, false, e.Message);
badTracker = true;
}
}
/// <summary>
/// Parses the response from the tracker, and updates the peer list
/// </summary>
/// <param name="stream">IO stream from response</param>
private void ParseTrackerResponse(IO.Stream stream)
{
this.peerList.Clear();
/*
// because the response stream does not support seeking, we copy the contents to a memorystream
// to send to the bencoder. This shouldnt cause too much of a performance penalty as it shouldnt
// be too large anyway.
byte[] data = new byte[ 1024 ];
IO.MemoryStream responseStream = new IO.MemoryStream();
int dataRead = 0;
while ((dataRead = stream.Read(data, 0, data.Length)) > 0)
{
responseStream.Write(data, 0, dataRead);
}
responseStream.Seek(0, IO.SeekOrigin.Begin);
*/
///
BEncode.Dictionary dic = BEncode.NextDictionary(stream);
// note: sometimes IPs can be duplicated in quick disconnection, so there is a check for any duplications
if (dic.Contains("failure reason"))
{
throw new IO.IOException("Tracker connection failed: " + dic.GetString("failure reason"));
}
else
{
this.updateInterval = dic.GetInteger("interval");
BEncode.Element peers = dic["peers"];
if (peers is BEncode.List)
{
// peer list comes as a list of dictionaries
BEncode.List dicList = (BEncode.List)peers;
foreach (BEncode.Dictionary dicPeer in dicList)
{
ByteField20 peerId = new ByteField20(dicPeer.GetBytes("peer id"));
string peerIp = dicPeer.GetString("ip");
int port = dicPeer.GetInteger("port");
PeerInformation peerinfo = new PeerInformation(peerIp, port, peerId);
if (!this.peerList.Contains(peerinfo))
this.peerList.Add(peerinfo);
}
}
else if (peers is BEncode.String)
{
// else its compressed (this is pretty common)
byte[] compactPeers = ((BEncode.String)peers).Data;
for (int i=0; i<compactPeers.Length; i += 6)
{
int ip1 = 0xFF & compactPeers[i];
int ip2 = 0xFF & compactPeers[i+1];
int ip3 = 0xFF & compactPeers[i+2];
int ip4 = 0xFF & compactPeers[i+3];
int po1 = 0xFF & compactPeers[i+4];
int po2 = 0xFF & compactPeers[i+5];
string peerIp = ip1 + "." + ip2 + "." + ip3 + "." + ip4;
int port = (po1 * 256) + po2;
PeerInformation peerinfo = new PeerInformation(peerIp, port);
if (!this.peerList.Contains(peerinfo))
this.peerList.Add(peerinfo);
}
}
else
throw new TrackerException("Unexcepted error");
}
}
/// <summary>
/// Gathers statistics about the torrent. This is known as "Scraping"
/// </summary>
/// <param name="infofile">Metainfo file on the torrent</param>
/// <param name="numSeeds">Number of seeds on the torrent</param>
/// <param name="numLeechers">Number of peers (leechers) on the torrent</param>
/// <param name="numFinished">Number of successful downloads so far</param>
public static void Scrape(MetainfoFile infofile, out int numSeeds, out int numLeechers, out int numFinished)
{
string name;
Scrape(infofile, out numSeeds, out numLeechers, out numFinished, out name);
}
/// <summary>
/// Gathers statistics about the torrent. This is known as "Scraping"
/// </summary>
/// <param name="infofile">Metainfo file on the torrent</param>
/// <param name="numSeeds">Number of seeds on the torrent</param>
/// <param name="numLeechers">Number of peers (leechers) on the torrent</param>
/// <param name="numFinished">Number of successful downloads so far</param>
/// <param name="name">Name of the torrent</param>
public static void Scrape(MetainfoFile infofile, out int numSeeds, out int numLeechers, out int numFinished, out string name)
{
numSeeds = numLeechers = numFinished = 0;
name = "";
// determine the scrape url.
string announceUrl = infofile.AnnounceUrl;
int lastSlashIndex = announceUrl.LastIndexOf('/');
if (lastSlashIndex < 0)
return;
const string announce = "announce";
// check that "announce" exists after the last slash in the url - if it doesn't, scraping isn't supported.
if (announceUrl.Substring(lastSlashIndex+1, announce.Length).CompareTo(announce) != 0)
return;
string scapeUrl = announceUrl.Substring(0, lastSlashIndex+1) + "scrape" + announceUrl.Substring(lastSlashIndex + 1 + announce.Length);
scapeUrl += "?";
scapeUrl += "info_hash=" + UriEscape(infofile.InfoDigest.Data);
Net.WebRequest request = Net.WebRequest.Create(scapeUrl);
Net.WebResponse response = request.GetResponse();
IO.Stream stream = response.GetResponseStream();
// because the response stream does not support seeking, we copy the contents to a memorystream
// to send to the bencoder. This shouldnt cause too much of a performance penalty as it shouldnt
// be too large anyway.
byte[] data = new byte[ 1024 ];
IO.MemoryStream responseStream = new IO.MemoryStream();
int dataRead = 0;
while ((dataRead = stream.Read(data, 0, data.Length)) > 0)
{
responseStream.Write(data, 0, dataRead);
}
responseStream.Seek(0, IO.SeekOrigin.Begin);
///
BEncode.Dictionary mainDic = BEncode.NextDictionary(responseStream);
if (mainDic.Contains("files"))
{
// extract file information - as we supplied the info_hash value, this dictionary should only contain one value
BEncode.Dictionary filesDic = mainDic.GetDictionary("files");
foreach (BEncode.String infoHash in filesDic.Keys)
{
BEncode.Dictionary dic = filesDic.GetDictionary(infoHash);
if (dic.Contains("downloaded"))
numFinished = dic.GetInteger("downloaded");
if (dic.Contains("incomplete"))
numLeechers = dic.GetInteger("incomplete");
if (dic.Contains("complete"))
numSeeds = dic.GetInteger("complete");
if (dic.Contains("name"))
name = dic.GetString("name");
}
}
else if (mainDic.Contains("failure reason"))
throw new TrackerException("Tracker connection failed: " + mainDic.GetString("failure reason"));
}
#region IDisposable Members
/// <summary>
/// Disposes the object
/// </summary>
public void Dispose()
{
if (this.updateTimer != null)
this.updateTimer.Dispose();
this.updateTimer = null;
}
#endregion
}
}
| |
using UnityEngine;
using System.Collections.Generic;
namespace Rx
{
public class DebugShape2 : MonoBehaviour
{
public static bool hackHide = false;
protected Color unselectedVertexColor = Color.grey;
protected Color selectedVertexColor = Color.white;
protected Color controlledVertexColor = Color.blue;
protected Color highlightedVertexColor = Color.red;
protected Color unselectedEdgeColor = Color.grey;
protected Color selectedEdgeColor = Color.white;
protected Color controlledEdgeColor = Color.blue;
protected Color highlightedEdgeColor = Color.red;
protected Vector3 defaultVertexSize = new Vector3( 3.0f, 2.5f, 1.0f );
protected Vector3 hoverVertexSize = new Vector3( 5.0f, 4.5f, 1.0f );
protected Vector3 controlledVertexSize = new Vector3( 5.0f, 4.5f, 1.0f );
protected Color pointOfIntersectionColor = Color.red;
protected Vector3 pointOfIntersectionSize = new Vector3( 6.0f, 6.0f, 1.0f );
// For polygons only.
protected List<Vector2> fusedVertices = new List<Vector2>();
public List<Vector2> vertices = new List<Vector2>();
protected int minVertices = 0;
protected int maxVertices = int.MaxValue;
protected int hoverVertexIndex = -1;
protected int controlledVertexIndex = -1;
protected float sqMinDistanceToHoverVertex = 200.0f;
public bool IsSelected { get; set; }
public bool IsHighlighted { get; set; }
public List<Vector2> PointsOfIntersection { get; set; }
public List<Vector2> GetWorldVertices()
{
List<Vector2> result = new List<Vector2>( vertices.Count );
Vector2 gameObjectPosition = new Vector2( transform.position.x, transform.position.y );
for ( int index = 0; index < vertices.Count; ++index )
{
result.Add( vertices[index] + gameObjectPosition );
}
return result;
}
public void ReverseVertices()
{
vertices.Reverse();
controlledVertexIndex = vertices.Count - controlledVertexIndex - 1;
}
public void ShiftUpVertices()
{
List<Vector2> originalVertices = new List<Vector2>( vertices );
for (int src = 0; src < originalVertices.Count; ++src )
{
int dst = (src + 1) % originalVertices.Count;
vertices[dst] = originalVertices[src];
}
}
#region Events
public virtual void OnMouseMove( Vector2 mousePosition )
{
hoverVertexIndex = -1;
float sqNearestVertexDistance = float.MaxValue;
for ( int index = 0; index < vertices.Count; ++index )
{
float sqDistanceToVertex = ( ToWorld2( vertices[index] ) - mousePosition ).SqrMagnitude();
if ( ( sqDistanceToVertex < sqMinDistanceToHoverVertex ) && ( sqDistanceToVertex < sqNearestVertexDistance ) )
{
hoverVertexIndex = index;
}
}
}
public virtual void OnMouseDrag( Vector2 mousePosition )
{
if ( controlledVertexIndex != -1 )
{
vertices[controlledVertexIndex] = ToLocal2( mousePosition );
}
}
public virtual void OnMouseDown( Vector2 mousePosition )
{
if ( hoverVertexIndex != -1 )
{
controlledVertexIndex = hoverVertexIndex;
}
else
{
controlledVertexIndex = -1;
}
}
public virtual void OnKeyDown( KeyCode keyCode, Vector2 mousePosition )
{
switch ( keyCode )
{
case KeyCode.I:
{
if ( vertices.Count < maxVertices )
{
if ( controlledVertexIndex == -1 )
{
vertices.Add( mousePosition );
controlledVertexIndex = vertices.Count - 1;
}
else
{
vertices.Insert( controlledVertexIndex + 1, ToLocal2( mousePosition ) );
controlledVertexIndex = controlledVertexIndex + 1;
}
}
}
break;
case KeyCode.K:
{
if ( ( controlledVertexIndex != -1 ) && ( vertices.Count > minVertices ) )
{
vertices.RemoveAt( controlledVertexIndex );
controlledVertexIndex = -1;
}
}
break;
}
}
#endregion
#region Drawing
public virtual void OnDrawGizmos()
{
if ( hackHide )
{
return;
}
if ( vertices.Count >= 0 )
{
if ( !IsSelected )
{
controlledVertexIndex = -1;
}
DrawEdges();
DrawVertices();
DrawPointsOfIntersection();
}
}
protected void DrawEdges()
{
for ( int index = 0; index < vertices.Count; ++index )
{
int nextIndex = index + 1;
if ( nextIndex == vertices.Count )
{
nextIndex = 0;
}
Gizmos.color = unselectedEdgeColor;
if ( IsHighlighted )
{
Gizmos.color = highlightedEdgeColor;
}
else if ( index == controlledVertexIndex )
{
Gizmos.color = controlledEdgeColor;
}
else if ( IsSelected )
{
Gizmos.color = selectedEdgeColor;
}
Gizmos.DrawLine( ToWorld3( vertices[index] ), ToWorld3( vertices[nextIndex] ) );
}
}
protected void DrawVertices()
{
for ( int index = 0; index < vertices.Count; ++index )
{
if ( IsHighlighted )
{
Gizmos.color = highlightedVertexColor;
Gizmos.DrawCube( ToWorld3( vertices[index] ), defaultVertexSize );
}
else if ( index == controlledVertexIndex )
{
Gizmos.color = controlledVertexColor;
Gizmos.DrawCube( ToWorld3( vertices[index] ), controlledVertexSize );
}
else
{
if ( IsSelected )
{
Gizmos.color = selectedVertexColor;
}
else
{
Gizmos.color = unselectedVertexColor;
}
if ( index == hoverVertexIndex )
{
Gizmos.DrawCube( ToWorld3( vertices[index] ), hoverVertexSize );
}
else
{
Gizmos.DrawCube( ToWorld3( vertices[index] ), defaultVertexSize );
}
}
}
}
protected void DrawPointsOfIntersection()
{
if ( PointsOfIntersection != null )
{
foreach ( Vector2 point in PointsOfIntersection )
{
Gizmos.color = pointOfIntersectionColor;
Gizmos.DrawCube( new Vector3( point.x, point.y, transform.position.z ), pointOfIntersectionSize );
}
}
}
protected Vector2 ToLocal2( Vector2 worldPosition )
{
return worldPosition - Helpers.AsVector2( transform.position );
}
protected Vector2 ToWorld2( Vector2 localPosition )
{
return localPosition + Helpers.AsVector2( transform.position );
}
protected Vector3 ToWorld3( Vector2 localPosition )
{
return Helpers.AsVector3( localPosition, 0.0f ) + transform.position;
}
public void CenterGizmo()
{
// Just do a simple, unweighted average to find the "center" of the polygon.
if ( vertices.Count > 0 )
{
Vector2 curPosition = new Vector2( transform.position.x, transform.position.y );
Vector2 center = Vector2.zero;
foreach ( Vector2 vertex in vertices )
{
center += vertex + curPosition;
}
center /= vertices.Count;
Vector2 positionDelta = center - curPosition;
for ( int index = 0; index < vertices.Count; ++index )
{
vertices[index] -= positionDelta;
}
transform.position = new Vector3( center.x, center.y, transform.position.z );
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Net;
using System.Net.Http;
using System.Web;
using System.IO;
using System.Reflection;
using System.Threading;
using Mustache;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using CodeFirstWebFramework;
namespace AccountServer {
/// <summary>
/// Base class for all app modules
/// </summary>
[Auth(AccessLevel.ReadOnly)]
public abstract class AppModule : CodeFirstWebFramework.AppModule {
public new Database Database {
get {
return (Database)base.Database;
}
}
public new Settings Settings {
get { return (Settings)base.Settings; }
}
public string NewVersion {
get { return Program.NewVersion; }
}
/// <summary>
/// True if user does have Authorise
/// </summary>
public bool Authorise
{
get { return UserAccessLevel >= AccessLevel.Authorise; }
}
/// <summary>
/// Generic object for templates to use - usually contains data from the database
/// </summary>
public object Record;
/// <summary>
/// Get the last document of the given type with NameAddressId == id
/// </summary>
public object DocumentLast(int id, DocType type) {
JObject result = new JObject();
Extended_Document header = Database.QueryOne<Extended_Document>("SELECT * FROM Extended_Document WHERE DocumentTypeId = " + (int)type
+ " AND DocumentNameAddressId = " + id
+ " ORDER BY DocumentDate DESC, idDocument DESC");
if (header.idDocument != null) {
if (Utils.ExtractNumber(header.DocumentIdentifier) > 0)
header.DocumentIdentifier = "";
result.AddRange("header", header,
"detail", Database.Query("idJournal, DocumentId, Line.VatCodeId, VatRate, JournalNum, Journal.AccountId, Memo, LineAmount, VatAmount, LineAmount + VatAmount AS Gross",
"WHERE Journal.DocumentId = " + header.idDocument + " AND idLine IS NOT NULL ORDER BY JournalNum",
"Document", "Journal", "Line"));
}
return result;
}
/// <summary>
/// Allocate the next unused cheque number/deposit number/etc.
/// </summary>
protected void allocateDocumentIdentifier(Extended_Document document) {
if ((document.idDocument == null || document.idDocument == 0) && document.DocumentIdentifier == "<next>") {
FullAccount acct = null;
DocType type = (DocType)document.DocumentTypeId;
switch (type) {
case DocType.Withdrawal:
case DocType.Deposit:
case DocType.CreditCardCharge:
case DocType.CreditCardCredit:
acct = Database.QueryOne<FullAccount>("*", "WHERE idAccount = " + document.DocumentAccountId, "Account");
break;
}
allocateDocumentIdentifier(document, acct);
}
}
/// <summary>
/// Allocate the next unused cheque number/deposit number/etc.
/// </summary>
protected void allocateDocumentIdentifier(Extended_Document document, FullAccount acct) {
if ((document.idDocument == null || document.idDocument == 0) && document.DocumentIdentifier == "<next>") {
DocType type = (DocType)document.DocumentTypeId;
int nextDocId = 0;
switch (type) {
case DocType.Invoice:
case DocType.Payment:
case DocType.CreditMemo:
case DocType.Bill:
case DocType.BillPayment:
case DocType.Credit:
case DocType.GeneralJournal:
nextDocId = Settings.NextNumber(type);
break;
case DocType.Withdrawal:
case DocType.Deposit:
case DocType.CreditCardCharge:
case DocType.CreditCardCredit:
nextDocId = acct.NextNumber(type);
break;
}
document.DocumentIdentifier = nextDocId != 0 ? nextDocId.ToString() : "";
}
}
/// <summary>
/// Check AcctType type is one of the supplied account tyes
/// </summary>
protected AcctType checkAcctType(int? type, params AcctType[] allowed) {
Utils.Check(type != null, "Account Type missing");
AcctType t = (AcctType)type;
Utils.Check(Array.IndexOf(allowed, t) >= 0, "Cannot use this screen to edit {0}s", t.UnCamel());
return t;
}
/// <summary>
/// Check AcctType type is one of the supplied account tyes
/// </summary>
protected AcctType checkAcctType(JToken type, params AcctType[] allowed) {
return checkAcctType(type.To<int?>(), allowed);
}
/// <summary>
/// Check type of supplied account is one of the supplied account tyes
/// </summary>
protected AcctType checkAccountIsAcctType(int? account, params AcctType[] allowed) {
Utils.Check(account != null, "Account missing");
Account a = Database.Get<Account>((int)account);
return checkAcctType(a.AccountTypeId, allowed);
}
/// <summary>
/// Check type is one of the supplied document types
/// </summary>
protected DocType checkDocType(int? type, params DocType[] allowed) {
Utils.Check(type != null, "Document Type missing");
DocType t = (DocType)type;
Utils.Check(Array.IndexOf(allowed, t) >= 0, "Cannot use this screen to edit {0}s", t.UnCamel());
return t;
}
/// <summary>
/// Check type is one of the supplied document types
/// </summary>
protected DocType checkDocType(JToken type, params DocType[] allowed) {
return checkDocType(type.To<int?>(), allowed);
}
/// <summary>
/// Check type is the supplied name type ("C" for customer, "S" for supplier, "O" for other)
/// </summary>
protected void checkNameType(string type, string allowed) {
Utils.Check(type == allowed, "Name is not a {0}", allowed.NameType());
}
/// <summary>
/// Check NameAddress record is the supplied name type ("C" for customer, "S" for supplier, "O" for other)
/// </summary>
protected void checkNameType(int? id, string allowed) {
Utils.Check(id != null, allowed.NameType() + " missing");
NameAddress n = Database.Get<NameAddress>((int)id);
checkNameType(n.Type, allowed);
}
/// <summary>
/// Check NameAddress record is the supplied name type ("C" for customer, "S" for supplier, "O" for other)
/// </summary>
protected void checkNameType(JToken id, string allowed) {
checkNameType(id.To<int?>(), allowed);
}
/// <summary>
/// Delete a document, first checking it is one of the supplied types
/// </summary>
protected AjaxReturn deleteDocument(int id, params DocType[] allowed) {
AjaxReturn result = new AjaxReturn();
Database.BeginTransaction();
Extended_Document record = getDocument<Extended_Document>(id);
Utils.Check(record != null && record.idDocument != null, "Record does not exist");
DocType type = checkDocType(record.DocumentTypeId, allowed);
if (record.DocumentOutstanding != record.DocumentAmount) {
result.error = type.UnCamel() + " has been " +
(type == DocType.Payment || type == DocType.BillPayment ? "used to pay or part pay invoices" : "paid or part paid")
+ " it cannot be deleted";
} else if(record.VatPaid > 0) {
result.error = "VAT has been declared on " + type.UnCamel() + " it cannot be deleted";
} else {
Database.Audit(AuditType.Delete, "Document", id, getCompleteDocument(record));
Database.Execute("DELETE FROM StockTransaction WHERE idStockTransaction IN (SELECT idJournal FROM Journal WHERE DocumentId = " + id + ")");
Database.Execute("DELETE FROM Line WHERE idLine IN (SELECT idJournal FROM Journal WHERE DocumentId = " + id + ")");
Database.Execute("DELETE FROM Journal WHERE DocumentId = " + id);
Database.Execute("DELETE FROM Document WHERE idDocument = " + id);
Database.Commit();
result.message = type.UnCamel() + " deleted";
}
return result;
}
/// <summary>
/// List all the journals that post to this account, along with document info and the balance after the posting.
/// Detects documents which are splits (i.e. have more than 2 journals) and sets the DocumentAccountName to "-split-"
/// </summary>
protected IEnumerable<JObject> detailsWithBalance(int id) {
JObject last = null; // previous document
int lastId = 0; // Id of previous journal
decimal balance = 0; // Running total balance
// Query gets all journals to this account, joined to document header
// Then joins to any other journals for this document, so documents with only 2 journals
// will appear once, but if there are more than 2 journals the document will appear more times
foreach (JObject l in Database.Query(@"SELECT Journal.idJournal, Document.*, NameAddress.Name As DocumentName, DocType, Journal.Cleared AS Clr, Journal.Amount As DocumentAmount, AccountName As DocumentAccountName
FROM Journal
LEFT JOIN Document ON idDocument = Journal.DocumentId
LEFT JOIN DocumentType ON DocumentType.idDocumentType = Document.DocumentTypeId
LEFT JOIN NameAddress ON NameAddress.idNameAddress = Journal.NameAddressId
LEFT JOIN Journal AS J ON J.DocumentId = Journal.DocumentId AND J.AccountId <> Journal.AccountId
LEFT JOIN Account ON Account.idAccount = J.AccountId
WHERE Journal.AccountId = " + id + @"
ORDER BY DocumentDate, idDocument")) {
if (last != null) {
if (lastId == l.AsInt("idJournal")) {
// More than 1 line in this document
last["DocumentAccountName"] = "-split-";
// Only emit each journal to this account once
continue;
}
balance += last.AsDecimal("DocumentAmount");
last["Balance"] = balance;
yield return last;
}
last = l;
lastId = l.AsInt("idJournal");
}
if (last != null) {
balance += last.AsDecimal("DocumentAmount");
last["Balance"] = balance;
yield return last;
}
}
/// <summary>
/// Make sure the DocumentnameAddressId for a document is filled in,
/// creating a new record if DocumentName does not already exist in the NameAddress table.
/// </summary>
/// <param name="nameType">The type the NameAddress record must be (S, C or O)</param>
protected void fixNameAddress(Extended_Document document, string nameType) {
if (document.DocumentNameAddressId == null || document.DocumentNameAddressId == 0) {
document.DocumentNameAddressId = string.IsNullOrWhiteSpace(document.DocumentName) ? 1 :
Database.ForeignKey("NameAddress",
"Type", nameType,
"Name", document.DocumentName,
"Address", document.DocumentAddress);
} else {
checkNameType(document.DocumentNameAddressId, nameType);
}
}
/// <summary>
/// Get a complete document (header and details) by id
/// </summary>
protected JObject getCompleteDocument(int? id) {
Extended_Document doc = getDocument<Extended_Document>(id);
if (doc.idDocument == null) return null;
return getCompleteDocument(doc);
}
/// <summary>
/// Get a complete document (including details) from the supplied document header
/// </summary>
protected JObject getCompleteDocument<T>(T document) where T : Extended_Document {
return new JObject().AddRange("header", document,
"detail", Database.Query(@"SELECT Journal.*, AccountName, Name, Qty, ProductId, ProductName, LineAmount, Line.VatCodeId, Code, VatRate, VatAmount
FROM Journal
LEFT JOIN Line ON idLine = idJournal
LEFT JOIN Account ON idAccount = Journal.AccountId
LEFT JOIN NameAddress ON idNameAddress = NameAddressId
LEFT JOIN Product ON idProduct = ProductId
LEFT JOIN VatCode ON idVatCode = Line.VatCodeId
WHERE Journal.DocumentId = " + document.idDocument));
}
/// <summary>
/// Read the current copy of the supplied document from the database
/// </summary>
protected T getDocument<T>(T document) where T : JsonObject {
if (document.Id == null) return Database.EmptyRecord<T>();
return getDocument<T>((int)document.Id);
}
/// <summary>
/// Read the current copy of the supplied document id from the database
/// </summary>
protected T getDocument<T>(int? id) where T : JsonObject {
return Database.QueryOne<T>("SELECT * FROM Extended_Document WHERE idDocument = " + (id == null ? "NULL" : id.ToString()));
}
/// <summary>
/// Fill in the "next" and "previous" variables in record with the next and previous
/// document ids.
/// </summary>
/// <param name="sql">Sql to add to document select to limit the documents returned,
/// e.g. to the next cheque from this bank account.</param>
protected void nextPreviousDocument(JObject record, string sql) {
JObject header = (JObject)record["header"];
int id = header.AsInt("idDocument");
string d = Database.Quote(header.AsDate("DocumentDate"));
JObject next = id == 0 ? null : Database.QueryOne("SELECT idDocument FROM Document " + sql
+ " AND (DocumentDate > " + d + " OR (DocumentDate = " + d + " AND idDocument > " + id + "))"
+ " ORDER BY DocumentDate, idDocument");
if(next != null || ReadWrite)
record["next"] = next == null ? 0 : next.AsInt("idDocument");
JObject previous = Database.QueryOne("SELECT idDocument FROM Document " + sql
+ (id == 0 ? "" : " AND (DocumentDate < " + d + " OR (DocumentDate = " + d + " AND idDocument < " + id + "))")
+ " ORDER BY DocumentDate DESC, idDocument DESC");
if (previous != null || ReadWrite)
record["previous"] = previous == null ? 0 : previous.AsInt("idDocument");
}
/// <summary>
/// Return the sign to use for documents of the supplied type.
/// </summary>
/// <returns>-1 or 1</returns>
static public int SignFor(DocType docType) {
switch (docType) {
case DocType.Invoice:
case DocType.Payment:
case DocType.Credit:
case DocType.Deposit:
case DocType.CreditCardCredit:
case DocType.GeneralJournal:
case DocType.Sell:
return -1;
default:
return 1;
}
}
/// <summary>
/// Save an arbitrary JObject to the database, optionally also saving an audit trail
/// </summary>
public AjaxReturn SaveRecord(JsonObject record, bool audit) {
AjaxReturn retval = new AjaxReturn();
try {
if (record.Id <= 0)
record.Id = null;
Database.Update(record, audit);
retval.id = record.Id;
} catch (Exception ex) {
Message = ex.Message;
retval.error = ex.Message;
}
return retval;
}
// Select values
public JObjectEnumerable SelectAccounts() {
return Database.Query(@"idAccount AS id, AccountName AS value, AcctType AS category, Protected + HideAccount as hide",
"WHERE HideAccount = 0 or HideAccount is null ORDER BY idAccountType, AccountName",
"Account");
}
public JObjectEnumerable SelectAllAccounts() {
return Database.Query(@"idAccount AS id, AccountName AS value, AcctType AS category, HideAccount as hide",
" ORDER BY idAccountType, AccountName",
"Account");
}
public JObjectEnumerable SelectAccountTypes() {
return Database.Query(@"idAccountType AS id, AcctType AS value",
" ORDER BY idAccountType",
"AccountType");
}
public IEnumerable<JObject> SelectAuditTypes() {
for (AuditType t = AuditType.Insert; t <= AuditType.Delete; t++) {
yield return new JObject().AddRange("id", (int)t, "value", t.UnCamel());
}
}
public JObjectEnumerable SelectBankAccounts() {
return Database.Query(@"idAccount AS id, AccountName AS value, AcctType AS category, HideAccount AS hide",
"WHERE AccountTypeId " + Database.In(AcctType.Bank,AcctType.CreditCard)
+ " ORDER BY idAccountType, AccountName",
"Account");
}
public JObjectEnumerable SelectBankOrOtherALAccounts() {
return Database.Query(@"idAccount AS id, AccountName AS value, AcctType AS category, HideAccount AS hide",
"WHERE AccountTypeId " + Database.In(AcctType.Bank, AcctType.CreditCard, AcctType.OtherAsset, AcctType.OtherLiability)
+ " ORDER BY idAccountType, AccountName",
"Account");
}
public JObjectEnumerable SelectBankOrStockAccounts() {
return Database.Query(@"idAccount AS id, AccountName AS value, AcctType AS category, HideAccount AS hide",
"WHERE AccountTypeId " + Database.In(AcctType.Bank, AcctType.CreditCard, AcctType.Investment, AcctType.OtherAsset, AcctType.OtherLiability)
+ " ORDER BY idAccountType, AccountName",
"Account");
}
public JObjectEnumerable SelectCustomers() {
return SelectNames("C");
}
public JObjectEnumerable SelectDocumentTypes() {
return Database.Query(@"idDocumentType AS id, DocType AS value",
" ORDER BY idDocumentType",
"DocumentType");
}
public JObjectEnumerable SelectExpenseAccounts() {
return Database.Query(@"idAccount AS id, AccountName AS value, AcctType AS category, Protected + HideAccount as hide",
"WHERE AccountTypeId " + Database.In(AcctType.Expense, AcctType.OtherExpense) + " ORDER BY idAccountType, AccountName",
"Account");
}
public JObjectEnumerable SelectIncomeAccounts() {
return Database.Query(@"idAccount AS id, AccountName AS value, AcctType AS category, Protected + HideAccount as hide",
"WHERE AccountTypeId = " + (int)AcctType.Income + " ORDER BY idAccountType, AccountName",
"Account");
}
public JObjectEnumerable SelectNames() {
return Database.Query(@"idNameAddress AS id, Name AS value, CASE Type WHEN 'C' THEN 'Customers' WHEN 'S' THEN 'Suppliers' ELSE 'Others' END AS category, Hidden as hide",
" ORDER BY Type, Name",
"NameAddress");
}
public JObjectEnumerable SelectNames(string nameType) {
return Database.Query(@"idNameAddress AS id, Name AS value, Hidden as hide, Address, Telephone",
"WHERE Type = " + Database.Quote(nameType) + " ORDER BY Name",
"NameAddress");
}
public IEnumerable<JObject> SelectNameTypes() {
return new JObject[] {
new JObject().AddRange("id", "C", "value", "Customer"),
new JObject().AddRange("id", "S", "value", "Supplier"),
new JObject().AddRange("id", "M", "value", "Member"),
new JObject().AddRange("id", "O", "value", "Other")
};
}
public JObjectEnumerable SelectMemberTypes() {
return Database.Query(@"SELECT idMemberType AS id, MemberTypeName AS value, AnnualSubscription, NumberOfPayments
FROM MemberType
ORDER BY MemberTypeName");
}
public JObjectEnumerable SelectOthers() {
return SelectNames("O");
}
public JObjectEnumerable SelectProducts() {
return Database.Query(@"idProduct AS id, ProductName AS value, ProductDescription, UnitPrice, VatCodeId, Code, VatDescription, Rate, AccountId, Unit",
" ORDER BY ProductName",
"Product");
}
public JObjectEnumerable SelectReportGroups() {
return Database.Query(@"ReportGroup AS id, ReportGroup AS value",
" GROUP BY ReportGroup ORDER BY ReportGroup",
"Report");
}
public JObjectEnumerable SelectSecurities() {
return Database.Query(@"idSecurity AS id, SecurityName AS value",
" ORDER BY SecurityName",
"Security");
}
public JObjectEnumerable SelectSuppliers() {
return SelectNames("S");
}
public JObjectEnumerable SelectUsers() {
return Database.Query(@"idUser AS id, Login AS value",
"ORDER BY Login",
"User");
}
public IEnumerable<JObject> SelectVatCodes() {
List<JObject> result = Database.Query(@"idVatCode AS id, Code, VatDescription, Rate",
" ORDER BY Code",
"VatCode").ToList();
foreach (JObject o in result)
o["value"] = o.AsString("Code") + " (" + o.AsDecimal("Rate") + "%)";
result.Insert(0, new JObject().AddRange("id", null,
"value", "",
"Rate", 0));
return result;
}
public IEnumerable<JObject> SelectVatTypes() {
return new JObject[] {
new JObject().AddRange("id", -1, "value", "Sales"),
new JObject().AddRange("id", 1, "value", "Purchases")
};
}
public JObjectEnumerable SelectVatPayments() {
return Database.Query(@"SELECT idDocument as id, DocumentDate as value
FROM Document
JOIN Journal ON DocumentId = idDocument
WHERE AccountId = 8
AND JournalNum = 2
AND DocumentTypeId IN (7, 8, 9, 10)
ORDER BY idDocument");
}
}
/// <summary>
/// Class to show errors
/// </summary>
public class ErrorModule : AppModule {
}
}
| |
using Kitware.VTK;
using System;
// input file is C:\VTK\Graphics\Testing\Tcl\rectGrid.tcl
// output file is AVrectGrid.cs
/// <summary>
/// The testing class derived from AVrectGrid
/// </summary>
public class AVrectGridClass
{
/// <summary>
/// The main entry method called by the CSharp driver
/// </summary>
/// <param name="argv"></param>
public static void AVrectGrid(String [] argv)
{
//Prefix Content is: ""
VTK_VARY_RADIUS_BY_VECTOR = 2;
// create pipeline[]
//[]
reader = new vtkDataSetReader();
reader.SetFileName((string)"" + (VTK_DATA_ROOT.ToString()) + "/Data/RectGrid2.vtk");
reader.Update();
toRectilinearGrid = new vtkCastToConcrete();
toRectilinearGrid.SetInputConnection((vtkAlgorithmOutput)reader.GetOutputPort());
toRectilinearGrid.Update();
plane = new vtkRectilinearGridGeometryFilter();
plane.SetInputData((vtkDataObject)toRectilinearGrid.GetRectilinearGridOutput());
plane.SetExtent((int)0,(int)100,(int)0,(int)100,(int)15,(int)15);
warper = new vtkWarpVector();
warper.SetInputConnection((vtkAlgorithmOutput)plane.GetOutputPort());
warper.SetScaleFactor((double)0.05);
planeMapper = new vtkDataSetMapper();
planeMapper.SetInputConnection((vtkAlgorithmOutput)warper.GetOutputPort());
planeMapper.SetScalarRange((double)0.197813,(double)0.710419);
planeActor = new vtkActor();
planeActor.SetMapper((vtkMapper)planeMapper);
cutPlane = new vtkPlane();
cutPlane.SetOrigin(reader.GetOutput().GetCenter()[0],reader.GetOutput().GetCenter()[1],reader.GetOutput().GetCenter()[2]);
cutPlane.SetNormal((double)1,(double)0,(double)0);
planeCut = new vtkCutter();
planeCut.SetInputData((vtkDataObject)toRectilinearGrid.GetRectilinearGridOutput());
planeCut.SetCutFunction((vtkImplicitFunction)cutPlane);
cutMapper = new vtkDataSetMapper();
cutMapper.SetInputConnection((vtkAlgorithmOutput)planeCut.GetOutputPort());
cutMapper.SetScalarRange((double)((vtkDataSet)reader.GetOutput()).GetPointData().GetScalars().GetRange()[0], (double)((vtkDataSet)reader.GetOutput()).GetPointData().GetScalars().GetRange()[1]);
cutActor = new vtkActor();
cutActor.SetMapper((vtkMapper)cutMapper);
iso = new vtkContourFilter();
iso.SetInputData((vtkDataObject)toRectilinearGrid.GetRectilinearGridOutput());
iso.SetValue((int)0,(double)0.7);
normals = new vtkPolyDataNormals();
normals.SetInputConnection((vtkAlgorithmOutput)iso.GetOutputPort());
normals.SetFeatureAngle((double)45);
isoMapper = vtkPolyDataMapper.New();
isoMapper.SetInputConnection((vtkAlgorithmOutput)normals.GetOutputPort());
isoMapper.ScalarVisibilityOff();
isoActor = new vtkActor();
isoActor.SetMapper((vtkMapper)isoMapper);
isoActor.GetProperty().SetColor((double) 1.0000, 0.8941, 0.7686 );
isoActor.GetProperty().SetRepresentationToWireframe();
streamer = new vtkStreamLine();
streamer.SetInputConnection((vtkAlgorithmOutput)reader.GetOutputPort());
streamer.SetStartPosition((double)-1.2,(double)-0.1,(double)1.3);
streamer.SetMaximumPropagationTime((double)500);
streamer.SetStepLength((double)0.05);
streamer.SetIntegrationStepLength((double)0.05);
streamer.SetIntegrationDirectionToIntegrateBothDirections();
streamTube = new vtkTubeFilter();
streamTube.SetInputConnection((vtkAlgorithmOutput)streamer.GetOutputPort());
streamTube.SetRadius((double)0.025);
streamTube.SetNumberOfSides((int)6);
streamTube.SetVaryRadius((int)VTK_VARY_RADIUS_BY_VECTOR);
mapStreamTube = vtkPolyDataMapper.New();
mapStreamTube.SetInputConnection((vtkAlgorithmOutput)streamTube.GetOutputPort());
mapStreamTube.SetScalarRange((double)((vtkDataSet)reader.GetOutput()).GetPointData().GetScalars().GetRange()[0], (double)((vtkDataSet)reader.GetOutput()).GetPointData().GetScalars().GetRange()[1]);
streamTubeActor = new vtkActor();
streamTubeActor.SetMapper((vtkMapper)mapStreamTube);
streamTubeActor.GetProperty().BackfaceCullingOn();
outline = new vtkOutlineFilter();
outline.SetInputData((vtkDataObject)toRectilinearGrid.GetRectilinearGridOutput());
outlineMapper = vtkPolyDataMapper.New();
outlineMapper.SetInputConnection((vtkAlgorithmOutput)outline.GetOutputPort());
outlineActor = new vtkActor();
outlineActor.SetMapper((vtkMapper)outlineMapper);
outlineActor.GetProperty().SetColor((double) 0.0000, 0.0000, 0.0000 );
// Graphics stuff[]
// Create the RenderWindow, Renderer and both Actors[]
//[]
ren1 = vtkRenderer.New();
renWin = vtkRenderWindow.New();
renWin.SetMultiSamples(0);
renWin.AddRenderer((vtkRenderer)ren1);
iren = new vtkRenderWindowInteractor();
iren.SetRenderWindow((vtkRenderWindow)renWin);
// Add the actors to the renderer, set the background and size[]
//[]
ren1.AddActor((vtkProp)outlineActor);
ren1.AddActor((vtkProp)planeActor);
ren1.AddActor((vtkProp)cutActor);
ren1.AddActor((vtkProp)isoActor);
ren1.AddActor((vtkProp)streamTubeActor);
ren1.SetBackground((double)1,(double)1,(double)1);
renWin.SetSize((int)400,(int)400);
cam1 = ren1.GetActiveCamera();
cam1.SetClippingRange((double)3.76213,(double)10.712);
cam1.SetFocalPoint((double)-0.0842503,(double)-0.136905,(double)0.610234);
cam1.SetPosition((double)2.53813,(double)2.2678,(double)-5.22172);
cam1.SetViewUp((double)-0.241047,(double)0.930635,(double)0.275343);
iren.Initialize();
// render the image[]
//[]
// prevent the tk window from showing up then start the event loop[]
//deleteAllVTKObjects();
}
static string VTK_DATA_ROOT;
static int threshold;
static int VTK_VARY_RADIUS_BY_VECTOR;
static vtkDataSetReader reader;
static vtkCastToConcrete toRectilinearGrid;
static vtkRectilinearGridGeometryFilter plane;
static vtkWarpVector warper;
static vtkDataSetMapper planeMapper;
static vtkActor planeActor;
static vtkPlane cutPlane;
static vtkCutter planeCut;
static vtkDataSetMapper cutMapper;
static vtkActor cutActor;
static vtkContourFilter iso;
static vtkPolyDataNormals normals;
static vtkPolyDataMapper isoMapper;
static vtkActor isoActor;
static vtkStreamLine streamer;
static vtkTubeFilter streamTube;
static vtkPolyDataMapper mapStreamTube;
static vtkActor streamTubeActor;
static vtkOutlineFilter outline;
static vtkPolyDataMapper outlineMapper;
static vtkActor outlineActor;
static vtkRenderer ren1;
static vtkRenderWindow renWin;
static vtkRenderWindowInteractor iren;
static vtkCamera cam1;
///<summary> A Get Method for Static Variables </summary>
public static string GetVTK_DATA_ROOT()
{
return VTK_DATA_ROOT;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetVTK_DATA_ROOT(string toSet)
{
VTK_DATA_ROOT = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static int Getthreshold()
{
return threshold;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setthreshold(int toSet)
{
threshold = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static int GetVTK_VARY_RADIUS_BY_VECTOR()
{
return VTK_VARY_RADIUS_BY_VECTOR;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetVTK_VARY_RADIUS_BY_VECTOR(int toSet)
{
VTK_VARY_RADIUS_BY_VECTOR = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkDataSetReader Getreader()
{
return reader;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setreader(vtkDataSetReader toSet)
{
reader = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkCastToConcrete GettoRectilinearGrid()
{
return toRectilinearGrid;
}
///<summary> A Set Method for Static Variables </summary>
public static void SettoRectilinearGrid(vtkCastToConcrete toSet)
{
toRectilinearGrid = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRectilinearGridGeometryFilter Getplane()
{
return plane;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setplane(vtkRectilinearGridGeometryFilter toSet)
{
plane = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkWarpVector Getwarper()
{
return warper;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setwarper(vtkWarpVector toSet)
{
warper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkDataSetMapper GetplaneMapper()
{
return planeMapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetplaneMapper(vtkDataSetMapper toSet)
{
planeMapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor GetplaneActor()
{
return planeActor;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetplaneActor(vtkActor toSet)
{
planeActor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPlane GetcutPlane()
{
return cutPlane;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetcutPlane(vtkPlane toSet)
{
cutPlane = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkCutter GetplaneCut()
{
return planeCut;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetplaneCut(vtkCutter toSet)
{
planeCut = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkDataSetMapper GetcutMapper()
{
return cutMapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetcutMapper(vtkDataSetMapper toSet)
{
cutMapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor GetcutActor()
{
return cutActor;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetcutActor(vtkActor toSet)
{
cutActor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkContourFilter Getiso()
{
return iso;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setiso(vtkContourFilter toSet)
{
iso = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataNormals Getnormals()
{
return normals;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setnormals(vtkPolyDataNormals toSet)
{
normals = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper GetisoMapper()
{
return isoMapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetisoMapper(vtkPolyDataMapper toSet)
{
isoMapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor GetisoActor()
{
return isoActor;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetisoActor(vtkActor toSet)
{
isoActor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkStreamLine Getstreamer()
{
return streamer;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setstreamer(vtkStreamLine toSet)
{
streamer = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkTubeFilter GetstreamTube()
{
return streamTube;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetstreamTube(vtkTubeFilter toSet)
{
streamTube = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper GetmapStreamTube()
{
return mapStreamTube;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetmapStreamTube(vtkPolyDataMapper toSet)
{
mapStreamTube = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor GetstreamTubeActor()
{
return streamTubeActor;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetstreamTubeActor(vtkActor toSet)
{
streamTubeActor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkOutlineFilter Getoutline()
{
return outline;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setoutline(vtkOutlineFilter toSet)
{
outline = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper GetoutlineMapper()
{
return outlineMapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetoutlineMapper(vtkPolyDataMapper toSet)
{
outlineMapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor GetoutlineActor()
{
return outlineActor;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetoutlineActor(vtkActor toSet)
{
outlineActor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderer Getren1()
{
return ren1;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setren1(vtkRenderer toSet)
{
ren1 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindow GetrenWin()
{
return renWin;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetrenWin(vtkRenderWindow toSet)
{
renWin = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindowInteractor Getiren()
{
return iren;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setiren(vtkRenderWindowInteractor toSet)
{
iren = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkCamera Getcam1()
{
return cam1;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setcam1(vtkCamera toSet)
{
cam1 = toSet;
}
///<summary>Deletes all static objects created</summary>
public static void deleteAllVTKObjects()
{
//clean up vtk objects
if(reader!= null){reader.Dispose();}
if(toRectilinearGrid!= null){toRectilinearGrid.Dispose();}
if(plane!= null){plane.Dispose();}
if(warper!= null){warper.Dispose();}
if(planeMapper!= null){planeMapper.Dispose();}
if(planeActor!= null){planeActor.Dispose();}
if(cutPlane!= null){cutPlane.Dispose();}
if(planeCut!= null){planeCut.Dispose();}
if(cutMapper!= null){cutMapper.Dispose();}
if(cutActor!= null){cutActor.Dispose();}
if(iso!= null){iso.Dispose();}
if(normals!= null){normals.Dispose();}
if(isoMapper!= null){isoMapper.Dispose();}
if(isoActor!= null){isoActor.Dispose();}
if(streamer!= null){streamer.Dispose();}
if(streamTube!= null){streamTube.Dispose();}
if(mapStreamTube!= null){mapStreamTube.Dispose();}
if(streamTubeActor!= null){streamTubeActor.Dispose();}
if(outline!= null){outline.Dispose();}
if(outlineMapper!= null){outlineMapper.Dispose();}
if(outlineActor!= null){outlineActor.Dispose();}
if(ren1!= null){ren1.Dispose();}
if(renWin!= null){renWin.Dispose();}
if(iren!= null){iren.Dispose();}
if(cam1!= null){cam1.Dispose();}
}
}
//--- end of script --//
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System.Patterns.UI.Forms;
using System.Text;
namespace System.Web.UI.WebControls
{
/// <summary>
/// ListBoxEx
/// </summary>
public class ListBoxEx : ListBox, IFormControl
{
private string _staticTextSeparator = ", ";
/// <summary>
/// Gets or sets the view mode.
/// </summary>
/// <value>
/// The view mode.
/// </value>
public FormFieldViewMode ViewMode { get; set; }
#region Option-Groups
/// <summary>
/// Creates the begin group list item.
/// </summary>
/// <param name="text">The text.</param>
/// <returns></returns>
public static ListItem CreateBeginGroupListItem(string text)
{
var listItem = new ListItem(text);
listItem.Attributes["group"] = "begin";
return listItem;
}
/// <summary>
/// Creates the end group list item.
/// </summary>
/// <returns></returns>
public static ListItem CreateEndGroupListItem()
{
var listItem = new ListItem();
listItem.Attributes["group"] = "end";
return listItem;
}
//public string DataGroupPathField { get; set; }
//protected override void PerformDataBinding(IEnumerable dataSource)
//{
// if (dataSource != null)
// throw new ArgumentNullException("dataSource");
// string dataGroupPathField = DataGroupPathField;
// if (string.IsNullOrEmpty(dataGroupPathField))
// base.PerformDataBinding(dataSource);
//}
//[Match("match with ListBox RenderContents")]
/// <summary>
/// Renders the contents.
/// </summary>
/// <param name="w">The w.</param>
protected override void RenderContents(HtmlTextWriter w)
{
var itemHash = Items;
var itemCount = itemHash.Count;
if (itemCount > 0)
{
var isA = false;
for (int itemKey = 0; itemKey < itemCount; itemKey++)
{
var listItem = itemHash[itemKey];
if (listItem.Enabled)
switch (listItem.Attributes["group"])
{
case "begin":
w.WriteBeginTag("optgroup");
w.WriteAttribute("label", listItem.Text);
w.Write('>');
break;
case "end":
w.WriteEndTag("optgroup");
break;
default:
w.WriteBeginTag("option");
if (listItem.Selected)
{
if (isA)
VerifyMultiSelect();
isA = true;
w.WriteAttribute("selected", "selected");
}
w.WriteAttribute("value", listItem.Value, true);
if (listItem.Attributes.Count > 0)
listItem.Attributes.Render(w);
if (Page != null)
Page.ClientScript.RegisterForEventValidation(UniqueID, listItem.Value);
w.Write('>');
HttpUtility.HtmlEncode(listItem.Text, w);
w.WriteEndTag("option");
w.WriteLine();
break;
}
}
}
}
#endregion
/// <summary>
/// Renders the specified w.
/// </summary>
/// <param name="w">The w.</param>
protected override void Render(HtmlTextWriter w)
{
switch (ViewMode)
{
case FormFieldViewMode.Static:
RenderStaticText(w);
break;
case FormFieldViewMode.StaticWithHidden:
RenderStaticText(w);
RenderHidden(w);
break;
case FormFieldViewMode.Hidden:
RenderHidden(w);
break;
default:
base.Render(w);
break;
}
}
/// <summary>
/// Renders the hidden.
/// </summary>
/// <param name="w">The w.</param>
protected void RenderHidden(HtmlTextWriter w)
{
var b = new StringBuilder();
foreach (ListItem item in Items)
if (item.Selected)
b.Append(item.Value + ",");
if (b.Length > 0)
b.Length--;
w.AddAttribute(HtmlTextWriterAttribute.Type, "hidden");
w.AddAttribute(HtmlTextWriterAttribute.Id, ClientID);
w.AddAttribute(HtmlTextWriterAttribute.Name, UniqueID);
w.AddAttribute(HtmlTextWriterAttribute.Value, b.ToString());
w.RenderBeginTag(HtmlTextWriterTag.Input);
w.RenderEndTag();
}
/// <summary>
/// Renders the static text.
/// </summary>
/// <param name="w">The w.</param>
protected virtual void RenderStaticText(HtmlTextWriter w)
{
var staticTextSeparator = StaticTextSeparator;
var b = new StringBuilder();
foreach (ListItem item in Items)
if (item.Selected)
b.Append(HttpUtility.HtmlEncode(item.Text) + staticTextSeparator);
var staticTextSeparatorLength = staticTextSeparator.Length;
if (b.Length > staticTextSeparatorLength)
b.Length -= staticTextSeparatorLength;
w.AddAttribute(HtmlTextWriterAttribute.Class, "static");
w.RenderBeginTag(HtmlTextWriterTag.Span);
w.Write(b.ToString());
w.RenderEndTag();
}
/// <summary>
/// Gets or sets the static text separator.
/// </summary>
/// <value>
/// The static text separator.
/// </value>
public string StaticTextSeparator
{
get { return _staticTextSeparator; }
set
{
if (value == null)
throw new ArgumentNullException("value");
_staticTextSeparator = value;
}
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.Video;
namespace VNEngine
{
public class UIManager : MonoBehaviour
{
public static UIManager ui_manager;
// CSV to load so our UI can be put into the proper language
public TextAsset Localized_UI_CSV;
// Each language has a dictionary, then that dictionary is searched for a specific key
[HideInInspector]
public Dictionary<string, Dictionary<string, string>> Localized_UI_Dictionaries = new Dictionary<string, Dictionary<string, string>>();
[HideInInspector]
List<LocalizeTextElement> localized_ui_elements = new List<LocalizeTextElement>(); // Elements that were localized. Get localized again if the language changes
public Font[] fonts;
public Transform actor_parent;
public Text text_panel;
public Text speaker_panel;
public GameObject choice_panel;
public Image background; // Background image
public Image foreground; // Image appears in front of ALL ui elements
public Text log_text; // Log containing all dialogue spoken
public Text scroll_log; // Log accessed by using the mouse scroll wheel when hovering over the dialogue panel
public ScrollRect scroll_log_rect;
public GameObject item_grid; // Item grid where Items are placed
public Text item_description;
public Image large_item_image;
public GameObject ingame_topbar;
public GameObject item_menu;
public GameObject log_menu;
public GameObject entire_UI_panel;
public GameObject ingame_UI_menu;
public VideoPlayer video_player;
public Transform foreground_static_image_parent;
public Transform background_static_image_parent;
public Image autoplay_image;
public Sprite autoplay_on_image;
// Used by ChoiceNode
public Text choice_text_banner;
public Button[] choice_buttons;
public GameObject actor_positions;
// Text options
public Slider text_scroll_speed_slider;
public Slider text_size_slider;
public Toggle text_autosize;
public FontDropDown font_drop_down;
public Dropdown language_dropdown;
public Button save_button;
public GameObject loading_icon;
public Text loading_text;
// Canvas properties
public Canvas canvas;
public float canvas_width;
public float canvas_height;
void Awake()
{
ui_manager = this;
if (canvas == null)
{
canvas = this.GetComponentInChildren<Canvas>();
Debug.LogError("No canvas, please fill the Canvas field with a DialogueCanvas", this.gameObject);
}
canvas_width = canvas.GetComponent<CanvasScaler>().referenceResolution.x;
canvas_height = canvas.GetComponent<CanvasScaler>().referenceResolution.y;
if (Localized_UI_CSV != null)
Localized_UI_Dictionaries = CSVReader.Generate_Localized_Dictionary(Localized_UI_CSV);
else
Debug.Log("No Localized_UI_CSV specified", this.gameObject);
// Get the current language stored in player prefs
Set_Language(PlayerPrefs.GetString("Language", LocalizationManager.Supported_Languages[0]));
}
// Allows you to set the language in LocalizedManager.Language. Be sure to change the support languages in LocalizationManager.cs
public void Set_Language(string language)
{
LocalizationManager.Set_Language(language);
// Set the language dropdown correctly in the menu
if (language_dropdown != null)
{
int x = 0;
foreach (string s in LocalizationManager.Supported_Languages)
{
if (s == LocalizationManager.Language)
{
language_dropdown.value = x;
break;
}
x++;
}
}
Apply_Localization_Change();
}
// Takes an int which is used to index the supported languages array in LocalizationManager.cs
public void Set_Language(int language)
{
Set_Language(LocalizationManager.Supported_Languages[language]);
}
public void Apply_Localization_Change()
{
if (VNSceneManager.scene_manager != null
&& VNSceneManager.current_conversation != null
&& VNSceneManager.current_conversation.Get_Current_Node() != null)
{
if (VNSceneManager.current_conversation.Get_Current_Node().GetType() == typeof(DialogueNode))
{
DialogueNode n = (DialogueNode)VNSceneManager.current_conversation.Get_Current_Node();
n.GetLocalizedText(true);
}
else if (VNSceneManager.current_conversation.Get_Current_Node().GetType() == typeof(ChoiceNode))
{
ChoiceNode n = (ChoiceNode)VNSceneManager.current_conversation.Get_Current_Node();
n.LanguageChanged();
}
}
foreach (LocalizeTextElement e in localized_ui_elements)
{
if (e != null)
{
e.LocalizeText();
}
}
}
// Returns the associated value with the given key for the language that has been set
// Returns "" if the key is null or empty
public string Get_Localized_UI_Entry(string key)
{
if (Localized_UI_Dictionaries == null || Localized_UI_Dictionaries.Count == 0)
{
Debug.Log("Could not find Localized UI CSV for key " + key + ". Please drag in a localization CSV into the UI Manager", this.gameObject);
return "";
}
// Check for any potential errors
if (string.IsNullOrEmpty(key))
{
Debug.LogError("Get_Localized_UI_Entry key passed in is null or empty", this.gameObject);
return "";
}
if (!Localized_UI_Dictionaries.ContainsKey(LocalizationManager.Language))
{
Debug.LogError("Get_Localized_UI_Entry could not find language " + LocalizationManager.Language, this.gameObject);
return "";
}
if (!Localized_UI_Dictionaries[LocalizationManager.Language].ContainsKey(key))
{
Debug.LogError("Get_Localized_UI_Entry could not find the key " + key, this.gameObject);
return "";
}
return Localized_UI_Dictionaries[LocalizationManager.Language][key];
}
public void Add_Localized_UI_Element_To_List(LocalizeTextElement element)
{
if (!localized_ui_elements.Contains(element))
{
localized_ui_elements.Add(element);
}
}
// Fades in an image over a set amount of time
public IEnumerator Fade_In_Image(Image img, float over_time)
{
Color tmp_color = img.color;
tmp_color.a = 0;
float value = 0;
while (value < over_time)
{
value += Time.deltaTime;
tmp_color.a = Mathf.Lerp(0, 1, value / over_time);
img.color = tmp_color;
yield return null;
}
yield break;
}
// Fades in an image out over a set amount of time
public IEnumerator Fade_Out_Image(Image img, float over_time, bool destroy_after)
{
Color tmp_color = img.color;
tmp_color.a = 1;
float value = 0;
while (value < over_time)
{
value += Time.deltaTime;
tmp_color.a = Mathf.Lerp(1, 0, value / over_time);
img.color = tmp_color;
yield return null;
}
if (destroy_after)
Destroy(img.gameObject);
yield break;
}
}
}
| |
// Copyright 2009 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using CommandLine;
using NodaTime.TimeZones;
using NodaTime.TimeZones.Cldr;
using NodaTime.TzdbCompiler.Tzdb;
using NodaTime.Xml;
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace NodaTime.TzdbCompiler
{
/// <summary>
/// Main entry point for the time zone information compiler. In theory we could support
/// multiple sources and formats but currently we only support one:
/// https://www.iana.org/time-zones. This system refers to it as TZDB.
/// This also requires a windowsZone.xml file from the Unicode CLDR repository, to
/// map Windows time zone names to TZDB IDs.
/// </summary>
internal sealed class Program
{
/// <summary>
/// Runs the compiler from the command line.
/// </summary>
/// <param name="arguments">The command line arguments. Each compiler defines its own.</param>
/// <returns>0 for success, non-0 for error.</returns>
private static async Task<int> Main(string[] arguments)
{
CompilerOptions options = new CompilerOptions();
ICommandLineParser parser = new CommandLineParser(new CommandLineParserSettings(Console.Error) { MutuallyExclusive = true });
if (!parser.ParseArguments(arguments, options))
{
return 1;
}
var tzdbCompiler = new TzdbZoneInfoCompiler();
var tzdb = await tzdbCompiler.CompileAsync(options.SourceDirectoryName!);
tzdb.LogCounts();
if (options.ZoneId != null)
{
tzdb.GenerateDateTimeZone(options.ZoneId);
return 0;
}
var windowsZones = LoadWindowsZones(options, tzdb.Version);
if (options.WindowsOverride != null)
{
var overrideFile = CldrWindowsZonesParser.Parse(options.WindowsOverride);
windowsZones = MergeWindowsZones(windowsZones, overrideFile);
}
LogWindowsZonesSummary(windowsZones);
var writer = new TzdbStreamWriter();
using (var stream = CreateOutputStream(options))
{
writer.Write(tzdb, windowsZones, NameIdMappingSupport.StandardNameToIdMap, stream);
}
if (options.OutputFileName != null)
{
Console.WriteLine("Reading generated data and validating...");
var source = Read(options);
source.Validate();
}
if (options.XmlSchema is object)
{
Console.WriteLine($"Writing XML schema to {options.XmlSchema}");
var source = Read(options);
var provider = new DateTimeZoneCache(source);
XmlSerializationSettings.DateTimeZoneProvider = provider;
var settings = new XmlWriterSettings { Indent = true, NewLineChars = "\n", Encoding = new UTF8Encoding() };
using var xmlWriter = XmlWriter.Create(options.XmlSchema, settings);
XmlSchemaDefinition.NodaTimeXmlSchema.Write(xmlWriter);
}
return 0;
}
/// <summary>
/// Loads the best windows zones file based on the options. If the WindowsMapping option is
/// just a straight file, that's used. If it's a directory, this method loads all the XML files
/// in the directory (expecting them all to be mapping files) and then picks the best one based
/// on the version of TZDB we're targeting - basically, the most recent one before or equal to the
/// target version.
/// </summary>
private static WindowsZones LoadWindowsZones(CompilerOptions options, string targetTzdbVersion)
{
var mappingPath = options.WindowsMapping!;
if (File.Exists(mappingPath))
{
return CldrWindowsZonesParser.Parse(mappingPath);
}
if (!Directory.Exists(mappingPath))
{
throw new Exception($"{mappingPath} does not exist as either a file or a directory");
}
var xmlFiles = Directory.GetFiles(mappingPath, "*.xml");
if (xmlFiles.Length == 0)
{
throw new Exception($"{mappingPath} does not contain any XML files");
}
var allFiles = xmlFiles
// Expect that we've ordered the files so that this gives "most recent first",
// to handle consecutive CLDR versions that have the same TZDB version.
.OrderByDescending(file => file, StringComparer.Ordinal)
.Select(file => CldrWindowsZonesParser.Parse(file))
// Note: this is stable, so files with the same TZDB version will stay in reverse filename order.
.OrderByDescending(zones => zones.TzdbVersion)
.ToList();
var versions = string.Join(", ", allFiles.Select(z => z.TzdbVersion).ToArray());
var bestFile = allFiles
.Where(zones => StringComparer.Ordinal.Compare(zones.TzdbVersion, targetTzdbVersion) <= 0)
.FirstOrDefault();
if (bestFile is null)
{
throw new Exception($"No zones files suitable for version {targetTzdbVersion}. Found versions targeting: [{versions}]");
}
Console.WriteLine($"Picked Windows Zones with TZDB version {bestFile.TzdbVersion} out of [{versions}] as best match for {targetTzdbVersion}");
return bestFile;
}
private static void LogWindowsZonesSummary(WindowsZones windowsZones)
{
Console.WriteLine("Windows Zones:");
Console.WriteLine($" Version: {windowsZones.Version}");
Console.WriteLine($" TZDB version: {windowsZones.TzdbVersion}");
Console.WriteLine($" Windows version: {windowsZones.WindowsVersion}");
Console.WriteLine($" {windowsZones.MapZones.Count} MapZones");
Console.WriteLine($" {windowsZones.PrimaryMapping.Count} primary mappings");
}
private static Stream CreateOutputStream(CompilerOptions options)
{
// If we don't have an actual file, just write to an empty stream.
// That way, while debugging, we still get to see all the data written etc.
if (options.OutputFileName is null)
{
return new MemoryStream();
}
string file = Path.ChangeExtension(options.OutputFileName, "nzd");
return File.Create(file);
}
private static TzdbDateTimeZoneSource Read(CompilerOptions options)
{
string file = Path.ChangeExtension(options.OutputFileName!, "nzd");
using (var stream = File.OpenRead(file))
{
return TzdbDateTimeZoneSource.FromStream(stream);
}
}
/// <summary>
/// Merge two WindowsZones objects together. The result has versions present in override,
/// but falling back to the original for versions absent in the override. The set of MapZones
/// in the result is the union of those in the original and override, but any ID/Territory
/// pair present in both results in the override taking priority, unless the override has an
/// empty "type" entry, in which case the entry is removed entirely.
///
/// While this method could reasonably be in WindowsZones class, it's only needed in
/// TzdbCompiler - and here is as good a place as any.
///
/// The resulting MapZones will be ordered by Windows ID followed by territory.
/// </summary>
/// <param name="windowsZones">The original WindowsZones</param>
/// <param name="overrideFile">The WindowsZones to override entries in the original</param>
/// <returns>A merged zones object.</returns>
internal static WindowsZones MergeWindowsZones(WindowsZones originalZones, WindowsZones overrideZones)
{
var version = overrideZones.Version == "" ? originalZones.Version : overrideZones.Version;
var tzdbVersion = overrideZones.TzdbVersion == "" ? originalZones.TzdbVersion : overrideZones.TzdbVersion;
var windowsVersion = overrideZones.WindowsVersion == "" ? originalZones.WindowsVersion : overrideZones.WindowsVersion;
// Work everything out using dictionaries, and then sort.
var mapZones = originalZones.MapZones.ToDictionary(mz => new { mz.WindowsId, mz.Territory });
foreach (var overrideMapZone in overrideZones.MapZones)
{
var key = new { overrideMapZone.WindowsId, overrideMapZone.Territory };
if (overrideMapZone.TzdbIds.Count == 0)
{
mapZones.Remove(key);
}
else
{
mapZones[key] = overrideMapZone;
}
}
var mapZoneList = mapZones
.OrderBy(pair => pair.Key.WindowsId)
.ThenBy(pair => pair.Key.Territory)
.Select(pair => pair.Value)
.ToList();
return new WindowsZones(version, tzdbVersion, windowsVersion, mapZoneList);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace VowTracker.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using NQuery.Runtime;
namespace NQuery.Compilation
{
internal sealed class AggregateBinder : StandardVisitor
{
private class AggregateList
{
private List<AggregateExpression> _aggregateExpressions = new List<AggregateExpression>();
public void Add(AggregateExpression aggregateExpression)
{
AggregateExpression matchingAggregateExpression = null;
foreach (AggregateExpression existingAggregateExpression in _aggregateExpressions)
{
if (existingAggregateExpression.IsStructuralEqualTo(aggregateExpression))
{
matchingAggregateExpression = existingAggregateExpression;
break;
}
}
if (matchingAggregateExpression != null)
{
aggregateExpression.ValueDefinition = matchingAggregateExpression.ValueDefinition;
}
else
{
RowBufferEntry rowBufferEntry = new RowBufferEntry(aggregateExpression.Aggregator.ReturnType);
AggregatedValueDefinition aggregatedValueDefinition = new AggregatedValueDefinition();
aggregatedValueDefinition.Target = rowBufferEntry;
aggregatedValueDefinition.Aggregate = aggregateExpression.Aggregate;
aggregatedValueDefinition.Aggregator = aggregateExpression.Aggregator;
aggregatedValueDefinition.Argument = aggregateExpression.Argument;
aggregateExpression.ValueDefinition = aggregatedValueDefinition;
_aggregateExpressions.Add(aggregateExpression);
}
}
public ICollection<AggregateExpression> Values
{
get { return _aggregateExpressions; }
}
}
private IErrorReporter _errorReporter;
private Dictionary<QueryScope, AggregateList> _aggregateDependencies = new Dictionary<QueryScope, AggregateList>();
private Stack<AggregateList> _unscopedAggregateExpressionStack = new Stack<AggregateList>();
public AggregateBinder(IErrorReporter errorReporter)
{
_errorReporter = errorReporter;
}
#region Helpers
private void AddAggregateDependency(QueryScope associatedScope, AggregateExpression aggregateExpression)
{
if (associatedScope == null)
{
AggregateList currentUnscopedAggregateList = _unscopedAggregateExpressionStack.Peek();
currentUnscopedAggregateList.Add(aggregateExpression);
}
else
{
AggregateList associatedAggregateExpressions;
if (!_aggregateDependencies.TryGetValue(associatedScope, out associatedAggregateExpressions))
{
associatedAggregateExpressions = new AggregateList();
_aggregateDependencies.Add(associatedScope, associatedAggregateExpressions);
}
associatedAggregateExpressions.Add(aggregateExpression);
}
}
private ICollection<AggregateExpression> GetAggregateDependencies(QueryScope associatedScope)
{
AggregateList associatedAggregateExpressions;
if (_aggregateDependencies.TryGetValue(associatedScope, out associatedAggregateExpressions))
return associatedAggregateExpressions.Values;
return null;
}
private bool QueryHasAggregates(QueryScope queryScope)
{
if (_unscopedAggregateExpressionStack.Peek().Values.Count > 0)
return true;
AggregateList queryAggregateList;
if (_aggregateDependencies.TryGetValue(queryScope, out queryAggregateList) &&
queryAggregateList.Values.Count > 0)
return true;
return false;
}
#endregion
public override ExpressionNode VisitAggregagateExpression(AggregateExpression expression)
{
MetaInfo metaInfo = AstUtil.GetMetaInfo(expression.Argument);
// Find associated query scope and ensure the aggregate's argument does not mix
// tables from different query scopes.
QueryScope associatedScope = null;
foreach (TableRefBinding tableDependency in metaInfo.TableDependencies)
{
if (associatedScope == null)
associatedScope = tableDependency.Scope;
else if (associatedScope != tableDependency.Scope)
_errorReporter.AggregateContainsColumnsFromDifferentQueries(expression.Argument);
}
// Enter aggregate dependency.
AddAggregateDependency(associatedScope, expression);
return expression;
}
public override QueryNode VisitSelectQuery(SelectQuery query)
{
_unscopedAggregateExpressionStack.Push(new AggregateList());
// Visit FROM table references
if (query.TableReferences != null)
query.TableReferences = VisitTableReference(query.TableReferences);
if (QueryHasAggregates(query.QueryScope))
{
_errorReporter.AggregateInOn();
return query;
}
// Visit WHERE expression
if (query.WhereClause != null)
query.WhereClause = VisitExpression(query.WhereClause);
if (QueryHasAggregates(query.QueryScope))
{
_errorReporter.AggregateInWhere();
return query;
}
// Visit GROUP BY clause
if (query.GroupByColumns != null)
{
for (int i = 0; i < query.GroupByColumns.Length; i++)
query.GroupByColumns[i] = VisitExpression(query.GroupByColumns[i]);
}
if (QueryHasAggregates(query.QueryScope))
{
_errorReporter.AggregateInGroupBy();
return query;
}
// Visit select list.
for (int i = 0; i < query.SelectColumns.Length; i++)
query.SelectColumns[i].Expression = VisitExpression(query.SelectColumns[i].Expression);
// Visit having clause.
if (query.HavingClause != null)
query.HavingClause = VisitExpression(query.HavingClause);
// Visit ORDER BY.
if (query.OrderByColumns != null)
{
for (int i = 0; i < query.OrderByColumns.Length; i++)
query.OrderByColumns[i].Expression = VisitExpression(query.OrderByColumns[i].Expression);
}
AggregateList unscopedAggregateList = _unscopedAggregateExpressionStack.Pop();
ICollection<AggregateExpression> directAggregateDependencies = GetAggregateDependencies(query.QueryScope);
List<AggregateExpression> aggregateDependencies = new List<AggregateExpression>();
aggregateDependencies.AddRange(unscopedAggregateList.Values);
if (directAggregateDependencies != null)
aggregateDependencies.AddRange(directAggregateDependencies);
query.AggregateDependencies = aggregateDependencies.ToArray();
return query;
}
public override QueryNode VisitSortedQuery(SortedQuery query)
{
query.Input = VisitQuery(query.Input);
// NOTE: We don't visit the ORDER BY columns since they can only refer to existing expressions
// in the output of the inner most query. Later phases will ensure this is true.
return query;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO;
using Internal.Cryptography;
using Internal.NativeCrypto;
using static Internal.NativeCrypto.CapiHelper;
namespace System.Security.Cryptography
{
public sealed partial class RSACryptoServiceProvider : RSA, ICspAsymmetricAlgorithm
{
private int _keySize;
private readonly CspParameters _parameters;
private readonly bool _randomKeyContainer;
private SafeKeyHandle _safeKeyHandle;
private SafeProvHandle _safeProvHandle;
private static volatile CspProviderFlags s_useMachineKeyStore = 0;
public RSACryptoServiceProvider()
: this(0, new CspParameters(CapiHelper.DefaultRsaProviderType,
null,
null,
s_useMachineKeyStore),
true)
{
}
public RSACryptoServiceProvider(int dwKeySize)
: this(dwKeySize,
new CspParameters(CapiHelper.DefaultRsaProviderType,
null,
null,
s_useMachineKeyStore), false)
{
}
public RSACryptoServiceProvider(int dwKeySize, CspParameters parameters)
: this(dwKeySize, parameters, false)
{
}
public RSACryptoServiceProvider(CspParameters parameters)
: this(0, parameters, true)
{
}
private RSACryptoServiceProvider(int keySize, CspParameters parameters, bool useDefaultKeySize)
{
if (keySize < 0)
{
throw new ArgumentOutOfRangeException("dwKeySize", "ArgumentOutOfRange_NeedNonNegNum");
}
_parameters = CapiHelper.SaveCspParameters(
CapiHelper.CspAlgorithmType.Rsa,
parameters,
s_useMachineKeyStore,
out _randomKeyContainer);
_keySize = useDefaultKeySize ? 1024 : keySize;
// If this is not a random container we generate, create it eagerly
// in the constructor so we can report any errors now.
if (!_randomKeyContainer)
{
// Force-read the SafeKeyHandle property, which will summon it into existence.
SafeKeyHandle localHandle = SafeKeyHandle;
Debug.Assert(localHandle != null);
}
}
private SafeProvHandle SafeProvHandle
{
get
{
if (_safeProvHandle == null)
{
lock (_parameters)
{
if (_safeProvHandle == null)
{
SafeProvHandle hProv = CapiHelper.CreateProvHandle(_parameters, _randomKeyContainer);
Debug.Assert(hProv != null);
Debug.Assert(!hProv.IsInvalid);
Debug.Assert(!hProv.IsClosed);
_safeProvHandle = hProv;
}
}
return _safeProvHandle;
}
return _safeProvHandle;
}
set
{
lock (_parameters)
{
SafeProvHandle current = _safeProvHandle;
if (ReferenceEquals(value, current))
{
return;
}
if (current != null)
{
SafeKeyHandle keyHandle = _safeKeyHandle;
_safeKeyHandle = null;
keyHandle?.Dispose();
current.Dispose();
}
_safeProvHandle = value;
}
}
}
private SafeKeyHandle SafeKeyHandle
{
get
{
if (_safeKeyHandle == null)
{
lock (_parameters)
{
if (_safeKeyHandle == null)
{
SafeKeyHandle hKey = CapiHelper.GetKeyPairHelper(
CapiHelper.CspAlgorithmType.Rsa,
_parameters,
_keySize,
SafeProvHandle);
Debug.Assert(hKey != null);
Debug.Assert(!hKey.IsInvalid);
Debug.Assert(!hKey.IsClosed);
_safeKeyHandle = hKey;
}
}
}
return _safeKeyHandle;
}
set
{
lock (_parameters)
{
SafeKeyHandle current = _safeKeyHandle;
if (ReferenceEquals(value, current))
{
return;
}
_safeKeyHandle = value;
current?.Dispose();
}
}
}
/// <summary>
/// CspKeyContainerInfo property
/// </summary>
public CspKeyContainerInfo CspKeyContainerInfo
{
get
{
// Desktop compat: Read the SafeKeyHandle property to force the key to load,
// because it might throw here.
SafeKeyHandle localHandle = SafeKeyHandle;
Debug.Assert(localHandle != null);
return new CspKeyContainerInfo(_parameters, _randomKeyContainer);
}
}
/// <summary>
/// _keySize property
/// </summary>
public override int KeySize
{
get
{
byte[] keySize = CapiHelper.GetKeyParameter(SafeKeyHandle, Constants.CLR_KEYLEN);
_keySize = (keySize[0] | (keySize[1] << 8) | (keySize[2] << 16) | (keySize[3] << 24));
return _keySize;
}
}
public override KeySizes[] LegalKeySizes
{
get
{
return new[] { new KeySizes(384, 16384, 8) };
}
}
/// <summary>
/// get set Persisted key in CSP
/// </summary>
public bool PersistKeyInCsp
{
get
{
return CapiHelper.GetPersistKeyInCsp(SafeProvHandle);
}
set
{
bool oldPersistKeyInCsp = this.PersistKeyInCsp;
if (value == oldPersistKeyInCsp)
{
return; // Do nothing
}
CapiHelper.SetPersistKeyInCsp(SafeProvHandle, value);
}
}
/// <summary>
/// Gets the information of key if it is a public key
/// </summary>
public bool PublicOnly
{
get
{
byte[] publicKey = CapiHelper.GetKeyParameter(SafeKeyHandle, Constants.CLR_PUBLICKEYONLY);
return (publicKey[0] == 1);
}
}
/// <summary>
/// MachineKey store properties
/// </summary>
public static bool UseMachineKeyStore
{
get
{
return (s_useMachineKeyStore == CspProviderFlags.UseMachineKeyStore);
}
set
{
s_useMachineKeyStore = (value ? CspProviderFlags.UseMachineKeyStore : 0);
}
}
/// <summary>
/// Decrypt raw data, generally used for decrypting symmetric key material
/// </summary>
/// <param name="rgb">encrypted data</param>
/// <param name="fOAEP">true to use OAEP padding (PKCS #1 v2), false to use PKCS #1 type 2 padding</param>
/// <returns>decrypted data</returns>
public byte[] Decrypt(byte[] rgb, bool fOAEP)
{
if (rgb == null)
{
throw new ArgumentNullException(nameof(rgb));
}
// Save the KeySize value to a local because it has non-trivial cost.
int keySize = KeySize;
// size check -- must be exactly the modulus size
if (rgb.Length != (keySize / 8))
{
throw new CryptographicException(SR.Cryptography_RSA_DecryptWrongSize);
}
byte[] decryptedKey;
CapiHelper.DecryptKey(SafeKeyHandle, rgb, rgb.Length, fOAEP, out decryptedKey);
return decryptedKey;
}
/// <summary>
/// This method is not supported. Use Decrypt(byte[], RSAEncryptionPadding) instead.
/// </summary>
public override byte[] DecryptValue(byte[] rgb) => base.DecryptValue(rgb);
/// <summary>
/// Dispose the key handles
/// </summary>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (_safeKeyHandle != null && !_safeKeyHandle.IsClosed)
{
_safeKeyHandle.Dispose();
}
if (_safeProvHandle != null && !_safeProvHandle.IsClosed)
{
_safeProvHandle.Dispose();
}
}
/// <summary>
/// Encrypt raw data, generally used for encrypting symmetric key material.
/// </summary>
/// <remarks>
/// This method can only encrypt (keySize - 88 bits) of data, so should not be used for encrypting
/// arbitrary byte arrays. Instead, encrypt a symmetric key with this method, and use the symmetric
/// key to encrypt the sensitive data.
/// </remarks>
/// <param name="rgb">raw data to encrypt</param>
/// <param name="fOAEP">true to use OAEP padding (PKCS #1 v2), false to use PKCS #1 type 2 padding</param>
/// <returns>Encrypted key</returns>
public byte[] Encrypt(byte[] rgb, bool fOAEP)
{
if (rgb == null)
{
throw new ArgumentNullException(nameof(rgb));
}
if (fOAEP)
{
int rsaSize = (KeySize + 7) / 8;
const int OaepSha1Overhead = 20 + 20 + 2;
// Normalize the Windows 7 and Windows 8.1+ exception
if (rsaSize - OaepSha1Overhead < rgb.Length)
{
const int NTE_BAD_LENGTH = unchecked((int)0x80090004);
throw NTE_BAD_LENGTH.ToCryptographicException();
}
}
byte[] encryptedKey = null;
CapiHelper.EncryptKey(SafeKeyHandle, rgb, rgb.Length, fOAEP, ref encryptedKey);
return encryptedKey;
}
/// <summary>
/// This method is not supported. Use Encrypt(byte[], RSAEncryptionPadding) instead.
/// </summary>
public override byte[] EncryptValue(byte[] rgb) => base.EncryptValue(rgb);
/// <summary>
///Exports a blob containing the key information associated with an RSACryptoServiceProvider object.
/// </summary>
public byte[] ExportCspBlob(bool includePrivateParameters)
{
return CapiHelper.ExportKeyBlob(includePrivateParameters, SafeKeyHandle);
}
/// <summary>
/// Exports the RSAParameters
/// </summary>
public override RSAParameters ExportParameters(bool includePrivateParameters)
{
byte[] cspBlob = ExportCspBlob(includePrivateParameters);
return cspBlob.ToRSAParameters(includePrivateParameters);
}
/// <summary>
/// This method helps Acquire the default CSP and avoids the need for static SafeProvHandle
/// in CapiHelper class
/// </summary>
private SafeProvHandle AcquireSafeProviderHandle()
{
SafeProvHandle safeProvHandle;
CapiHelper.AcquireCsp(new CspParameters(CapiHelper.DefaultRsaProviderType), out safeProvHandle);
return safeProvHandle;
}
/// <summary>
/// Imports a blob that represents RSA key information
/// </summary>
/// <param name="keyBlob"></param>
public void ImportCspBlob(byte[] keyBlob)
{
SafeKeyHandle safeKeyHandle;
if (IsPublic(keyBlob))
{
SafeProvHandle safeProvHandleTemp = AcquireSafeProviderHandle();
CapiHelper.ImportKeyBlob(safeProvHandleTemp, (CspProviderFlags)0, false, keyBlob, out safeKeyHandle);
// The property set will take care of releasing any already-existing resources.
SafeProvHandle = safeProvHandleTemp;
}
else
{
CapiHelper.ImportKeyBlob(SafeProvHandle, _parameters.Flags, false, keyBlob, out safeKeyHandle);
}
// The property set will take care of releasing any already-existing resources.
SafeKeyHandle = safeKeyHandle;
}
/// <summary>
/// Imports the specified RSAParameters
/// </summary>
public override void ImportParameters(RSAParameters parameters)
{
byte[] keyBlob = parameters.ToKeyBlob();
ImportCspBlob(keyBlob);
}
/// <summary>
/// Computes the hash value of a subset of the specified byte array using the
/// specified hash algorithm, and signs the resulting hash value.
/// </summary>
/// <param name="buffer">The input data for which to compute the hash</param>
/// <param name="offset">The offset into the array from which to begin using data</param>
/// <param name="count">The number of bytes in the array to use as data. </param>
/// <param name="halg">The hash algorithm to use to create the hash value. </param>
/// <returns>The RSA signature for the specified data.</returns>
public byte[] SignData(byte[] buffer, int offset, int count, object halg)
{
int calgHash = CapiHelper.ObjToHashAlgId(halg);
HashAlgorithm hash = CapiHelper.ObjToHashAlgorithm(halg);
byte[] hashVal = hash.ComputeHash(buffer, offset, count);
return SignHash(hashVal, calgHash);
}
/// <summary>
/// Computes the hash value of a subset of the specified byte array using the
/// specified hash algorithm, and signs the resulting hash value.
/// </summary>
/// <param name="buffer">The input data for which to compute the hash</param>
/// <param name="halg">The hash algorithm to use to create the hash value. </param>
/// <returns>The RSA signature for the specified data.</returns>
public byte[] SignData(byte[] buffer, object halg)
{
int calgHash = CapiHelper.ObjToHashAlgId(halg);
HashAlgorithm hash = CapiHelper.ObjToHashAlgorithm(halg);
byte[] hashVal = hash.ComputeHash(buffer);
return SignHash(hashVal, calgHash);
}
/// <summary>
/// Computes the hash value of a subset of the specified byte array using the
/// specified hash algorithm, and signs the resulting hash value.
/// </summary>
/// <param name="inputStream">The input data for which to compute the hash</param>
/// <param name="halg">The hash algorithm to use to create the hash value. </param>
/// <returns>The RSA signature for the specified data.</returns>
public byte[] SignData(Stream inputStream, object halg)
{
int calgHash = CapiHelper.ObjToHashAlgId(halg);
HashAlgorithm hash = CapiHelper.ObjToHashAlgorithm(halg);
byte[] hashVal = hash.ComputeHash(inputStream);
return SignHash(hashVal, calgHash);
}
/// <summary>
/// Computes the hash value of a subset of the specified byte array using the
/// specified hash algorithm, and signs the resulting hash value.
/// </summary>
/// <param name="rgbHash">The input data for which to compute the hash</param>
/// <param name="str">The hash algorithm to use to create the hash value. </param>
/// <returns>The RSA signature for the specified data.</returns>
public byte[] SignHash(byte[] rgbHash, string str)
{
if (rgbHash == null)
throw new ArgumentNullException(nameof(rgbHash));
if (PublicOnly)
throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey);
int calgHash = CapiHelper.NameOrOidToHashAlgId(str, OidGroup.HashAlgorithm);
return SignHash(rgbHash, calgHash);
}
/// <summary>
/// Computes the hash value of a subset of the specified byte array using the
/// specified hash algorithm, and signs the resulting hash value.
/// </summary>
/// <param name="rgbHash">The input data for which to compute the hash</param>
/// <param name="calgHash">The hash algorithm to use to create the hash value. </param>
/// <returns>The RSA signature for the specified data.</returns>
private byte[] SignHash(byte[] rgbHash, int calgHash)
{
Debug.Assert(rgbHash != null);
return CapiHelper.SignValue(
SafeProvHandle,
SafeKeyHandle,
_parameters.KeyNumber,
CapiHelper.CALG_RSA_SIGN,
calgHash,
rgbHash);
}
/// <summary>
/// Verifies the signature of a hash value.
/// </summary>
public bool VerifyData(byte[] buffer, object halg, byte[] signature)
{
int calgHash = CapiHelper.ObjToHashAlgId(halg);
HashAlgorithm hash = CapiHelper.ObjToHashAlgorithm(halg);
byte[] hashVal = hash.ComputeHash(buffer);
return VerifyHash(hashVal, calgHash, signature);
}
/// <summary>
/// Verifies the signature of a hash value.
/// </summary>
public bool VerifyHash(byte[] rgbHash, string str, byte[] rgbSignature)
{
if (rgbHash == null)
throw new ArgumentNullException(nameof(rgbHash));
if (rgbSignature == null)
throw new ArgumentNullException(nameof(rgbSignature));
int calgHash = CapiHelper.NameOrOidToHashAlgId(str, OidGroup.HashAlgorithm);
return VerifyHash(rgbHash, calgHash, rgbSignature);
}
/// <summary>
/// Verifies the signature of a hash value.
/// </summary>
private bool VerifyHash(byte[] rgbHash, int calgHash, byte[] rgbSignature)
{
return CapiHelper.VerifySign(
SafeProvHandle,
SafeKeyHandle,
CapiHelper.CALG_RSA_SIGN,
calgHash,
rgbHash,
rgbSignature);
}
/// <summary>
/// find whether an RSA key blob is public.
/// </summary>
private static bool IsPublic(byte[] keyBlob)
{
if (keyBlob == null)
{
throw new ArgumentNullException(nameof(keyBlob));
}
// The CAPI RSA public key representation consists of the following sequence:
// - BLOBHEADER
// - RSAPUBKEY
// The first should be PUBLICKEYBLOB and magic should be RSA_PUB_MAGIC "RSA1"
if (keyBlob[0] != CapiHelper.PUBLICKEYBLOB)
{
return false;
}
if (keyBlob[11] != 0x31 || keyBlob[10] != 0x41 || keyBlob[9] != 0x53 || keyBlob[8] != 0x52)
{
return false;
}
return true;
}
protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm)
{
// we're sealed and the base should have checked this already
Debug.Assert(data != null);
Debug.Assert(count >= 0 && count <= data.Length);
Debug.Assert(offset >= 0 && offset <= data.Length - count);
Debug.Assert(!string.IsNullOrEmpty(hashAlgorithm.Name));
using (HashAlgorithm hash = GetHashAlgorithm(hashAlgorithm))
{
return hash.ComputeHash(data, offset, count);
}
}
protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm)
{
// we're sealed and the base should have checked this already
Debug.Assert(data != null);
Debug.Assert(!string.IsNullOrEmpty(hashAlgorithm.Name));
using (HashAlgorithm hash = GetHashAlgorithm(hashAlgorithm))
{
return hash.ComputeHash(data);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5351", Justification = "MD5 is used when the user asks for it.")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5350", Justification = "SHA1 is used when the user asks for it.")]
private static HashAlgorithm GetHashAlgorithm(HashAlgorithmName hashAlgorithm)
{
switch (hashAlgorithm.Name)
{
case "MD5":
return MD5.Create();
case "SHA1":
return SHA1.Create();
case "SHA256":
return SHA256.Create();
case "SHA384":
return SHA384.Create();
case "SHA512":
return SHA512.Create();
default:
throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithm.Name);
}
}
private static int GetAlgorithmId(HashAlgorithmName hashAlgorithm)
{
switch (hashAlgorithm.Name)
{
case "MD5":
return CapiHelper.CALG_MD5;
case "SHA1":
return CapiHelper.CALG_SHA1;
case "SHA256":
return CapiHelper.CALG_SHA_256;
case "SHA384":
return CapiHelper.CALG_SHA_384;
case "SHA512":
return CapiHelper.CALG_SHA_512;
default:
throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithm.Name);
}
}
public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
if (padding == null)
throw new ArgumentNullException(nameof(padding));
if (padding == RSAEncryptionPadding.Pkcs1)
{
return Encrypt(data, fOAEP: false);
}
else if (padding == RSAEncryptionPadding.OaepSHA1)
{
return Encrypt(data, fOAEP: true);
}
else
{
throw PaddingModeNotSupported();
}
}
public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
if (padding == null)
throw new ArgumentNullException(nameof(padding));
if (padding == RSAEncryptionPadding.Pkcs1)
{
return Decrypt(data, fOAEP: false);
}
else if (padding == RSAEncryptionPadding.OaepSHA1)
{
return Decrypt(data, fOAEP: true);
}
else
{
throw PaddingModeNotSupported();
}
}
public override byte[] SignHash(
byte[] hash,
HashAlgorithmName hashAlgorithm,
RSASignaturePadding padding)
{
if (hash == null)
throw new ArgumentNullException(nameof(hash));
if (string.IsNullOrEmpty(hashAlgorithm.Name))
throw HashAlgorithmNameNullOrEmpty();
if (padding == null)
throw new ArgumentNullException(nameof(padding));
if (padding != RSASignaturePadding.Pkcs1)
throw PaddingModeNotSupported();
return SignHash(hash, GetAlgorithmId(hashAlgorithm));
}
public override bool VerifyHash(
byte[] hash,
byte[] signature,
HashAlgorithmName hashAlgorithm,
RSASignaturePadding padding)
{
if (hash == null)
throw new ArgumentNullException(nameof(hash));
if (signature == null)
throw new ArgumentNullException(nameof(signature));
if (string.IsNullOrEmpty(hashAlgorithm.Name))
throw HashAlgorithmNameNullOrEmpty();
if (padding == null)
throw new ArgumentNullException(nameof(padding));
if (padding != RSASignaturePadding.Pkcs1)
throw PaddingModeNotSupported();
return VerifyHash(hash, GetAlgorithmId(hashAlgorithm), signature);
}
public override string KeyExchangeAlgorithm
{
get
{
if (_parameters.KeyNumber == (int) KeySpec.AT_KEYEXCHANGE)
{
return "RSA-PKCS1-KeyEx";
}
return null;
}
}
public override string SignatureAlgorithm
{
get
{
return "http://www.w3.org/2000/09/xmldsig#rsa-sha1";
}
}
private static Exception PaddingModeNotSupported()
{
return new CryptographicException(SR.Cryptography_InvalidPaddingMode);
}
private static Exception HashAlgorithmNameNullOrEmpty()
{
return new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, "hashAlgorithm");
}
}
}
| |
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 OData.Areas.HelpPage.ModelDescriptions;
using OData.Areas.HelpPage.Models;
namespace OData.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);
}
}
}
}
| |
using System.Runtime.InteropServices;
using SolidWorks.Interop.swpublished;
namespace SolidworksAddinFramework
{
/// <summary>
/// Passing objects that use generics as IDispatch during COM interop causes a invalid cast exception.
/// This is a proxy for implementations of IPropertyManagerPage2Handler9. It
/// seems that passing an instance of this interface that uses generics somewhere in the inheritence
/// chain causes COM to bork.
///
/// See: http://stackoverflow.com/questions/35438895/passing-an-object-in-c-sharp-that-inherits-from-a-generic-causes-a-cast-exceptio/35449486#35449486
///
/// The solution is just to create a proxy for the interface that wraps the original instance. There
/// are probably some nuget packages around that can do this automagically but I just used resharper
/// to generate the below code.
/// </summary>
[ComVisible(true)]
public class PropertyManagerPage2Handler9Wrapper : IPropertyManagerPage2Handler9
{
private readonly IPropertyManagerPage2Handler9 _Implementation;
public PropertyManagerPage2Handler9Wrapper(IPropertyManagerPage2Handler9 implementation)
{
_Implementation = implementation;
}
public void AfterActivation()
{
_Implementation.AfterActivation();
}
public void OnClose(int reason)
{
_Implementation.OnClose(reason);
}
public void AfterClose()
{
_Implementation.AfterClose();
}
public bool OnHelp()
{
return _Implementation.OnHelp();
}
public bool OnPreviousPage()
{
return _Implementation.OnPreviousPage();
}
public bool OnNextPage()
{
return _Implementation.OnNextPage();
}
public bool OnPreview()
{
return _Implementation.OnPreview();
}
public void OnWhatsNew()
{
_Implementation.OnWhatsNew();
}
public void OnUndo()
{
_Implementation.OnUndo();
}
public void OnRedo()
{
_Implementation.OnRedo();
}
public bool OnTabClicked(int id)
{
return _Implementation.OnTabClicked(id);
}
public void OnGroupExpand(int id, bool expanded)
{
_Implementation.OnGroupExpand(id, expanded);
}
public void OnGroupCheck(int id, bool Checked)
{
_Implementation.OnGroupCheck(id, Checked);
}
public void OnCheckboxCheck(int id, bool Checked)
{
_Implementation.OnCheckboxCheck(id, Checked);
}
public void OnOptionCheck(int id)
{
_Implementation.OnOptionCheck(id);
}
public void OnButtonPress(int id)
{
_Implementation.OnButtonPress(id);
}
public void OnTextboxChanged(int id, string text)
{
_Implementation.OnTextboxChanged(id, text);
}
public void OnNumberboxChanged(int id, double value)
{
_Implementation.OnNumberboxChanged(id, value);
}
public void OnComboboxEditChanged(int id, string text)
{
_Implementation.OnComboboxEditChanged(id, text);
}
public void OnComboboxSelectionChanged(int id, int item)
{
_Implementation.OnComboboxSelectionChanged(id, item);
}
public void OnListboxSelectionChanged(int id, int item)
{
_Implementation.OnListboxSelectionChanged(id, item);
}
public void OnSelectionboxFocusChanged(int id)
{
_Implementation.OnSelectionboxFocusChanged(id);
}
public void OnSelectionboxListChanged(int id, int count)
{
_Implementation.OnSelectionboxListChanged(id, count);
}
public void OnSelectionboxCalloutCreated(int id)
{
_Implementation.OnSelectionboxCalloutCreated(id);
}
public void OnSelectionboxCalloutDestroyed(int id)
{
_Implementation.OnSelectionboxCalloutDestroyed(id);
}
public bool OnSubmitSelection(int id, object selection, int selType, ref string itemText)
{
return _Implementation.OnSubmitSelection(id, selection, selType, ref itemText);
}
public int OnActiveXControlCreated(int id, bool status)
{
return _Implementation.OnActiveXControlCreated(id, status);
}
public void OnSliderPositionChanged(int id, double value)
{
_Implementation.OnSliderPositionChanged(id, value);
}
public void OnSliderTrackingCompleted(int id, double value)
{
_Implementation.OnSliderTrackingCompleted(id, value);
}
public bool OnKeystroke(int wparam, int message, int lparam, int id)
{
return _Implementation.OnKeystroke(wparam, message, lparam, id);
}
public void OnPopupMenuItem(int id)
{
_Implementation.OnPopupMenuItem(id);
}
public void OnPopupMenuItemUpdate(int id, ref int retval)
{
_Implementation.OnPopupMenuItemUpdate(id, ref retval);
}
public void OnGainedFocus(int id)
{
_Implementation.OnGainedFocus(id);
}
public void OnLostFocus(int id)
{
_Implementation.OnLostFocus(id);
}
public int OnWindowFromHandleControlCreated(int id, bool status)
{
return _Implementation.OnWindowFromHandleControlCreated(id, status);
}
public void OnListboxRMBUp(int id, int posX, int posY)
{
_Implementation.OnListboxRMBUp(id, posX, posY);
}
public void OnNumberBoxTrackingCompleted(int id, double value)
{
_Implementation.OnNumberBoxTrackingCompleted(id, value);
}
}
}
| |
// =================================================================================================
// ADOBE SYSTEMS INCORPORATED
// Copyright 2006 Adobe Systems Incorporated
// All Rights Reserved
//
// NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms
// of the Adobe license agreement accompanying it.
// =================================================================================================
using System.Collections;
using System.Xml;
using Com.Adobe.Xmp;
using Com.Adobe.Xmp.Options;
using Sharpen;
namespace Com.Adobe.Xmp.Impl
{
/// <summary>Parser for "normal" XML serialisation of RDF.</summary>
/// <since>14.07.2006</since>
public class ParseRDF : XMPError, XMPConst
{
public const int RdftermOther = 0;
/// <summary>Start of coreSyntaxTerms.</summary>
public const int RdftermRdf = 1;
public const int RdftermId = 2;
public const int RdftermAbout = 3;
public const int RdftermParseType = 4;
public const int RdftermResource = 5;
public const int RdftermNodeId = 6;
/// <summary>End of coreSyntaxTerms</summary>
public const int RdftermDatatype = 7;
/// <summary>Start of additions for syntax Terms.</summary>
public const int RdftermDescription = 8;
/// <summary>End of of additions for syntaxTerms.</summary>
public const int RdftermLi = 9;
/// <summary>Start of oldTerms.</summary>
public const int RdftermAboutEach = 10;
public const int RdftermAboutEachPrefix = 11;
/// <summary>End of oldTerms.</summary>
public const int RdftermBagId = 12;
public const int RdftermFirstCore = RdftermRdf;
public const int RdftermLastCore = RdftermDatatype;
/// <summary>! Yes, the syntax terms include the core terms.</summary>
public const int RdftermFirstSyntax = RdftermFirstCore;
public const int RdftermLastSyntax = RdftermLi;
public const int RdftermFirstOld = RdftermAboutEach;
public const int RdftermLastOld = RdftermBagId;
/// <summary>this prefix is used for default namespaces</summary>
public const string DefaultPrefix = "_dflt";
/// <summary>The main parsing method.</summary>
/// <remarks>
/// The main parsing method. The XML tree is walked through from the root node and and XMP tree
/// is created. This is a raw parse, the normalisation of the XMP tree happens outside.
/// </remarks>
/// <param name="xmlRoot">the XML root node</param>
/// <returns>Returns an XMP metadata object (not normalized)</returns>
/// <exception cref="Com.Adobe.Xmp.XMPException">Occurs if the parsing fails for any reason.</exception>
internal static XMPMetaImpl Parse(XmlNode xmlRoot)
{
XMPMetaImpl xmp = new XMPMetaImpl();
Rdf_RDF(xmp, xmlRoot);
return xmp;
}
/// <summary>
/// Each of these parsing methods is responsible for recognizing an RDF
/// syntax production and adding the appropriate structure to the XMP tree.
/// </summary>
/// <remarks>
/// Each of these parsing methods is responsible for recognizing an RDF
/// syntax production and adding the appropriate structure to the XMP tree.
/// They simply return for success, failures will throw an exception.
/// </remarks>
/// <param name="xmp">the xmp metadata object that is generated</param>
/// <param name="rdfRdfNode">the top-level xml node</param>
/// <exception cref="Com.Adobe.Xmp.XMPException">thown on parsing errors</exception>
internal static void Rdf_RDF(XMPMetaImpl xmp, XmlNode rdfRdfNode)
{
if (rdfRdfNode.HasAttributes())
{
Rdf_NodeElementList(xmp, xmp.GetRoot(), rdfRdfNode);
}
else
{
throw new XMPException("Invalid attributes of rdf:RDF element", XMPErrorConstants.Badrdf);
}
}
/// <summary>
/// 7.2.10 nodeElementList<br />
/// ws* ( nodeElement ws* )
/// Note: this method is only called from the rdf:RDF-node (top level)
/// </summary>
/// <param name="xmp">the xmp metadata object that is generated</param>
/// <param name="xmpParent">the parent xmp node</param>
/// <param name="rdfRdfNode">the top-level xml node</param>
/// <exception cref="Com.Adobe.Xmp.XMPException">thown on parsing errors</exception>
private static void Rdf_NodeElementList(XMPMetaImpl xmp, XMPNode xmpParent, XmlNode rdfRdfNode)
{
for (int i = 0; i < rdfRdfNode.ChildNodes.Count; i++)
{
XmlNode child = rdfRdfNode.ChildNodes.Item(i);
// filter whitespaces (and all text nodes)
if (!IsWhitespaceNode(child))
{
Rdf_NodeElement(xmp, xmpParent, child, true);
}
}
}
/// <summary>
/// 7.2.5 nodeElementURIs
/// anyURI - ( coreSyntaxTerms | rdf:li | oldTerms )
/// 7.2.11 nodeElement
/// start-element ( URI == nodeElementURIs,
/// attributes == set ( ( idAttr | nodeIdAttr | aboutAttr )?, propertyAttr* ) )
/// propertyEltList
/// end-element()
/// A node element URI is rdf:Description or anything else that is not an RDF
/// term.
/// </summary>
/// <param name="xmp">the xmp metadata object that is generated</param>
/// <param name="xmpParent">the parent xmp node</param>
/// <param name="xmlNode">the currently processed XML node</param>
/// <param name="isTopLevel">Flag if the node is a top-level node</param>
/// <exception cref="Com.Adobe.Xmp.XMPException">thown on parsing errors</exception>
private static void Rdf_NodeElement(XMPMetaImpl xmp, XMPNode xmpParent, XmlNode xmlNode, bool isTopLevel)
{
int nodeTerm = GetRDFTermKind(xmlNode);
if (nodeTerm != RdftermDescription && nodeTerm != RdftermOther)
{
throw new XMPException("Node element must be rdf:Description or typed node", XMPErrorConstants.Badrdf);
}
else
{
if (isTopLevel && nodeTerm == RdftermOther)
{
throw new XMPException("Top level typed node not allowed", XMPErrorConstants.Badxmp);
}
else
{
Rdf_NodeElementAttrs(xmp, xmpParent, xmlNode, isTopLevel);
Rdf_PropertyElementList(xmp, xmpParent, xmlNode, isTopLevel);
}
}
}
/// <summary>
/// 7.2.7 propertyAttributeURIs
/// anyURI - ( coreSyntaxTerms | rdf:Description | rdf:li | oldTerms )
/// 7.2.11 nodeElement
/// start-element ( URI == nodeElementURIs,
/// attributes == set ( ( idAttr | nodeIdAttr | aboutAttr )?, propertyAttr* ) )
/// propertyEltList
/// end-element()
/// Process the attribute list for an RDF node element.
/// </summary>
/// <remarks>
/// 7.2.7 propertyAttributeURIs
/// anyURI - ( coreSyntaxTerms | rdf:Description | rdf:li | oldTerms )
/// 7.2.11 nodeElement
/// start-element ( URI == nodeElementURIs,
/// attributes == set ( ( idAttr | nodeIdAttr | aboutAttr )?, propertyAttr* ) )
/// propertyEltList
/// end-element()
/// Process the attribute list for an RDF node element. A property attribute URI is
/// anything other than an RDF term. The rdf:ID and rdf:nodeID attributes are simply ignored,
/// as are rdf:about attributes on inner nodes.
/// </remarks>
/// <param name="xmp">the xmp metadata object that is generated</param>
/// <param name="xmpParent">the parent xmp node</param>
/// <param name="xmlNode">the currently processed XML node</param>
/// <param name="isTopLevel">Flag if the node is a top-level node</param>
/// <exception cref="Com.Adobe.Xmp.XMPException">thown on parsing errors</exception>
private static void Rdf_NodeElementAttrs(XMPMetaImpl xmp, XMPNode xmpParent, XmlNode xmlNode, bool isTopLevel)
{
// Used to detect attributes that are mutually exclusive.
int exclusiveAttrs = 0;
for (int i = 0; i < xmlNode.Attributes.Count; i++)
{
XmlNode attribute = xmlNode.Attributes.Item(i);
// quick hack, ns declarations do not appear in C++
// ignore "ID" without namespace
if ("xmlns".Equals(attribute.Prefix) || (attribute.Prefix == null && "xmlns".Equals(attribute.Name)))
{
continue;
}
int attrTerm = GetRDFTermKind(attribute);
switch (attrTerm)
{
case RdftermId:
case RdftermNodeId:
case RdftermAbout:
{
if (exclusiveAttrs > 0)
{
throw new XMPException("Mutally exclusive about, ID, nodeID attributes", XMPErrorConstants.Badrdf);
}
exclusiveAttrs++;
if (isTopLevel && (attrTerm == RdftermAbout))
{
// This is the rdf:about attribute on a top level node. Set
// the XMP tree name if
// it doesn't have a name yet. Make sure this name matches
// the XMP tree name.
if (xmpParent.GetName() != null && xmpParent.GetName().Length > 0)
{
if (!xmpParent.GetName().Equals(attribute.Value))
{
throw new XMPException("Mismatched top level rdf:about values", XMPErrorConstants.Badxmp);
}
}
else
{
xmpParent.SetName(attribute.Value);
}
}
break;
}
case RdftermOther:
{
AddChildNode(xmp, xmpParent, attribute, attribute.Value, isTopLevel);
break;
}
default:
{
throw new XMPException("Invalid nodeElement attribute", XMPErrorConstants.Badrdf);
}
}
}
}
/// <summary>
/// 7.2.13 propertyEltList
/// ws* ( propertyElt ws* )
/// </summary>
/// <param name="xmp">the xmp metadata object that is generated</param>
/// <param name="xmpParent">the parent xmp node</param>
/// <param name="xmlParent">the currently processed XML node</param>
/// <param name="isTopLevel">Flag if the node is a top-level node</param>
/// <exception cref="Com.Adobe.Xmp.XMPException">thown on parsing errors</exception>
private static void Rdf_PropertyElementList(XMPMetaImpl xmp, XMPNode xmpParent, XmlNode xmlParent, bool isTopLevel)
{
for (int i = 0; i < xmlParent.ChildNodes.Count; i++)
{
XmlNode currChild = xmlParent.ChildNodes.Item(i);
if (IsWhitespaceNode(currChild))
{
continue;
}
else
{
if (currChild.NodeType != System.Xml.XmlNodeType.Element)
{
throw new XMPException("Expected property element node not found", XMPErrorConstants.Badrdf);
}
else
{
Rdf_PropertyElement(xmp, xmpParent, currChild, isTopLevel);
}
}
}
}
/// <summary>
/// 7.2.14 propertyElt
/// resourcePropertyElt | literalPropertyElt | parseTypeLiteralPropertyElt |
/// parseTypeResourcePropertyElt | parseTypeCollectionPropertyElt |
/// parseTypeOtherPropertyElt | emptyPropertyElt
/// 7.2.15 resourcePropertyElt
/// start-element ( URI == propertyElementURIs, attributes == set ( idAttr? ) )
/// ws* nodeElement ws
/// end-element()
/// 7.2.16 literalPropertyElt
/// start-element (
/// URI == propertyElementURIs, attributes == set ( idAttr?, datatypeAttr?) )
/// text()
/// end-element()
/// 7.2.17 parseTypeLiteralPropertyElt
/// start-element (
/// URI == propertyElementURIs, attributes == set ( idAttr?, parseLiteral ) )
/// literal
/// end-element()
/// 7.2.18 parseTypeResourcePropertyElt
/// start-element (
/// URI == propertyElementURIs, attributes == set ( idAttr?, parseResource ) )
/// propertyEltList
/// end-element()
/// 7.2.19 parseTypeCollectionPropertyElt
/// start-element (
/// URI == propertyElementURIs, attributes == set ( idAttr?, parseCollection ) )
/// nodeElementList
/// end-element()
/// 7.2.20 parseTypeOtherPropertyElt
/// start-element ( URI == propertyElementURIs, attributes == set ( idAttr?, parseOther ) )
/// propertyEltList
/// end-element()
/// 7.2.21 emptyPropertyElt
/// start-element ( URI == propertyElementURIs,
/// attributes == set ( idAttr?, ( resourceAttr | nodeIdAttr )?, propertyAttr* ) )
/// end-element()
/// The various property element forms are not distinguished by the XML element name,
/// but by their attributes for the most part.
/// </summary>
/// <remarks>
/// 7.2.14 propertyElt
/// resourcePropertyElt | literalPropertyElt | parseTypeLiteralPropertyElt |
/// parseTypeResourcePropertyElt | parseTypeCollectionPropertyElt |
/// parseTypeOtherPropertyElt | emptyPropertyElt
/// 7.2.15 resourcePropertyElt
/// start-element ( URI == propertyElementURIs, attributes == set ( idAttr? ) )
/// ws* nodeElement ws
/// end-element()
/// 7.2.16 literalPropertyElt
/// start-element (
/// URI == propertyElementURIs, attributes == set ( idAttr?, datatypeAttr?) )
/// text()
/// end-element()
/// 7.2.17 parseTypeLiteralPropertyElt
/// start-element (
/// URI == propertyElementURIs, attributes == set ( idAttr?, parseLiteral ) )
/// literal
/// end-element()
/// 7.2.18 parseTypeResourcePropertyElt
/// start-element (
/// URI == propertyElementURIs, attributes == set ( idAttr?, parseResource ) )
/// propertyEltList
/// end-element()
/// 7.2.19 parseTypeCollectionPropertyElt
/// start-element (
/// URI == propertyElementURIs, attributes == set ( idAttr?, parseCollection ) )
/// nodeElementList
/// end-element()
/// 7.2.20 parseTypeOtherPropertyElt
/// start-element ( URI == propertyElementURIs, attributes == set ( idAttr?, parseOther ) )
/// propertyEltList
/// end-element()
/// 7.2.21 emptyPropertyElt
/// start-element ( URI == propertyElementURIs,
/// attributes == set ( idAttr?, ( resourceAttr | nodeIdAttr )?, propertyAttr* ) )
/// end-element()
/// The various property element forms are not distinguished by the XML element name,
/// but by their attributes for the most part. The exceptions are resourcePropertyElt and
/// literalPropertyElt. They are distinguished by their XML element content.
/// NOTE: The RDF syntax does not explicitly include the xml:lang attribute although it can
/// appear in many of these. We have to allow for it in the attibute counts below.
/// </remarks>
/// <param name="xmp">the xmp metadata object that is generated</param>
/// <param name="xmpParent">the parent xmp node</param>
/// <param name="xmlNode">the currently processed XML node</param>
/// <param name="isTopLevel">Flag if the node is a top-level node</param>
/// <exception cref="Com.Adobe.Xmp.XMPException">thown on parsing errors</exception>
private static void Rdf_PropertyElement(XMPMetaImpl xmp, XMPNode xmpParent, XmlNode xmlNode, bool isTopLevel)
{
int nodeTerm = GetRDFTermKind(xmlNode);
if (!IsPropertyElementName(nodeTerm))
{
throw new XMPException("Invalid property element name", XMPErrorConstants.Badrdf);
}
// remove the namespace-definitions from the list
XmlAttributeCollection attributes = xmlNode.Attributes;
IList nsAttrs = null;
for (int i = 0; i < attributes.Count; i++)
{
XmlNode attribute = attributes.Item(i);
if ("xmlns".Equals(attribute.Prefix) || (attribute.Prefix == null && "xmlns".Equals(attribute.Name)))
{
if (nsAttrs == null)
{
nsAttrs = new ArrayList();
}
nsAttrs.Add(attribute.Name);
}
}
if (nsAttrs != null)
{
for (Iterator it = nsAttrs.Iterator(); it.HasNext(); )
{
string ns = (string)it.Next();
attributes.RemoveNamedItem(ns);
}
}
if (attributes.Count > 3)
{
// Only an emptyPropertyElt can have more than 3 attributes.
Rdf_EmptyPropertyElement(xmp, xmpParent, xmlNode, isTopLevel);
}
else
{
// Look through the attributes for one that isn't rdf:ID or xml:lang,
// it will usually tell what we should be dealing with.
// The called routines must verify their specific syntax!
for (int i_1 = 0; i_1 < attributes.Count; i_1++)
{
XmlNode attribute = attributes.Item(i_1);
string attrLocal = attribute.LocalName;
string attrNS = attribute.NamespaceURI;
string attrValue = attribute.Value;
if (!(XMPConstConstants.XmlLang.Equals(attribute.Name) && !("ID".Equals(attrLocal) && XMPConstConstants.NsRdf.Equals(attrNS))))
{
if ("datatype".Equals(attrLocal) && XMPConstConstants.NsRdf.Equals(attrNS))
{
Rdf_LiteralPropertyElement(xmp, xmpParent, xmlNode, isTopLevel);
}
else
{
if (!("parseType".Equals(attrLocal) && XMPConstConstants.NsRdf.Equals(attrNS)))
{
Rdf_EmptyPropertyElement(xmp, xmpParent, xmlNode, isTopLevel);
}
else
{
if ("Literal".Equals(attrValue))
{
Rdf_ParseTypeLiteralPropertyElement();
}
else
{
if ("Resource".Equals(attrValue))
{
Rdf_ParseTypeResourcePropertyElement(xmp, xmpParent, xmlNode, isTopLevel);
}
else
{
if ("Collection".Equals(attrValue))
{
Rdf_ParseTypeCollectionPropertyElement();
}
else
{
Rdf_ParseTypeOtherPropertyElement();
}
}
}
}
}
return;
}
}
// Only rdf:ID and xml:lang, could be a resourcePropertyElt, a literalPropertyElt,
// or an emptyPropertyElt. Look at the child XML nodes to decide which.
if (xmlNode.HasChildNodes)
{
for (int i_2 = 0; i_2 < xmlNode.ChildNodes.Count; i_2++)
{
XmlNode currChild = xmlNode.ChildNodes.Item(i_2);
if (currChild.NodeType != System.Xml.XmlNodeType.Text)
{
Rdf_ResourcePropertyElement(xmp, xmpParent, xmlNode, isTopLevel);
return;
}
}
Rdf_LiteralPropertyElement(xmp, xmpParent, xmlNode, isTopLevel);
}
else
{
Rdf_EmptyPropertyElement(xmp, xmpParent, xmlNode, isTopLevel);
}
}
}
/// <summary>
/// 7.2.15 resourcePropertyElt
/// start-element ( URI == propertyElementURIs, attributes == set ( idAttr? ) )
/// ws* nodeElement ws
/// end-element()
/// This handles structs using an rdf:Description node,
/// arrays using rdf:Bag/Seq/Alt, and typedNodes.
/// </summary>
/// <remarks>
/// 7.2.15 resourcePropertyElt
/// start-element ( URI == propertyElementURIs, attributes == set ( idAttr? ) )
/// ws* nodeElement ws
/// end-element()
/// This handles structs using an rdf:Description node,
/// arrays using rdf:Bag/Seq/Alt, and typedNodes. It also catches and cleans up qualified
/// properties written with rdf:Description and rdf:value.
/// </remarks>
/// <param name="xmp">the xmp metadata object that is generated</param>
/// <param name="xmpParent">the parent xmp node</param>
/// <param name="xmlNode">the currently processed XML node</param>
/// <param name="isTopLevel">Flag if the node is a top-level node</param>
/// <exception cref="Com.Adobe.Xmp.XMPException">thown on parsing errors</exception>
private static void Rdf_ResourcePropertyElement(XMPMetaImpl xmp, XMPNode xmpParent, XmlNode xmlNode, bool isTopLevel)
{
if (isTopLevel && "iX:changes".Equals(xmlNode.Name))
{
// Strip old "punchcard" chaff which has on the prefix "iX:".
return;
}
XMPNode newCompound = AddChildNode(xmp, xmpParent, xmlNode, string.Empty, isTopLevel);
// walk through the attributes
for (int i = 0; i < xmlNode.Attributes.Count; i++)
{
XmlNode attribute = xmlNode.Attributes.Item(i);
if ("xmlns".Equals(attribute.Prefix) || (attribute.Prefix == null && "xmlns".Equals(attribute.Name)))
{
continue;
}
string attrLocal = attribute.LocalName;
string attrNS = attribute.NamespaceURI;
if (XMPConstConstants.XmlLang.Equals(attribute.Name))
{
AddQualifierNode(newCompound, XMPConstConstants.XmlLang, attribute.Value);
}
else
{
if ("ID".Equals(attrLocal) && XMPConstConstants.NsRdf.Equals(attrNS))
{
continue;
}
else
{
// Ignore all rdf:ID attributes.
throw new XMPException("Invalid attribute for resource property element", XMPErrorConstants.Badrdf);
}
}
}
// walk through the children
XmlNode currChild = null;
bool found = false;
int i_1;
for (i_1 = 0; i_1 < xmlNode.ChildNodes.Count; i_1++)
{
currChild = xmlNode.ChildNodes.Item(i_1);
if (!IsWhitespaceNode(currChild))
{
if (currChild.NodeType == System.Xml.XmlNodeType.Element && !found)
{
bool isRDF = XMPConstConstants.NsRdf.Equals(currChild.NamespaceURI);
string childLocal = currChild.LocalName;
if (isRDF && "Bag".Equals(childLocal))
{
newCompound.GetOptions().SetArray(true);
}
else
{
if (isRDF && "Seq".Equals(childLocal))
{
newCompound.GetOptions().SetArray(true).SetArrayOrdered(true);
}
else
{
if (isRDF && "Alt".Equals(childLocal))
{
newCompound.GetOptions().SetArray(true).SetArrayOrdered(true).SetArrayAlternate(true);
}
else
{
newCompound.GetOptions().SetStruct(true);
if (!isRDF && !"Description".Equals(childLocal))
{
string typeName = currChild.NamespaceURI;
if (typeName == null)
{
throw new XMPException("All XML elements must be in a namespace", XMPErrorConstants.Badxmp);
}
typeName += ':' + childLocal;
AddQualifierNode(newCompound, "rdf:type", typeName);
}
}
}
}
Rdf_NodeElement(xmp, newCompound, currChild, false);
if (newCompound.GetHasValueChild())
{
FixupQualifiedNode(newCompound);
}
else
{
if (newCompound.GetOptions().IsArrayAlternate())
{
XMPNodeUtils.DetectAltText(newCompound);
}
}
found = true;
}
else
{
if (found)
{
// found second child element
throw new XMPException("Invalid child of resource property element", XMPErrorConstants.Badrdf);
}
else
{
throw new XMPException("Children of resource property element must be XML elements", XMPErrorConstants.Badrdf);
}
}
}
}
if (!found)
{
// didn't found any child elements
throw new XMPException("Missing child of resource property element", XMPErrorConstants.Badrdf);
}
}
/// <summary>
/// 7.2.16 literalPropertyElt
/// start-element ( URI == propertyElementURIs,
/// attributes == set ( idAttr?, datatypeAttr?) )
/// text()
/// end-element()
/// Add a leaf node with the text value and qualifiers for the attributes.
/// </summary>
/// <param name="xmp">the xmp metadata object that is generated</param>
/// <param name="xmpParent">the parent xmp node</param>
/// <param name="xmlNode">the currently processed XML node</param>
/// <param name="isTopLevel">Flag if the node is a top-level node</param>
/// <exception cref="Com.Adobe.Xmp.XMPException">thown on parsing errors</exception>
private static void Rdf_LiteralPropertyElement(XMPMetaImpl xmp, XMPNode xmpParent, XmlNode xmlNode, bool isTopLevel)
{
XMPNode newChild = AddChildNode(xmp, xmpParent, xmlNode, null, isTopLevel);
for (int i = 0; i < xmlNode.Attributes.Count; i++)
{
XmlNode attribute = xmlNode.Attributes.Item(i);
if ("xmlns".Equals(attribute.Prefix) || (attribute.Prefix == null && "xmlns".Equals(attribute.Name)))
{
continue;
}
string attrNS = attribute.NamespaceURI;
string attrLocal = attribute.LocalName;
if (XMPConstConstants.XmlLang.Equals(attribute.Name))
{
AddQualifierNode(newChild, XMPConstConstants.XmlLang, attribute.Value);
}
else
{
if (XMPConstConstants.NsRdf.Equals(attrNS) && ("ID".Equals(attrLocal) || "datatype".Equals(attrLocal)))
{
continue;
}
else
{
// Ignore all rdf:ID and rdf:datatype attributes.
throw new XMPException("Invalid attribute for literal property element", XMPErrorConstants.Badrdf);
}
}
}
string textValue = string.Empty;
for (int i_1 = 0; i_1 < xmlNode.ChildNodes.Count; i_1++)
{
XmlNode child = xmlNode.ChildNodes.Item(i_1);
if (child.NodeType == System.Xml.XmlNodeType.Text)
{
textValue += child.Value;
}
else
{
throw new XMPException("Invalid child of literal property element", XMPErrorConstants.Badrdf);
}
}
newChild.SetValue(textValue);
}
/// <summary>
/// 7.2.17 parseTypeLiteralPropertyElt
/// start-element ( URI == propertyElementURIs,
/// attributes == set ( idAttr?, parseLiteral ) )
/// literal
/// end-element()
/// </summary>
/// <exception cref="Com.Adobe.Xmp.XMPException">thown on parsing errors</exception>
private static void Rdf_ParseTypeLiteralPropertyElement()
{
throw new XMPException("ParseTypeLiteral property element not allowed", XMPErrorConstants.Badxmp);
}
/// <summary>
/// 7.2.18 parseTypeResourcePropertyElt
/// start-element ( URI == propertyElementURIs,
/// attributes == set ( idAttr?, parseResource ) )
/// propertyEltList
/// end-element()
/// Add a new struct node with a qualifier for the possible rdf:ID attribute.
/// </summary>
/// <remarks>
/// 7.2.18 parseTypeResourcePropertyElt
/// start-element ( URI == propertyElementURIs,
/// attributes == set ( idAttr?, parseResource ) )
/// propertyEltList
/// end-element()
/// Add a new struct node with a qualifier for the possible rdf:ID attribute.
/// Then process the XML child nodes to get the struct fields.
/// </remarks>
/// <param name="xmp">the xmp metadata object that is generated</param>
/// <param name="xmpParent">the parent xmp node</param>
/// <param name="xmlNode">the currently processed XML node</param>
/// <param name="isTopLevel">Flag if the node is a top-level node</param>
/// <exception cref="Com.Adobe.Xmp.XMPException">thown on parsing errors</exception>
private static void Rdf_ParseTypeResourcePropertyElement(XMPMetaImpl xmp, XMPNode xmpParent, XmlNode xmlNode, bool isTopLevel)
{
XMPNode newStruct = AddChildNode(xmp, xmpParent, xmlNode, string.Empty, isTopLevel);
newStruct.GetOptions().SetStruct(true);
for (int i = 0; i < xmlNode.Attributes.Count; i++)
{
XmlNode attribute = xmlNode.Attributes.Item(i);
if ("xmlns".Equals(attribute.Prefix) || (attribute.Prefix == null && "xmlns".Equals(attribute.Name)))
{
continue;
}
string attrLocal = attribute.LocalName;
string attrNS = attribute.NamespaceURI;
if (XMPConstConstants.XmlLang.Equals(attribute.Name))
{
AddQualifierNode(newStruct, XMPConstConstants.XmlLang, attribute.Value);
}
else
{
if (XMPConstConstants.NsRdf.Equals(attrNS) && ("ID".Equals(attrLocal) || "parseType".Equals(attrLocal)))
{
continue;
}
else
{
// The caller ensured the value is "Resource".
// Ignore all rdf:ID attributes.
throw new XMPException("Invalid attribute for ParseTypeResource property element", XMPErrorConstants.Badrdf);
}
}
}
Rdf_PropertyElementList(xmp, newStruct, xmlNode, false);
if (newStruct.GetHasValueChild())
{
FixupQualifiedNode(newStruct);
}
}
/// <summary>
/// 7.2.19 parseTypeCollectionPropertyElt
/// start-element ( URI == propertyElementURIs,
/// attributes == set ( idAttr?, parseCollection ) )
/// nodeElementList
/// end-element()
/// </summary>
/// <exception cref="Com.Adobe.Xmp.XMPException">thown on parsing errors</exception>
private static void Rdf_ParseTypeCollectionPropertyElement()
{
throw new XMPException("ParseTypeCollection property element not allowed", XMPErrorConstants.Badxmp);
}
/// <summary>
/// 7.2.20 parseTypeOtherPropertyElt
/// start-element ( URI == propertyElementURIs, attributes == set ( idAttr?, parseOther ) )
/// propertyEltList
/// end-element()
/// </summary>
/// <exception cref="Com.Adobe.Xmp.XMPException">thown on parsing errors</exception>
private static void Rdf_ParseTypeOtherPropertyElement()
{
throw new XMPException("ParseTypeOther property element not allowed", XMPErrorConstants.Badxmp);
}
/// <summary>
/// 7.2.21 emptyPropertyElt
/// start-element ( URI == propertyElementURIs,
/// attributes == set (
/// idAttr?, ( resourceAttr | nodeIdAttr )?, propertyAttr* ) )
/// end-element()
/// <ns:Prop1/> <!-- a simple property with an empty value -->
/// <ns:Prop2 rdf:resource="http: *www.adobe.com/"/> <!-- a URI value -->
/// <ns:Prop3 rdf:value="..." ns:Qual="..."/> <!-- a simple qualified property -->
/// <ns:Prop4 ns:Field1="..." ns:Field2="..."/> <!-- a struct with simple fields -->
/// An emptyPropertyElt is an element with no contained content, just a possibly empty set of
/// attributes.
/// </summary>
/// <remarks>
/// 7.2.21 emptyPropertyElt
/// start-element ( URI == propertyElementURIs,
/// attributes == set (
/// idAttr?, ( resourceAttr | nodeIdAttr )?, propertyAttr* ) )
/// end-element()
/// <ns:Prop1/> <!-- a simple property with an empty value -->
/// <ns:Prop2 rdf:resource="http: *www.adobe.com/"/> <!-- a URI value -->
/// <ns:Prop3 rdf:value="..." ns:Qual="..."/> <!-- a simple qualified property -->
/// <ns:Prop4 ns:Field1="..." ns:Field2="..."/> <!-- a struct with simple fields -->
/// An emptyPropertyElt is an element with no contained content, just a possibly empty set of
/// attributes. An emptyPropertyElt can represent three special cases of simple XMP properties: a
/// simple property with an empty value (ns:Prop1), a simple property whose value is a URI
/// (ns:Prop2), or a simple property with simple qualifiers (ns:Prop3).
/// An emptyPropertyElt can also represent an XMP struct whose fields are all simple and
/// unqualified (ns:Prop4).
/// It is an error to use both rdf:value and rdf:resource - that can lead to invalid RDF in the
/// verbose form written using a literalPropertyElt.
/// The XMP mapping for an emptyPropertyElt is a bit different from generic RDF, partly for
/// design reasons and partly for historical reasons. The XMP mapping rules are:
/// <ol>
/// <li> If there is an rdf:value attribute then this is a simple property
/// with a text value.
/// All other attributes are qualifiers.
/// <li> If there is an rdf:resource attribute then this is a simple property
/// with a URI value.
/// All other attributes are qualifiers.
/// <li> If there are no attributes other than xml:lang, rdf:ID, or rdf:nodeID
/// then this is a simple
/// property with an empty value.
/// <li> Otherwise this is a struct, the attributes other than xml:lang, rdf:ID,
/// or rdf:nodeID are fields.
/// </ol>
/// </remarks>
/// <param name="xmp">the xmp metadata object that is generated</param>
/// <param name="xmpParent">the parent xmp node</param>
/// <param name="xmlNode">the currently processed XML node</param>
/// <param name="isTopLevel">Flag if the node is a top-level node</param>
/// <exception cref="Com.Adobe.Xmp.XMPException">thown on parsing errors</exception>
private static void Rdf_EmptyPropertyElement(XMPMetaImpl xmp, XMPNode xmpParent, XmlNode xmlNode, bool isTopLevel)
{
bool hasPropertyAttrs = false;
bool hasResourceAttr = false;
bool hasNodeIDAttr = false;
bool hasValueAttr = false;
XmlNode valueNode = null;
// ! Can come from rdf:value or rdf:resource.
if (xmlNode.HasChildNodes)
{
throw new XMPException("Nested content not allowed with rdf:resource or property attributes", XMPErrorConstants.Badrdf);
}
// First figure out what XMP this maps to and remember the XML node for a simple value.
for (int i = 0; i < xmlNode.Attributes.Count; i++)
{
XmlNode attribute = xmlNode.Attributes.Item(i);
if ("xmlns".Equals(attribute.Prefix) || (attribute.Prefix == null && "xmlns".Equals(attribute.Name)))
{
continue;
}
int attrTerm = GetRDFTermKind(attribute);
switch (attrTerm)
{
case RdftermId:
{
// Nothing to do.
break;
}
case RdftermResource:
{
if (hasNodeIDAttr)
{
throw new XMPException("Empty property element can't have both rdf:resource and rdf:nodeID", XMPErrorConstants.Badrdf);
}
else
{
if (hasValueAttr)
{
throw new XMPException("Empty property element can't have both rdf:value and rdf:resource", XMPErrorConstants.Badxmp);
}
}
hasResourceAttr = true;
if (!hasValueAttr)
{
valueNode = attribute;
}
break;
}
case RdftermNodeId:
{
if (hasResourceAttr)
{
throw new XMPException("Empty property element can't have both rdf:resource and rdf:nodeID", XMPErrorConstants.Badrdf);
}
hasNodeIDAttr = true;
break;
}
case RdftermOther:
{
if ("value".Equals(attribute.LocalName) && XMPConstConstants.NsRdf.Equals(attribute.NamespaceURI))
{
if (hasResourceAttr)
{
throw new XMPException("Empty property element can't have both rdf:value and rdf:resource", XMPErrorConstants.Badxmp);
}
hasValueAttr = true;
valueNode = attribute;
}
else
{
if (!XMPConstConstants.XmlLang.Equals(attribute.Name))
{
hasPropertyAttrs = true;
}
}
break;
}
default:
{
throw new XMPException("Unrecognized attribute of empty property element", XMPErrorConstants.Badrdf);
}
}
}
// Create the right kind of child node and visit the attributes again
// to add the fields or qualifiers.
// ! Because of implementation vagaries,
// the xmpParent is the tree root for top level properties.
// ! The schema is found, created if necessary, by addChildNode.
XMPNode childNode = AddChildNode(xmp, xmpParent, xmlNode, string.Empty, isTopLevel);
bool childIsStruct = false;
if (hasValueAttr || hasResourceAttr)
{
childNode.SetValue(valueNode != null ? valueNode.Value : string.Empty);
if (!hasValueAttr)
{
// ! Might have both rdf:value and rdf:resource.
childNode.GetOptions().SetURI(true);
}
}
else
{
if (hasPropertyAttrs)
{
childNode.GetOptions().SetStruct(true);
childIsStruct = true;
}
}
for (int i_1 = 0; i_1 < xmlNode.Attributes.Count; i_1++)
{
XmlNode attribute = xmlNode.Attributes.Item(i_1);
if (attribute == valueNode || "xmlns".Equals(attribute.Prefix) || (attribute.Prefix == null && "xmlns".Equals(attribute.Name)))
{
continue;
}
// Skip the rdf:value or rdf:resource attribute holding the value.
int attrTerm = GetRDFTermKind(attribute);
switch (attrTerm)
{
case RdftermId:
case RdftermNodeId:
{
break;
}
case RdftermResource:
{
// Ignore all rdf:ID and rdf:nodeID attributes.
AddQualifierNode(childNode, "rdf:resource", attribute.Value);
break;
}
case RdftermOther:
{
if (!childIsStruct)
{
AddQualifierNode(childNode, attribute.Name, attribute.Value);
}
else
{
if (XMPConstConstants.XmlLang.Equals(attribute.Name))
{
AddQualifierNode(childNode, XMPConstConstants.XmlLang, attribute.Value);
}
else
{
AddChildNode(xmp, childNode, attribute, attribute.Value, false);
}
}
break;
}
default:
{
throw new XMPException("Unrecognized attribute of empty property element", XMPErrorConstants.Badrdf);
}
}
}
}
/// <summary>Adds a child node.</summary>
/// <param name="xmp">the xmp metadata object that is generated</param>
/// <param name="xmpParent">the parent xmp node</param>
/// <param name="xmlNode">the currently processed XML node</param>
/// <param name="value">Node value</param>
/// <param name="isTopLevel">Flag if the node is a top-level node</param>
/// <returns>Returns the newly created child node.</returns>
/// <exception cref="Com.Adobe.Xmp.XMPException">thown on parsing errors</exception>
private static XMPNode AddChildNode(XMPMetaImpl xmp, XMPNode xmpParent, XmlNode xmlNode, string value, bool isTopLevel)
{
XMPSchemaRegistry registry = XMPMetaFactory.GetSchemaRegistry();
string @namespace = xmlNode.NamespaceURI;
string childName;
if (@namespace != null)
{
if (XMPConstConstants.NsDcDeprecated.Equals(@namespace))
{
// Fix a legacy DC namespace
@namespace = XMPConstConstants.NsDc;
}
string prefix = registry.GetNamespacePrefix(@namespace);
if (prefix == null)
{
prefix = xmlNode.Prefix != null ? xmlNode.Prefix : DefaultPrefix;
prefix = registry.RegisterNamespace(@namespace, prefix);
}
childName = prefix + xmlNode.LocalName;
}
else
{
throw new XMPException("XML namespace required for all elements and attributes", XMPErrorConstants.Badrdf);
}
// create schema node if not already there
PropertyOptions childOptions = new PropertyOptions();
bool isAlias = false;
if (isTopLevel)
{
// Lookup the schema node, adjust the XMP parent pointer.
// Incoming parent must be the tree root.
XMPNode schemaNode = XMPNodeUtils.FindSchemaNode(xmp.GetRoot(), @namespace, DefaultPrefix, true);
schemaNode.SetImplicit(false);
// Clear the implicit node bit.
// need runtime check for proper 32 bit code.
xmpParent = schemaNode;
// If this is an alias set the alias flag in the node
// and the hasAliases flag in the tree.
if (registry.FindAlias(childName) != null)
{
isAlias = true;
xmp.GetRoot().SetHasAliases(true);
schemaNode.SetHasAliases(true);
}
}
// Make sure that this is not a duplicate of a named node.
bool isArrayItem = "rdf:li".Equals(childName);
bool isValueNode = "rdf:value".Equals(childName);
// Create XMP node and so some checks
XMPNode newChild = new XMPNode(childName, value, childOptions);
newChild.SetAlias(isAlias);
// Add the new child to the XMP parent node, a value node first.
if (!isValueNode)
{
xmpParent.AddChild(newChild);
}
else
{
xmpParent.AddChild(1, newChild);
}
if (isValueNode)
{
if (isTopLevel || !xmpParent.GetOptions().IsStruct())
{
throw new XMPException("Misplaced rdf:value element", XMPErrorConstants.Badrdf);
}
xmpParent.SetHasValueChild(true);
}
if (isArrayItem)
{
if (!xmpParent.GetOptions().IsArray())
{
throw new XMPException("Misplaced rdf:li element", XMPErrorConstants.Badrdf);
}
newChild.SetName(XMPConstConstants.ArrayItemName);
}
return newChild;
}
/// <summary>Adds a qualifier node.</summary>
/// <param name="xmpParent">the parent xmp node</param>
/// <param name="name">
/// the name of the qualifier which has to be
/// QName including the <b>default prefix</b>
/// </param>
/// <param name="value">the value of the qualifier</param>
/// <returns>Returns the newly created child node.</returns>
/// <exception cref="Com.Adobe.Xmp.XMPException">thown on parsing errors</exception>
private static XMPNode AddQualifierNode(XMPNode xmpParent, string name, string value)
{
bool isLang = XMPConstConstants.XmlLang.Equals(name);
XMPNode newQual = null;
// normalize value of language qualifiers
newQual = new XMPNode(name, isLang ? Utils.NormalizeLangValue(value) : value, null);
xmpParent.AddQualifier(newQual);
return newQual;
}
/// <summary>The parent is an RDF pseudo-struct containing an rdf:value field.</summary>
/// <remarks>
/// The parent is an RDF pseudo-struct containing an rdf:value field. Fix the
/// XMP data model. The rdf:value node must be the first child, the other
/// children are qualifiers. The form, value, and children of the rdf:value
/// node are the real ones. The rdf:value node's qualifiers must be added to
/// the others.
/// </remarks>
/// <param name="xmpParent">the parent xmp node</param>
/// <exception cref="Com.Adobe.Xmp.XMPException">thown on parsing errors</exception>
private static void FixupQualifiedNode(XMPNode xmpParent)
{
System.Diagnostics.Debug.Assert(xmpParent.GetOptions().IsStruct() && xmpParent.HasChildren());
XMPNode valueNode = xmpParent.GetChild(1);
System.Diagnostics.Debug.Assert("rdf:value".Equals(valueNode.GetName()));
// Move the qualifiers on the value node to the parent.
// Make sure an xml:lang qualifier stays at the front.
// Check for duplicate names between the value node's qualifiers and the parent's children.
// The parent's children are about to become qualifiers. Check here, between the groups.
// Intra-group duplicates are caught by XMPNode#addChild(...).
if (valueNode.GetOptions().GetHasLanguage())
{
if (xmpParent.GetOptions().GetHasLanguage())
{
throw new XMPException("Redundant xml:lang for rdf:value element", XMPErrorConstants.Badxmp);
}
XMPNode langQual = valueNode.GetQualifier(1);
valueNode.RemoveQualifier(langQual);
xmpParent.AddQualifier(langQual);
}
// Start the remaining copy after the xml:lang qualifier.
for (int i = 1; i <= valueNode.GetQualifierLength(); i++)
{
XMPNode qualifier = valueNode.GetQualifier(i);
xmpParent.AddQualifier(qualifier);
}
// Change the parent's other children into qualifiers.
// This loop starts at 1, child 0 is the rdf:value node.
for (int i_1 = 2; i_1 <= xmpParent.GetChildrenLength(); i_1++)
{
XMPNode qualifier = xmpParent.GetChild(i_1);
xmpParent.AddQualifier(qualifier);
}
// Move the options and value last, other checks need the parent's original options.
// Move the value node's children to be the parent's children.
System.Diagnostics.Debug.Assert(xmpParent.GetOptions().IsStruct() || xmpParent.GetHasValueChild());
xmpParent.SetHasValueChild(false);
xmpParent.GetOptions().SetStruct(false);
xmpParent.GetOptions().MergeWith(valueNode.GetOptions());
xmpParent.SetValue(valueNode.GetValue());
xmpParent.RemoveChildren();
for (Iterator it = valueNode.IterateChildren(); it.HasNext(); )
{
XMPNode child = (XMPNode)it.Next();
xmpParent.AddChild(child);
}
}
/// <summary>Checks if the node is a white space.</summary>
/// <param name="node">an XML-node</param>
/// <returns>
/// Returns whether the node is a whitespace node,
/// i.e. a text node that contains only whitespaces.
/// </returns>
private static bool IsWhitespaceNode(XmlNode node)
{
if (node.NodeType != System.Xml.XmlNodeType.Text)
{
return false;
}
string value = node.Value;
for (int i = 0; i < value.Length; i++)
{
if (!char.IsWhiteSpace(value[i]))
{
return false;
}
}
return true;
}
/// <summary>
/// 7.2.6 propertyElementURIs
/// anyURI - ( coreSyntaxTerms | rdf:Description | oldTerms )
/// </summary>
/// <param name="term">the term id</param>
/// <returns>Return true if the term is a property element name.</returns>
private static bool IsPropertyElementName(int term)
{
if (term == RdftermDescription || IsOldTerm(term))
{
return false;
}
else
{
return (!IsCoreSyntaxTerm(term));
}
}
/// <summary>
/// 7.2.4 oldTerms<br />
/// rdf:aboutEach | rdf:aboutEachPrefix | rdf:bagID
/// </summary>
/// <param name="term">the term id</param>
/// <returns>Returns true if the term is an old term.</returns>
private static bool IsOldTerm(int term)
{
return RdftermFirstOld <= term && term <= RdftermLastOld;
}
/// <summary>
/// 7.2.2 coreSyntaxTerms<br />
/// rdf:RDF | rdf:ID | rdf:about | rdf:parseType | rdf:resource | rdf:nodeID |
/// rdf:datatype
/// </summary>
/// <param name="term">the term id</param>
/// <returns>Return true if the term is a core syntax term</returns>
private static bool IsCoreSyntaxTerm(int term)
{
return RdftermFirstCore <= term && term <= RdftermLastCore;
}
/// <summary>Determines the ID for a certain RDF Term.</summary>
/// <remarks>
/// Determines the ID for a certain RDF Term.
/// Arranged to hopefully minimize the parse time for large XMP.
/// </remarks>
/// <param name="node">an XML node</param>
/// <returns>Returns the term ID.</returns>
private static int GetRDFTermKind(XmlNode node)
{
string localName = node.LocalName;
string @namespace = node.NamespaceURI;
if (@namespace == null && ("about".Equals(localName) || "ID".Equals(localName)) && (node is XmlAttribute) && XMPConstConstants.NsRdf.Equals(((XmlAttribute)node).OwnerElement.NamespaceURI))
{
@namespace = XMPConstConstants.NsRdf;
}
if (XMPConstConstants.NsRdf.Equals(@namespace))
{
if ("li".Equals(localName))
{
return RdftermLi;
}
else
{
if ("parseType".Equals(localName))
{
return RdftermParseType;
}
else
{
if ("Description".Equals(localName))
{
return RdftermDescription;
}
else
{
if ("about".Equals(localName))
{
return RdftermAbout;
}
else
{
if ("resource".Equals(localName))
{
return RdftermResource;
}
else
{
if ("RDF".Equals(localName))
{
return RdftermRdf;
}
else
{
if ("ID".Equals(localName))
{
return RdftermId;
}
else
{
if ("nodeID".Equals(localName))
{
return RdftermNodeId;
}
else
{
if ("datatype".Equals(localName))
{
return RdftermDatatype;
}
else
{
if ("aboutEach".Equals(localName))
{
return RdftermAboutEach;
}
else
{
if ("aboutEachPrefix".Equals(localName))
{
return RdftermAboutEachPrefix;
}
else
{
if ("bagID".Equals(localName))
{
return RdftermBagId;
}
}
}
}
}
}
}
}
}
}
}
}
}
return RdftermOther;
}
}
}
| |
using Amazon.CloudWatchLogs;
using Amazon.CloudWatchLogs.Model;
using Serilog.Events;
using Serilog.Formatting;
using Serilog.Sinks.PeriodicBatching;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Serilog.Sinks.AwsCloudWatch
{
/// <summary>
/// A Serilog log sink that publishes to AWS CloudWatch Logs
/// </summary>
/// <seealso cref="Serilog.Sinks.PeriodicBatching.PeriodicBatchingSink" />
public class CloudWatchLogSink : PeriodicBatchingSink
{
/// <summary>
/// The maximum log event size = 256 KB - 26 B
/// </summary>
public const int MaxLogEventSize = 262118;
/// <summary>
/// The maximum log event batch size = 1 MB
/// </summary>
public const int MaxLogEventBatchSize = 1048576;
/// <summary>
/// The maximum log event batch count
/// </summary>
public const int MaxLogEventBatchCount = 10000;
/// <summary>
/// When in a batch, each message must have a buffer of 26 bytes
/// </summary>
public const int MessageBufferSize = 26;
/// <summary>
/// The maximum span of events in a batch
/// </summary>
public static readonly TimeSpan MaxBatchEventSpan = TimeSpan.FromDays(1);
/// <summary>
/// The span of time to backoff when an error occurs
/// </summary>
public static readonly TimeSpan ErrorBackoffStartingInterval = TimeSpan.FromMilliseconds(100);
private readonly IAmazonCloudWatchLogs cloudWatchClient;
private readonly ICloudWatchSinkOptions options;
private bool hasInit;
private string logStreamName;
private string nextSequenceToken;
private readonly ITextFormatter textFormatter;
private readonly SemaphoreSlim syncObject = new SemaphoreSlim(1);
/// <summary>
/// Initializes a new instance of the <see cref="CloudWatchLogSink"/> class.
/// </summary>
/// <param name="cloudWatchClient">The cloud watch client.</param>
/// <param name="options">The options.</param>
public CloudWatchLogSink(IAmazonCloudWatchLogs cloudWatchClient, ICloudWatchSinkOptions options) : base(options.BatchSizeLimit, options.Period, options.QueueSizeLimit)
{
if (string.IsNullOrEmpty(options?.LogGroupName))
{
throw new ArgumentException($"{nameof(ICloudWatchSinkOptions)}.{nameof(options.LogGroupName)} must be specified.");
}
if (options.BatchSizeLimit < 1)
{
throw new ArgumentException($"{nameof(ICloudWatchSinkOptions)}.{nameof(options.BatchSizeLimit)} must be a value greater than 0.");
}
this.cloudWatchClient = cloudWatchClient;
this.options = options;
if (options.TextFormatter == null)
{
throw new System.ArgumentException($"{nameof(options.TextFormatter)} is required");
}
textFormatter = options.TextFormatter;
}
/// <summary>
/// Ensures the component is initialized.
/// </summary>
private async Task EnsureInitializedAsync()
{
if (hasInit)
{
return;
}
// create log group
await CreateLogGroupAsync();
// create log stream
UpdateLogStreamName();
await CreateLogStreamAsync();
hasInit = true;
}
/// <summary>
/// Creates the log group.
/// </summary>
/// <exception cref="Serilog.Sinks.AwsCloudWatch.AwsCloudWatchSinkException"></exception>
private async Task CreateLogGroupAsync()
{
if (options.CreateLogGroup)
{
// see if the log group already exists
var describeRequest = new DescribeLogGroupsRequest
{
LogGroupNamePrefix = options.LogGroupName
};
var logGroups = await cloudWatchClient
.DescribeLogGroupsAsync(describeRequest);
var logGroup = logGroups
.LogGroups
.FirstOrDefault(lg => string.Equals(lg.LogGroupName, options.LogGroupName, StringComparison.Ordinal));
// create log group if it doesn't exist
if (logGroup == null)
{
var createRequest = new CreateLogGroupRequest(options.LogGroupName);
var createResponse = await cloudWatchClient.CreateLogGroupAsync(createRequest);
// update the retention policy if a specific period is defined
if (options.LogGroupRetentionPolicy != LogGroupRetentionPolicy.Indefinitely)
{
var putRetentionRequest = new PutRetentionPolicyRequest(options.LogGroupName, (int)options.LogGroupRetentionPolicy);
await cloudWatchClient.PutRetentionPolicyAsync(putRetentionRequest);
}
}
}
}
/// <summary>
/// Updates the name of the log stream.
/// </summary>
private void UpdateLogStreamName()
{
logStreamName = options.LogStreamNameProvider.GetLogStreamName();
nextSequenceToken = null; // always reset on a new stream
}
/// <summary>
/// Creates the log stream if needed.
/// </summary>
/// <exception cref="Serilog.Sinks.AwsCloudWatch.AwsCloudWatchSinkException"></exception>
private async Task CreateLogStreamAsync()
{
// see if the log stream already exists
var logStream = await GetLogStreamAsync();
// create log stream if it doesn't exist
if (logStream == null)
{
var createLogStreamRequest = new CreateLogStreamRequest
{
LogGroupName = options.LogGroupName,
LogStreamName = logStreamName
};
var createLogStreamResponse = await cloudWatchClient.CreateLogStreamAsync(createLogStreamRequest);
}
else
{
nextSequenceToken = logStream.UploadSequenceToken;
}
}
/// <summary>
/// Updates the log stream sequence token.
/// </summary>
/// <exception cref="Serilog.Sinks.AwsCloudWatch.AwsCloudWatchSinkException"></exception>
private async Task UpdateLogStreamSequenceTokenAsync()
{
var logStream = await GetLogStreamAsync();
nextSequenceToken = logStream?.UploadSequenceToken;
}
/// <summary>
/// Attempts to get the log stream defined by <see cref="logStreamName"/>.
/// </summary>
/// <returns>The matching log stream or null if no match can be found.</returns>
private async Task<LogStream> GetLogStreamAsync()
{
var describeLogStreamsRequest = new DescribeLogStreamsRequest
{
LogGroupName = options.LogGroupName,
LogStreamNamePrefix = logStreamName
};
var describeLogStreamsResponse = await cloudWatchClient
.DescribeLogStreamsAsync(describeLogStreamsRequest);
return describeLogStreamsResponse
.LogStreams
.SingleOrDefault(ls => string.Equals(ls.LogStreamName, logStreamName, StringComparison.Ordinal));
}
/// <summary>
/// Creates a batch of events.
/// </summary>
/// <param name="logEvents">The entire set of log events.</param>
/// <returns>A batch of events meeting defined restrictions.</returns>
private List<InputLogEvent> CreateBatch(Queue<InputLogEvent> logEvents)
{
DateTime? first = null;
var batchSize = 0;
var batch = new List<InputLogEvent>();
while (batch.Count < MaxLogEventBatchCount && logEvents.Count > 0) // ensure < max batch count
{
var @event = logEvents.Peek();
if (!first.HasValue)
{
first = @event.Timestamp;
}
else if (@event.Timestamp.Subtract(first.Value) > MaxBatchEventSpan) // ensure batch spans no more than 24 hours
{
break;
}
var proposedBatchSize = batchSize + System.Text.Encoding.UTF8.GetByteCount(@event.Message) + MessageBufferSize;
if (proposedBatchSize < MaxLogEventBatchSize) // ensure < max batch size
{
batchSize = proposedBatchSize;
batch.Add(@event);
logEvents.Dequeue();
}
else
{
break;
}
}
return batch;
}
/// <summary>
/// Publish the batch of log events to AWS CloudWatch Logs.
/// </summary>
/// <param name="batch">The request.</param>
private async Task PublishBatchAsync(List<InputLogEvent> batch)
{
if (batch?.Count == 0)
{
return;
}
var success = false;
var attemptIndex = 0;
while (!success && attemptIndex <= options.RetryAttempts)
{
try
{
// creates the request to upload a new event to CloudWatch
var putLogEventsRequest = new PutLogEventsRequest
{
LogGroupName = options.LogGroupName,
LogStreamName = logStreamName,
SequenceToken = nextSequenceToken,
LogEvents = batch
};
// actually upload the event to CloudWatch
var putLogEventsResponse = await cloudWatchClient.PutLogEventsAsync(putLogEventsRequest);
// remember the next sequence token, which is required
nextSequenceToken = putLogEventsResponse.NextSequenceToken;
success = true;
}
catch (ServiceUnavailableException e)
{
// retry with back-off
Debugging.SelfLog.WriteLine("Service unavailable. Attempt: {0} Error: {1}", attemptIndex, e);
await Task.Delay(ErrorBackoffStartingInterval.Milliseconds * (int)Math.Pow(2, attemptIndex));
attemptIndex++;
}
catch (ResourceNotFoundException e)
{
// no retry with back-off because..
// if one of these fails, we get out of the loop.
// if they're both successful, we don't hit this case again.
Debugging.SelfLog.WriteLine("Resource was not found. Error: {0}", e);
await CreateLogGroupAsync();
await CreateLogStreamAsync();
}
catch (DataAlreadyAcceptedException e)
{
Debugging.SelfLog.WriteLine("Data already accepted. Attempt: {0} Error: {1}", attemptIndex, e);
try
{
await UpdateLogStreamSequenceTokenAsync();
}
catch (Exception ex)
{
Debugging.SelfLog.WriteLine("Unable to update log stream sequence. Attempt: {0} Error: {1}", attemptIndex, ex);
// try again with a different log stream
UpdateLogStreamName();
await CreateLogStreamAsync();
}
attemptIndex++;
}
catch (InvalidSequenceTokenException e)
{
Debugging.SelfLog.WriteLine("Invalid sequence token. Attempt: {0} Error: {1}", attemptIndex, e);
try
{
await UpdateLogStreamSequenceTokenAsync();
}
catch (Exception ex)
{
Debugging.SelfLog.WriteLine("Unable to update log stream sequence. Attempt: {0} Error: {1}", attemptIndex, ex);
// try again with a different log stream
UpdateLogStreamName();
await CreateLogStreamAsync();
}
attemptIndex++;
}
catch (Exception e)
{
Debugging.SelfLog.WriteLine("Unhandled exception. Error: {0}", e);
break;
}
}
}
/// <summary>
/// Emit a batch of log events, running asynchronously.
/// </summary>
/// <param name="events">The events to emit.</param>
protected override async Task EmitBatchAsync(IEnumerable<LogEvent> events)
{
try
{
await syncObject.WaitAsync();
if (events?.Count() == 0)
{
return;
}
try
{
await EnsureInitializedAsync();
}
catch (Exception ex)
{
Debugging.SelfLog.WriteLine("Error initializing log stream. No logs will be sent to AWS CloudWatch. Exception was {0}.", ex);
return;
}
try
{
var logEvents =
new Queue<InputLogEvent>(events
.OrderBy(e => e.Timestamp) // log events need to be ordered by timestamp within a single bulk upload to CloudWatch
.Select( // transform
@event =>
{
string message = null;
using (var writer = new StringWriter())
{
textFormatter.Format(@event, writer);
writer.Flush();
message = writer.ToString();
}
var messageLength = Encoding.UTF8.GetByteCount(message);
if (messageLength > MaxLogEventSize)
{
// truncate event message
Debugging.SelfLog.WriteLine("Truncating log event with length of {0}", messageLength);
var buffer = Encoding.UTF8.GetBytes(message);
message = Encoding.UTF8.GetString(buffer, 0, MaxLogEventSize);
}
return new InputLogEvent
{
Message = message,
Timestamp = @event.Timestamp.UtcDateTime
};
}));
while (logEvents.Count > 0)
{
var batch = CreateBatch(logEvents);
await PublishBatchAsync(batch);
}
}
catch (Exception ex)
{
try
{
Debugging.SelfLog.WriteLine("Error sending logs. No logs will be sent to AWS CloudWatch. Error was {0}", ex);
}
catch
{
// we even failed to log to the trace logger - giving up trying to put something out
}
}
}
finally
{
syncObject.Release();
}
}
}
}
| |
/*
* 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 Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "LocalInventoryServicesConnector")]
public class LocalInventoryServicesConnector : ISharedRegionModule, IInventoryService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Scene used by this module. This currently needs to be publicly settable for HGInventoryBroker.
/// </summary>
public Scene Scene { get; set; }
private IInventoryService m_InventoryService;
private IUserManagement m_UserManager;
private IUserManagement UserManager
{
get
{
if (m_UserManager == null)
{
m_UserManager = Scene.RequestModuleInterface<IUserManagement>();
}
return m_UserManager;
}
}
private bool m_Enabled = false;
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "LocalInventoryServicesConnector"; }
}
public void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("InventoryServices", "");
if (name == Name)
{
IConfig inventoryConfig = source.Configs["InventoryService"];
if (inventoryConfig == null)
{
m_log.Error("[LOCAL INVENTORY SERVICES CONNECTOR]: InventoryService missing from OpenSim.ini");
return;
}
string serviceDll = inventoryConfig.GetString("LocalServiceModule", String.Empty);
if (serviceDll == String.Empty)
{
m_log.Error("[LOCAL INVENTORY SERVICES CONNECTOR]: No LocalServiceModule named in section InventoryService");
return;
}
Object[] args = new Object[] { source };
m_log.DebugFormat("[LOCAL INVENTORY SERVICES CONNECTOR]: Service dll = {0}", serviceDll);
m_InventoryService = ServerUtils.LoadPlugin<IInventoryService>(serviceDll, args);
if (m_InventoryService == null)
{
m_log.Error("[LOCAL INVENTORY SERVICES CONNECTOR]: Can't load inventory service");
throw new Exception("Unable to proceed. Please make sure your ini files in config-include are updated according to .example's");
}
m_Enabled = true;
m_log.Info("[LOCAL INVENTORY SERVICES CONNECTOR]: Local inventory connector enabled");
}
}
}
public void PostInitialise()
{
}
public void Close()
{
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
scene.RegisterModuleInterface<IInventoryService>(this);
if (Scene == null)
Scene = scene;
}
public void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
}
public void RegionLoaded(Scene scene)
{
if (!m_Enabled)
return;
}
#region IInventoryService
public bool CreateUserInventory(UUID user)
{
return m_InventoryService.CreateUserInventory(user);
}
public List<InventoryFolderBase> GetInventorySkeleton(UUID userId)
{
return m_InventoryService.GetInventorySkeleton(userId);
}
public InventoryFolderBase GetRootFolder(UUID userID)
{
return m_InventoryService.GetRootFolder(userID);
}
public InventoryFolderBase GetFolderForType(UUID userID, AssetType type)
{
return m_InventoryService.GetFolderForType(userID, type);
}
public InventoryCollection GetFolderContent(UUID userID, UUID folderID)
{
InventoryCollection invCol = m_InventoryService.GetFolderContent(userID, folderID);
if (UserManager != null)
{
// Protect ourselves against the caller subsequently modifying the items list
List<InventoryItemBase> items = new List<InventoryItemBase>(invCol.Items);
Util.RunThreadNoTimeout(delegate
{
foreach (InventoryItemBase item in items)
if (!string.IsNullOrEmpty(item.CreatorData))
UserManager.AddUser(item.CreatorIdAsUuid, item.CreatorData);
}, "GetFolderContent", null);
}
return invCol;
}
public List<InventoryItemBase> GetFolderItems(UUID userID, UUID folderID)
{
return m_InventoryService.GetFolderItems(userID, folderID);
}
/// <summary>
/// Add a new folder to the user's inventory
/// </summary>
/// <param name="folder"></param>
/// <returns>true if the folder was successfully added</returns>
public bool AddFolder(InventoryFolderBase folder)
{
return m_InventoryService.AddFolder(folder);
}
/// <summary>
/// Update a folder in the user's inventory
/// </summary>
/// <param name="folder"></param>
/// <returns>true if the folder was successfully updated</returns>
public bool UpdateFolder(InventoryFolderBase folder)
{
return m_InventoryService.UpdateFolder(folder);
}
/// <summary>
/// Move an inventory folder to a new location
/// </summary>
/// <param name="folder">A folder containing the details of the new location</param>
/// <returns>true if the folder was successfully moved</returns>
public bool MoveFolder(InventoryFolderBase folder)
{
return m_InventoryService.MoveFolder(folder);
}
public bool DeleteFolders(UUID ownerID, List<UUID> folderIDs)
{
return m_InventoryService.DeleteFolders(ownerID, folderIDs);
}
/// <summary>
/// Purge an inventory folder of all its items and subfolders.
/// </summary>
/// <param name="folder"></param>
/// <returns>true if the folder was successfully purged</returns>
public bool PurgeFolder(InventoryFolderBase folder)
{
return m_InventoryService.PurgeFolder(folder);
}
public bool AddItem(InventoryItemBase item)
{
// m_log.DebugFormat(
// "[LOCAL INVENTORY SERVICES CONNECTOR]: Adding inventory item {0} to user {1} folder {2}",
// item.Name, item.Owner, item.Folder);
return m_InventoryService.AddItem(item);
}
/// <summary>
/// Update an item in the user's inventory
/// </summary>
/// <param name="item"></param>
/// <returns>true if the item was successfully updated</returns>
public bool UpdateItem(InventoryItemBase item)
{
return m_InventoryService.UpdateItem(item);
}
public bool MoveItems(UUID ownerID, List<InventoryItemBase> items)
{
return m_InventoryService.MoveItems(ownerID, items);
}
/// <summary>
/// Delete an item from the user's inventory
/// </summary>
/// <param name="item"></param>
/// <returns>true if the item was successfully deleted</returns>
public bool DeleteItems(UUID ownerID, List<UUID> itemIDs)
{
return m_InventoryService.DeleteItems(ownerID, itemIDs);
}
public InventoryItemBase GetItem(InventoryItemBase item)
{
// m_log.DebugFormat("[LOCAL INVENTORY SERVICES CONNECTOR]: Requesting inventory item {0}", item.ID);
// UUID requestedItemId = item.ID;
item = m_InventoryService.GetItem(item);
// if (null == item)
// m_log.ErrorFormat(
// "[LOCAL INVENTORY SERVICES CONNECTOR]: Could not find item with id {0}", requestedItemId);
return item;
}
public InventoryFolderBase GetFolder(InventoryFolderBase folder)
{
return m_InventoryService.GetFolder(folder);
}
/// <summary>
/// Does the given user have an inventory structure?
/// </summary>
/// <param name="userID"></param>
/// <returns></returns>
public bool HasInventoryForUser(UUID userID)
{
return m_InventoryService.HasInventoryForUser(userID);
}
public List<InventoryItemBase> GetActiveGestures(UUID userId)
{
return m_InventoryService.GetActiveGestures(userId);
}
#endregion IInventoryService
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Schema;
namespace System.Xml.Xsl.Runtime
{
/// <summary>
/// This internal class implements the XmlRawWriter interface by passing all calls to a wrapped XmlWriter implementation.
/// </summary>
sealed internal class XmlRawWriterWrapper : XmlRawWriter
{
private XmlWriter _wrapped;
public XmlRawWriterWrapper(XmlWriter writer)
{
_wrapped = writer;
}
//-----------------------------------------------
// XmlWriter interface
//-----------------------------------------------
public override XmlWriterSettings Settings
{
get { return _wrapped.Settings; }
}
public override void WriteDocType(string name, string pubid, string sysid, string subset)
{
_wrapped.WriteDocType(name, pubid, sysid, subset);
}
public override void WriteStartElement(string prefix, string localName, string ns)
{
_wrapped.WriteStartElement(prefix, localName, ns);
}
public override void WriteStartAttribute(string prefix, string localName, string ns)
{
_wrapped.WriteStartAttribute(prefix, localName, ns);
}
public override void WriteEndAttribute()
{
_wrapped.WriteEndAttribute();
}
public override void WriteCData(string text)
{
_wrapped.WriteCData(text);
}
public override void WriteComment(string text)
{
_wrapped.WriteComment(text);
}
public override void WriteProcessingInstruction(string name, string text)
{
_wrapped.WriteProcessingInstruction(name, text);
}
public override void WriteWhitespace(string ws)
{
_wrapped.WriteWhitespace(ws);
}
public override void WriteString(string text)
{
_wrapped.WriteString(text);
}
public override void WriteChars(char[] buffer, int index, int count)
{
_wrapped.WriteChars(buffer, index, count);
}
public override void WriteRaw(char[] buffer, int index, int count)
{
_wrapped.WriteRaw(buffer, index, count);
}
public override void WriteRaw(string data)
{
_wrapped.WriteRaw(data);
}
public override void WriteEntityRef(string name)
{
_wrapped.WriteEntityRef(name);
}
public override void WriteCharEntity(char ch)
{
_wrapped.WriteCharEntity(ch);
}
public override void WriteSurrogateCharEntity(char lowChar, char highChar)
{
_wrapped.WriteSurrogateCharEntity(lowChar, highChar);
}
public override void Close()
{
_wrapped.Close();
}
public override void Flush()
{
_wrapped.Flush();
}
public override void WriteValue(object value)
{
_wrapped.WriteValue(value);
}
public override void WriteValue(string value)
{
_wrapped.WriteValue(value);
}
public override void WriteValue(bool value)
{
_wrapped.WriteValue(value);
}
public override void WriteValue(DateTime value)
{
_wrapped.WriteValue(value);
}
public override void WriteValue(float value)
{
_wrapped.WriteValue(value);
}
public override void WriteValue(decimal value)
{
_wrapped.WriteValue(value);
}
public override void WriteValue(double value)
{
_wrapped.WriteValue(value);
}
public override void WriteValue(int value)
{
_wrapped.WriteValue(value);
}
public override void WriteValue(long value)
{
_wrapped.WriteValue(value);
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
((IDisposable)_wrapped).Dispose();
}
}
finally
{
base.Dispose(disposing);
}
}
//-----------------------------------------------
// XmlRawWriter interface
//-----------------------------------------------
/// <summary>
/// No-op.
/// </summary>
internal override void WriteXmlDeclaration(XmlStandalone standalone)
{
}
/// <summary>
/// No-op.
/// </summary>
internal override void WriteXmlDeclaration(string xmldecl)
{
}
/// <summary>
/// No-op.
/// </summary>
internal override void StartElementContent()
{
}
/// <summary>
/// Forward to WriteEndElement().
/// </summary>
internal override void WriteEndElement(string prefix, string localName, string ns)
{
_wrapped.WriteEndElement();
}
/// <summary>
/// Forward to WriteFullEndElement().
/// </summary>
internal override void WriteFullEndElement(string prefix, string localName, string ns)
{
_wrapped.WriteFullEndElement();
}
/// <summary>
/// Forward to WriteAttribute();
/// </summary>
internal override void WriteNamespaceDeclaration(string prefix, string ns)
{
if (prefix.Length == 0)
_wrapped.WriteAttributeString(string.Empty, "xmlns", XmlReservedNs.NsXmlNs, ns);
else
_wrapped.WriteAttributeString("xmlns", prefix, XmlReservedNs.NsXmlNs, ns);
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: UIntPtr
**
**
** Purpose: Platform independent integer
**
**
===========================================================*/
namespace System {
using System;
using System.Globalization;
using System.Runtime.Serialization;
using System.Security;
using System.Diagnostics.Contracts;
[Serializable]
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(true)]
public struct UIntPtr : ISerializable
{
[SecurityCritical]
unsafe private void* m_value;
public static readonly UIntPtr Zero;
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe UIntPtr(uint value)
{
m_value = (void *)value;
}
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe UIntPtr(ulong value)
{
#if WIN32
m_value = (void*)checked((uint)value);
#else
m_value = (void *)value;
#endif
}
[System.Security.SecurityCritical]
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public unsafe UIntPtr(void* value)
{
m_value = value;
}
[System.Security.SecurityCritical] // auto-generated
private unsafe UIntPtr(SerializationInfo info, StreamingContext context) {
ulong l = info.GetUInt64("value");
if (Size==4 && l>UInt32.MaxValue) {
throw new ArgumentException(Environment.GetResourceString("Serialization_InvalidPtrValue"));
}
m_value = (void *)l;
}
#if FEATURE_SERIALIZATION
[System.Security.SecurityCritical]
unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info==null) {
throw new ArgumentNullException("info");
}
Contract.EndContractBlock();
info.AddValue("value", (ulong)m_value);
}
#endif
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe override bool Equals(Object obj) {
if (obj is UIntPtr) {
return (m_value == ((UIntPtr)obj).m_value);
}
return false;
}
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe override int GetHashCode() {
return unchecked((int)((long)m_value)) & 0x7fffffff;
}
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe uint ToUInt32() {
#if WIN32
return (uint)m_value;
#else
return checked((uint)m_value);
#endif
}
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe ulong ToUInt64() {
return (ulong)m_value;
}
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe override String ToString() {
Contract.Ensures(Contract.Result<String>() != null);
#if WIN32
return ((uint)m_value).ToString(CultureInfo.InvariantCulture);
#else
return ((ulong)m_value).ToString(CultureInfo.InvariantCulture);
#endif
}
[System.Runtime.Versioning.NonVersionable]
public static explicit operator UIntPtr (uint value)
{
return new UIntPtr(value);
}
[System.Runtime.Versioning.NonVersionable]
public static explicit operator UIntPtr (ulong value)
{
return new UIntPtr(value);
}
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe static explicit operator uint(UIntPtr value)
{
#if WIN32
return (uint)value.m_value;
#else
return checked((uint)value.m_value);
#endif
}
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe static explicit operator ulong (UIntPtr value)
{
return (ulong)value.m_value;
}
[System.Security.SecurityCritical]
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public static unsafe explicit operator UIntPtr (void* value)
{
return new UIntPtr(value);
}
[System.Security.SecurityCritical]
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public static unsafe explicit operator void* (UIntPtr value)
{
return value.m_value;
}
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe static bool operator == (UIntPtr value1, UIntPtr value2)
{
return value1.m_value == value2.m_value;
}
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe static bool operator != (UIntPtr value1, UIntPtr value2)
{
return value1.m_value != value2.m_value;
}
[System.Runtime.Versioning.NonVersionable]
public static UIntPtr Add(UIntPtr pointer, int offset) {
return pointer + offset;
}
[System.Runtime.Versioning.NonVersionable]
public static UIntPtr operator +(UIntPtr pointer, int offset) {
#if WIN32
return new UIntPtr(pointer.ToUInt32() + (uint)offset);
#else
return new UIntPtr(pointer.ToUInt64() + (ulong)offset);
#endif
}
[System.Runtime.Versioning.NonVersionable]
public static UIntPtr Subtract(UIntPtr pointer, int offset) {
return pointer - offset;
}
[System.Runtime.Versioning.NonVersionable]
public static UIntPtr operator -(UIntPtr pointer, int offset) {
#if WIN32
return new UIntPtr(pointer.ToUInt32() - (uint)offset);
#else
return new UIntPtr(pointer.ToUInt64() - (ulong)offset);
#endif
}
public static int Size
{
[System.Runtime.Versioning.NonVersionable]
get
{
#if WIN32
return 4;
#else
return 8;
#endif
}
}
[System.Security.SecuritySafeCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public unsafe void* ToPointer()
{
return m_value;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Web.Script.Serialization;
// Note: To enable JSON (JavaScriptSerializer) add following reference: System.Web.Extensions
namespace OrderStreaming
{
public class hftRequest
{
public getAuthorizationChallengeRequest getAuthorizationChallenge { get; set; }
public getAuthorizationTokenRequest getAuthorizationToken { get; set; }
public getOrderRequest getOrder { get; set; }
}
public class hftResponse
{
public getAuthorizationChallengeResponse getAuthorizationChallengeResponse { get; set; }
public getAuthorizationTokenResponse getAuthorizationTokenResponse { get; set; }
public getOrderResponse getOrderResponse { get; set; }
}
public class getAuthorizationChallengeRequest
{
public string user { get; set; }
public getAuthorizationChallengeRequest(String user)
{
this.user = user;
}
}
public class getAuthorizationChallengeResponse
{
public string challenge { get; set; }
public string timestamp { get; set; }
}
public class getAuthorizationTokenRequest
{
public string user { get; set; }
public string challengeresp { get; set; }
public getAuthorizationTokenRequest(String user, String challengeresp)
{
this.user = user;
this.challengeresp = challengeresp;
}
}
public class getAuthorizationTokenResponse
{
public string token { get; set; }
public string timestamp { get; set; }
}
public class getOrderRequest
{
public string user { get; set; }
public string token { get; set; }
public List<string> security { get; set; }
public List<string> tinterface { get; set; }
public List<string> type { get; set; }
public int interval { get; set; }
public getOrderRequest(string user, string token, List<string> security, List<string> tinterface, List<string> type, int interval)
{
this.user = user;
this.token = token;
this.security = security;
this.tinterface = tinterface;
this.type = type;
this.interval = interval;
}
}
public class getOrderResponse
{
public int result { get; set; }
public string message { get; set; }
public List<orderTick> order { get; set; }
public orderHeartbeat heartbeat { get; set; }
public string timestamp { get; set; }
}
public class orderTick
{
public int tempid { get; set; }
public string orderid { get; set; }
public string fixid { get; set; }
public string account { get; set; }
public string tinterface { get; set; }
public string security { get; set; }
public int pips { get; set; }
public int quantity { get; set; }
public string side { get; set; }
public string type { get; set; }
public double limitprice { get; set; }
public int maxshowquantity { get; set; }
public string timeinforce { get; set; }
public int seconds { get; set; }
public int milliseconds { get; set; }
public string expiration { get; set; }
public double finishedprice { get; set; }
public int finishedquantity { get; set; }
public string commcurrency { get; set; }
public double commission { get; set; }
public double priceatstart { get; set; }
public int userparam { get; set; }
public string status { get; set; }
public string reason { get; set; }
}
public class orderHeartbeat
{
public List<string> security { get; set; }
public List<string> tinterface { get; set; }
}
class OrderStreaming
{
private static bool ssl = true;
private static String URL = "/getOrder";
private static String domain;
private static String url_stream;
//private static String url_polling;
private static String url_challenge;
private static String url_token;
private static String user;
private static String password;
private static String authentication_port;
private static String request_port;
private static String ssl_cert;
private static String challenge;
private static String token;
private static int interval;
public static void Exec()
{
// get properties from file
getProperties();
HttpWebRequest httpWebRequest;
JavaScriptSerializer serializer;
HttpWebResponse httpResponse;
X509Certificate certificate1 = null;
if (ssl)
{
using (WebClient client = new WebClient())
{
client.DownloadFile(ssl_cert, "ssl.cert");
}
certificate1 = new X509Certificate("ssl.cert");
}
// get challenge
httpWebRequest = (HttpWebRequest)WebRequest.Create(domain + ":" + authentication_port + url_challenge);
serializer = new JavaScriptSerializer();
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
if (ssl)
{
httpWebRequest.ClientCertificates.Add(certificate1);
}
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
hftRequest request = new hftRequest();
request.getAuthorizationChallenge = new getAuthorizationChallengeRequest(user);
streamWriter.WriteLine(serializer.Serialize(request));
}
httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
hftResponse response;
try
{
response = serializer.Deserialize<hftResponse>(streamReader.ReadLine());
challenge = response.getAuthorizationChallengeResponse.challenge;
}
catch (SocketException ex) { Console.WriteLine(ex.Message); }
catch (IOException ioex) { Console.WriteLine(ioex.Message); }
}
// create challenge response
String res = challenge;
char[] passwordArray = password.ToCharArray();
foreach (byte passwordLetter in passwordArray)
{
int value = Convert.ToInt32(passwordLetter);
string hexOutput = String.Format("{0:X}", value);
res = res + hexOutput;
}
int NumberChars = res.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
{
bytes[i / 2] = Convert.ToByte(res.Substring(i, 2), 16);
}
SHA1 sha = new SHA1CryptoServiceProvider();
byte[] tokenArray = sha.ComputeHash(bytes);
string challengeresp = BitConverter.ToString(tokenArray);
challengeresp = challengeresp.Replace("-", "");
// get token with challenge response
httpWebRequest = (HttpWebRequest)WebRequest.Create(domain + ":" + authentication_port + url_token);
serializer = new JavaScriptSerializer();
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
if (ssl)
{
httpWebRequest.ClientCertificates.Add(certificate1);
}
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
hftRequest request = new hftRequest();
request.getAuthorizationToken = new getAuthorizationTokenRequest(user, challengeresp);
streamWriter.WriteLine(serializer.Serialize(request));
}
httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
hftResponse response;
try
{
response = serializer.Deserialize<hftResponse>(streamReader.ReadLine());
token = response.getAuthorizationTokenResponse.token;
}
catch (SocketException ex) { Console.WriteLine(ex.Message); }
catch (IOException ioex) { Console.WriteLine(ioex.Message); }
}
// -----------------------------------------
// Prepare and send a order request
// -----------------------------------------
httpWebRequest = (HttpWebRequest)WebRequest.Create(domain + ":" + request_port + url_stream + URL);
serializer = new JavaScriptSerializer();
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
if (ssl)
{
httpWebRequest.ClientCertificates.Add(certificate1);
}
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
hftRequest request = new hftRequest();
request.getOrder = new getOrderRequest(user, token, new List<string> { "EUR/USD", "GBP/JPY", "GBP/USD" }, null, null, interval);
streamWriter.WriteLine(serializer.Serialize(request));
}
// --------------------------------------------------------------
// Wait for continuous responses from server (streaming)
// --------------------------------------------------------------
httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
hftResponse response;
String line;
try
{
while ((line = streamReader.ReadLine()) != null)
{
response = serializer.Deserialize<hftResponse>(line);
if (response.getOrderResponse != null)
{
if (response.getOrderResponse.timestamp != null)
{
Console.WriteLine("Response timestamp: " + response.getOrderResponse.timestamp + " Contents:");
}
if (response.getOrderResponse.order != null)
{
foreach (orderTick tick in response.getOrderResponse.order)
{
Console.WriteLine("TempId: " + tick.tempid + " OrderId: " + tick.orderid + " Security: " + tick.security + " Account: " + tick.account + " Quantity: " + tick.quantity + " Type: " + tick.type + " Side: " + tick.side + " Status: " + tick.status);
}
}
if (response.getOrderResponse.heartbeat != null)
{
Console.WriteLine("Heartbeat!");
}
if (response.getOrderResponse.message != null)
{
Console.WriteLine("Message from server: " + response.getOrderResponse.message);
}
}
}
}
catch (SocketException ex) { Console.WriteLine(ex.Message); }
catch (IOException ioex) { Console.WriteLine(ioex.Message); }
}
}
private static void getProperties()
{
try
{
foreach (var row in File.ReadAllLines("config.properties"))
{
//Console.WriteLine(row);
if ("url-stream".Equals(row.Split('=')[0]))
{
url_stream = row.Split('=')[1];
}
/*
if ("url-polling".Equals(row.Split('=')[0]))
{
url_polling = row.Split('=')[1];
}
*/
if ("url-challenge".Equals(row.Split('=')[0]))
{
url_challenge = row.Split('=')[1];
}
if ("url-token".Equals(row.Split('=')[0]))
{
url_token = row.Split('=')[1];
}
if ("user".Equals(row.Split('=')[0]))
{
user = row.Split('=')[1];
}
if ("password".Equals(row.Split('=')[0]))
{
password = row.Split('=')[1];
}
if ("interval".Equals(row.Split('=')[0]))
{
interval = Int32.Parse(row.Split('=')[1]);
}
if (ssl)
{
if ("ssl-domain".Equals(row.Split('=')[0]))
{
domain = row.Split('=')[1];
}
if ("ssl-authentication-port".Equals(row.Split('=')[0]))
{
authentication_port = row.Split('=')[1];
}
if ("ssl-request-port".Equals(row.Split('=')[0]))
{
request_port = row.Split('=')[1];
}
if ("ssl-cert".Equals(row.Split('=')[0]))
{
ssl_cert = row.Split('=')[1];
}
}
else
{
if ("domain".Equals(row.Split('=')[0]))
{
domain = row.Split('=')[1];
}
if ("authentication-port".Equals(row.Split('=')[0]))
{
authentication_port = row.Split('=')[1];
}
if ("request-port".Equals(row.Split('=')[0]))
{
request_port = row.Split('=')[1];
}
}
}
}
catch (IOException ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*=============================================================================
**
**
**
** Purpose: Class for creating and managing a threadpool
**
**
=============================================================================*/
#pragma warning disable 0420
/*
* Below you'll notice two sets of APIs that are separated by the
* use of 'Unsafe' in their names. The unsafe versions are called
* that because they do not propagate the calling stack onto the
* worker thread. This allows code to lose the calling stack and
* thereby elevate its security privileges. Note that this operation
* is much akin to the combined ability to control security policy
* and control security evidence. With these privileges, a person
* can gain the right to load assemblies that are fully trusted which
* then assert full trust and can call any code they want regardless
* of the previous stack information.
*/
using Internal.Runtime.Augments;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
namespace System.Threading
{
internal static class ThreadPoolGlobals
{
public static readonly int processorCount = Environment.ProcessorCount;
private static ThreadPoolWorkQueue _workQueue;
public static ThreadPoolWorkQueue workQueue
{
get
{
return LazyInitializer.EnsureInitialized(ref _workQueue, () => new ThreadPoolWorkQueue());
}
}
}
internal sealed class ThreadPoolWorkQueue
{
internal static class WorkStealingQueueList
{
private static volatile WorkStealingQueue[] _queues = new WorkStealingQueue[0];
public static WorkStealingQueue[] Queues => _queues;
public static void Add(WorkStealingQueue queue)
{
Debug.Assert(queue != null);
while (true)
{
WorkStealingQueue[] oldQueues = _queues;
Debug.Assert(Array.IndexOf(oldQueues, queue) == -1);
var newQueues = new WorkStealingQueue[oldQueues.Length + 1];
Array.Copy(oldQueues, 0, newQueues, 0, oldQueues.Length);
newQueues[newQueues.Length - 1] = queue;
if (Interlocked.CompareExchange(ref _queues, newQueues, oldQueues) == oldQueues)
{
break;
}
}
}
public static void Remove(WorkStealingQueue queue)
{
Debug.Assert(queue != null);
while (true)
{
WorkStealingQueue[] oldQueues = _queues;
if (oldQueues.Length == 0)
{
return;
}
int pos = Array.IndexOf(oldQueues, queue);
if (pos == -1)
{
Debug.Fail("Should have found the queue");
return;
}
var newQueues = new WorkStealingQueue[oldQueues.Length - 1];
if (pos == 0)
{
Array.Copy(oldQueues, 1, newQueues, 0, newQueues.Length);
}
else if (pos == oldQueues.Length - 1)
{
Array.Copy(oldQueues, 0, newQueues, 0, newQueues.Length);
}
else
{
Array.Copy(oldQueues, 0, newQueues, 0, pos);
Array.Copy(oldQueues, pos + 1, newQueues, pos, newQueues.Length - pos);
}
if (Interlocked.CompareExchange(ref _queues, newQueues, oldQueues) == oldQueues)
{
break;
}
}
}
}
internal sealed class WorkStealingQueue
{
private const int INITIAL_SIZE = 32;
internal volatile IThreadPoolWorkItem[] m_array = new IThreadPoolWorkItem[INITIAL_SIZE];
private volatile int m_mask = INITIAL_SIZE - 1;
#if DEBUG
// in debug builds, start at the end so we exercise the index reset logic.
private const int START_INDEX = int.MaxValue;
#else
private const int START_INDEX = 0;
#endif
private volatile int m_headIndex = START_INDEX;
private volatile int m_tailIndex = START_INDEX;
private SpinLock m_foreignLock = new SpinLock(enableThreadOwnerTracking: false);
public void LocalPush(IThreadPoolWorkItem obj)
{
int tail = m_tailIndex;
// We're going to increment the tail; if we'll overflow, then we need to reset our counts
if (tail == int.MaxValue)
{
bool lockTaken = false;
try
{
m_foreignLock.Enter(ref lockTaken);
if (m_tailIndex == int.MaxValue)
{
//
// Rather than resetting to zero, we'll just mask off the bits we don't care about.
// This way we don't need to rearrange the items already in the queue; they'll be found
// correctly exactly where they are. One subtlety here is that we need to make sure that
// if head is currently < tail, it remains that way. This happens to just fall out from
// the bit-masking, because we only do this if tail == int.MaxValue, meaning that all
// bits are set, so all of the bits we're keeping will also be set. Thus it's impossible
// for the head to end up > than the tail, since you can't set any more bits than all of
// them.
//
m_headIndex = m_headIndex & m_mask;
m_tailIndex = tail = m_tailIndex & m_mask;
Debug.Assert(m_headIndex <= m_tailIndex);
}
}
finally
{
if (lockTaken)
m_foreignLock.Exit(useMemoryBarrier: true);
}
}
// When there are at least 2 elements' worth of space, we can take the fast path.
if (tail < m_headIndex + m_mask)
{
Volatile.Write(ref m_array[tail & m_mask], obj);
m_tailIndex = tail + 1;
}
else
{
// We need to contend with foreign pops, so we lock.
bool lockTaken = false;
try
{
m_foreignLock.Enter(ref lockTaken);
int head = m_headIndex;
int count = m_tailIndex - m_headIndex;
// If there is still space (one left), just add the element.
if (count >= m_mask)
{
// We're full; expand the queue by doubling its size.
var newArray = new IThreadPoolWorkItem[m_array.Length << 1];
for (int i = 0; i < m_array.Length; i++)
newArray[i] = m_array[(i + head) & m_mask];
// Reset the field values, incl. the mask.
m_array = newArray;
m_headIndex = 0;
m_tailIndex = tail = count;
m_mask = (m_mask << 1) | 1;
}
Volatile.Write(ref m_array[tail & m_mask], obj);
m_tailIndex = tail + 1;
}
finally
{
if (lockTaken)
m_foreignLock.Exit(useMemoryBarrier: false);
}
}
}
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")]
public bool LocalFindAndPop(IThreadPoolWorkItem obj)
{
// Fast path: check the tail. If equal, we can skip the lock.
if (m_array[(m_tailIndex - 1) & m_mask] == obj)
{
IThreadPoolWorkItem unused = LocalPop();
Debug.Assert(unused == null || unused == obj);
return unused != null;
}
// Else, do an O(N) search for the work item. The theory of work stealing and our
// inlining logic is that most waits will happen on recently queued work. And
// since recently queued work will be close to the tail end (which is where we
// begin our search), we will likely find it quickly. In the worst case, we
// will traverse the whole local queue; this is typically not going to be a
// problem (although degenerate cases are clearly an issue) because local work
// queues tend to be somewhat shallow in length, and because if we fail to find
// the work item, we are about to block anyway (which is very expensive).
for (int i = m_tailIndex - 2; i >= m_headIndex; i--)
{
if (m_array[i & m_mask] == obj)
{
// If we found the element, block out steals to avoid interference.
bool lockTaken = false;
try
{
m_foreignLock.Enter(ref lockTaken);
// If we encountered a race condition, bail.
if (m_array[i & m_mask] == null)
return false;
// Otherwise, null out the element.
Volatile.Write(ref m_array[i & m_mask], null);
// And then check to see if we can fix up the indexes (if we're at
// the edge). If we can't, we just leave nulls in the array and they'll
// get filtered out eventually (but may lead to superflous resizing).
if (i == m_tailIndex)
m_tailIndex -= 1;
else if (i == m_headIndex)
m_headIndex += 1;
return true;
}
finally
{
if (lockTaken)
m_foreignLock.Exit(useMemoryBarrier: false);
}
}
}
return false;
}
public IThreadPoolWorkItem LocalPop() => m_headIndex < m_tailIndex ? LocalPopCore() : null;
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")]
private IThreadPoolWorkItem LocalPopCore()
{
while (true)
{
int tail = m_tailIndex;
if (m_headIndex >= tail)
{
return null;
}
// Decrement the tail using a fence to ensure subsequent read doesn't come before.
tail -= 1;
Interlocked.Exchange(ref m_tailIndex, tail);
// If there is no interaction with a take, we can head down the fast path.
if (m_headIndex <= tail)
{
int idx = tail & m_mask;
IThreadPoolWorkItem obj = Volatile.Read(ref m_array[idx]);
// Check for nulls in the array.
if (obj == null) continue;
m_array[idx] = null;
return obj;
}
else
{
// Interaction with takes: 0 or 1 elements left.
bool lockTaken = false;
try
{
m_foreignLock.Enter(ref lockTaken);
if (m_headIndex <= tail)
{
// Element still available. Take it.
int idx = tail & m_mask;
IThreadPoolWorkItem obj = Volatile.Read(ref m_array[idx]);
// Check for nulls in the array.
if (obj == null) continue;
m_array[idx] = null;
return obj;
}
else
{
// If we encountered a race condition and element was stolen, restore the tail.
m_tailIndex = tail + 1;
return null;
}
}
finally
{
if (lockTaken)
m_foreignLock.Exit(useMemoryBarrier: false);
}
}
}
}
public bool CanSteal => m_headIndex < m_tailIndex;
public IThreadPoolWorkItem TrySteal(ref bool missedSteal)
{
while (true)
{
if (CanSteal)
{
bool taken = false;
try
{
m_foreignLock.TryEnter(ref taken);
if (taken)
{
// Increment head, and ensure read of tail doesn't move before it (fence).
int head = m_headIndex;
Interlocked.Exchange(ref m_headIndex, head + 1);
if (head < m_tailIndex)
{
int idx = head & m_mask;
IThreadPoolWorkItem obj = Volatile.Read(ref m_array[idx]);
// Check for nulls in the array.
if (obj == null) continue;
m_array[idx] = null;
return obj;
}
else
{
// Failed, restore head.
m_headIndex = head;
}
}
}
finally
{
if (taken)
m_foreignLock.Exit(useMemoryBarrier: false);
}
missedSteal = true;
}
return null;
}
}
}
internal readonly LowLevelConcurrentQueue<IThreadPoolWorkItem> workItems = new LowLevelConcurrentQueue<IThreadPoolWorkItem>();
private volatile int numOutstandingThreadRequests = 0;
// The number of threads executing work items in the Dispatch method
internal volatile int numWorkingThreads;
public ThreadPoolWorkQueue()
{
}
public ThreadPoolWorkQueueThreadLocals EnsureCurrentThreadHasQueue() =>
ThreadPoolWorkQueueThreadLocals.threadLocals ??
(ThreadPoolWorkQueueThreadLocals.threadLocals = new ThreadPoolWorkQueueThreadLocals(this));
internal void EnsureThreadRequested()
{
//
// If we have not yet requested #procs threads, then request a new thread.
//
int count = numOutstandingThreadRequests;
while (count < ThreadPoolGlobals.processorCount)
{
int prev = Interlocked.CompareExchange(ref numOutstandingThreadRequests, count + 1, count);
if (prev == count)
{
ThreadPool.RequestWorkerThread();
break;
}
count = prev;
}
}
internal void MarkThreadRequestSatisfied()
{
//
// One of our outstanding thread requests has been satisfied.
// Decrement the count so that future calls to EnsureThreadRequested will succeed.
//
int count = numOutstandingThreadRequests;
while (count > 0)
{
int prev = Interlocked.CompareExchange(ref numOutstandingThreadRequests, count - 1, count);
if (prev == count)
{
break;
}
count = prev;
}
}
public void Enqueue(IThreadPoolWorkItem callback, bool forceGlobal)
{
ThreadPoolWorkQueueThreadLocals tl = null;
if (!forceGlobal)
tl = ThreadPoolWorkQueueThreadLocals.threadLocals;
if (null != tl)
{
tl.workStealingQueue.LocalPush(callback);
}
else
{
workItems.Enqueue(callback);
}
EnsureThreadRequested();
}
internal bool LocalFindAndPop(IThreadPoolWorkItem callback)
{
ThreadPoolWorkQueueThreadLocals tl = ThreadPoolWorkQueueThreadLocals.threadLocals;
return tl != null && tl.workStealingQueue.LocalFindAndPop(callback);
}
public IThreadPoolWorkItem Dequeue(ThreadPoolWorkQueueThreadLocals tl, ref bool missedSteal)
{
WorkStealingQueue localWsq = tl.workStealingQueue;
IThreadPoolWorkItem callback;
if ((callback = localWsq.LocalPop()) == null && // first try the local queue
!workItems.TryDequeue(out callback)) // then try the global queue
{
// finally try to steal from another thread's local queue
WorkStealingQueue[] queues = WorkStealingQueueList.Queues;
int c = queues.Length;
Debug.Assert(c > 0, "There must at least be a queue for this thread.");
int maxIndex = c - 1;
int i = tl.random.Next(c);
while (c > 0)
{
i = (i < maxIndex) ? i + 1 : 0;
WorkStealingQueue otherQueue = queues[i];
if (otherQueue != localWsq && otherQueue.CanSteal)
{
callback = otherQueue.TrySteal(ref missedSteal);
if (callback != null)
{
break;
}
}
c--;
}
}
return callback;
}
/// <summary>
/// Dispatches work items to this thread.
/// </summary>
/// <returns>
/// <c>true</c> if this thread did as much work as was available or its quantum expired.
/// <c>false</c> if this thread stopped working early.
/// </returns>
internal static bool Dispatch()
{
var workQueue = ThreadPoolGlobals.workQueue;
//
// Save the start time
//
int startTickCount = Environment.TickCount;
//
// Update our records to indicate that an outstanding request for a thread has now been fulfilled.
// From this point on, we are responsible for requesting another thread if we stop working for any
// reason, and we believe there might still be work in the queue.
//
workQueue.MarkThreadRequestSatisfied();
Interlocked.Increment(ref workQueue.numWorkingThreads);
//
// Assume that we're going to need another thread if this one returns to the VM. We'll set this to
// false later, but only if we're absolutely certain that the queue is empty.
//
bool needAnotherThread = true;
IThreadPoolWorkItem workItem = null;
try
{
//
// Set up our thread-local data
//
ThreadPoolWorkQueueThreadLocals tl = workQueue.EnsureCurrentThreadHasQueue();
//
// Loop until our quantum expires or there is no work.
//
while (ThreadPool.KeepDispatching(startTickCount))
{
bool missedSteal = false;
workItem = workQueue.Dequeue(tl, ref missedSteal);
if (workItem == null)
{
//
// No work.
// If we missed a steal, though, there may be more work in the queue.
// Instead of looping around and trying again, we'll just request another thread. Hopefully the thread
// that owns the contended work-stealing queue will pick up its own workitems in the meantime,
// which will be more efficient than this thread doing it anyway.
//
needAnotherThread = missedSteal;
// Tell the VM we're returning normally, not because Hill Climbing asked us to return.
return true;
}
//
// If we found work, there may be more work. Ask for another thread so that the other work can be processed
// in parallel. Note that this will only ask for a max of #procs threads, so it's safe to call it for every dequeue.
//
workQueue.EnsureThreadRequested();
try
{
SynchronizationContext.SetSynchronizationContext(null);
workItem.ExecuteWorkItem();
}
finally
{
workItem = null;
SynchronizationContext.SetSynchronizationContext(null);
}
RuntimeThread.CurrentThread.ResetThreadPoolThread();
if (!ThreadPool.NotifyWorkItemComplete())
return false;
}
// If we get here, it's because our quantum expired.
return true;
}
catch (Exception e)
{
// Work items should not allow exceptions to escape. For example, Task catches and stores any exceptions.
Environment.FailFast("Unhandled exception in ThreadPool dispatch loop", e);
return true; // Will never actually be executed because Environment.FailFast doesn't return
}
finally
{
int numWorkers = Interlocked.Decrement(ref workQueue.numWorkingThreads);
Debug.Assert(numWorkers >= 0);
//
// If we are exiting for any reason other than that the queue is definitely empty, ask for another
// thread to pick up where we left off.
//
if (needAnotherThread)
workQueue.EnsureThreadRequested();
}
}
}
// Simple random number generator. We don't need great randomness, we just need a little and for it to be fast.
internal struct FastRandom // xorshift prng
{
private uint _w, _x, _y, _z;
public FastRandom(int seed)
{
_x = (uint)seed;
_w = 88675123;
_y = 362436069;
_z = 521288629;
}
public int Next(int maxValue)
{
Debug.Assert(maxValue > 0);
uint t = _x ^ (_x << 11);
_x = _y; _y = _z; _z = _w;
_w = _w ^ (_w >> 19) ^ (t ^ (t >> 8));
return (int)(_w % (uint)maxValue);
}
}
// Holds a WorkStealingQueue, and remmoves it from the list when this object is no longer referened.
internal sealed class ThreadPoolWorkQueueThreadLocals
{
[ThreadStatic]
public static ThreadPoolWorkQueueThreadLocals threadLocals;
public readonly ThreadPoolWorkQueue workQueue;
public readonly ThreadPoolWorkQueue.WorkStealingQueue workStealingQueue;
public FastRandom random = new FastRandom(Environment.CurrentManagedThreadId); // mutable struct, do not copy or make readonly
public ThreadPoolWorkQueueThreadLocals(ThreadPoolWorkQueue tpq)
{
workQueue = tpq;
workStealingQueue = new ThreadPoolWorkQueue.WorkStealingQueue();
ThreadPoolWorkQueue.WorkStealingQueueList.Add(workStealingQueue);
}
private void CleanUp()
{
if (null != workStealingQueue)
{
if (null != workQueue)
{
IThreadPoolWorkItem cb;
while ((cb = workStealingQueue.LocalPop()) != null)
{
Debug.Assert(null != cb);
workQueue.Enqueue(cb, forceGlobal: true);
}
}
ThreadPoolWorkQueue.WorkStealingQueueList.Remove(workStealingQueue);
}
}
~ThreadPoolWorkQueueThreadLocals()
{
// Since the purpose of calling CleanUp is to transfer any pending workitems into the global
// queue so that they will be executed by another thread, there's no point in doing this cleanup
// if we're in the process of shutting down or unloading the AD. In those cases, the work won't
// execute anyway. And there are subtle races involved there that would lead us to do the wrong
// thing anyway. So we'll only clean up if this is a "normal" finalization.
if (!(Environment.HasShutdownStarted /*|| AppDomain.CurrentDomain.IsFinalizingForUnload()*/))
CleanUp();
}
}
public delegate void WaitCallback(Object state);
public delegate void WaitOrTimerCallback(Object state, bool timedOut); // signalled or timed out
//
// Interface to something that can be queued to the TP. This is implemented by
// QueueUserWorkItemCallback, Task, and potentially other internal types.
// For example, SemaphoreSlim represents callbacks using its own type that
// implements IThreadPoolWorkItem.
//
// If we decide to expose some of the workstealing
// stuff, this is NOT the thing we want to expose to the public.
//
internal interface IThreadPoolWorkItem
{
void ExecuteWorkItem();
}
internal abstract class QueueUserWorkItemCallbackBase : IThreadPoolWorkItem
{
#if DEBUG
private volatile int executed;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1821:RemoveEmptyFinalizers")]
~QueueUserWorkItemCallbackBase()
{
Debug.Assert(
executed != 0 || Environment.HasShutdownStarted /*|| AppDomain.CurrentDomain.IsFinalizingForUnload()*/,
"A QueueUserWorkItemCallback was never called!");
}
protected void MarkExecuted()
{
GC.SuppressFinalize(this);
Debug.Assert(
0 == Interlocked.Exchange(ref executed, 1),
"A QueueUserWorkItemCallback was called twice!");
}
#endif
public virtual void ExecuteWorkItem()
{
#if DEBUG
MarkExecuted();
#endif
}
}
internal sealed class QueueUserWorkItemCallback : QueueUserWorkItemCallbackBase
{
private WaitCallback _callback;
private readonly object _state;
private readonly ExecutionContext _context;
internal static readonly ContextCallback s_executionContextShim = state =>
{
var obj = (QueueUserWorkItemCallback)state;
WaitCallback c = obj._callback;
Debug.Assert(c != null);
obj._callback = null;
c(obj._state);
};
internal QueueUserWorkItemCallback(WaitCallback callback, object state, ExecutionContext context)
{
_callback = callback;
_state = state;
_context = context;
}
public override void ExecuteWorkItem()
{
base.ExecuteWorkItem();
try
{
if (_context == null)
{
WaitCallback c = _callback;
_callback = null;
c(_state);
}
else
{
ExecutionContext.Run(_context, s_executionContextShim, this);
}
}
catch (Exception e)
{
RuntimeAugments.ReportUnhandledException(e);
throw; //unreachable
}
}
}
internal sealed class QueueUserWorkItemCallback<TState> : QueueUserWorkItemCallbackBase
{
private Action<TState> _callback;
private readonly TState _state;
private readonly ExecutionContext _context;
internal static readonly ContextCallback s_executionContextShim = state =>
{
var obj = (QueueUserWorkItemCallback<TState>)state;
Action<TState> c = obj._callback;
Debug.Assert(c != null);
obj._callback = null;
c(obj._state);
};
internal QueueUserWorkItemCallback(Action<TState> callback, TState state, ExecutionContext context)
{
_callback = callback;
_state = state;
_context = context;
}
public override void ExecuteWorkItem()
{
base.ExecuteWorkItem();
try
{
if (_context == null)
{
Action<TState> c = _callback;
_callback = null;
c(_state);
}
else
{
ExecutionContext.RunInternal(_context, s_executionContextShim, this);
}
}
catch (Exception e)
{
RuntimeAugments.ReportUnhandledException(e);
throw; //unreachable
}
}
}
internal sealed class QueueUserWorkItemCallbackDefaultContext : QueueUserWorkItemCallbackBase
{
private WaitCallback _callback;
private readonly object _state;
internal static readonly ContextCallback s_executionContextShim = state =>
{
var obj = (QueueUserWorkItemCallbackDefaultContext)state;
WaitCallback c = obj._callback;
Debug.Assert(c != null);
obj._callback = null;
c(obj._state);
};
internal QueueUserWorkItemCallbackDefaultContext(WaitCallback callback, object state)
{
_callback = callback;
_state = state;
}
public override void ExecuteWorkItem()
{
base.ExecuteWorkItem();
try
{
ExecutionContext.Run(ExecutionContext.Default, s_executionContextShim, this);
}
catch (Exception e)
{
RuntimeAugments.ReportUnhandledException(e);
throw; //unreachable
}
}
}
internal sealed class QueueUserWorkItemCallbackDefaultContext<TState> : QueueUserWorkItemCallbackBase
{
private Action<TState> _callback;
private readonly TState _state;
internal static readonly ContextCallback s_executionContextShim = state =>
{
var obj = (QueueUserWorkItemCallbackDefaultContext<TState>)state;
Action<TState> c = obj._callback;
Debug.Assert(c != null);
obj._callback = null;
c(obj._state);
};
internal QueueUserWorkItemCallbackDefaultContext(Action<TState> callback, TState state)
{
_callback = callback;
_state = state;
}
public override void ExecuteWorkItem()
{
base.ExecuteWorkItem();
try
{
ExecutionContext.Run(ExecutionContext.Default, s_executionContextShim, this);
}
catch (Exception e)
{
RuntimeAugments.ReportUnhandledException(e);
throw; //unreachable
}
}
}
internal class _ThreadPoolWaitOrTimerCallback
{
private WaitOrTimerCallback _waitOrTimerCallback;
private ExecutionContext _executionContext;
private Object _state;
private static readonly ContextCallback _ccbt = new ContextCallback(WaitOrTimerCallback_Context_t);
private static readonly ContextCallback _ccbf = new ContextCallback(WaitOrTimerCallback_Context_f);
internal _ThreadPoolWaitOrTimerCallback(WaitOrTimerCallback waitOrTimerCallback, Object state, bool flowExecutionContext)
{
_waitOrTimerCallback = waitOrTimerCallback;
_state = state;
if (flowExecutionContext)
{
// capture the exection context
_executionContext = ExecutionContext.Capture();
}
}
private static void WaitOrTimerCallback_Context_t(Object state) =>
WaitOrTimerCallback_Context(state, timedOut: true);
private static void WaitOrTimerCallback_Context_f(Object state) =>
WaitOrTimerCallback_Context(state, timedOut: false);
private static void WaitOrTimerCallback_Context(Object state, bool timedOut)
{
_ThreadPoolWaitOrTimerCallback helper = (_ThreadPoolWaitOrTimerCallback)state;
helper._waitOrTimerCallback(helper._state, timedOut);
}
// call back helper
internal static void PerformWaitOrTimerCallback(_ThreadPoolWaitOrTimerCallback helper, bool timedOut)
{
Debug.Assert(helper != null, "Null state passed to PerformWaitOrTimerCallback!");
// call directly if it is an unsafe call OR EC flow is suppressed
if (helper._executionContext == null)
{
WaitOrTimerCallback callback = helper._waitOrTimerCallback;
callback(helper._state, timedOut);
}
else
{
ExecutionContext.Run(helper._executionContext, timedOut ? _ccbt : _ccbf, helper);
}
}
}
public static partial class ThreadPool
{
[CLSCompliant(false)]
public static RegisteredWaitHandle RegisterWaitForSingleObject(
WaitHandle waitObject,
WaitOrTimerCallback callBack,
Object state,
uint millisecondsTimeOutInterval,
bool executeOnlyOnce)
{
if (millisecondsTimeOutInterval > (uint)int.MaxValue && millisecondsTimeOutInterval != uint.MaxValue)
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
return RegisterWaitForSingleObject(waitObject, callBack, state, millisecondsTimeOutInterval, executeOnlyOnce, true);
}
[CLSCompliant(false)]
public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(
WaitHandle waitObject,
WaitOrTimerCallback callBack,
Object state,
uint millisecondsTimeOutInterval,
bool executeOnlyOnce)
{
if (millisecondsTimeOutInterval > (uint)int.MaxValue && millisecondsTimeOutInterval != uint.MaxValue)
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
return RegisterWaitForSingleObject(waitObject, callBack, state, millisecondsTimeOutInterval, executeOnlyOnce, false);
}
public static RegisteredWaitHandle RegisterWaitForSingleObject(
WaitHandle waitObject,
WaitOrTimerCallback callBack,
Object state,
int millisecondsTimeOutInterval,
bool executeOnlyOnce)
{
if (millisecondsTimeOutInterval < -1)
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)millisecondsTimeOutInterval, executeOnlyOnce, true);
}
public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(
WaitHandle waitObject,
WaitOrTimerCallback callBack,
Object state,
int millisecondsTimeOutInterval,
bool executeOnlyOnce)
{
if (millisecondsTimeOutInterval < -1)
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)millisecondsTimeOutInterval, executeOnlyOnce, false);
}
public static RegisteredWaitHandle RegisterWaitForSingleObject(
WaitHandle waitObject,
WaitOrTimerCallback callBack,
Object state,
long millisecondsTimeOutInterval,
bool executeOnlyOnce)
{
if (millisecondsTimeOutInterval < -1 || millisecondsTimeOutInterval > int.MaxValue)
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)millisecondsTimeOutInterval, executeOnlyOnce, true);
}
public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(
WaitHandle waitObject,
WaitOrTimerCallback callBack,
Object state,
long millisecondsTimeOutInterval,
bool executeOnlyOnce)
{
if (millisecondsTimeOutInterval < -1 || millisecondsTimeOutInterval > int.MaxValue)
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)millisecondsTimeOutInterval, executeOnlyOnce, false);
}
public static RegisteredWaitHandle RegisterWaitForSingleObject(
WaitHandle waitObject,
WaitOrTimerCallback callBack,
Object state,
TimeSpan timeout,
bool executeOnlyOnce)
{
int tm = WaitHandle.ToTimeoutMilliseconds(timeout);
return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)tm, executeOnlyOnce, true);
}
public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(
WaitHandle waitObject,
WaitOrTimerCallback callBack,
Object state,
TimeSpan timeout,
bool executeOnlyOnce)
{
int tm = WaitHandle.ToTimeoutMilliseconds(timeout);
return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)tm, executeOnlyOnce, false);
}
public static bool QueueUserWorkItem(WaitCallback callBack) =>
QueueUserWorkItem(callBack, null);
public static bool QueueUserWorkItem(WaitCallback callBack, object state)
{
if (callBack == null)
{
throw new ArgumentNullException(nameof(callBack));
}
ExecutionContext context = ExecutionContext.Capture();
IThreadPoolWorkItem tpcallBack = context == ExecutionContext.Default ?
new QueueUserWorkItemCallbackDefaultContext(callBack, state) :
(IThreadPoolWorkItem)new QueueUserWorkItemCallback(callBack, state, context);
ThreadPoolGlobals.workQueue.Enqueue(tpcallBack, forceGlobal: true);
return true;
}
public static bool QueueUserWorkItem<TState>(Action<TState> callBack, TState state, bool preferLocal)
{
if (callBack == null)
{
throw new ArgumentNullException(nameof(callBack));
}
ExecutionContext context = ExecutionContext.Capture();
IThreadPoolWorkItem tpcallBack = context == ExecutionContext.Default ?
new QueueUserWorkItemCallbackDefaultContext<TState>(callBack, state) :
(IThreadPoolWorkItem)new QueueUserWorkItemCallback<TState>(callBack, state, context);
ThreadPoolGlobals.workQueue.Enqueue(tpcallBack, forceGlobal: !preferLocal);
return true;
}
public static bool UnsafeQueueUserWorkItem(WaitCallback callBack, Object state)
{
if (callBack == null)
{
throw new ArgumentNullException(nameof(callBack));
}
IThreadPoolWorkItem tpcallBack = new QueueUserWorkItemCallback(callBack, state, null);
ThreadPoolGlobals.workQueue.Enqueue(tpcallBack, forceGlobal: true);
return true;
}
internal static void UnsafeQueueCustomWorkItem(IThreadPoolWorkItem workItem, bool forceGlobal)
{
Debug.Assert(null != workItem);
ThreadPoolGlobals.workQueue.Enqueue(workItem, forceGlobal);
}
// This method tries to take the target callback out of the current thread's queue.
internal static bool TryPopCustomWorkItem(IThreadPoolWorkItem workItem)
{
Debug.Assert(null != workItem);
return ThreadPoolGlobals.workQueue.LocalFindAndPop(workItem);
}
// Get all workitems. Called by TaskScheduler in its debugger hooks.
internal static IEnumerable<IThreadPoolWorkItem> GetQueuedWorkItems()
{
// Enumerate the global queue
foreach (IThreadPoolWorkItem workItem in ThreadPoolGlobals.workQueue.workItems)
{
yield return workItem;
}
// Enumerate each local queue
foreach (ThreadPoolWorkQueue.WorkStealingQueue wsq in ThreadPoolWorkQueue.WorkStealingQueueList.Queues)
{
if (wsq != null && wsq.m_array != null)
{
IThreadPoolWorkItem[] items = wsq.m_array;
for (int i = 0; i < items.Length; i++)
{
IThreadPoolWorkItem item = items[i];
if (item != null)
{
yield return item;
}
}
}
}
}
internal static IEnumerable<IThreadPoolWorkItem> GetLocallyQueuedWorkItems()
{
ThreadPoolWorkQueue.WorkStealingQueue wsq = ThreadPoolWorkQueueThreadLocals.threadLocals.workStealingQueue;
if (wsq != null && wsq.m_array != null)
{
IThreadPoolWorkItem[] items = wsq.m_array;
for (int i = 0; i < items.Length; i++)
{
IThreadPoolWorkItem item = items[i];
if (item != null)
yield return item;
}
}
}
internal static IEnumerable<IThreadPoolWorkItem> GetGloballyQueuedWorkItems() => ThreadPoolGlobals.workQueue.workItems;
private static object[] ToObjectArray(IEnumerable<IThreadPoolWorkItem> workitems)
{
int i = 0;
foreach (IThreadPoolWorkItem item in workitems)
{
i++;
}
object[] result = new object[i];
i = 0;
foreach (IThreadPoolWorkItem item in workitems)
{
if (i < result.Length) //just in case someone calls us while the queues are in motion
result[i] = item;
i++;
}
return result;
}
// This is the method the debugger will actually call, if it ends up calling
// into ThreadPool directly. Tests can use this to simulate a debugger, as well.
internal static object[] GetQueuedWorkItemsForDebugger() =>
ToObjectArray(GetQueuedWorkItems());
internal static object[] GetGloballyQueuedWorkItemsForDebugger() =>
ToObjectArray(GetGloballyQueuedWorkItems());
internal static object[] GetLocallyQueuedWorkItemsForDebugger() =>
ToObjectArray(GetLocallyQueuedWorkItems());
unsafe private static void NativeOverlappedCallback(object obj)
{
NativeOverlapped* overlapped = (NativeOverlapped*)(IntPtr)obj;
_IOCompletionCallback.PerformIOCompletionCallback(0, 0, overlapped);
}
[CLSCompliant(false)]
unsafe public static bool UnsafeQueueNativeOverlapped(NativeOverlapped* overlapped)
{
// OS doesn't signal handle, so do it here (CoreCLR does this assignment in ThreadPoolNative::CorPostQueuedCompletionStatus)
overlapped->InternalLow = (IntPtr)0;
// Both types of callbacks are executed on the same thread pool
return UnsafeQueueUserWorkItem(NativeOverlappedCallback, (IntPtr)overlapped);
}
[Obsolete("ThreadPool.BindHandle(IntPtr) has been deprecated. Please use ThreadPool.BindHandle(SafeHandle) instead.", false)]
public static bool BindHandle(IntPtr osHandle)
{
throw new PlatformNotSupportedException(SR.Arg_PlatformNotSupported); // Replaced by ThreadPoolBoundHandle.BindHandle
}
public static bool BindHandle(SafeHandle osHandle)
{
throw new PlatformNotSupportedException(SR.Arg_PlatformNotSupported); // Replaced by ThreadPoolBoundHandle.BindHandle
}
internal static bool IsThreadPoolThread { get { return ThreadPoolWorkQueueThreadLocals.threadLocals != null; } }
}
}
| |
namespace Scout
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Windows.Forms.ListViewGroup listViewGroup1 = new System.Windows.Forms.ListViewGroup("Coming Up", System.Windows.Forms.HorizontalAlignment.Left);
System.Windows.Forms.ListViewGroup listViewGroup2 = new System.Windows.Forms.ListViewGroup("Past Due", System.Windows.Forms.HorizontalAlignment.Left);
System.Windows.Forms.ListViewGroup listViewGroup3 = new System.Windows.Forms.ListViewGroup("Completed", System.Windows.Forms.HorizontalAlignment.Left);
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.tabs = new System.Windows.Forms.TabControl();
this.messageTab = new System.Windows.Forms.TabPage();
this.label = new System.Windows.Forms.Label();
this.newMessage = new Microsoft.Ink.InkEdit();
this.label3 = new System.Windows.Forms.Label();
this.messages = new Scout.MessageListControl();
this.comments = new Scout.MessageListControl();
this.todoTab = new System.Windows.Forms.TabPage();
this.linkLabel1 = new System.Windows.Forms.LinkLabel();
this.label1 = new System.Windows.Forms.Label();
this.addItem = new Microsoft.Ink.InkEdit();
this.toDoListControl1 = new Scout.ToDoListControl();
this.todoList = new System.Windows.Forms.ComboBox();
this.milestoneTab = new System.Windows.Forms.TabPage();
this.label2 = new System.Windows.Forms.Label();
this.addMilestone = new Microsoft.Ink.InkEdit();
this.listMilestones = new System.Windows.Forms.ListView();
this.columnHeader1 = new System.Windows.Forms.ColumnHeader();
this.Due = new System.Windows.Forms.ColumnHeader();
this.panel1 = new System.Windows.Forms.Panel();
this.label4 = new System.Windows.Forms.Label();
this.logout = new System.Windows.Forms.LinkLabel();
this.settings = new System.Windows.Forms.LinkLabel();
this.projects = new System.Windows.Forms.ComboBox();
this.menuMilestones = new System.Windows.Forms.ContextMenuStrip(this.components);
this.editToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.deleteThisMilesoneToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.label5 = new System.Windows.Forms.Label();
this.tabs.SuspendLayout();
this.messageTab.SuspendLayout();
this.todoTab.SuspendLayout();
this.milestoneTab.SuspendLayout();
this.panel1.SuspendLayout();
this.menuMilestones.SuspendLayout();
this.SuspendLayout();
//
// tabs
//
this.tabs.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tabs.Controls.Add(this.messageTab);
this.tabs.Controls.Add(this.todoTab);
this.tabs.Controls.Add(this.milestoneTab);
this.tabs.Font = new System.Drawing.Font("Lucida Sans Unicode", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.tabs.ItemSize = new System.Drawing.Size(120, 40);
this.tabs.Location = new System.Drawing.Point(0, 77);
this.tabs.Name = "tabs";
this.tabs.SelectedIndex = 0;
this.tabs.Size = new System.Drawing.Size(651, 499);
this.tabs.SizeMode = System.Windows.Forms.TabSizeMode.Fixed;
this.tabs.TabIndex = 0;
this.tabs.Selected += new System.Windows.Forms.TabControlEventHandler(this.tabs_Selected);
//
// messageTab
//
this.messageTab.BackColor = System.Drawing.Color.White;
this.messageTab.Controls.Add(this.label);
this.messageTab.Controls.Add(this.newMessage);
this.messageTab.Controls.Add(this.label3);
this.messageTab.Controls.Add(this.messages);
this.messageTab.Controls.Add(this.comments);
this.messageTab.Location = new System.Drawing.Point(4, 44);
this.messageTab.Name = "messageTab";
this.messageTab.Padding = new System.Windows.Forms.Padding(3);
this.messageTab.Size = new System.Drawing.Size(643, 451);
this.messageTab.TabIndex = 0;
this.messageTab.Text = "Messages";
//
// label
//
this.label.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.label.AutoSize = true;
this.label.Location = new System.Drawing.Point(9, 393);
this.label.Name = "label";
this.label.Size = new System.Drawing.Size(129, 20);
this.label.TabIndex = 4;
this.label.Text = "Add a message";
//
// newMessage
//
this.newMessage.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.newMessage.Location = new System.Drawing.Point(144, 374);
this.newMessage.Name = "newMessage";
this.newMessage.Size = new System.Drawing.Size(489, 67);
this.newMessage.TabIndex = 3;
this.newMessage.Text = "";
this.newMessage.UseMouseForInput = true;
this.newMessage.Recognition += new Microsoft.Ink.InkEditRecognitionEventHandler(this.newMessage_Recognition);
//
// label3
//
this.label3.AutoSize = true;
this.label3.ForeColor = System.Drawing.Color.DimGray;
this.label3.Location = new System.Drawing.Point(8, 6);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(281, 20);
this.label3.TabIndex = 2;
this.label3.Text = "Tap a message to view comments.";
//
// messages
//
this.messages.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.messages.AutoScroll = true;
this.messages.BackColor = System.Drawing.Color.Transparent;
this.messages.Location = new System.Drawing.Point(10, 42);
this.messages.Margin = new System.Windows.Forms.Padding(5);
this.messages.Name = "messages";
this.messages.Size = new System.Drawing.Size(623, 325);
this.messages.TabIndex = 0;
this.messages.MessageClicked += new System.EventHandler<Scout.MessageListEventArgs>(this.messages_MessageClicked);
this.messages.MouseClick += new System.Windows.Forms.MouseEventHandler(this.messages_MouseClick);
//
// comments
//
this.comments.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.comments.AutoScroll = true;
this.comments.BackColor = System.Drawing.Color.Transparent;
this.comments.Location = new System.Drawing.Point(10, 42);
this.comments.Margin = new System.Windows.Forms.Padding(8);
this.comments.Name = "comments";
this.comments.Size = new System.Drawing.Size(623, 322);
this.comments.TabIndex = 1;
this.comments.Visible = false;
this.comments.MessageClicked += new System.EventHandler<Scout.MessageListEventArgs>(this.comments_MessageClicked);
this.comments.MouseClick += new System.Windows.Forms.MouseEventHandler(this.comments_MouseClick);
//
// todoTab
//
this.todoTab.BackColor = System.Drawing.Color.White;
this.todoTab.Controls.Add(this.label5);
this.todoTab.Controls.Add(this.linkLabel1);
this.todoTab.Controls.Add(this.label1);
this.todoTab.Controls.Add(this.addItem);
this.todoTab.Controls.Add(this.toDoListControl1);
this.todoTab.Controls.Add(this.todoList);
this.todoTab.Location = new System.Drawing.Point(4, 44);
this.todoTab.Name = "todoTab";
this.todoTab.Padding = new System.Windows.Forms.Padding(3);
this.todoTab.Size = new System.Drawing.Size(643, 451);
this.todoTab.TabIndex = 1;
this.todoTab.Text = "To-Do";
//
// linkLabel1
//
this.linkLabel1.AutoSize = true;
this.linkLabel1.Location = new System.Drawing.Point(526, 24);
this.linkLabel1.Name = "linkLabel1";
this.linkLabel1.Size = new System.Drawing.Size(106, 20);
this.linkLabel1.TabIndex = 4;
this.linkLabel1.TabStop = true;
this.linkLabel1.Text = "Create list...";
this.linkLabel1.VisitedLinkColor = System.Drawing.Color.Blue;
this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked);
//
// label1
//
this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(8, 397);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(105, 20);
this.label1.TabIndex = 2;
this.label1.Text = "Add an item";
//
// addItem
//
this.addItem.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.addItem.Location = new System.Drawing.Point(119, 376);
this.addItem.Name = "addItem";
this.addItem.Size = new System.Drawing.Size(513, 67);
this.addItem.TabIndex = 2;
this.addItem.Text = "";
this.addItem.UseMouseForInput = true;
this.addItem.Recognition += new Microsoft.Ink.InkEditRecognitionEventHandler(this.addItem_Recognition);
//
// toDoListControl1
//
this.toDoListControl1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.toDoListControl1.AutoScroll = true;
this.toDoListControl1.BackColor = System.Drawing.Color.White;
this.toDoListControl1.Location = new System.Drawing.Point(8, 90);
this.toDoListControl1.Margin = new System.Windows.Forms.Padding(0);
this.toDoListControl1.Name = "toDoListControl1";
this.toDoListControl1.Size = new System.Drawing.Size(624, 269);
this.toDoListControl1.TabIndex = 3;
//
// todoList
//
this.todoList.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.todoList.FormattingEnabled = true;
this.todoList.Location = new System.Drawing.Point(8, 16);
this.todoList.Name = "todoList";
this.todoList.Size = new System.Drawing.Size(471, 28);
this.todoList.TabIndex = 0;
//
// milestoneTab
//
this.milestoneTab.BackColor = System.Drawing.Color.White;
this.milestoneTab.Controls.Add(this.label2);
this.milestoneTab.Controls.Add(this.addMilestone);
this.milestoneTab.Controls.Add(this.listMilestones);
this.milestoneTab.Location = new System.Drawing.Point(4, 44);
this.milestoneTab.Name = "milestoneTab";
this.milestoneTab.Padding = new System.Windows.Forms.Padding(3);
this.milestoneTab.Size = new System.Drawing.Size(643, 451);
this.milestoneTab.TabIndex = 2;
this.milestoneTab.Text = "Milestones";
//
// label2
//
this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.label2.Location = new System.Drawing.Point(8, 365);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(94, 54);
this.label2.TabIndex = 6;
this.label2.Text = "Add a new milestone";
//
// addMilestone
//
this.addMilestone.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.addMilestone.Location = new System.Drawing.Point(108, 350);
this.addMilestone.Name = "addMilestone";
this.addMilestone.Size = new System.Drawing.Size(513, 79);
this.addMilestone.TabIndex = 5;
this.addMilestone.Text = "";
this.addMilestone.UseMouseForInput = true;
this.addMilestone.Recognition += new Microsoft.Ink.InkEditRecognitionEventHandler(this.addMilestone_Recognition);
//
// listMilestones
//
this.listMilestones.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.listMilestones.CheckBoxes = true;
this.listMilestones.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader1,
this.Due});
this.listMilestones.FullRowSelect = true;
listViewGroup1.Header = "Coming Up";
listViewGroup1.Name = "groupComingUp";
listViewGroup2.Header = "Past Due";
listViewGroup2.Name = "groupPast";
listViewGroup3.Header = "Completed";
listViewGroup3.Name = "groupCompleted";
this.listMilestones.Groups.AddRange(new System.Windows.Forms.ListViewGroup[] {
listViewGroup1,
listViewGroup2,
listViewGroup3});
this.listMilestones.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None;
this.listMilestones.Location = new System.Drawing.Point(8, 28);
this.listMilestones.Name = "listMilestones";
this.listMilestones.Size = new System.Drawing.Size(613, 304);
this.listMilestones.TabIndex = 0;
this.listMilestones.UseCompatibleStateImageBehavior = false;
this.listMilestones.View = System.Windows.Forms.View.Details;
this.listMilestones.MouseClick += new System.Windows.Forms.MouseEventHandler(this.listMilestones_MouseClick);
//
// columnHeader1
//
this.columnHeader1.Text = "Milestone";
//
// panel1
//
this.panel1.Controls.Add(this.label4);
this.panel1.Controls.Add(this.logout);
this.panel1.Controls.Add(this.settings);
this.panel1.Controls.Add(this.projects);
this.panel1.Dock = System.Windows.Forms.DockStyle.Top;
this.panel1.Location = new System.Drawing.Point(0, 0);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(651, 77);
this.panel1.TabIndex = 1;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Font = new System.Drawing.Font("Lucida Sans Unicode", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label4.ForeColor = System.Drawing.Color.White;
this.label4.Location = new System.Drawing.Point(13, 26);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(63, 16);
this.label4.TabIndex = 2;
this.label4.Text = "Project:";
//
// logout
//
this.logout.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.logout.AutoSize = true;
this.logout.Font = new System.Drawing.Font("Lucida Sans Unicode", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.logout.LinkColor = System.Drawing.Color.WhiteSmoke;
this.logout.Location = new System.Drawing.Point(564, 28);
this.logout.Name = "logout";
this.logout.Size = new System.Drawing.Size(60, 16);
this.logout.TabIndex = 1;
this.logout.TabStop = true;
this.logout.Text = "Log-out";
this.logout.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.logout_LinkClicked);
//
// settings
//
this.settings.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.settings.AutoSize = true;
this.settings.Font = new System.Drawing.Font("Lucida Sans Unicode", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.settings.LinkColor = System.Drawing.Color.WhiteSmoke;
this.settings.Location = new System.Drawing.Point(489, 28);
this.settings.Name = "settings";
this.settings.Size = new System.Drawing.Size(59, 16);
this.settings.TabIndex = 1;
this.settings.TabStop = true;
this.settings.Text = "Settings";
this.settings.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.settings_LinkClicked);
//
// projects
//
this.projects.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.projects.Font = new System.Drawing.Font("Lucida Sans Unicode", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.projects.FormattingEnabled = true;
this.projects.Location = new System.Drawing.Point(86, 21);
this.projects.Name = "projects";
this.projects.Size = new System.Drawing.Size(372, 28);
this.projects.TabIndex = 0;
this.projects.SelectedIndexChanged += new System.EventHandler(this.projects_SelectedIndexChanged);
//
// menuMilestones
//
this.menuMilestones.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.editToolStripMenuItem,
this.deleteThisMilesoneToolStripMenuItem});
this.menuMilestones.Name = "menuMilestones";
this.menuMilestones.Size = new System.Drawing.Size(181, 48);
//
// editToolStripMenuItem
//
this.editToolStripMenuItem.Name = "editToolStripMenuItem";
this.editToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.editToolStripMenuItem.Text = "Edit this milesone...";
this.editToolStripMenuItem.Click += new System.EventHandler(this.editToolStripMenuItem_Click);
//
// deleteThisMilesoneToolStripMenuItem
//
this.deleteThisMilesoneToolStripMenuItem.Name = "deleteThisMilesoneToolStripMenuItem";
this.deleteThisMilesoneToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.deleteThisMilesoneToolStripMenuItem.Text = "&Delete this milesone";
this.deleteThisMilesoneToolStripMenuItem.Click += new System.EventHandler(this.deleteThisMilesoneToolStripMenuItem_Click);
//
// label5
//
this.label5.AutoSize = true;
this.label5.ForeColor = System.Drawing.Color.DimGray;
this.label5.Location = new System.Drawing.Point(8, 61);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(421, 20);
this.label5.TabIndex = 5;
this.label5.Text = "Tap-and-hold an item to change who\'s responsible.";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.Black;
this.ClientSize = new System.Drawing.Size(651, 576);
this.Controls.Add(this.tabs);
this.Controls.Add(this.panel1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Scout";
this.Load += new System.EventHandler(this.Form1_Load);
this.tabs.ResumeLayout(false);
this.messageTab.ResumeLayout(false);
this.messageTab.PerformLayout();
this.todoTab.ResumeLayout(false);
this.todoTab.PerformLayout();
this.milestoneTab.ResumeLayout(false);
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.menuMilestones.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TabControl tabs;
private System.Windows.Forms.TabPage messageTab;
private System.Windows.Forms.TabPage todoTab;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.ComboBox projects;
private System.Windows.Forms.TabPage milestoneTab;
private System.Windows.Forms.ComboBox todoList;
private System.Windows.Forms.Label label1;
private Microsoft.Ink.InkEdit addItem;
private ToDoListControl toDoListControl1;
private System.Windows.Forms.ListView listMilestones;
private System.Windows.Forms.ColumnHeader columnHeader1;
private System.Windows.Forms.ColumnHeader Due;
private System.Windows.Forms.Label label2;
private Microsoft.Ink.InkEdit addMilestone;
private System.Windows.Forms.ContextMenuStrip menuMilestones;
private System.Windows.Forms.ToolStripMenuItem editToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem deleteThisMilesoneToolStripMenuItem;
private System.Windows.Forms.LinkLabel linkLabel1;
private MessageListControl messages;
private MessageListControl comments;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.LinkLabel settings;
private System.Windows.Forms.LinkLabel logout;
private System.Windows.Forms.Label label;
private Microsoft.Ink.InkEdit newMessage;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label5;
}
}
| |
namespace System.Web.Services.Description {
using System.Xml;
using System.IO;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.ComponentModel;
using System.Text;
using System.Web.Services.Configuration;
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapBinding"]/*' />
[XmlFormatExtension("binding", SoapBinding.Namespace, typeof(Binding))]
[XmlFormatExtensionPrefix("soap", SoapBinding.Namespace)]
[XmlFormatExtensionPrefix("soapenc", "http://schemas.xmlsoap.org/soap/encoding/")]
public class SoapBinding : ServiceDescriptionFormatExtension {
SoapBindingStyle style = SoapBindingStyle.Document;
string transport;
static XmlSchema schema = null;
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapBinding.Namespace"]/*' />
public const string Namespace = "http://schemas.xmlsoap.org/wsdl/soap/";
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapBinding.HttpTransport"]/*' />
public const string HttpTransport = "http://schemas.xmlsoap.org/soap/http";
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapBinding.Transport"]/*' />
[XmlAttribute("transport")]
public string Transport {
get { return transport == null ? string.Empty : transport; }
set { transport = value; }
}
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapBinding.Style"]/*' />
[XmlAttribute("style"), DefaultValue(SoapBindingStyle.Document)]
public SoapBindingStyle Style {
get { return style; }
set { style = value; }
}
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapFormatExtensions.Schema"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static XmlSchema Schema {
get {
if (schema == null) {
schema = XmlSchema.Read(new StringReader(Schemas.Soap), null);
}
return schema;
}
}
}
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapBindingStyle"]/*' />
public enum SoapBindingStyle {
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapBindingStyle.Default"]/*' />
[XmlIgnore]
Default,
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapBindingStyle.Document"]/*' />
[XmlEnum("document")]
Document,
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapBindingStyle.Rpc"]/*' />
[XmlEnum("rpc")]
Rpc,
}
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapOperationBinding"]/*' />
[XmlFormatExtension("operation", SoapBinding.Namespace, typeof(OperationBinding))]
public class SoapOperationBinding : ServiceDescriptionFormatExtension {
string soapAction;
SoapBindingStyle style;
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapOperationBinding.SoapAction"]/*' />
[XmlAttribute("soapAction")]
public string SoapAction {
get { return soapAction == null ? string.Empty : soapAction; }
set { soapAction = value; }
}
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapOperationBinding.Style"]/*' />
[XmlAttribute("style"), DefaultValue(SoapBindingStyle.Default)]
public SoapBindingStyle Style {
get { return style; }
set { style = value; }
}
}
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapBodyBinding"]/*' />
[XmlFormatExtension("body", SoapBinding.Namespace, typeof(InputBinding), typeof(OutputBinding), typeof(MimePart))]
public class SoapBodyBinding : ServiceDescriptionFormatExtension {
SoapBindingUse use;
string ns;
string encoding;
string[] parts;
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapBodyBinding.Use"]/*' />
[XmlAttribute("use"), DefaultValue(SoapBindingUse.Default)]
public SoapBindingUse Use {
get { return use; }
set { use = value; }
}
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapBodyBinding.Namespace"]/*' />
[XmlAttribute("namespace"), DefaultValue("")]
public string Namespace {
get { return ns == null ? string.Empty : ns; }
set { ns = value; }
}
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapBodyBinding.Encoding"]/*' />
[XmlAttribute("encodingStyle"), DefaultValue("")]
public string Encoding {
get { return encoding == null ? string.Empty : encoding; }
set { encoding = value; }
}
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapBodyBinding.PartsString"]/*' />
[XmlAttribute("parts")]
public string PartsString {
get {
if (parts == null)
return null;
StringBuilder builder = new StringBuilder();
for (int i = 0; i < parts.Length; i++) {
if (i > 0) builder.Append(' ');
builder.Append(parts[i]);
}
return builder.ToString();
}
set {
if (value == null)
parts = null;
else
parts = value.Split(new char[] { ' ' });
}
}
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapBodyBinding.Parts"]/*' />
[XmlIgnore]
public string[] Parts {
get { return parts; }
set { parts = value; }
}
}
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapBindingUse"]/*' />
public enum SoapBindingUse {
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapBindingUse.Default"]/*' />
[XmlIgnore]
Default,
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapBindingUse.Encoded"]/*' />
[XmlEnum("encoded")]
Encoded,
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapBindingUse.Literal"]/*' />
[XmlEnum("literal")]
Literal,
}
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapFaultBinding"]/*' />
[XmlFormatExtension("fault", SoapBinding.Namespace, typeof(FaultBinding))]
public class SoapFaultBinding : ServiceDescriptionFormatExtension {
SoapBindingUse use;
string ns;
string encoding;
string name;
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapFaultBinding.Use"]/*' />
[XmlAttribute("use"), DefaultValue(SoapBindingUse.Default)]
public SoapBindingUse Use {
get { return use; }
set { use = value; }
}
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapFaultBinding.Use"]/*' />
[XmlAttribute("name")]
public string Name {
get { return name; }
set { name = value; }
}
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapFaultBinding.Namespace"]/*' />
[XmlAttribute("namespace")]
public string Namespace {
get { return ns == null ? string.Empty : ns; }
set { ns = value; }
}
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapFaultBinding.Encoding"]/*' />
[XmlAttribute("encodingStyle"), DefaultValue("")]
public string Encoding {
get { return encoding == null ? string.Empty : encoding; }
set { encoding = value; }
}
}
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapHeaderBinding"]/*' />
[XmlFormatExtension("header", SoapBinding.Namespace, typeof(InputBinding), typeof(OutputBinding))]
public class SoapHeaderBinding : ServiceDescriptionFormatExtension {
XmlQualifiedName message = XmlQualifiedName.Empty;
string part;
SoapBindingUse use;
string encoding;
string ns;
bool mapToProperty;
SoapHeaderFaultBinding fault;
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapHeaderBinding.MapToProperty"]/*' />
[XmlIgnore]
public bool MapToProperty {
get { return mapToProperty; }
set { mapToProperty = value; }
}
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapHeaderBinding.Message"]/*' />
[XmlAttribute("message")]
public XmlQualifiedName Message {
get { return message; }
set { message = value; }
}
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapHeaderBinding.Part"]/*' />
[XmlAttribute("part")]
public string Part {
get { return part; }
set { part = value; }
}
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapHeaderBinding.Use"]/*' />
[XmlAttribute("use"), DefaultValue(SoapBindingUse.Default)]
public SoapBindingUse Use {
get { return use; }
set { use = value; }
}
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapHeaderBinding.Encoding"]/*' />
[XmlAttribute("encodingStyle"), DefaultValue("")]
public string Encoding {
get { return encoding == null ? string.Empty : encoding; }
set { encoding = value; }
}
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapHeaderBinding.Namespace"]/*' />
[XmlAttribute("namespace"), DefaultValue("")]
public string Namespace {
get { return ns == null ? string.Empty : ns; }
set { ns = value; }
}
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapHeaderBinding.Fault"]/*' />
[XmlElement("headerfault")]
public SoapHeaderFaultBinding Fault {
get { return fault; }
set { fault = value; }
}
}
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapHeaderFaultBinding"]/*' />
public class SoapHeaderFaultBinding : ServiceDescriptionFormatExtension {
XmlQualifiedName message = XmlQualifiedName.Empty;
string part;
SoapBindingUse use;
string encoding;
string ns;
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapHeaderFaultBinding.Message"]/*' />
[XmlAttribute("message")]
public XmlQualifiedName Message {
get { return message; }
set { message = value; }
}
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapHeaderFaultBinding.Part"]/*' />
[XmlAttribute("part")]
public string Part {
get { return part; }
set { part = value; }
}
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapHeaderFaultBinding.Use"]/*' />
[XmlAttribute("use"), DefaultValue(SoapBindingUse.Default)]
public SoapBindingUse Use {
get { return use; }
set { use = value; }
}
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapHeaderFaultBinding.Encoding"]/*' />
[XmlAttribute("encodingStyle"), DefaultValue("")]
public string Encoding {
get { return encoding == null ? string.Empty : encoding; }
set { encoding = value; }
}
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapHeaderFaultBinding.Namespace"]/*' />
[XmlAttribute("namespace"), DefaultValue("")]
public string Namespace {
get { return ns == null ? string.Empty : ns; }
set { ns = value; }
}
}
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapAddressBinding"]/*' />
[XmlFormatExtension("address", SoapBinding.Namespace, typeof(Port))]
public class SoapAddressBinding : ServiceDescriptionFormatExtension {
string location;
/// <include file='doc\SoapFormatExtensions.uex' path='docs/doc[@for="SoapAddressBinding.Location"]/*' />
[XmlAttribute("location")]
public string Location {
get { return location == null ? string.Empty : location; }
set { location = value; }
}
}
}
| |
using FCT.LLC.GenericRepository;
namespace FCT.LLC.BusinessService.Entities
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.CodeDom.Compiler;
using System.Diagnostics;
using System.Runtime.Serialization;
[DataContract]
[DebuggerStepThrough]
[GeneratedCode("System.Runtime.Serialization", "4.0.0.0")]
[Table("tblProperty")]
public partial class tblProperty
{
public tblProperty()
{
tblPINs = new HashSet<tblPIN>();
tblBuilderLegalDescriptions = new HashSet<tblBuilderLegalDescription>();
}
[DataMember]
//[Key, ForeignKey("tblBuilderLegalDescription")]
[Key]
public int PropertyID { get; set; }
[DataMember]
public int DealID { get; set; }
[DataMember]
[StringLength(100)]
public string Address { get; set; }
[DataMember]
[StringLength(100)]
public string City { get; set; }
[DataMember]
[StringLength(2)]
public string Province { get; set; }
[StringLength(10)]
public string PostalCode { get; set; }
[DataMember]
[StringLength(15)]
public string HomePhone { get; set; }
[DataMember]
[StringLength(15)]
public string BusinessPhone { get; set; }
[DataMember]
[StringLength(4000)]
public string LegalDescription { get; set; }
[DataMember]
[StringLength(250)]
public string ARN { get; set; }
[DataMember]
public bool? IsCondo { get; set; }
[DataMember]
[StringLength(50)]
public string EstateType { get; set; }
[DataMember]
[StringLength(50)]
public string InstrumentNumber { get; set; }
[DataMember]
[Column(TypeName = "smalldatetime")]
public DateTime? RegistrationDate { get; set; }
[DataMember]
[Column(TypeName = "money")]
public decimal? AmountOfTaxesPaid { get; set; }
[DataMember]
public bool? TaxesPaidOnClosing { get; set; }
[DataMember]
[StringLength(50)]
public string PropertyType { get; set; }
[DataMember]
public int? NumberOfUnits { get; set; }
[DataMember]
[StringLength(50)]
public string OccupancyType { get; set; }
[DataMember]
public bool? IsNewHome { get; set; }
[DataMember]
[Column(TypeName = "money")]
public decimal? AnnualTaxAmount { get; set; }
[DataMember]
public bool? IsPrimaryProperty { get; set; }
[DataMember]
public bool? IsLenderToCollectPropertyTaxes { get; set; }
[DataMember]
[StringLength(100)]
public string RegistryOffice { get; set; }
[DataMember]
[StringLength(50)]
public string CondoLevel { get; set; }
[DataMember]
[StringLength(30)]
public string CondoUnitNumber { get; set; }
[DataMember]
[StringLength(50)]
public string CondoCorporationNumber { get; set; }
[DataMember]
[Column(TypeName = "timestamp")]
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
[MaxLength(8)]
public byte[] LastModified { get; set; }
[DataMember]
[StringLength(25)]
public string UnitNumber { get; set; }
[DataMember]
[StringLength(25)]
public string StreetNumber { get; set; }
[DataMember]
[StringLength(100)]
public string Address2 { get; set; }
[DataMember]
[StringLength(50)]
public string Country { get; set; }
[DataMember]
[StringLength(20)]
public string BookFolioRoll { get; set; }
[DataMember]
[StringLength(20)]
public string PageFrame { get; set; }
[DataMember]
[StringLength(50)]
public string CondoDeclarationRegistrationNumber { get; set; }
[DataMember]
[Column(TypeName = "smalldatetime")]
public DateTime? CondoDeclarationRegistrationDate { get; set; }
[DataMember]
[StringLength(100)]
public string CondoBookNoOfDeclaration { get; set; }
[DataMember]
[StringLength(100)]
public string CondoPageNumberOfDeclaration { get; set; }
[DataMember]
[Column(TypeName = "smalldatetime")]
public DateTime? CondoDeclarationAcceptedDate { get; set; }
[DataMember]
[Column(TypeName = "smalldatetime")]
public DateTime? CondoPlanRegistrationDate { get; set; }
[DataMember]
[Column(TypeName = "smalldatetime")]
public DateTime? CondoDeclarationDate { get; set; }
[DataMember]
[StringLength(50)]
public string CondoPlanNumber { get; set; }
[DataMember]
[StringLength(25)]
public string AssignmentOfRentsRegistrationNumber { get; set; }
[DataMember]
public bool? RentAssignment { get; set; }
[DataMember]
public int? LenderPropertyID { get; set; }
[DataMember]
[StringLength(10)]
public string MortgagePriority { get; set; }
[DataMember]
[StringLength(100)]
public string OtherEstateTypeDescription { get; set; }
[DataMember]
[StringLength(255)]
public string Municipality { get; set; }
[DataMember]
[StringLength(100)]
public string CondoDeclarationModificationNumber { get; set; }
[DataMember]
[StringLength(100)]
public string JudicialDistrict { get; set; }
[DataMember]
[Column(TypeName = "smalldatetime")]
public DateTime? CondoDeclarationModificationDate { get; set; }
[DataMember]
public bool? IsCondominium { get; set; }
[DataMember]
public DateTime? AssignmentOfRentsRegistrationDate { get; set; }
[DataMember]
public bool? NewHomeWarranty { get; set; }
[DataMember]
public DateTime? TaxesPaidToDate { get; set; }
[DataMember]
public virtual tblDeal tblDeal { get; set; }
[DataMember]
public virtual vw_Deal vw_Deal { get; set; }
[DataMember]
public virtual ICollection<tblPIN> tblPINs { get; set; }
[DataMember]
public virtual ICollection<tblBuilderLegalDescription> tblBuilderLegalDescriptions { get; set; }
}
}
| |
// ***********************************************************************
// Copyright (c) 2011 Charlie Poole
//
// 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.IO;
using System.Reflection;
using NUnit.Common;
using NUnit.Options;
namespace NUnit.ConsoleRunner.Tests
{
using System.Collections.Generic;
using Framework;
[TestFixture]
public class CommandLineTests
{
#region General Tests
[Test]
public void NoInputFiles()
{
ConsoleOptions options = new ConsoleOptions();
Assert.True(options.Validate());
Assert.AreEqual(0, options.InputFiles.Count);
}
[TestCase("ShowHelp", "help|h")]
[TestCase("ShowVersion", "version|V")]
[TestCase("StopOnError", "stoponerror")]
[TestCase("WaitBeforeExit", "wait")]
[TestCase("NoHeader", "noheader|noh")]
[TestCase("RunAsX86", "x86")]
[TestCase("DisposeRunners", "dispose-runners")]
[TestCase("ShadowCopyFiles", "shadowcopy")]
[TestCase("TeamCity", "teamcity")]
[TestCase("DebugTests", "debug")]
[TestCase("PauseBeforeRun", "pause")]
[TestCase("LoadUserProfile", "loaduserprofile")]
#if DEBUG
[TestCase("DebugAgent", "debug-agent")]
#endif
public void CanRecognizeBooleanOptions(string propertyName, string pattern)
{
string[] prototypes = pattern.Split('|');
PropertyInfo property = GetPropertyInfo(propertyName);
Assert.AreEqual(typeof(bool), property.PropertyType, "Property '{0}' is wrong type", propertyName);
foreach (string option in prototypes)
{
ConsoleOptions options;
if (option.Length == 1)
{
options = new ConsoleOptions("-" + option);
Assert.AreEqual(true, (bool)property.GetValue(options, null), "Didn't recognize -" + option);
options = new ConsoleOptions("-" + option + "+");
Assert.AreEqual(true, (bool)property.GetValue(options, null), "Didn't recognize -" + option + "+");
options = new ConsoleOptions("-" + option + "-");
Assert.AreEqual(false, (bool)property.GetValue(options, null), "Didn't recognize -" + option + "-");
}
else
{
options = new ConsoleOptions("--" + option);
Assert.AreEqual(true, (bool)property.GetValue(options, null), "Didn't recognize --" + option);
}
options = new ConsoleOptions("/" + option);
Assert.AreEqual(true, (bool)property.GetValue(options, null), "Didn't recognize /" + option);
}
}
[TestCase("WhereClause", "where", new string[] { "cat==Fast" }, new string[0])]
[TestCase("ActiveConfig", "config", new string[] { "Debug" }, new string[0])]
[TestCase("ProcessModel", "process", new string[] { "InProcess", "Separate", "Multiple" }, new string[] { "JUNK" })]
[TestCase("DomainUsage", "domain", new string[] { "None", "Single", "Multiple" }, new string[] { "JUNK" })]
[TestCase("Framework", "framework", new string[] { "net-4.0" }, new string[0])]
[TestCase("OutFile", "output|out", new string[] { "output.txt" }, new string[0])]
[TestCase("ErrFile", "err", new string[] { "error.txt" }, new string[0])]
[TestCase("WorkDirectory", "work", new string[] { "results" }, new string[0])]
[TestCase("DisplayTestLabels", "labels", new string[] { "Off", "On", "All" }, new string[] { "JUNK" })]
[TestCase("InternalTraceLevel", "trace", new string[] { "Off", "Error", "Warning", "Info", "Debug", "Verbose" }, new string[] { "JUNK" })]
[TestCase("DefaultTestNamePattern", "test-name-format", new string[] { "{m}{a}" }, new string[0])]
public void CanRecognizeStringOptions(string propertyName, string pattern, string[] goodValues, string[] badValues)
{
string[] prototypes = pattern.Split('|');
PropertyInfo property = GetPropertyInfo(propertyName);
Assert.AreEqual(typeof(string), property.PropertyType);
foreach (string option in prototypes)
{
foreach (string value in goodValues)
{
string optionPlusValue = string.Format("--{0}:{1}", option, value);
ConsoleOptions options = new ConsoleOptions(optionPlusValue);
Assert.True(options.Validate(), "Should be valid: " + optionPlusValue);
Assert.AreEqual(value, (string)property.GetValue(options, null), "Didn't recognize " + optionPlusValue);
}
foreach (string value in badValues)
{
string optionPlusValue = string.Format("--{0}:{1}", option, value);
ConsoleOptions options = new ConsoleOptions(optionPlusValue);
Assert.False(options.Validate(), "Should not be valid: " + optionPlusValue);
}
}
}
[Test]
public void CanRegognizeInProcessOption()
{
ConsoleOptions options = new ConsoleOptions("--inprocess");
Assert.True(options.Validate(), "Should be valid: --inprocess");
Assert.AreEqual("InProcess", options.ProcessModel, "Didn't recognize --inprocess");
}
[TestCase("ProcessModel", "process", new string[] { "InProcess", "Separate", "Multiple" })]
[TestCase("DomainUsage", "domain", new string[] { "None", "Single", "Multiple" })]
[TestCase("DisplayTestLabels", "labels", new string[] { "Off", "On", "All" })]
[TestCase("InternalTraceLevel", "trace", new string[] { "Off", "Error", "Warning", "Info", "Debug", "Verbose" })]
public void CanRecognizeLowerCaseOptionValues(string propertyName, string optionName, string[] canonicalValues)
{
PropertyInfo property = GetPropertyInfo(propertyName);
Assert.AreEqual(typeof(string), property.PropertyType);
foreach (string canonicalValue in canonicalValues)
{
string lowercaseValue = canonicalValue.ToLowerInvariant();
string optionPlusValue = string.Format("--{0}:{1}", optionName, lowercaseValue);
ConsoleOptions options = new ConsoleOptions(optionPlusValue);
Assert.True(options.Validate(), "Should be valid: " + optionPlusValue);
Assert.AreEqual(canonicalValue, (string)property.GetValue(options, null), "Didn't recognize " + optionPlusValue);
}
}
[TestCase("DefaultTimeout", "timeout")]
[TestCase("RandomSeed", "seed")]
[TestCase("NumberOfTestWorkers", "workers")]
[TestCase("MaxAgents", "agents")]
public void CanRecognizeIntOptions(string propertyName, string pattern)
{
string[] prototypes = pattern.Split('|');
PropertyInfo property = GetPropertyInfo(propertyName);
Assert.AreEqual(typeof(int), property.PropertyType);
foreach (string option in prototypes)
{
ConsoleOptions options = new ConsoleOptions("--" + option + ":42");
Assert.AreEqual(42, (int)property.GetValue(options, null), "Didn't recognize --" + option + ":42");
}
}
//[TestCase("InternalTraceLevel", "trace", typeof(InternalTraceLevel))]
//public void CanRecognizeEnumOptions(string propertyName, string pattern, Type enumType)
//{
// string[] prototypes = pattern.Split('|');
// PropertyInfo property = GetPropertyInfo(propertyName);
// Assert.IsNotNull(property, "Property {0} not found", propertyName);
// Assert.IsTrue(property.PropertyType.IsEnum, "Property {0} is not an enum", propertyName);
// Assert.AreEqual(enumType, property.PropertyType);
// foreach (string option in prototypes)
// {
// foreach (string name in Enum.GetNames(enumType))
// {
// {
// ConsoleOptions options = new ConsoleOptions("--" + option + ":" + name);
// Assert.AreEqual(name, property.GetValue(options, null).ToString(), "Didn't recognize -" + option + ":" + name);
// }
// }
// }
//}
[TestCase("--where")]
[TestCase("--config")]
[TestCase("--process")]
[TestCase("--domain")]
[TestCase("--framework")]
[TestCase("--timeout")]
[TestCase("--output")]
[TestCase("--err")]
[TestCase("--work")]
[TestCase("--trace")]
[TestCase("--test-name-format")]
[TestCase("--params")]
public void MissingValuesAreReported(string option)
{
ConsoleOptions options = new ConsoleOptions(option + "=");
Assert.False(options.Validate(), "Missing value should not be valid");
Assert.AreEqual("Missing required value for option '" + option + "'.", options.ErrorMessages[0]);
}
[Test]
public void AssemblyName()
{
ConsoleOptions options = new ConsoleOptions("nunit.tests.dll");
Assert.True(options.Validate());
Assert.AreEqual(1, options.InputFiles.Count);
Assert.AreEqual("nunit.tests.dll", options.InputFiles[0]);
}
//[Test]
//public void FixtureNamePlusAssemblyIsValid()
//{
// ConsoleOptions options = new ConsoleOptions( "-fixture:NUnit.Tests.AllTests", "nunit.tests.dll" );
// Assert.AreEqual("nunit.tests.dll", options.Parameters[0]);
// Assert.AreEqual("NUnit.Tests.AllTests", options.fixture);
// Assert.IsTrue(options.Validate());
//}
[Test]
public void AssemblyAloneIsValid()
{
ConsoleOptions options = new ConsoleOptions("nunit.tests.dll");
Assert.True(options.Validate());
Assert.AreEqual(0, options.ErrorMessages.Count, "command line should be valid");
}
[Test, Platform("32-Bit")]
public void X86AndInProcessAreCompatibleIn32BitProcess()
{
ConsoleOptions options = new ConsoleOptions("nunit.tests.dll", "--x86", "--inprocess");
Assert.True(options.Validate());
Assert.AreEqual(0, options.ErrorMessages.Count, "command line should be valid");
}
[Test, Platform("64-Bit")]
public void X86AndInProcessAreNotCompatibleIn64BitProcess()
{
ConsoleOptions options = new ConsoleOptions("nunit.tests.dll", "--x86", "--inprocess");
Assert.False(options.Validate(), "Should be invalid");
Assert.AreEqual("The --x86 and --inprocess options are incompatible.", options.ErrorMessages[0]);
}
[Test]
public void InvalidOption()
{
ConsoleOptions options = new ConsoleOptions("-assembly:nunit.tests.dll");
Assert.False(options.Validate());
Assert.AreEqual(1, options.ErrorMessages.Count);
Assert.AreEqual("Invalid argument: -assembly:nunit.tests.dll", options.ErrorMessages[0]);
}
//[Test]
//public void NoFixtureNameProvided()
//{
// ConsoleOptions options = new ConsoleOptions( "-fixture:", "nunit.tests.dll" );
// Assert.IsFalse(options.Validate());
//}
[Test]
public void InvalidCommandLineParms()
{
ConsoleOptions options = new ConsoleOptions("-garbage:TestFixture", "-assembly:Tests.dll");
Assert.False(options.Validate());
Assert.AreEqual(2, options.ErrorMessages.Count);
Assert.AreEqual("Invalid argument: -garbage:TestFixture", options.ErrorMessages[0]);
Assert.AreEqual("Invalid argument: -assembly:Tests.dll", options.ErrorMessages[1]);
}
#endregion
#region Timeout Option
[Test]
public void TimeoutIsMinusOneIfNoOptionIsProvided()
{
ConsoleOptions options = new ConsoleOptions("tests.dll");
Assert.True(options.Validate());
Assert.AreEqual(-1, options.DefaultTimeout);
}
[Test]
public void TimeoutThrowsExceptionIfOptionHasNoValue()
{
Assert.Throws<OptionException>(() => new ConsoleOptions("tests.dll", "-timeout"));
}
[Test]
public void TimeoutParsesIntValueCorrectly()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "-timeout:5000");
Assert.True(options.Validate());
Assert.AreEqual(5000, options.DefaultTimeout);
}
[Test]
public void TimeoutCausesErrorIfValueIsNotInteger()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "-timeout:abc");
Assert.False(options.Validate());
Assert.AreEqual(-1, options.DefaultTimeout);
}
#endregion
#region EngineResult Option
[Test]
public void ResultOptionWithFilePath()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "-result:results.xml");
Assert.True(options.Validate());
Assert.AreEqual(1, options.InputFiles.Count, "assembly should be set");
Assert.AreEqual("tests.dll", options.InputFiles[0]);
OutputSpecification spec = options.ResultOutputSpecifications[0];
Assert.AreEqual("results.xml", spec.OutputPath);
Assert.AreEqual("nunit3", spec.Format);
Assert.Null(spec.Transform);
}
[Test]
public void ResultOptionWithFilePathAndFormat()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "-result:results.xml;format=nunit2");
Assert.True(options.Validate());
Assert.AreEqual(1, options.InputFiles.Count, "assembly should be set");
Assert.AreEqual("tests.dll", options.InputFiles[0]);
OutputSpecification spec = options.ResultOutputSpecifications[0];
Assert.AreEqual("results.xml", spec.OutputPath);
Assert.AreEqual("nunit2", spec.Format);
Assert.Null(spec.Transform);
}
[Test]
public void ResultOptionWithFilePathAndTransform()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "-result:results.xml;transform=transform.xslt");
Assert.True(options.Validate());
Assert.AreEqual(1, options.InputFiles.Count, "assembly should be set");
Assert.AreEqual("tests.dll", options.InputFiles[0]);
OutputSpecification spec = options.ResultOutputSpecifications[0];
Assert.AreEqual("results.xml", spec.OutputPath);
Assert.AreEqual("user", spec.Format);
Assert.AreEqual("transform.xslt", spec.Transform);
}
[Test]
public void FileNameWithoutResultOptionLooksLikeParameter()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "results.xml");
Assert.True(options.Validate());
Assert.AreEqual(0, options.ErrorMessages.Count);
Assert.AreEqual(2, options.InputFiles.Count);
}
[Test]
public void ResultOptionWithoutFileNameIsInvalid()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "-result:");
Assert.False(options.Validate(), "Should not be valid");
Assert.AreEqual(1, options.ErrorMessages.Count, "An error was expected");
}
[Test]
public void ResultOptionMayBeRepeated()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "-result:results.xml", "-result:nunit2results.xml;format=nunit2", "-result:myresult.xml;transform=mytransform.xslt");
Assert.True(options.Validate(), "Should be valid");
var specs = options.ResultOutputSpecifications;
Assert.AreEqual(3, specs.Count);
var spec1 = specs[0];
Assert.AreEqual("results.xml", spec1.OutputPath);
Assert.AreEqual("nunit3", spec1.Format);
Assert.Null(spec1.Transform);
var spec2 = specs[1];
Assert.AreEqual("nunit2results.xml", spec2.OutputPath);
Assert.AreEqual("nunit2", spec2.Format);
Assert.Null(spec2.Transform);
var spec3 = specs[2];
Assert.AreEqual("myresult.xml", spec3.OutputPath);
Assert.AreEqual("user", spec3.Format);
Assert.AreEqual("mytransform.xslt", spec3.Transform);
}
[Test]
public void DefaultResultSpecification()
{
var options = new ConsoleOptions("test.dll");
Assert.AreEqual(1, options.ResultOutputSpecifications.Count);
var spec = options.ResultOutputSpecifications[0];
Assert.AreEqual("TestResult.xml", spec.OutputPath);
Assert.AreEqual("nunit3", spec.Format);
Assert.Null(spec.Transform);
}
[Test]
public void NoResultSuppressesDefaultResultSpecification()
{
var options = new ConsoleOptions("test.dll", "-noresult");
Assert.AreEqual(0, options.ResultOutputSpecifications.Count);
}
[Test]
public void NoResultSuppressesAllResultSpecifications()
{
var options = new ConsoleOptions("test.dll", "-result:results.xml", "-noresult", "-result:nunit2results.xml;format=nunit2");
Assert.AreEqual(0, options.ResultOutputSpecifications.Count);
}
#endregion
#region Explore Option
[Test]
public void ExploreOptionWithoutPath()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "-explore");
Assert.True(options.Validate());
Assert.True(options.Explore);
}
[Test]
public void ExploreOptionWithFilePath()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "-explore:results.xml");
Assert.True(options.Validate());
Assert.AreEqual(1, options.InputFiles.Count, "assembly should be set");
Assert.AreEqual("tests.dll", options.InputFiles[0]);
Assert.True(options.Explore);
OutputSpecification spec = options.ExploreOutputSpecifications[0];
Assert.AreEqual("results.xml", spec.OutputPath);
Assert.AreEqual("nunit3", spec.Format);
Assert.Null(spec.Transform);
}
[Test]
public void ExploreOptionWithFilePathAndFormat()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "-explore:results.xml;format=cases");
Assert.True(options.Validate());
Assert.AreEqual(1, options.InputFiles.Count, "assembly should be set");
Assert.AreEqual("tests.dll", options.InputFiles[0]);
Assert.True(options.Explore);
OutputSpecification spec = options.ExploreOutputSpecifications[0];
Assert.AreEqual("results.xml", spec.OutputPath);
Assert.AreEqual("cases", spec.Format);
Assert.Null(spec.Transform);
}
[Test]
public void ExploreOptionWithFilePathAndTransform()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "-explore:results.xml;transform=myreport.xslt");
Assert.True(options.Validate());
Assert.AreEqual(1, options.InputFiles.Count, "assembly should be set");
Assert.AreEqual("tests.dll", options.InputFiles[0]);
Assert.True(options.Explore);
OutputSpecification spec = options.ExploreOutputSpecifications[0];
Assert.AreEqual("results.xml", spec.OutputPath);
Assert.AreEqual("user", spec.Format);
Assert.AreEqual("myreport.xslt", spec.Transform);
}
[Test]
public void ExploreOptionWithFilePathUsingEqualSign()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "-explore=C:/nunit/tests/bin/Debug/console-test.xml");
Assert.True(options.Validate());
Assert.True(options.Explore);
Assert.AreEqual(1, options.InputFiles.Count, "assembly should be set");
Assert.AreEqual("tests.dll", options.InputFiles[0]);
Assert.AreEqual("C:/nunit/tests/bin/Debug/console-test.xml", options.ExploreOutputSpecifications[0].OutputPath);
}
[Test]
[TestCase(true, null, true)]
[TestCase(false, null, false)]
[TestCase(true, false, true)]
[TestCase(false, false, false)]
[TestCase(true, true, true)]
[TestCase(false, true, true)]
public void ShouldSetTeamCityFlagAccordingToArgsAndDefauls(bool hasTeamcityInCmd, bool? defaultTeamcity, bool expectedTeamCity)
{
// Given
List<string> args = new List<string> { "tests.dll" };
if (hasTeamcityInCmd)
{
args.Add("--teamcity");
}
ConsoleOptions options;
if (defaultTeamcity.HasValue)
{
options = new ConsoleOptions(new DefaultOptionsProviderStub(defaultTeamcity.Value), args.ToArray());
}
else
{
options = new ConsoleOptions(args.ToArray());
}
// When
var actualTeamCity = options.TeamCity;
// Then
Assert.AreEqual(actualTeamCity, expectedTeamCity);
}
#endregion
#region Testlist Option
[Test]
public void ShouldNotFailOnEmptyLine()
{
var testListPath = Path.Combine(TestContext.CurrentContext.TestDirectory, "TestListWithEmptyLine.tst");
// Not copying this test file into releases
Assume.That(testListPath, Does.Exist);
var options = new ConsoleOptions("--testlist=" + testListPath);
Assert.That(options.errorMessages, Is.Empty);
Assert.That(options.TestList, Is.EqualTo(new[] {"AmazingTest"}));
}
#endregion
#region Test Parameters
[Test]
public void SingleTestParameter()
{
var options = new ConsoleOptions("--params=X=5");
Assert.That(options.errorMessages, Is.Empty);
Assert.That(options.TestParameters, Is.EqualTo("X=5"));
}
[Test]
public void TwoTestParametersInOneOption()
{
var options = new ConsoleOptions("--params:X=5;Y=7");
Assert.That(options.errorMessages, Is.Empty);
Assert.That(options.TestParameters, Is.EqualTo("X=5;Y=7"));
}
[Test]
public void TwoTestParametersInSeparateOptions()
{
var options = new ConsoleOptions("-p:X=5", "-p:Y=7");
Assert.That(options.errorMessages, Is.Empty);
Assert.That(options.TestParameters, Is.EqualTo("X=5;Y=7"));
}
[Test]
public void ThreeTestParametersInTwoOptions()
{
var options = new ConsoleOptions("--params:X=5;Y=7", "-p:Z=3");
Assert.That(options.errorMessages, Is.Empty);
Assert.That(options.TestParameters, Is.EqualTo("X=5;Y=7;Z=3"));
}
[Test]
public void ParameterWithoutEqualSignIsInvalid()
{
var options = new ConsoleOptions("--params=X5");
Assert.That(options.ErrorMessages.Count, Is.EqualTo(1));
}
[Test]
public void DisplayTestParameters()
{
if (TestContext.Parameters.Count == 0)
{
Console.WriteLine("No Test Parameters were passed");
return;
}
Console.WriteLine("Test Parameters---");
foreach (var name in TestContext.Parameters.Names)
Console.WriteLine(" Name: {0} Value: {1}", name, TestContext.Parameters[name]);
}
#endregion
#region Helper Methods
private static FieldInfo GetFieldInfo(string fieldName)
{
FieldInfo field = typeof(ConsoleOptions).GetField(fieldName);
Assert.IsNotNull(field, "The field '{0}' is not defined", fieldName);
return field;
}
private static PropertyInfo GetPropertyInfo(string propertyName)
{
PropertyInfo property = typeof(ConsoleOptions).GetProperty(propertyName);
Assert.IsNotNull(property, "The property '{0}' is not defined", propertyName);
return property;
}
#endregion
internal sealed class DefaultOptionsProviderStub : IDefaultOptionsProvider
{
public DefaultOptionsProviderStub(bool teamCity)
{
TeamCity = teamCity;
}
public bool TeamCity { get; private set; }
}
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using DotSpatial.Serialization;
namespace DotSpatial.Symbology
{
/// <summary>
/// Pattern that uses a gradient.
/// </summary>
public class GradientPattern : Pattern, IGradientPattern
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="GradientPattern"/> class.
/// </summary>
public GradientPattern()
{
GradientType = GradientType.Linear;
Colors = new Color[2];
Colors[0] = SymbologyGlobal.RandomLightColor(1F);
Colors[1] = Colors[0].Darker(.3F);
Positions = new[] { 0F, 1F };
Angle = -45;
}
/// <summary>
/// Initializes a new instance of the <see cref="GradientPattern"/> class using the specified colors.
/// </summary>
/// <param name="startColor">The start color.</param>
/// <param name="endColor">The end color.</param>
public GradientPattern(Color startColor, Color endColor)
: this(startColor, endColor, -45)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="GradientPattern"/> class using the specified colors and angle.
/// </summary>
/// <param name="startColor">The start color.</param>
/// <param name="endColor">The end color.</param>
/// <param name="angle">The direction of the gradient, measured in degrees clockwise from the x-axis.</param>
public GradientPattern(Color startColor, Color endColor, double angle)
: this(startColor, endColor, angle, GradientType.Linear)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="GradientPattern"/> class using the specified colors, angle and style.
/// </summary>
/// <param name="startColor">The start color.</param>
/// <param name="endColor">The end color.</param>
/// <param name="angle">The direction of the gradient, measured in degrees clockwise from the x-axis.</param>
/// <param name="style">Controls how the gradient is drawn.</param>
public GradientPattern(Color startColor, Color endColor, double angle, GradientType style)
{
Colors = new Color[2];
Colors[0] = startColor;
Colors[1] = endColor;
Positions = new[] { 0F, 1F };
Angle = angle;
GradientType = style;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the angle for the gradient pattern.
/// </summary>
[Serialize("Angle")]
public double Angle { get; set; }
/// <summary>
/// Gets or sets the colors (0 = start color, 1 = end color).
/// </summary>
[Serialize("Colors")]
public Color[] Colors { get; set; }
/// <summary>
/// Gets or sets the gradient type.
/// </summary>
[Serialize("GradientTypes")]
public GradientType GradientType { get; set; }
/// <summary>
/// Gets or sets the start positions (0 = start color, 1 = end color).
/// </summary>
[Serialize("Positions")]
public float[] Positions { get; set; }
#endregion
#region Methods
/// <summary>
/// Handles the drawing code for linear gradient paths.
/// </summary>
/// <param name="g">Graphics object used for drawing.</param>
/// <param name="gp">Path that gets drawn.</param>
public override void FillPath(Graphics g, GraphicsPath gp)
{
RectangleF bounds = Bounds;
if (bounds.IsEmpty) bounds = gp.GetBounds();
if (bounds.Width == 0 || bounds.Height == 0) return;
// also don't draw gradient for very small polygons
if (bounds.Width < 0.01 || bounds.Height < 0.01) return;
if (GradientType == GradientType.Linear)
{
using (LinearGradientBrush b = new LinearGradientBrush(bounds, Colors[0], Colors[Colors.Length - 1], (float)-Angle))
{
ColorBlend cb = new ColorBlend
{
Positions = Positions,
Colors = Colors
};
b.InterpolationColors = cb;
g.FillPath(b, gp);
}
}
else if (GradientType == GradientType.Circular)
{
PointF center = new PointF(bounds.X + (bounds.Width / 2), bounds.Y + (bounds.Height / 2));
float x = (float)(center.X - (Math.Sqrt(2) * bounds.Width / 2));
float y = (float)(center.Y - (Math.Sqrt(2) * bounds.Height / 2));
float w = (float)(bounds.Width * Math.Sqrt(2));
float h = (float)(bounds.Height * Math.Sqrt(2));
RectangleF circum = new RectangleF(x, y, w, h);
GraphicsPath round = new GraphicsPath();
round.AddEllipse(circum);
using (PathGradientBrush pgb = new PathGradientBrush(round))
{
ColorBlend cb = new ColorBlend
{
Colors = Colors,
Positions = Positions
};
pgb.InterpolationColors = cb;
g.FillPath(pgb, gp);
}
}
else if (GradientType == GradientType.Rectangular)
{
double a = bounds.Width / 2;
double b = bounds.Height / 2;
double angle = Angle;
if (angle < 0) angle = 360 + angle;
angle = angle % 90;
angle = 2 * (Math.PI * angle / 180);
double x = a * Math.Cos(angle);
double y = -b - (a * Math.Sin(angle));
PointF center = new PointF(bounds.X + (bounds.Width / 2), bounds.Y + (bounds.Height / 2));
PointF[] points = new PointF[5];
points[0] = new PointF((float)x + center.X, (float)y + center.Y);
x = a + (b * Math.Sin(angle));
y = b * Math.Cos(angle);
points[1] = new PointF((float)x + center.X, (float)y + center.Y);
x = -a * Math.Cos(angle);
y = b + (a * Math.Sin(angle));
points[2] = new PointF((float)x + center.X, (float)y + center.Y);
x = -a - (b * Math.Sin(angle));
y = -b * Math.Cos(angle);
points[3] = new PointF((float)x + center.X, (float)y + center.Y);
points[4] = points[0];
GraphicsPath rect = new GraphicsPath();
rect.AddPolygon(points);
using (PathGradientBrush pgb = new PathGradientBrush(rect))
{
ColorBlend cb = new ColorBlend
{
Colors = Colors,
Positions = Positions
};
pgb.InterpolationColors = cb;
g.FillPath(pgb, gp);
}
}
}
/// <summary>
/// Gets a color that can be used to represent this pattern. In some cases, a color is not
/// possible, in which case, this returns Gray.
/// </summary>
/// <returns>A single System.Color that can be used to represent this pattern.</returns>
public override Color GetFillColor()
{
Color l = Colors[0];
Color h = Colors[Colors.Length - 1];
int a = (l.A + h.A) / 2;
int r = (l.R + h.R) / 2;
int g = (l.G + h.G) / 2;
int b = (l.B + h.B) / 2;
return Color.FromArgb(a, r, g, b);
}
/// <summary>
/// Sets the fill color, keeping the approximate gradiant RGB changes the same, but adjusting
/// the mean color to the specifeid color.
/// </summary>
/// <param name="color">The mean color to apply.</param>
public override void SetFillColor(Color color)
{
if (Colors == null || Colors.Length == 0) return;
if (Colors.Length == 1)
{
Colors[0] = color;
return;
}
Color l = Colors[0];
Color h = Colors[Colors.Length - 1];
int da = (h.A - l.A) / 2;
int dr = (h.R - l.R) / 2;
int dg = (h.G - l.G) / 2;
int db = (h.B - l.B) / 2;
Colors[0] = Color.FromArgb(ByteSize(color.A - da), ByteSize(color.R - dr), ByteSize(color.G - dg), ByteSize(color.B - db));
Colors[Colors.Length - 1] = Color.FromArgb(ByteSize(color.A + da), ByteSize(color.R + dr), ByteSize(color.G + dg), ByteSize(color.B + db));
}
private static int ByteSize(int value)
{
if (value > 255) return 255;
return value < 0 ? 0 : value;
}
#endregion
}
}
| |
#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_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_3_5 || UNITY_3_4 || UNITY_3_3
#define UNITY_LE_4_3
#endif
using UnityEngine;
using UnityEditor;
using Pathfinding;
using System.Collections;
using Pathfinding.Serialization.JsonFx;
namespace Pathfinding {
/*
#if !AstarRelease
[CustomGraphEditor (typeof(CustomGridGraph),"CustomGrid Graph")]
//[CustomGraphEditor (typeof(LineTraceGraph),"Grid Tracing Graph")]
#endif
*/
[CustomGraphEditor (typeof(GridGraph),"Grid Graph")]
public class GridGraphEditor : GraphEditor {
[JsonMember]
public bool locked = true;
float newNodeSize;
[JsonMember]
public bool showExtra = false;
/** Should textures be allowed to be used.
* This can be set to false by inheriting graphs not implemeting that feature */
[JsonMember]
public bool textureVisible = true;
Matrix4x4 savedMatrix;
Vector3 savedCenter;
public bool isMouseDown = false;
[JsonMember]
public GridPivot pivot;
GraphNode node1;
/** Rounds a vector's components to whole numbers if very close to them */
public static Vector3 RoundVector3 ( Vector3 v ) {
if (Mathf.Abs ( v.x - Mathf.Round(v.x)) < 0.001f ) v.x = Mathf.Round ( v.x );
if (Mathf.Abs ( v.y - Mathf.Round(v.y)) < 0.001f ) v.y = Mathf.Round ( v.y );
if (Mathf.Abs ( v.z - Mathf.Round(v.z)) < 0.001f ) v.z = Mathf.Round ( v.z );
return v;
}
#if UNITY_LE_4_3
/** Draws an integer field */
public int IntField (string label, int value, int offset, int adjust, out Rect r) {
return IntField (new GUIContent (label),value,offset,adjust,out r);
}
/** Draws an integer field */
public int IntField (GUIContent label, int value, int offset, int adjust, out Rect r) {
GUIStyle intStyle = EditorStyles.numberField;
EditorGUILayoutx.BeginIndent ();
Rect r1 = GUILayoutUtility.GetRect (label,intStyle);
Rect r2 = GUILayoutUtility.GetRect (new GUIContent (value.ToString ()),intStyle);
EditorGUILayoutx.EndIndent();
r2.width += (r2.x-r1.x);
r2.x = r1.x+offset;
r2.width -= offset+offset+adjust;
r = new Rect ();
r.x = r2.x+r2.width;
r.y = r1.y;
r.width = offset;
r.height = r1.height;
GUI.SetNextControlName ("IntField_"+label.text);
value = EditorGUI.IntField (r2,"",value);
bool on = GUI.GetNameOfFocusedControl () == "IntField_"+label.text;
if (Event.current.type == EventType.Repaint) {
intStyle.Draw (r1,label,false,false,false,on);
}
return value;
}
#endif
public override void OnInspectorGUI (NavGraph target) {
GridGraph graph = target as GridGraph;
//GUILayout.BeginHorizontal ();
//GUILayout.BeginVertical ();
Rect lockRect;
GUIStyle lockStyle = AstarPathEditor.astarSkin.FindStyle ("GridSizeLock");
if (lockStyle == null) {
lockStyle = new GUIStyle ();
}
#if !UNITY_LE_4_3 || true
GUILayout.BeginHorizontal ();
GUILayout.BeginVertical ();
int newWidth = EditorGUILayout.IntField (new GUIContent ("Width (nodes)","Width of the graph in nodes"), graph.width);
int newDepth = EditorGUILayout.IntField (new GUIContent ("Depth (nodes)","Depth (or height you might also call it) of the graph in nodes"), graph.depth);
GUILayout.EndVertical ();
lockRect = GUILayoutUtility.GetRect (lockStyle.fixedWidth,lockStyle.fixedHeight);
// Add a small offset to make it better centred around the controls
lockRect.y += 3;
GUILayout.EndHorizontal ();
// All the layouts mess up the margin to the next control, so add it manually
GUILayout.Space (2);
#elif UNITY_4
Rect tmpLockRect;
int newWidth = IntField (new GUIContent ("Width (nodes)","Width of the graph in nodes"),graph.width,100,0, out lockRect, out sizeSelected1);
int newDepth = IntField (new GUIContent ("Depth (nodes)","Depth (or height you might also call it) of the graph in nodes"),graph.depth,100,0, out tmpLockRect, out sizeSelected2);
#else
Rect tmpLockRect;
int newWidth = IntField (new GUIContent ("Width (nodes)","Width of the graph in nodes"),graph.width,50,0, out lockRect, out sizeSelected1);
int newDepth = IntField (new GUIContent ("Depth (nodes)","Depth (or height you might also call it) of the graph in nodes"),graph.depth,50,0, out tmpLockRect, out sizeSelected2);
#endif
lockRect.width = lockStyle.fixedWidth;
lockRect.height = lockStyle.fixedHeight;
lockRect.x += lockStyle.margin.left;
lockRect.y += lockStyle.margin.top;
locked = GUI.Toggle (lockRect,locked,new GUIContent ("","If the width and depth values are locked, changing the node size will scale the grid which keeping the number of nodes consistent instead of keeping the size the same and changing the number of nodes in the graph"),lockStyle);
//GUILayout.EndHorizontal ();
if (newWidth != graph.width || newDepth != graph.depth) {
SnapSizeToNodes (newWidth,newDepth,graph);
}
GUI.SetNextControlName ("NodeSize");
newNodeSize = EditorGUILayout.FloatField (new GUIContent ("Node size","The size of a single node. The size is the side of the node square in world units"),graph.nodeSize);
newNodeSize = newNodeSize <= 0.01F ? 0.01F : newNodeSize;
float prevRatio = graph.aspectRatio;
graph.aspectRatio = EditorGUILayout.FloatField (new GUIContent ("Aspect Ratio","Scaling of the nodes width/depth ratio. Good for isometric games"),graph.aspectRatio);
graph.isometricAngle = EditorGUILayout.FloatField (new GUIContent ("Isometric Angle", "For an isometric 2D game, you can use this parameter to scale the graph correctly."), graph.isometricAngle);
if (graph.nodeSize != newNodeSize || prevRatio != graph.aspectRatio) {
if (!locked) {
graph.nodeSize = newNodeSize;
Matrix4x4 oldMatrix = graph.matrix;
graph.GenerateMatrix ();
if (graph.matrix != oldMatrix) {
//Rescann the graphs
//AstarPath.active.AutoScan ();
GUI.changed = true;
}
} else {
float delta = newNodeSize / graph.nodeSize;
graph.nodeSize = newNodeSize;
graph.unclampedSize = new Vector2 (newWidth*graph.nodeSize,newDepth*graph.nodeSize);
Vector3 newCenter = graph.matrix.MultiplyPoint3x4 (new Vector3 ((newWidth/2F)*delta,0,(newDepth/2F)*delta));
graph.center = newCenter;
graph.GenerateMatrix ();
//Make sure the width & depths stay the same
graph.width = newWidth;
graph.depth = newDepth;
AutoScan ();
}
}
Vector3 pivotPoint;
Vector3 diff;
#if UNITY_LE_4_3
EditorGUIUtility.LookLikeControls ();
#endif
#if !UNITY_4
EditorGUILayoutx.BeginIndent ();
#else
GUILayout.BeginHorizontal ();
#endif
switch (pivot) {
case GridPivot.Center:
graph.center = RoundVector3 ( graph.center );
graph.center = EditorGUILayout.Vector3Field ("Center",graph.center);
break;
case GridPivot.TopLeft:
pivotPoint = graph.matrix.MultiplyPoint3x4 (new Vector3 (0,0,graph.depth));
pivotPoint = RoundVector3 ( pivotPoint );
diff = pivotPoint-graph.center;
pivotPoint = EditorGUILayout.Vector3Field ("Top-Left",pivotPoint);
graph.center = pivotPoint-diff;
break;
case GridPivot.TopRight:
pivotPoint = graph.matrix.MultiplyPoint3x4 (new Vector3 (graph.width,0,graph.depth));
pivotPoint = RoundVector3 ( pivotPoint );
diff = pivotPoint-graph.center;
pivotPoint = EditorGUILayout.Vector3Field ("Top-Right",pivotPoint);
graph.center = pivotPoint-diff;
break;
case GridPivot.BottomLeft:
pivotPoint = graph.matrix.MultiplyPoint3x4 (new Vector3 (0,0,0));
pivotPoint = RoundVector3 ( pivotPoint );
diff = pivotPoint-graph.center;
pivotPoint = EditorGUILayout.Vector3Field ("Bottom-Left",pivotPoint);
graph.center = pivotPoint-diff;
break;
case GridPivot.BottomRight:
pivotPoint = graph.matrix.MultiplyPoint3x4 (new Vector3 (graph.width,0,0));
pivotPoint = RoundVector3 ( pivotPoint );
diff = pivotPoint-graph.center;
pivotPoint = EditorGUILayout.Vector3Field ("Bottom-Right",pivotPoint);
graph.center = pivotPoint-diff;
break;
}
graph.GenerateMatrix ();
pivot = PivotPointSelector (pivot);
#if !UNITY_4
EditorGUILayoutx.EndIndent ();
EditorGUILayoutx.BeginIndent ();
#else
GUILayout.EndHorizontal ();
#endif
graph.rotation = EditorGUILayout.Vector3Field ("Rotation",graph.rotation);
#if UNITY_LE_4_3
//Add some space to make the Rotation and postion fields be better aligned (instead of the pivot point selector)
//GUILayout.Space (19+7);
#endif
//GUILayout.EndHorizontal ();
#if !UNITY_4
EditorGUILayoutx.EndIndent ();
#endif
#if UNITY_LE_4_3
EditorGUIUtility.LookLikeInspector ();
#endif
if (GUILayout.Button (new GUIContent ("Snap Size","Snap the size to exactly fit nodes"),GUILayout.MaxWidth (100),GUILayout.MaxHeight (16))) {
SnapSizeToNodes (newWidth,newDepth,graph);
}
Separator ();
graph.cutCorners = EditorGUILayout.Toggle (new GUIContent ("Cut Corners","Enables or disables cutting corners. See docs for image example"),graph.cutCorners);
graph.neighbours = (NumNeighbours)EditorGUILayout.EnumPopup (new GUIContent ("Connections","Sets how many connections a node should have to it's neighbour nodes."),graph.neighbours);
graph.maxClimb = EditorGUILayout.FloatField (new GUIContent ("Max Climb","How high, relative to the graph, should a climbable level be. A zero (0) indicates infinity"),graph.maxClimb);
if ( graph.maxClimb < 0 ) graph.maxClimb = 0;
EditorGUI.indentLevel++;
graph.maxClimbAxis = EditorGUILayout.IntPopup (new GUIContent ("Climb Axis","Determines which axis the above setting should test on"),graph.maxClimbAxis,new GUIContent[3] {new GUIContent ("X"),new GUIContent ("Y"),new GUIContent ("Z")},new int[3] {0,1,2});
EditorGUI.indentLevel--;
if ( graph.maxClimb > 0 && Mathf.Abs((Quaternion.Euler (graph.rotation) * new Vector3 (graph.nodeSize,0,graph.nodeSize))[graph.maxClimbAxis]) > graph.maxClimb ) {
EditorGUILayout.HelpBox ("Nodes are spaced further apart than this in the grid. You might want to increase this value or change the axis", MessageType.Warning );
}
//GUILayout.EndHorizontal ();
graph.maxSlope = EditorGUILayout.Slider (new GUIContent ("Max Slope","Sets the max slope in degrees for a point to be walkable. Only enabled if Height Testing is enabled."),graph.maxSlope,0,90F);
graph.erodeIterations = EditorGUILayout.IntField (new GUIContent ("Erosion iterations","Sets how many times the graph should be eroded. This adds extra margin to objects. This will not work when using Graph Updates, so if you can, use the Diameter setting in collision settings instead"),graph.erodeIterations);
graph.erodeIterations = graph.erodeIterations < 0 ? 0 : (graph.erodeIterations > 16 ? 16 : graph.erodeIterations); //Clamp iterations to [0,16]
if ( graph.erodeIterations > 0 ) {
EditorGUI.indentLevel++;
graph.erosionUseTags = EditorGUILayout.Toggle (new GUIContent ("Erosion Uses Tags","Instead of making nodes unwalkable, " +
"nodes will have their tag set to a value corresponding to their erosion level, " +
"which is a quite good measurement of their distance to the closest wall.\nSee online documentation for more info."),
graph.erosionUseTags);
if (graph.erosionUseTags) {
EditorGUI.indentLevel++;
graph.erosionFirstTag = EditorGUILayoutx.SingleTagField ("First Tag",graph.erosionFirstTag);
EditorGUI.indentLevel--;
}
EditorGUI.indentLevel--;
}
DrawCollisionEditor (graph.collision);
if ( graph.collision.use2D ) {
if ( Mathf.Abs ( Vector3.Dot ( Vector3.forward, Quaternion.Euler (graph.rotation) * Vector3.up ) ) < 0.9f ) {
EditorGUILayout.HelpBox ("When using 2D it is recommended to rotate the graph so that it aligns with the 2D plane.", MessageType.Warning );
}
}
Separator ();
GUILayout.Label (new GUIContent ("Advanced"), EditorStyles.boldLabel);
showExtra = EditorGUILayout.Foldout (showExtra, "Penalty Modifications");
if (showExtra) {
EditorGUI.indentLevel+=2;
graph.penaltyAngle = ToggleGroup (new GUIContent ("Angle Penalty","Adds a penalty based on the slope of the node"),graph.penaltyAngle);
//bool preGUI = GUI.enabled;
//GUI.enabled = graph.penaltyAngle && GUI.enabled;
if (graph.penaltyAngle) {
EditorGUI.indentLevel++;
graph.penaltyAngleFactor = EditorGUILayout.FloatField (new GUIContent ("Factor","Scale of the penalty. A negative value should not be used"),graph.penaltyAngleFactor);
graph.penaltyAnglePower = EditorGUILayout.Slider ("Power", graph.penaltyAnglePower, 0.1f, 10f);
//GUI.enabled = preGUI;
HelpBox ("Applies penalty to nodes based on the angle of the hit surface during the Height Testing\nPenalty applied is: P=(1-cos(angle)^power)*factor.");
EditorGUI.indentLevel--;
}
graph.penaltyPosition = ToggleGroup ("Position Penalty",graph.penaltyPosition);
//EditorGUILayout.Toggle ("Position Penalty",graph.penaltyPosition);
//preGUI = GUI.enabled;
//GUI.enabled = graph.penaltyPosition && GUI.enabled;
if (graph.penaltyPosition) {
EditorGUI.indentLevel++;
graph.penaltyPositionOffset = EditorGUILayout.FloatField ("Offset",graph.penaltyPositionOffset);
graph.penaltyPositionFactor = EditorGUILayout.FloatField ("Factor",graph.penaltyPositionFactor);
HelpBox ("Applies penalty to nodes based on their Y coordinate\nSampled in Int3 space, i.e it is multiplied with Int3.Precision first ("+Int3.Precision+")\n" +
"Be very careful when using negative values since a negative penalty will underflow and instead get really high");
//GUI.enabled = preGUI;
EditorGUI.indentLevel--;
}
GUI.enabled = false;
ToggleGroup (new GUIContent ("Use Texture",AstarPathEditor.AstarProTooltip),false);
GUI.enabled = true;
EditorGUI.indentLevel-=2;
}
}
/** Displays an object field for objects which must be in the 'Resources' folder.
* If the selected object is not in the resources folder, a warning message with a Fix button will be shown
*/
[System.Obsolete("Use ObjectField instead")]
public UnityEngine.Object ResourcesField (string label, UnityEngine.Object obj, System.Type type) {
#if UNITY_3_3
obj = EditorGUILayout.ObjectField (label,obj,type);
#else
obj = EditorGUILayout.ObjectField (label,obj,type,false);
#endif
if (obj != null) {
string path = AssetDatabase.GetAssetPath (obj);
if (!path.Contains ("Resources/")) {
if (FixLabel ("Object must be in the 'Resources' folder")) {
if (!System.IO.Directory.Exists (Application.dataPath+"/Resources")) {
System.IO.Directory.CreateDirectory (Application.dataPath+"/Resources");
AssetDatabase.Refresh ();
}
string ext = System.IO.Path.GetExtension(path);
string error = AssetDatabase.MoveAsset (path,"Assets/Resources/"+obj.name+ext);
if (error == "") {
//Debug.Log ("Successful move");
} else {
Debug.LogError ("Couldn't move asset - "+error);
}
}
}
}
return obj;
}
public void SnapSizeToNodes (int newWidth, int newDepth, GridGraph graph) {
//Vector2 preSize = graph.unclampedSize;
/*if (locked) {
graph.unclampedSize = new Vector2 (newWidth*newNodeSize,newDepth*newNodeSize);
graph.nodeSize = newNodeSize;
graph.GenerateMatrix ();
Vector3 newCenter = graph.matrix.MultiplyPoint3x4 (new Vector3 (newWidth/2F,0,newDepth/2F));
graph.center = newCenter;
AstarPath.active.AutoScan ();
} else {*/
graph.unclampedSize = new Vector2 (newWidth*graph.nodeSize,newDepth*graph.nodeSize);
Vector3 newCenter = graph.matrix.MultiplyPoint3x4 (new Vector3 (newWidth/2F,0,newDepth/2F));
graph.center = newCenter;
graph.GenerateMatrix ();
AutoScan ();
//}
GUI.changed = true;
}
public static GridPivot PivotPointSelector (GridPivot pivot) {
GUISkin skin = AstarPathEditor.astarSkin;
GUIStyle background = skin.FindStyle ("GridPivotSelectBackground");
Rect r = GUILayoutUtility.GetRect (19,19,background);
#if !UNITY_LE_4_3
// I have no idea... but it is required for it to work well
r.y -= 14;
#endif
r.width = 19;
r.height = 19;
if (background == null) {
return pivot;
}
if (Event.current.type == EventType.Repaint) {
background.Draw (r,false,false,false,false);
}
if (GUI.Toggle (new Rect (r.x,r.y,7,7),pivot == GridPivot.TopLeft, "",skin.FindStyle ("GridPivotSelectButton")))
pivot = GridPivot.TopLeft;
if (GUI.Toggle (new Rect (r.x+12,r.y,7,7),pivot == GridPivot.TopRight,"",skin.FindStyle ("GridPivotSelectButton")))
pivot = GridPivot.TopRight;
if (GUI.Toggle (new Rect (r.x+12,r.y+12,7,7),pivot == GridPivot.BottomRight,"",skin.FindStyle ("GridPivotSelectButton")))
pivot = GridPivot.BottomRight;
if (GUI.Toggle (new Rect (r.x,r.y+12,7,7),pivot == GridPivot.BottomLeft,"",skin.FindStyle ("GridPivotSelectButton")))
pivot = GridPivot.BottomLeft;
if (GUI.Toggle (new Rect (r.x+6,r.y+6,7,7),pivot == GridPivot.Center,"",skin.FindStyle ("GridPivotSelectButton")))
pivot = GridPivot.Center;
return pivot;
}
//GraphUndo undoState;
//byte[] savedBytes;
public override void OnSceneGUI (NavGraph target) {
Event e = Event.current;
GridGraph graph = target as GridGraph;
Matrix4x4 matrixPre = graph.matrix;
graph.GenerateMatrix ();
if (e.type == EventType.MouseDown) {
isMouseDown = true;
} else if (e.type == EventType.MouseUp) {
isMouseDown = false;
}
if (!isMouseDown) {
savedMatrix = graph.boundsMatrix;
}
Handles.matrix = savedMatrix;
if ((graph.GetType() == typeof(GridGraph) && graph.nodes == null) || (graph.uniformWidthDepthGrid && graph.depth*graph.width != graph.nodes.Length) || graph.matrix != matrixPre) {
//Rescan the graphs
if (AutoScan ()) {
GUI.changed = true;
}
}
Matrix4x4 inversed = savedMatrix.inverse;
Handles.color = AstarColor.BoundsHandles;
Handles.DrawCapFunction cap = Handles.CylinderCap;
Vector2 extents = graph.unclampedSize*0.5F;
Vector3 center = inversed.MultiplyPoint3x4 (graph.center);
#if UNITY_3_3
if (Tools.current == 3) {
#else
if (Tools.current == Tool.Scale) {
#endif
Vector3 p1 = Handles.Slider (center+new Vector3 (extents.x,0,0), Vector3.right, 0.1F*HandleUtility.GetHandleSize (center+new Vector3 (extents.x,0,0)),cap,0);
Vector3 p2 = Handles.Slider (center+new Vector3 (0,0,extents.y), Vector3.forward, 0.1F*HandleUtility.GetHandleSize (center+new Vector3 (0,0,extents.y)),cap,0);
//Vector3 p3 = Handles.Slider (center+new Vector3 (0,extents.y,0), Vector3.up, 0.1F*HandleUtility.GetHandleSize (center+new Vector3 (0,extents.y,0)),cap,0);
Vector3 p4 = Handles.Slider (center+new Vector3 (-extents.x,0,0), -Vector3.right, 0.1F*HandleUtility.GetHandleSize (center+new Vector3 (-extents.x,0,0)),cap,0);
Vector3 p5 = Handles.Slider (center+new Vector3 (0,0,-extents.y), -Vector3.forward, 0.1F*HandleUtility.GetHandleSize (center+new Vector3 (0,0,-extents.y)),cap,0);
Vector3 p6 = Handles.Slider (center, Vector3.up, 0.1F*HandleUtility.GetHandleSize (center),cap,0);
Vector3 r1 = new Vector3 (p1.x,p6.y,p2.z);
Vector3 r2 = new Vector3 (p4.x,p6.y,p5.z);
//Debug.Log (graph.boundsMatrix.MultiplyPoint3x4 (Vector3.zero)+" "+graph.boundsMatrix.MultiplyPoint3x4 (Vector3.one));
//if (Tools.viewTool != ViewTool.Orbit) {
graph.center = savedMatrix.MultiplyPoint3x4 ((r1+r2)/2F);
Vector3 tmp = r1-r2;
graph.unclampedSize = new Vector2(tmp.x,tmp.z);
//}
#if UNITY_3_3
} else if (Tools.current == 1) {
#else
} else if (Tools.current == Tool.Move) {
#endif
if (Tools.pivotRotation == PivotRotation.Local) {
center = Handles.PositionHandle (center,Quaternion.identity);
if (Tools.viewTool != ViewTool.Orbit) {
graph.center = savedMatrix.MultiplyPoint3x4 (center);
}
} else {
Handles.matrix = Matrix4x4.identity;
center = Handles.PositionHandle (graph.center,Quaternion.identity);
if (Tools.viewTool != ViewTool.Orbit) {
graph.center = center;
}
}
#if UNITY_3_3
} else if (Tools.current == 2) {
#else
} else if (Tools.current == Tool.Rotate) {
#endif
//The rotation handle doesn't seem to be able to handle different matrixes of some reason
Handles.matrix = Matrix4x4.identity;
Quaternion rot = Handles.RotationHandle (Quaternion.Euler (graph.rotation),graph.center);
if (Tools.viewTool != ViewTool.Orbit) {
graph.rotation = rot.eulerAngles;
}
}
//graph.size.x = Mathf.Max (graph.size.x,1);
//graph.size.y = Mathf.Max (graph.size.y,1);
//graph.size.z = Mathf.Max (graph.size.z,1);
Handles.matrix = Matrix4x4.identity;
}
public enum GridPivot {
Center,
TopLeft,
TopRight,
BottomLeft,
BottomRight
}
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit;
using System.Drawing;
using System.Drawing.Drawing2D;
using Point = System.Drawing.Point;
namespace Revit.SDK.Samples.ShaftHolePuncher.CS
{
/// <summary>
/// ProfileNull class contains method to draw a coordinate system,
/// and contains method used to create Shaft Opening
/// </summary>
public class ProfileNull : Profile
{
Level level1 = null; //level 1 used to create Shaft Opening
Level level2 = null; //level 2 used to create Shaft Opening
float m_scale = 1; //scale of shaft opening
/// <summary>
/// Scale property to get/set scale of shaft opening
/// </summary>
public float Scale
{
get
{
return m_scale;
}
set
{
m_scale = value;
}
}
/// <summary>
/// constructor
/// </summary>
/// <param name="commandData">object which contains reference of Revit Application</param>
public ProfileNull(ExternalCommandData commandData)
: base(commandData)
{
GetLevels();
m_to2DMatrix = new Matrix4();
m_moveToCenterMatrix = new Matrix4();
}
/// <summary>
/// get level1 and level2 used to create shaft opening
/// </summary>
private void GetLevels()
{
IList<Element> levelList = (new FilteredElementCollector(m_commandData.Application.ActiveUIDocument.Document)).OfClass(typeof(Level)).ToElements();
IEnumerable<Level> levels = from elem in levelList
let level = elem as Level
where level != null && "Level 1" == level.Name
select level;
if (levels.Count()>0)
{
level1 = levels.First();
}
levels = from elem in levelList
let level = elem as Level
where level != null && "Level 2" == level.Name
select level;
if (levels.Count() > 0)
{
level2 = levels.First();
}
}
/// <summary>
/// calculate the matrix for scale
/// </summary>
/// <param name="size">pictureBox size</param>
/// <returns>maxtrix to scale the opening curve</returns>
public override Matrix4 ComputeScaleMatrix(Size size)
{
m_scaleMatrix = new Matrix4(m_scale);
return m_scaleMatrix;
}
/// <summary>
/// calculate the matrix used to transform 3D to 2D.
/// because profile of shaft opening in Revit is 2d too,
/// so we need do nothing but new a matrix
/// </summary>
/// <returns>maxtrix is use to transform 3d points to 2d</returns>
public override Matrix4 Compute3DTo2DMatrix()
{
m_transformMatrix = new Matrix4();
return m_transformMatrix;
}
/// <summary>
/// draw the coordinate system
/// </summary>
/// <param name="graphics">form graphic</param>
/// <param name="pen">pen used to draw line in pictureBox</param>
/// <param name="matrix4">Matrix used to transform 3d to 2d
/// and make picture in right scale </param>
public override void Draw2D(Graphics graphics, Pen pen, Matrix4 matrix4)
{
graphics.Transform = new System.Drawing.Drawing2D.Matrix(
1, 0, 0, 1, 0, 0);
//draw X axis
graphics.DrawLine(pen, new Point(20, 280), new Point(400, 280));
graphics.DrawPie(pen, 400, 265, 30, 30, 165, 30);
//draw Y axis
graphics.DrawLine(pen, new Point(20, 280), new Point(20, 50));
graphics.DrawPie(pen, 5, 20, 30, 30, 75, 30);
//draw scale
graphics.DrawLine(pen, new Point(120, 275), new Point(120, 285));
graphics.DrawLine(pen, new Point(220, 275), new Point(220, 285));
graphics.DrawLine(pen, new Point(320, 275), new Point(320, 285));
graphics.DrawLine(pen, new Point(15, 80), new Point(25, 80));
graphics.DrawLine(pen, new Point(15, 180), new Point(25, 180));
//dimension
Font font = new Font("Verdana", 10, FontStyle.Regular);
graphics.DrawString("100'", font, Brushes.Blue, new PointF(122, 266));
graphics.DrawString("200'", font, Brushes.Blue, new PointF(222, 266));
graphics.DrawString("300'", font, Brushes.Blue, new PointF(322, 266));
graphics.DrawString("100'", font, Brushes.Blue, new PointF(22, 181));
graphics.DrawString("200'", font, Brushes.Blue, new PointF(22, 81));
graphics.DrawString("(0,0)", font, Brushes.Blue, new PointF(10, 280));
}
/// <summary>
/// move the points to the center and scale as user selected.
/// profile of shaft opening in Revit is 2d too, so don't need transform points to 2d
/// </summary>
/// <param name="ps">contain the points to be transformed</param>
/// <returns>Vector list contains points have been transformed</returns>
public override List<Vector4> Transform2DTo3D(Point[] ps)
{
List<Vector4> result = new List<Vector4>();
foreach (Point point in ps)
{
//because our coordinate system is different with window UI
//so we should change what we got from UI coordinate
Vector4 v = new Vector4((point.X - 20), - (point.Y - 280), 0);
v = m_scaleMatrix.Transform(v);
result.Add(v);
}
return result;
}
/// <summary>
/// Create Shaft Opening
/// </summary>
/// <param name="points">points used to create Opening</param>
/// <returns>newly created Opening</returns>
public override Opening CreateOpening(List<Vector4> points)
{
Autodesk.Revit.DB.XYZ p1, p2; Line curve;
CurveArray curves = m_appCreator.NewCurveArray();
for (int i = 0; i < points.Count - 1; i++)
{
p1 = new Autodesk.Revit.DB.XYZ (points[i].X, points[i].Y, points[i].Z);
p2 = new Autodesk.Revit.DB.XYZ (points[i + 1].X, points[i + 1].Y, points[i + 1].Z);
curve = m_appCreator.NewLine(p1, p2, true);
curves.Append(curve);
}
//close the curve
p1 = new Autodesk.Revit.DB.XYZ (points[0].X, points[0].Y, points[0].Z);
p2 = new Autodesk.Revit.DB.XYZ (points[points.Count - 1].X,
points[points.Count - 1].Y, points[points.Count - 1].Z);
curve = m_appCreator.NewLine(p1, p2, true);
curves.Append(curve);
return m_docCreator.NewOpening(level1, level2, curves);
}
}
}
| |
using ColossalFramework;
using ColossalFramework.UI;
using ColossalFramework.Globalization;
using ICities;
using UnityEngine;
using System;
using System.Collections.Generic;
using System.Threading;
namespace FavoriteCims
{
public class PeopleInsideServiceBuildingsButton : UIButton
{
InstanceID BuildingID = InstanceID.Empty;
BuildingManager MyBuilding = Singleton<BuildingManager>.instance;
public UIAlignAnchor Alignment;
public UIPanel RefPanel;
PeopleInsideServiceBuildingsPanel BuildingPanel;
public override void Start() {
var uiView = UIView.GetAView();
////////////////////////////////////////////////
////////////Building Button///////////////////
///////////////////////////////////////////////
this.name = "PeopleInsideServiceBuildingsButton";
this.atlas = MyAtlas.FavCimsAtlas;
this.size = new Vector2(32,36);
this.playAudioEvents = true;
this.AlignTo (RefPanel, Alignment);
this.tooltipBox = uiView.defaultTooltipBox;
if (FavCimsMainClass.FullScreenContainer.GetComponentInChildren<PeopleInsideServiceBuildingsPanel> () != null) {
this.BuildingPanel = FavCimsMainClass.FullScreenContainer.GetComponentInChildren<PeopleInsideServiceBuildingsPanel>();
} else {
this.BuildingPanel = FavCimsMainClass.FullScreenContainer.AddUIComponent(typeof(PeopleInsideServiceBuildingsPanel)) as PeopleInsideServiceBuildingsPanel;
}
this.BuildingPanel.BuildingID = InstanceID.Empty;
this.BuildingPanel.Hide();
this.eventClick += (component, eventParam) => {
if(!BuildingID.IsEmpty && !BuildingPanel.isVisible) {
this.BuildingPanel.BuildingID = BuildingID;
this.BuildingPanel.RefPanel = RefPanel;
this.BuildingPanel.Show();
} else {
this.BuildingPanel.BuildingID = InstanceID.Empty;
this.BuildingPanel.Hide();
}
};
}
public override void Update() {
if (FavCimsMainClass.UnLoading)
return;
if (this.isVisible) {
this.tooltip = null;
if(CityServiceWorldInfoPanel.GetCurrentInstanceID() != InstanceID.Empty) {
BuildingID = CityServiceWorldInfoPanel.GetCurrentInstanceID();
}
if(BuildingPanel != null) {
if(!BuildingPanel.isVisible) {
this.Unfocus();
} else {
this.Focus();
}
}
if (!BuildingID.IsEmpty && BuildingID.Type == InstanceType.Building) {
BuildingInfo buildingInfo = MyBuilding.m_buildings.m_buffer [BuildingID.Building].Info;
switch (buildingInfo.m_class.m_service)
{
case ItemClass.Service.FireDepartment:
this.tooltip = FavCimsLang.text("View_List") + " " + FavCimsLang.text("OnBuilding_Workers");
this.normalBgSprite = "CommercialBuildingButtonIcon";
this.hoveredBgSprite = "CommercialBuildingButtonIconHovered";
this.focusedBgSprite = "CommercialBuildingButtonIconHovered";
this.pressedBgSprite = "CommercialBuildingButtonIconHovered";
this.disabledBgSprite = "CommercialBuildingButtonIconDisabled";
break;
case ItemClass.Service.HealthCare:
this.tooltip = FavCimsLang.text("View_List") + " " + FavCimsLang.text("OnBuilding_Workers");
this.normalBgSprite = "CommercialBuildingButtonIcon";
this.hoveredBgSprite = "CommercialBuildingButtonIconHovered";
this.focusedBgSprite = "CommercialBuildingButtonIconHovered";
this.pressedBgSprite = "CommercialBuildingButtonIconHovered";
this.disabledBgSprite = "CommercialBuildingButtonIconDisabled";
break;
case ItemClass.Service.PoliceDepartment:
this.tooltip = FavCimsLang.text("View_List") + " " + FavCimsLang.text("OnBuilding_Workers");
this.normalBgSprite = "CommercialBuildingButtonIcon";
this.hoveredBgSprite = "CommercialBuildingButtonIconHovered";
this.focusedBgSprite = "CommercialBuildingButtonIconHovered";
this.pressedBgSprite = "CommercialBuildingButtonIconHovered";
this.disabledBgSprite = "CommercialBuildingButtonIconDisabled";
break;
case ItemClass.Service.Garbage:
this.tooltip = FavCimsLang.text("View_List") + " " + FavCimsLang.text("OnBuilding_Workers");
this.normalBgSprite = "IndustrialBuildingButtonIcon";
this.hoveredBgSprite = "IndustrialBuildingButtonIconHovered";
this.focusedBgSprite = "IndustrialBuildingButtonIconHovered";
this.pressedBgSprite = "IndustrialBuildingButtonIconHovered";
this.disabledBgSprite = "IndustrialBuildingButtonIconDisabled";
break;
case ItemClass.Service.Electricity:
this.tooltip = FavCimsLang.text("View_List") + " " + FavCimsLang.text("OnBuilding_Workers");
this.normalBgSprite = "IndustrialBuildingButtonIcon";
this.hoveredBgSprite = "IndustrialBuildingButtonIconHovered";
this.focusedBgSprite = "IndustrialBuildingButtonIconHovered";
this.pressedBgSprite = "IndustrialBuildingButtonIconHovered";
this.disabledBgSprite = "IndustrialBuildingButtonIconDisabled";
break;
case ItemClass.Service.Education:
this.tooltip = FavCimsLang.text("View_List") + " " + FavCimsLang.text("OnBuilding_Workers");
this.normalBgSprite = "CommercialBuildingButtonIcon";
this.hoveredBgSprite = "CommercialBuildingButtonIconHovered";
this.focusedBgSprite = "CommercialBuildingButtonIconHovered";
this.pressedBgSprite = "CommercialBuildingButtonIconHovered";
this.disabledBgSprite = "CommercialBuildingButtonIconDisabled";
break;
case ItemClass.Service.Beautification:
this.tooltip = FavCimsLang.text("View_List") + " " + FavCimsLang.text("OnBuilding_Guests");
this.normalBgSprite = "CommercialBuildingButtonIcon";
this.hoveredBgSprite = "CommercialBuildingButtonIconHovered";
this.focusedBgSprite = "CommercialBuildingButtonIconHovered";
this.pressedBgSprite = "CommercialBuildingButtonIconHovered";
this.disabledBgSprite = "CommercialBuildingButtonIconDisabled";
break;/*
case ItemClass.Service.Government:
this.tooltip = FavCimsLang.text("View_List") + " " + FavCimsLang.text("OnBuilding_Workers");
this.normalBgSprite = "CommercialBuildingButtonIcon";
this.hoveredBgSprite = "CommercialBuildingButtonIconHovered";
this.focusedBgSprite = "CommercialBuildingButtonIconHovered";
this.pressedBgSprite = "CommercialBuildingButtonIconHovered";
this.disabledBgSprite = "CommercialBuildingButtonIconDisabled";
break;*/
case ItemClass.Service.PublicTransport:
this.tooltip = FavCimsLang.text("View_List") + " " + FavCimsLang.text("OnBuilding_Workers");
this.normalBgSprite = "IndustrialBuildingButtonIcon";
this.hoveredBgSprite = "IndustrialBuildingButtonIconHovered";
this.focusedBgSprite = "IndustrialBuildingButtonIconHovered";
this.pressedBgSprite = "IndustrialBuildingButtonIconHovered";
this.disabledBgSprite = "IndustrialBuildingButtonIconDisabled";
break;
case ItemClass.Service.Monument:
this.tooltip = FavCimsLang.text("View_List") + " " + FavCimsLang.text("CitizenOnBuilding");
this.normalBgSprite = "CommercialBuildingButtonIcon";
this.hoveredBgSprite = "CommercialBuildingButtonIconHovered";
this.focusedBgSprite = "CommercialBuildingButtonIconHovered";
this.pressedBgSprite = "CommercialBuildingButtonIconHovered";
this.disabledBgSprite = "CommercialBuildingButtonIconDisabled";
break;
default:
this.tooltip = FavCimsLang.text("View_List") + " " + FavCimsLang.text("OnBuilding_Workers");
this.normalBgSprite = "CommercialBuildingButtonIcon";
this.hoveredBgSprite = "CommercialBuildingButtonIconHovered";
this.focusedBgSprite = "CommercialBuildingButtonIconHovered";
this.pressedBgSprite = "CommercialBuildingButtonIconHovered";
this.disabledBgSprite = "CommercialBuildingButtonIconDisabled";
break;
}
/*
if(buildingInfo.m_class.m_service != ItemClass.Service.None) {
this.tooltip = FavCimsLang.text("CitizenOnBuilding");
this.normalBgSprite = "CommercialBuildingButtonIcon";
this.hoveredBgSprite = "CommercialBuildingButtonIconHovered";
this.focusedBgSprite = "CommercialBuildingButtonIconHovered";
this.pressedBgSprite = "CommercialBuildingButtonIconHovered";
this.disabledBgSprite = "CommercialBuildingButtonIconDisabled";
}*/
if(Convert.ToInt32(MyBuilding.m_buildings.m_buffer[BuildingID.Building].m_citizenCount) == 0) {
BuildingPanel.Hide ();
this.tooltip = FavCimsLang.text("BuildingIsEmpty");
this.isEnabled = false; //disabled sprite
} else {
this.isEnabled = true; //normal sprite
}
} else {
BuildingPanel.Hide ();
this.Unfocus ();
this.isEnabled = false; //disabled sprite
}
} else {
this.isEnabled = false; //disabled sprite
BuildingPanel.Hide ();
BuildingID = InstanceID.Empty;
}
}
}
public class PeopleInsideServiceBuildingsPanel : UIPanel
{
const float Run = 0.5f;
float seconds = Run;
bool execute = false;
bool firstRun = true;
public static bool Wait = false;
bool Garbage = false;
public InstanceID BuildingID;
public UIPanel RefPanel;
BuildingManager MyBuilding = Singleton<BuildingManager>.instance;
CitizenManager MyCitizen = Singleton<CitizenManager>.instance;
public static Dictionary<uint, uint> CimsOnBuilding = new Dictionary<uint, uint> ();
public static int WorkersCount = 0;
public static int GuestsCount = 0;
BuildingInfo buildingInfo;
const int MaxWorkersUnit = 40; // **Important** *same of MaxGuestsUnit*
const int MaxGuestsUnit = 40;
UIPanel WorkersPanel;
UIPanel WorkersPanelSubRow;
UIButton WorkersPanelIcon;
UIButton WorkersPanelText;
WorkersServiceBuildingPanelRow[] WorkersBodyRow = new WorkersServiceBuildingPanelRow[MaxWorkersUnit*5];
UIPanel GuestsPanel;
UIPanel GuestsPanelSubRow;
UIButton GuestsPanelIcon;
UIButton GuestsPanelText;
GuestsServiceBuildingPanelRow[] GuestsBodyRow = new GuestsServiceBuildingPanelRow[MaxGuestsUnit*5];
uint BuildingUnits;
UIPanel Title;
UITextureSprite TitleSpriteBg;
UIButton TitleBuildingName;
UIPanel Body;
UITextureSprite BodySpriteBg;
UIScrollablePanel BodyRows;
UIPanel Footer;
UITextureSprite FooterSpriteBg;
UIScrollablePanel BodyPanelScrollBar;
UIScrollbar BodyScrollBar;
UISlicedSprite BodyPanelTrackSprite;
UISlicedSprite thumbSprite;
public override void Start() {
try {
this.width = 250;
this.height = 0;
this.name = "FavCimsPeopleInsideServiceBuildingsPanel";
this.absolutePosition = new Vector3 (0, 0);
this.Hide ();
Title = this.AddUIComponent<UIPanel> ();
Title.name = "PeopleInsideServiceBuildingsPanelTitle";
Title.width = this.width;
Title.height = 41;
Title.relativePosition = Vector3.zero;
TitleSpriteBg = Title.AddUIComponent<UITextureSprite> ();
TitleSpriteBg.name = "PeopleInsideServiceBuildingsPanelTitleBG";
TitleSpriteBg.width = Title.width;
TitleSpriteBg.height = Title.height;
TitleSpriteBg.texture = TextureDB.VehiclePanelTitleBackground;
TitleSpriteBg.relativePosition = Vector3.zero;
//UIButton Building Name
TitleBuildingName = Title.AddUIComponent<UIButton> ();
TitleBuildingName.name = "PeopleInsideServiceBuildingsPanelName";
TitleBuildingName.width = Title.width;
TitleBuildingName.height = Title.height;
TitleBuildingName.textVerticalAlignment = UIVerticalAlignment.Middle;
TitleBuildingName.textHorizontalAlignment = UIHorizontalAlignment.Center;
TitleBuildingName.playAudioEvents = false;
TitleBuildingName.font = UIDynamicFont.FindByName ("OpenSans-Regular");
TitleBuildingName.font.size = 15;
TitleBuildingName.textScale = 1f;
TitleBuildingName.wordWrap = true;
TitleBuildingName.textPadding.left = 5;
TitleBuildingName.textPadding.right = 5;
TitleBuildingName.textColor = new Color32 (204, 204, 51, 40); //r,g,b,a
TitleBuildingName.hoveredTextColor = new Color32 (204, 204, 51, 40); //r,g,b,a
TitleBuildingName.pressedTextColor = new Color32 (204, 204, 51, 40); //r,g,b,a
TitleBuildingName.focusedTextColor = new Color32 (204, 204, 51, 40); //r,g,b,a
TitleBuildingName.useDropShadow = true;
TitleBuildingName.dropShadowOffset = new Vector2 (1, -1);
TitleBuildingName.dropShadowColor = new Color32 (0, 0, 0, 0);
TitleBuildingName.relativePosition = Vector3.zero;
Body = this.AddUIComponent<UIPanel> ();
Body.name = "PeopleInsideServiceBuildingsBody";
Body.width = this.width;
Body.autoLayoutDirection = LayoutDirection.Vertical;
Body.autoLayout = true;
Body.clipChildren = true;
Body.height = 0;
Body.relativePosition = new Vector3 (0, Title.height);
BodySpriteBg = Body.AddUIComponent<UITextureSprite> ();
BodySpriteBg.name = "PeopleInsideServiceBuildingsDataContainer";
BodySpriteBg.width = Body.width;
BodySpriteBg.height = Body.height;
BodySpriteBg.texture = TextureDB.VehiclePanelBackground;
BodySpriteBg.relativePosition = Vector3.zero;
BodyRows = BodySpriteBg.AddUIComponent<UIScrollablePanel> ();
BodyRows.name = "BodyRows";
BodyRows.width = BodySpriteBg.width - 24;
BodyRows.autoLayoutDirection = LayoutDirection.Vertical;
BodyRows.autoLayout = true;
BodyRows.relativePosition = new Vector3 (12, 0);
string[] LabelPanelName = new string[2] { "Workers", "Guests" };
for (int i = 0; i < 2; i++) {
if (i == 0) {
WorkersPanel = BodyRows.AddUIComponent<UIPanel> ();
WorkersPanel.width = 226;
WorkersPanel.height = 25;
WorkersPanel.name = "LabelPanel_" + LabelPanelName [i] + "_0";
WorkersPanel.autoLayoutDirection = LayoutDirection.Vertical;
WorkersPanel.autoLayout = true;
WorkersPanel.Hide ();
WorkersPanelSubRow = WorkersPanel.AddUIComponent<UIPanel> ();
WorkersPanelSubRow.width = 226;
WorkersPanelSubRow.height = 25;
WorkersPanelSubRow.name = "TitlePanel_" + LabelPanelName [i] + "_0";
WorkersPanelSubRow.atlas = MyAtlas.FavCimsAtlas;
WorkersPanelSubRow.backgroundSprite = "bg_row2";
WorkersPanelIcon = WorkersPanelSubRow.AddUIComponent<UIButton> ();
WorkersPanelIcon.name = "LabelPanelIcon_" + LabelPanelName [i] + "_0";
WorkersPanelIcon.width = 17;
WorkersPanelIcon.height = 17;
WorkersPanelIcon.atlas = MyAtlas.FavCimsAtlas;
WorkersPanelIcon.relativePosition = new Vector3 (5, 4);
WorkersPanelText = WorkersPanelSubRow.AddUIComponent<UIButton> ();
WorkersPanelText.name = "LabelPanelText_" + LabelPanelName [i] + "_0";
WorkersPanelText.width = 200;
WorkersPanelText.height = 25;
WorkersPanelText.textVerticalAlignment = UIVerticalAlignment.Middle;
WorkersPanelText.textHorizontalAlignment = UIHorizontalAlignment.Left;
WorkersPanelText.playAudioEvents = true;
WorkersPanelText.font = UIDynamicFont.FindByName ("OpenSans-Regular");
WorkersPanelText.font.size = 15;
WorkersPanelText.textScale = 0.80f;
WorkersPanelText.useDropShadow = true;
WorkersPanelText.dropShadowOffset = new Vector2 (1, -1);
WorkersPanelText.dropShadowColor = new Color32 (0, 0, 0, 0);
WorkersPanelText.textPadding.left = 5;
WorkersPanelText.textPadding.right = 5;
WorkersPanelText.textColor = new Color32 (51, 51, 51, 160); //r,g,b,a
WorkersPanelText.isInteractive = false;
WorkersPanelText.relativePosition = new Vector3 (WorkersPanelIcon.relativePosition.x + WorkersPanelIcon.width, 1);
int row = 0;
for (int a = 0; a < MaxWorkersUnit*5; a++) {
WorkersBodyRow [row] = BodyRows.AddUIComponent (typeof(WorkersServiceBuildingPanelRow)) as WorkersServiceBuildingPanelRow;
WorkersBodyRow [row].name = "Row_" + LabelPanelName[i] + "_" + a.ToString ();
WorkersBodyRow [row].OnBuilding = 0;
WorkersBodyRow [row].citizen = 0;
WorkersBodyRow [row].Hide ();
row++;
}
} else {
GuestsPanel = BodyRows.AddUIComponent<UIPanel> ();
GuestsPanel.width = 226;
GuestsPanel.height = 25;
GuestsPanel.name = "LabelPanel_" + LabelPanelName [i] + "_0";
GuestsPanel.autoLayoutDirection = LayoutDirection.Vertical;
GuestsPanel.autoLayout = true;
GuestsPanel.Hide ();
GuestsPanelSubRow = GuestsPanel.AddUIComponent<UIPanel> ();
GuestsPanelSubRow.width = 226;
GuestsPanelSubRow.height = 25;
GuestsPanelSubRow.name = "TitlePanel_" + LabelPanelName [i] + "_0";
GuestsPanelSubRow.atlas = MyAtlas.FavCimsAtlas;
GuestsPanelSubRow.backgroundSprite = "bg_row2";
GuestsPanelIcon = GuestsPanelSubRow.AddUIComponent<UIButton> ();
GuestsPanelIcon.name = "LabelPanelIcon_" + LabelPanelName [i] + "_0";
GuestsPanelIcon.width = 17;
GuestsPanelIcon.height = 17;
GuestsPanelIcon.atlas = MyAtlas.FavCimsAtlas;
GuestsPanelIcon.relativePosition = new Vector3 (5, 4);
GuestsPanelText = GuestsPanelSubRow.AddUIComponent<UIButton> ();
GuestsPanelText.name = "LabelPanelText_" + LabelPanelName [i] + "_0";
GuestsPanelText.width = 200;
GuestsPanelText.height = 25;
GuestsPanelText.textVerticalAlignment = UIVerticalAlignment.Middle;
GuestsPanelText.textHorizontalAlignment = UIHorizontalAlignment.Left;
GuestsPanelText.playAudioEvents = true;
GuestsPanelText.font = UIDynamicFont.FindByName ("OpenSans-Regular");
GuestsPanelText.font.size = 15;
GuestsPanelText.textScale = 0.80f;
GuestsPanelText.useDropShadow = true;
GuestsPanelText.dropShadowOffset = new Vector2 (1, -1);
GuestsPanelText.dropShadowColor = new Color32 (0, 0, 0, 0);
GuestsPanelText.textPadding.left = 5;
GuestsPanelText.textPadding.right = 5;
GuestsPanelText.textColor = new Color32 (51, 51, 51, 160); //r,g,b,a
GuestsPanelText.isInteractive = false;
GuestsPanelText.relativePosition = new Vector3 (GuestsPanelIcon.relativePosition.x + GuestsPanelIcon.width, 1);
int row = 0;
for (int a = 0; a < MaxGuestsUnit*5; a++) {
GuestsBodyRow [row] = BodyRows.AddUIComponent (typeof(GuestsServiceBuildingPanelRow)) as GuestsServiceBuildingPanelRow;
GuestsBodyRow [row].name = "Row_" + LabelPanelName[i] + "_" + a.ToString ();
GuestsBodyRow [row].OnBuilding = 0;
GuestsBodyRow [row].citizen = 0;
GuestsBodyRow [row].Hide ();
row++;
}
}
}
BodyPanelScrollBar = BodySpriteBg.AddUIComponent<UIScrollablePanel> ();
BodyPanelScrollBar.name = "BodyPanelScrollBar";
BodyPanelScrollBar.width = 10;
BodyPanelScrollBar.relativePosition = new Vector3 (BodyRows.width + 12, 0);
BodyScrollBar = BodyPanelScrollBar.AddUIComponent<UIScrollbar> ();
BodyScrollBar.width = 10;
BodyScrollBar.name = "BodyScrollBar";
BodyScrollBar.orientation = UIOrientation.Vertical;
BodyScrollBar.pivot = UIPivotPoint.TopRight;
BodyScrollBar.AlignTo (BodyScrollBar.parent, UIAlignAnchor.TopRight);
BodyScrollBar.minValue = 0;
BodyScrollBar.value = 0;
BodyScrollBar.incrementAmount = 25;
BodyPanelTrackSprite = BodyScrollBar.AddUIComponent<UISlicedSprite> ();
BodyPanelTrackSprite.autoSize = true;
BodyPanelTrackSprite.name = "BodyScrollBarTrackSprite";
//BodyPanelTrackSprite.size = BodyPanelTrackSprite.parent.size;
BodyPanelTrackSprite.fillDirection = UIFillDirection.Vertical;
BodyPanelTrackSprite.atlas = MyAtlas.FavCimsAtlas;
BodyPanelTrackSprite.spriteName = "scrollbartrack";
//BodyPanelTrackSprite.spriteName = "ScrollbarTrack";
BodyPanelTrackSprite.relativePosition = BodyScrollBar.relativePosition;
BodyScrollBar.trackObject = BodyPanelTrackSprite;
thumbSprite = BodyScrollBar.AddUIComponent<UISlicedSprite> ();
thumbSprite.name = "BodyScrollBarThumbSprite";
thumbSprite.autoSize = true;
thumbSprite.width = thumbSprite.parent.width;
thumbSprite.fillDirection = UIFillDirection.Vertical;
thumbSprite.atlas = MyAtlas.FavCimsAtlas;
thumbSprite.spriteName = "scrollbarthumb";
//thumbSprite.spriteName = "ScrollbarThumb";
thumbSprite.relativePosition = BodyScrollBar.relativePosition;
BodyScrollBar.thumbObject = thumbSprite;
BodyRows.verticalScrollbar = BodyScrollBar;
/* Thx to CNightwing for this piece of code */
BodyRows.eventMouseWheel += (component, eventParam) => {
var sign = Math.Sign (eventParam.wheelDelta);
BodyRows.scrollPosition += new Vector2 (0, sign * (-1) * BodyScrollBar.incrementAmount);
};
/* End */
Footer = this.AddUIComponent<UIPanel> ();
Footer.name = "PeopleInsideServiceBuildingsFooter";
Footer.width = this.width;
Footer.height = 12;
Footer.relativePosition = new Vector3 (0, Title.height + Body.height);
FooterSpriteBg = Footer.AddUIComponent<UITextureSprite> ();
FooterSpriteBg.width = Footer.width;
FooterSpriteBg.height = Footer.height;
FooterSpriteBg.texture = TextureDB.VehiclePanelFooterBackground;
FooterSpriteBg.relativePosition = Vector3.zero;
UIComponent FavCimsBuildingPanelTrigger_esc = UIView.Find<UIButton> ("Esc");
if (FavCimsBuildingPanelTrigger_esc != null) {
FavCimsBuildingPanelTrigger_esc.eventClick += (component, eventParam) => this.Hide ();
}
} catch (Exception ex) {
Debug.Error (" Service Building Panel Start() : " + ex.ToString ());
}
}
public override void Update() {
if (FavCimsMainClass.UnLoading)
return;
if(BuildingID.IsEmpty) {
if(Garbage) {
Wait = true;
CimsOnBuilding.Clear();
WorkersCount = 0;
GuestsCount = 0;
try
{
WorkersPanel.Hide();
//WorkersPanel.height = 25;
for(int a = 0; a < MaxWorkersUnit*5; a++) {
WorkersBodyRow[a].Hide();
WorkersBodyRow[a].citizen = 0;
WorkersBodyRow[a].OnBuilding = 0;
WorkersBodyRow[a].firstRun = true;
}
GuestsPanel.Hide();
//GuestsPanel.height = 25;
for(int a = 0; a < MaxGuestsUnit*5; a++) {
GuestsBodyRow[a].Hide();
GuestsBodyRow[a].citizen = 0;
GuestsBodyRow[a].OnBuilding = 0;
GuestsBodyRow[a].firstRun = true;
}
Wait = false;
}catch /*(Exception ex)*/ {
//Debug.Error(" Flush Error : " + ex.ToString());
}
Garbage = false;
}
firstRun = true;
return;
}
try
{
buildingInfo = MyBuilding.m_buildings.m_buffer [BuildingID.Building].Info;
if(!CityServiceWorldInfoPanel.GetCurrentInstanceID().IsEmpty && CityServiceWorldInfoPanel.GetCurrentInstanceID() != BuildingID) {
Wait = true;
CimsOnBuilding.Clear();
WorkersCount = 0;
GuestsCount = 0;
WorkersPanel.Hide();
//WorkersPanel.height = 25;
for(int a = 0; a < MaxWorkersUnit*5; a++) {
WorkersBodyRow[a].Hide();
WorkersBodyRow[a].citizen = 0;
WorkersBodyRow[a].OnBuilding = 0;
WorkersBodyRow[a].firstRun = true;
}
GuestsPanel.Hide();
//GuestsPanel.height = 25;
for(int a = 0; a < MaxGuestsUnit*5; a++) {
GuestsBodyRow[a].Hide();
GuestsBodyRow[a].citizen = 0;
GuestsBodyRow[a].OnBuilding = 0;
GuestsBodyRow[a].firstRun = true;
}
BuildingID = CityServiceWorldInfoPanel.GetCurrentInstanceID();
if(BuildingID.IsEmpty) {
return;
}
Wait = false;
}
if (this.isVisible && !BuildingID.IsEmpty) {
Garbage = true;
this.absolutePosition = new Vector3 (RefPanel.absolutePosition.x + RefPanel.width + 5, RefPanel.absolutePosition.y);
this.height = RefPanel.height - 15;
if(25 + ((float)CimsOnBuilding.Count * 25) < (this.height - Title.height - Footer.height)) {
Body.height = this.height - Title.height - Footer.height;
} else if(25 + ((float)CimsOnBuilding.Count * 25) > 400) {
Body.height = 400;
} else {
Body.height = 25 + ((float)CimsOnBuilding.Count * 25);
}
//se dimensione pannello = refpanel => scollbar hide?
BodySpriteBg.height = Body.height;
Footer.relativePosition = new Vector3(0, Title.height + Body.height);
BodyRows.height = Body.height;
BodyPanelScrollBar.height = Body.height;
BodyScrollBar.height = Body.height;
BodyPanelTrackSprite.size = BodyPanelTrackSprite.parent.size;
//thumbSprite.autoSize = true;
seconds -= 1 * Time.deltaTime;
if (seconds <= 0 || firstRun) {
execute = true;
seconds = Run;
} else {
execute = false;
}
if(execute) {
firstRun = false;
BuildingUnits = MyBuilding.m_buildings.m_buffer [BuildingID.Building].m_citizenUnits;
int unitnum = 0;
int rownum = 0;
int total_workers = 0;
while (BuildingUnits != 0 && unitnum < MaxGuestsUnit) {
uint nextUnit = MyCitizen.m_units.m_buffer [BuildingUnits].m_nextUnit;
for (int i = 0; i < 5; i++) {
uint citizen = MyCitizen.m_units.m_buffer [BuildingUnits].GetCitizen (i);
Citizen cItizen = MyCitizen.m_citizens.m_buffer[citizen];
//if (citizen != 0 && !CimsOnBuilding.ContainsKey(citizen) && cItizen.GetBuildingByLocation() == BuildingID.Building) {
if (citizen != 0) {
int forcedToGuest = 0;
InstanceID Target;
CitizenInfo citizenInfo = this.MyCitizen.m_citizens.m_buffer [citizen].GetCitizenInfo (citizen);
string status = citizenInfo.m_citizenAI.GetLocalizedStatus (citizen, ref this.MyCitizen.m_citizens.m_buffer [citizen], out Target);
//int keyIndex = Array.FindIndex(Locale., w => w.IsKey);
//string statusKey = search <= values[key]
if(cItizen.m_workBuilding == BuildingID.Building && buildingInfo.m_class.m_service == ItemClass.Service.Education) {
if(Locale.Get("CITIZEN_STATUS_AT_SCHOOL") == status)
forcedToGuest = 1;
}
if(BuildingID.Building == cItizen.m_workBuilding && forcedToGuest == 0)
total_workers++;
if(!CimsOnBuilding.ContainsKey(citizen)) {
if(buildingInfo.m_class.m_service == ItemClass.Service.PoliceDepartment) {
TitleBuildingName.text = FavCimsLang.text("OnPolice_Building_Service");
} else if(buildingInfo.m_class.m_service == ItemClass.Service.Education) {
TitleBuildingName.text = FavCimsLang.text("OnEducation_Building_Service");
} else if(buildingInfo.m_class.m_service == ItemClass.Service.HealthCare) {
TitleBuildingName.text = FavCimsLang.text("OnMedical_Building_Service");
} else if(buildingInfo.m_class.m_service == ItemClass.Service.Beautification) {
TitleBuildingName.text = FavCimsLang.text ("OnBuilding_Guests");
} else if (buildingInfo.m_class.m_service == ItemClass.Service.Monument) {
TitleBuildingName.text = FavCimsLang.text ("CitizenOnBuildingTitle");
} else {
TitleBuildingName.text = FavCimsLang.text ("OnBuilding_Workers");
}
if (BuildingID.Building == cItizen.m_workBuilding && forcedToGuest == 0) {
WorkersPanel.Show();
WorkersPanelIcon.normalFgSprite = "BworkingIcon";
WorkersPanelText.text = FavCimsLang.text("OnBuilding_Workers") + " (" + FavCimsLang.text("OnBuilding_TotalWorkers") + " " + total_workers + ")";
if(cItizen.GetBuildingByLocation() == BuildingID.Building && cItizen.CurrentLocation != Citizen.Location.Moving) { //Solo quelli che si trovano nell'edificio
WorkersCount++;
if(WorkersPanel != null && WorkersBodyRow[unitnum] != null) {
if(WorkersBodyRow[rownum].citizen != 0 && CimsOnBuilding.ContainsKey(WorkersBodyRow[rownum].citizen)) {
Wait = true;
CimsOnBuilding.Remove(WorkersBodyRow[rownum].citizen);
}
CimsOnBuilding.Add(citizen, BuildingUnits);
//WorkersBodyRow[rownum].parent.height += 25;
WorkersBodyRow[rownum].OnBuilding = BuildingID.Building;
WorkersBodyRow[rownum].citizen = citizen;
WorkersBodyRow[rownum].LocType = Citizen.Location.Work;
WorkersBodyRow[rownum].firstRun = true;
WorkersBodyRow[rownum].Show();
if(Wait)
Wait = false;
}
}
if(WorkersCount == 0) {
WorkersPanelText.text = FavCimsLang.text("OnBuilding_NoWorkers") + " (" + FavCimsLang.text("OnBuilding_TotalWorkers") + " " + total_workers + ")";
}
} else {
GuestsPanel.Show();
if(buildingInfo.m_class.m_service == ItemClass.Service.PoliceDepartment) {
GuestsPanelIcon.atlas = MyAtlas.FavCimsAtlas;
GuestsPanelIcon.normalFgSprite = "FavCimsCrimeArrested";
GuestsPanelText.text = FavCimsLang.text("Citizen_Under_Arrest");
} else if(buildingInfo.m_class.m_service == ItemClass.Service.Education) {
GuestsPanelIcon.atlas = UIView.GetAView().defaultAtlas;
GuestsPanelIcon.normalFgSprite = "IconPolicySchoolsOut";
GuestsPanelText.text = FavCimsLang.text("Citizen_at_School");
} else if(buildingInfo.m_class.m_service == ItemClass.Service.HealthCare) {
GuestsPanelIcon.atlas = UIView.GetAView().defaultAtlas;
GuestsPanelIcon.normalFgSprite = "SubBarHealthcareDefault";
GuestsPanelText.text = FavCimsLang.text("Citizen_on_Clinic");
} else {
GuestsPanelIcon.atlas = MyAtlas.FavCimsAtlas;
GuestsPanelIcon.normalFgSprite = "BcommercialIcon";
GuestsPanelText.text = FavCimsLang.text("OnBuilding_Guests");
}
if(cItizen.GetBuildingByLocation() == BuildingID.Building && cItizen.CurrentLocation != Citizen.Location.Moving) { //Solo quelli che si trovano nell'edificio
GuestsCount++;
if(GuestsPanel != null && GuestsBodyRow[unitnum] != null) {
if(GuestsBodyRow[rownum].citizen != 0 && CimsOnBuilding.ContainsKey(GuestsBodyRow[rownum].citizen)) {
Wait = true;
CimsOnBuilding.Remove(GuestsBodyRow[rownum].citizen);
}
CimsOnBuilding.Add(citizen, BuildingUnits);
//GuestsBodyRow[rownum].parent.height += 25;
GuestsBodyRow[rownum].OnBuilding = BuildingID.Building;
GuestsBodyRow[rownum].citizen = citizen;
GuestsBodyRow[rownum].LocType = Citizen.Location.Visit;
GuestsBodyRow[rownum].firstRun = true;
GuestsBodyRow[rownum].Show();
if(Wait)
Wait = false;
}
}
if(GuestsCount == 0) {
if(buildingInfo.m_class.m_service == ItemClass.Service.PoliceDepartment) {
GuestsPanelText.text = FavCimsLang.text("OnBuilding_noArrested");
} else if(buildingInfo.m_class.m_service == ItemClass.Service.Education) {
GuestsPanelText.text = "Non ci sono studenti";
} else if(buildingInfo.m_class.m_service == ItemClass.Service.HealthCare) {
GuestsPanelText.text = "Nessun paziente";
} else {
GuestsPanelText.text = FavCimsLang.text("OnBuilding_NoGuests");
}
}
}
}
}
rownum++;
}
BuildingUnits = nextUnit;
if (++unitnum > 0x80000) {
break;
}
}
}
} //non mettere else che tanto non si esegue per via dell'event click sul bottone.
}catch /*(Exception ex)*/ {
//Debug.Error(" FavCimsVechiclePanelPT Update Error : " + ex.ToString());
}
}
}
public class WorkersServiceBuildingPanelRow : ResidentialBuildingPanelRow
{
public override bool Wait() {
if (PeopleInsideServiceBuildingsPanel.Wait) {
return true;
}
return false;
}
public override Dictionary<uint,uint> GetCimsDict() {
return PeopleInsideServiceBuildingsPanel.CimsOnBuilding;
}
public override void DecreaseWorkersCount() {
PeopleInsideServiceBuildingsPanel.WorkersCount--;
}
public override void DecreaseGuestsCount() {
PeopleInsideServiceBuildingsPanel.GuestsCount--;
}
}
public class GuestsServiceBuildingPanelRow : WorkersServiceBuildingPanelRow
{
}
}
| |
using System.Collections;
using System.Collections.Generic;
using System;
namespace APproject {
public class Parser {
public const int _EOF = 0;
public const int _ident = 1;
public const int _url = 2;
public const int _number = 3;
public const int _string = 4;
public const int maxT = 40;
const bool T = true;
const bool x = false;
const int minErrDist = 2;
public Scanner scanner;
public Errors errors;
public Token t; // last recognized token
public Token la; // lookahead token
int errDist = minErrDist;
public SymbolTable tab;
public ASTGenerator gen;
private int Afunid = 0;
public void controlForProcedurs(ASTNode node){
if(node != null && node.label == Labels.FunCall ){
Obj obj =(Obj)node.value;
if ( obj.kind == Kinds.fundec && obj.type == Types.fun)
SemErr("the function "+ obj.name +" must to return a correct type for the expression");
}
}
/*-------------------------------------------------------------------------------------------------------------------------------------------------------*/
public Parser(Scanner scanner) {
this.scanner = scanner;
errors = new Errors();
}
void SynErr (int n) {
if (errDist >= minErrDist) errors.SynErr(la.line, la.col, n);
errDist = 0;
}
public void SemErr (string msg) {
if (errDist >= minErrDist) errors.SemErr(t.line, t.col, msg);
errDist = 0;
}
void Get () {
for (;;) {
t = la;
la = scanner.Scan();
if (la.kind <= maxT) { ++errDist; break; }
la = t;
}
}
void Expect (int n) {
if (la.kind==n) Get(); else { SynErr(n); }
}
bool StartOf (int s) {
return set[s, la.kind];
}
void ExpectWeak (int n, int follow) {
if (la.kind == n) Get();
else {
SynErr(n);
while (!StartOf(follow)) Get();
}
}
bool WeakSeparator(int n, int syFol, int repFol) {
int kind = la.kind;
if (kind == n) {Get(); return true;}
else if (StartOf(repFol)) {return false;}
else {
SynErr(n);
while (!(set[syFol, kind] || set[repFol, kind] || set[0, kind])) {
Get();
kind = la.kind;
}
return StartOf(syFol);
}
}
void Fun() {
ASTNode node;
tab.OpenScope();
node = new Node(Labels.Program);
gen.initAST((Node) node);
while (la.kind == 5) {
ProcDecl();
}
tab.CloseScope();
}
void ProcDecl() {
Types type; string name; Obj proc; Obj formal;
FRType rtype; ASTNode fundecl, node1; Term parameter;
Expect(5);
if (la.kind == 1) {
Ident(out name);
proc = tab.NewObj(name, Kinds.fundec, Types.undef);
fundecl = new Node(Labels.FunDecl, proc);
tab.OpenScope(proc);
Expect(6);
while (la.kind == 1) {
Ident(out name);
Type(out type);
formal = tab.NewObj(name, Kinds.var, type);
tab.addFormal(proc,formal);
parameter = new Term(formal);
((Node)fundecl).addChildren(parameter);
while (la.kind == 7) {
Get();
Ident(out name);
Type(out type);
formal = tab.NewObj(name, Kinds.var, type);
tab.addFormal(proc,formal);
parameter = new Term(formal);
((Node)fundecl).addChildren(parameter);
}
}
Expect(8);
Node block = new Node(Labels.Block);
FRType(out rtype);
tab.setFRType(proc,rtype);
Expect(9);
while (StartOf(1)) {
if (la.kind == 22) {
VarDecl(out node1);
((Node)block).addChildren(node1);
} else {
Stat(out node1);
((Node)block).addChildren(node1);
}
}
Expect(10);
((Node)fundecl).addChildren(0,block);
gen.addChildren((Node)fundecl);
tab.CloseScope();
} else if (la.kind == 11) {
Get();
tab.NewObj("Main", Kinds.fundec, Types.undef);
fundecl = new Node(Labels.Main);
tab.OpenScope();
Expect(6);
Expect(8);
Expect(9);
while (StartOf(1)) {
if (la.kind == 22) {
VarDecl(out node1);
((Node)fundecl).addChildren(node1);
} else {
Stat(out node1);
((Node)fundecl).addChildren(node1);
}
}
Expect(10);
gen.addChildren((Node)fundecl);
tab.CloseScope();
} else SynErr(41);
}
void Ident(out string name) {
Expect(1);
name = t.val;
}
void Type(out Types type) {
type = Types.undef;
if (la.kind == 5) {
Get();
type = Types.fun;
} else if (la.kind == 26) {
Get();
type = Types.integer;
} else if (la.kind == 27) {
Get();
type = Types.boolean;
} else if (la.kind == 28) {
Get();
type = Types.url;
} else SynErr(42);
}
void FRType(out FRType rtype) {
Queue<Types> formals; Types type;
FRType rtype1;
rtype = new FRType();
if (la.kind == 5) {
Get();
rtype.type = Types.fun;
formals = new Queue<Types>();
Expect(6);
while (StartOf(2)) {
Type(out type);
formals.Enqueue(type);
while (la.kind == 7) {
Get();
Type(out type);
formals.Enqueue(type);
}
}
Expect(8);
FRType(out rtype1);
rtype1.formals = formals;
rtype.next = rtype1;
} else if (la.kind == 26) {
Get();
rtype.type = Types.integer;
} else if (la.kind == 27) {
Get();
rtype.type = Types.boolean;
} else SynErr(43);
}
void VarDecl(out ASTNode node) {
string name,name1,url; ArrayList names = new ArrayList();
Types type; Types type1; Obj obj,obj1, afobj;
Queue<Types> actualTypes = new Queue<Types>();
ASTNode node1;
Expect(22);
Ident(out name);
node = new Node (Labels.AssigDecl);
names.Add(name);
if (la.kind == 7) {
Get();
Ident(out name);
names.Add(name);
while (la.kind == 7) {
Get();
Ident(out name);
names.Add(name);
}
Type(out type);
Expect(15);
node = new Node (Labels.Decl);
if (type == Types.fun)
SemErr("you cannot declare a type fun without assign it");
foreach(string n in names)
{
obj = tab.NewObj(n, Kinds.var, type);
((Node)node).addChildren(new Term (obj));
}
} else if (StartOf(2)) {
Type(out type);
if (la.kind == 15) {
Get();
obj = tab.NewObj((string)names[0], Kinds.var, type);
if (type == Types.fun)
SemErr("you cannot declare a type fun without assign it");
node = new Node (Labels.Decl);
((Node)node).addChildren(new Term (obj));
} else if (la.kind == 12) {
Get();
switch (la.kind) {
case 17: {
Get();
Expect(6);
Expect(8);
Expect(15);
obj = tab.NewObj((string)names[0], Kinds.var, type);
tab.setAsyncControl(true);
if(type != Types.integer)
SemErr("incompatible types");
node = new Node (Labels.AssigDecl);
((Node)node).addChildren(new Term (obj));
((Node)node).addChildren(new Node(Labels.Read,la.line-1, la.col));
break;
}
case 1: case 3: case 6: case 23: case 24: case 25: {
CompleteExpr(out type1, out node1);
Expect(15);
if(type != Types.fun)
controlForProcedurs(node1);
obj = tab.NewObj((string)names[0], Kinds.var, type);
if (!(type == type1 || type1 == Types.fun))
SemErr("incompatible types");
node = new Node (Labels.AssigDecl);
((Node)node).addChildren(new Term (obj));
((Node)node).addChildren(node1);
break;
}
case 5: {
AProcDecl(out afobj,out node1);
Expect(15);
obj = tab.NewObj((string)names[0], Kinds.var, type);
if (type != Types.fun)
SemErr("incompatible types");
node = new Node (Labels.AssigDecl);
((Node)node).addChildren(new Term (obj));
((Node)node).addChildren(node1);
break;
}
case 2: {
URL(out url);
Expect(15);
obj = tab.NewObj((string)names[0], Kinds.var, type);
if (type != Types.url)
SemErr("imcompatible Types");
node = new Node (Labels.AssigDecl);
((Node)node).addChildren(new Term (obj));
((Node)node).addChildren(new Term (url));
break;
}
case 13: {
Get();
Expect(9);
Expect(14);
Ident(out name1);
obj = tab.NewObj((string)names[0], Kinds.var, type);
obj.isUsedInAsync = true;
obj1 = tab.Find(name1);
Node async = new Node(Labels.Async);
Node call = new Node(Labels.FunCall, obj1);
Expect(6);
while (StartOf(3)) {
CompleteExpr(out type, out node1);
controlForProcedurs(node1);
actualTypes.Enqueue(type);
((Node)call).addChildren(node1);
while (la.kind == 7) {
Get();
CompleteExpr(out type, out node1);
controlForProcedurs(node1);
actualTypes.Enqueue(type);
((Node)call).addChildren(node1);
}
}
Expect(8);
Expect(10);
Expect(15);
((Node)async).addChildren(call);
((Node)node).addChildren(new Term(obj));
((Node)node).addChildren(async);
if (obj1.kind != Kinds.fundec)
SemErr("object is not a procedure");
else if(tab.getAsyncControl(obj1))
SemErr("procedure " + obj1.name + " contain println or readln ");
if (obj1.type == Types.fun)
SemErr("wrong return type");
tab.checkActualFormalTypes(obj1, actualTypes);
if(obj.type != obj1.type)
SemErr("incompatible types");
break;
}
case 16: {
Get();
Expect(9);
obj = tab.NewObj((string)names[0], Kinds.var, type);
obj.isUsedInDasync = true;
tab.dasyncused = true;
Node dasync = new Node(Labels.Dsync);
if (la.kind == 1) {
Ident(out name1);
obj1 = tab.Find(name1);
if (obj1.type != Types.url)
SemErr("url expected");
dasync.addChildren(new Term(obj1));
} else if (la.kind == 2) {
URL(out url);
dasync.addChildren(new Term(url));
} else SynErr(44);
Expect(7);
Expect(14);
Ident(out name1);
obj1 = tab.Find(name1);
Node call = new Node(Labels.FunCall, obj1);
Expect(6);
while (StartOf(3)) {
CompleteExpr(out type, out node1);
controlForProcedurs(node1);
actualTypes.Enqueue(type);
((Node)call).addChildren(node1);
while (la.kind == 7) {
Get();
CompleteExpr(out type, out node1);
controlForProcedurs(node1);
actualTypes.Enqueue(type);
((Node)call).addChildren(node1);
}
}
Expect(8);
Expect(10);
Expect(15);
((Node)dasync).addChildren(call);
((Node)node).addChildren(new Term(obj));
((Node)node).addChildren(dasync);
if (obj1.kind != Kinds.fundec)
SemErr("object is not a procedure");
else if(tab.getAsyncControl(obj1))
SemErr("procedure " + obj1.name + " contain println or readln ");
if (obj1.type == Types.fun)
SemErr("wrong return type");
tab.checkActualFormalTypes(obj1, actualTypes);
if(obj.type != obj1.type)
SemErr("incompatible types");
break;
}
default: SynErr(45); break;
}
} else SynErr(46);
} else SynErr(47);
}
void Stat(out ASTNode node) {
Types type,type1; string name,url; string name1; Obj obj, obj1, robj;
Queue<Types> actualTypes = new Queue<Types>();
ASTNode node1;
node = new Node(Labels.Assig);
if (la.kind == 1) {
Ident(out name);
obj = tab.Find(name);
Expect(12);
if ( obj.kind != Kinds.var )
SemErr("cannot assign to procedure");
if (la.kind == 13) {
Get();
Expect(9);
Expect(14);
Ident(out name1);
obj.isUsedInAsync = true;
obj1 = tab.Find(name1);
Node async = new Node(Labels.Async);
Node call = new Node(Labels.FunCall, obj1);
Expect(6);
while (StartOf(3)) {
CompleteExpr(out type, out node1);
controlForProcedurs(node1);
actualTypes.Enqueue(type);
((Node)call).addChildren(node1);
while (la.kind == 7) {
Get();
CompleteExpr(out type, out node1);
controlForProcedurs(node1);
actualTypes.Enqueue(type);
((Node)call).addChildren(node1);
}
}
Expect(8);
Expect(10);
Expect(15);
((Node)async).addChildren(call);
((Node)node).addChildren(new Term(obj));
((Node)node).addChildren(async);
if (obj1.kind != Kinds.fundec)
SemErr("object is not a procedure");
else if(tab.getAsyncControl(obj1))
SemErr("procedure " + obj1.name + " contain println or readln ");
if (obj1.type == Types.fun)
SemErr("wrong return type");
tab.checkActualFormalTypes(obj1, actualTypes);
if(obj.type != obj1.type)
SemErr("incompatible types");
} else if (la.kind == 16) {
Get();
Expect(9);
obj.isUsedInDasync = true;
tab.dasyncused = true;
Node dasync = new Node(Labels.Dsync);
if (la.kind == 1) {
Ident(out name1);
obj1 = tab.Find(name1);
if (obj1.type != Types.url)
SemErr("url expected");
dasync.addChildren(new Term(obj1));
} else if (la.kind == 2) {
URL(out url);
dasync.addChildren(new Term(url));
} else SynErr(48);
Expect(7);
Expect(14);
Ident(out name1);
obj1 = tab.Find(name1);
Node call = new Node(Labels.FunCall, obj1);
Expect(6);
while (StartOf(3)) {
CompleteExpr(out type, out node1);
controlForProcedurs(node1);
actualTypes.Enqueue(type);
((Node)call).addChildren(node1);
while (la.kind == 7) {
Get();
CompleteExpr(out type, out node1);
controlForProcedurs(node1);
actualTypes.Enqueue(type);
((Node)call).addChildren(node1);
}
}
Expect(8);
Expect(10);
Expect(15);
((Node)dasync).addChildren(call);
((Node)node).addChildren(new Term(obj));
((Node)node).addChildren(dasync);
if (obj1.kind != Kinds.fundec)
SemErr("object is not a procedure");
else if(tab.getAsyncControl(obj1))
SemErr("procedure " + obj1.name + " contain println or readln ");
if (obj1.type == Types.fun)
SemErr("wrong return type");
tab.checkActualFormalTypes(obj1, actualTypes);
if(obj.type != obj1.type)
SemErr("incompatible types");
} else if (StartOf(3)) {
CompleteExpr(out type, out node1);
Expect(15);
if (obj.type != Types.fun)
controlForProcedurs(node1);
if ( !(type == obj.type || type == Types.fun) )
SemErr("incompatible types");
((Node)node).addChildren(new Term(obj));
((Node)node).addChildren(node1);
} else if (la.kind == 5) {
AProcDecl(out robj, out node1);
Expect(15);
((Node)node).addChildren(new Term(obj));
((Node)node).addChildren(node1);
} else if (la.kind == 17) {
Get();
Expect(6);
Expect(8);
Expect(15);
tab.setAsyncControl(true);
if(obj.type != Types.integer)
SemErr("incompatible types");
((Node)node).addChildren(new Term(obj));
((Node)node).addChildren(new Node(Labels.Read));
} else SynErr(49);
} else if (la.kind == 18) {
Get();
CompleteExpr(out type, out node1);
controlForProcedurs(node1);
int returnCounter = 0;
tab.ifNesting++;
node = new Node(Labels.If);
((Node)node).addChildren(node1);
Node thenBlock = new Node(Labels.Block);
if (!(type == Types.boolean || type == Types.fun))
SemErr("boolean type expected");
tab.OpenScope();
Expect(9);
while (StartOf(1)) {
if (la.kind == 14) {
Return(out node1);
if(tab.ifNesting == 1)
returnCounter++;
((Node)thenBlock).addChildren(node1);
} else if (StartOf(4)) {
Stat(out node1);
((Node)thenBlock).addChildren(node1);
} else {
VarDecl(out node1);
((Node)thenBlock).addChildren(node1);
}
}
Expect(10);
((Node)node).addChildren(thenBlock);
tab.ifNesting--;
tab.CloseScope();
if (la.kind == 19) {
tab.OpenScope();
Get();
tab.ifNesting++;
Node elseBlock = new Node(Labels.Block);
Expect(9);
while (StartOf(1)) {
if (la.kind == 14) {
Return(out node1);
if(tab.ifNesting == 1)
returnCounter++;
((Node)elseBlock).addChildren(node1);
} else if (StartOf(4)) {
Stat(out node1);
((Node)elseBlock).addChildren(node1);
} else {
VarDecl(out node1);
((Node)elseBlock).addChildren(node1);
}
}
Expect(10);
((Node)node).addChildren(elseBlock);
if (returnCounter == 2){
obj = tab.getOwner();
if(obj != null){
obj.returnIsSet=true;
}
}
tab.ifNesting--;
tab.CloseScope();
}
} else if (la.kind == 20) {
Get();
CompleteExpr(out type, out node1);
controlForProcedurs(node1);
node = new Node(Labels.While);
((Node)node).addChildren(node1);
Node whileBlock =new Node(Labels.Block);
if (type != Types.boolean)
SemErr("boolean type expected");
tab.OpenScope();
Expect(9);
while (StartOf(1)) {
if (StartOf(4)) {
Stat(out node1);
((Node)whileBlock).addChildren(node1);
} else {
VarDecl(out node1);
((Node)whileBlock).addChildren(node1);
}
}
Expect(10);
((Node)node).addChildren(whileBlock);
tab.CloseScope();
} else if (la.kind == 21) {
Get();
Expect(6);
tab.setAsyncControl(true);
node = new Node(Labels.Print,la.line, la.col);
if (StartOf(3)) {
CompleteExpr(out type, out node1);
controlForProcedurs(node1);
((Node)node).addChildren(node1);
} else if (la.kind == 4) {
Get();
string s = t.val.Remove(0, 1);
s = s.Remove(s.Length-1,1);
((Node)node).addChildren(new Term(s));
} else SynErr(50);
Expect(8);
Expect(15);
} else if (la.kind == 14) {
Return(out node);
} else SynErr(51);
}
void AProcDecl(out Obj robj, out ASTNode node) {
string name; Types type; FRType rtype; Obj formal;
ASTNode block, vardeclnode, statnode; Term parameter;
node = new Node(Labels.Afun);
robj = tab.NewObj(Convert.ToString(Afunid++), Kinds.fundec, Types.undef);
tab.OpenScope(robj);
Expect(5);
Expect(6);
while (la.kind == 1) {
Ident(out name);
Type(out type);
formal = tab.NewObj(name, Kinds.var, type);
tab.addFormal(robj,formal);
parameter = new Term(formal);
((Node)node).addChildren(parameter);
while (la.kind == 7) {
Get();
Ident(out name);
Type(out type);
formal = tab.NewObj(name, Kinds.var, type);
tab.addFormal(robj,formal);
parameter = new Term(formal);
((Node)node).addChildren(parameter);
}
}
Expect(8);
FRType(out rtype);
block = new Node(Labels.Block);
tab.setFRType(robj,rtype);
Expect(9);
while (StartOf(1)) {
if (la.kind == 22) {
VarDecl(out vardeclnode);
((Node)block).addChildren(vardeclnode);
} else {
Stat(out statnode);
((Node)block).addChildren(statnode);
}
}
Expect(10);
((Node)node).addChildren(0,block);
tab.CloseScope();
}
void CompleteExpr(out Types type, out ASTNode node) {
Types type1; ASTNode op, secondExpr;
Expr(out type,out node);
while (la.kind == 36 || la.kind == 37) {
BoolOp(out op);
Expr(out type1,out secondExpr);
controlForProcedurs(secondExpr);
if(type == Types.fun)
type = type1;
if(type1 == Types.fun)
type1 = type;
if (type != type1)
SemErr("incompatible types");
type = Types.boolean;
((Node)op).addChildren(node);
((Node)op).addChildren(secondExpr);
node = op;
}
}
void URL(out String url) {
Expect(2);
url = t.val.Remove(0, 1);
url = url.Remove(url.Length-1,1);
}
void Return(out ASTNode node) {
Types type; ASTNode node1; Obj obj,robj;
Expect(14);
node = new Node(Labels.Return);
bool controlofblock;
if (StartOf(3)) {
CompleteExpr(out type, out node1);
Expect(15);
((Node)node).addChildren(node1);
tab.getOwner(out obj , out controlofblock);
if(obj != null){
if(controlofblock)
obj.returnIsSet=true;
if(node1.label == Labels.FunCall){
robj =(Obj)node1.value;
if(robj.kind == Kinds.fundec)
tab.complexReturnTypeControl(obj.rtype,robj.rtype);
}
else if( obj.type != type )
SemErr("incompatible return type");
} else {
SemErr("return is not expected");
}
} else if (la.kind == 5) {
AProcDecl(out robj,out node1);
Expect(15);
((Node)node).addChildren(node1);
tab.getOwner(out obj,out controlofblock);
if(obj != null){
if(controlofblock)
obj.returnIsSet=true;
tab.complexReturnTypeControl(obj,robj);
}else {
SemErr("return is not expected");
}
} else SynErr(52);
}
void Expr(out Types type,out ASTNode node) {
Types type1; ASTNode op, secondSimpExpr;
SimpExpr(out type, out node);
if (StartOf(5)) {
RelOp(out op);
SimpExpr(out type1, out secondSimpExpr);
controlForProcedurs(secondSimpExpr);
if(type == Types.fun)
type = type1;
if(type1 == Types.fun)
type1 = type;
if (type != type1)
SemErr("incompatible types");
type = Types.boolean;
((Node)op).addChildren(node);
((Node)op).addChildren(secondSimpExpr);
node = op;
}
}
void BoolOp(out ASTNode op) {
op = new Node(Labels.And);
if (la.kind == 36) {
Get();
} else if (la.kind == 37) {
Get();
op = new Node(Labels.Or);
} else SynErr(53);
}
void SimpExpr(out Types type, out ASTNode node) {
Types type1; ASTNode op, secondTerm;
Term(out type, out node);
while (la.kind == 23 || la.kind == 29) {
AddOp(out op);
Term(out type1,out secondTerm);
controlForProcedurs(secondTerm);
if(type == Types.fun)
type = Types.integer;
if(type1 == Types.fun)
type1 = Types.integer;
if (type != Types.integer || type1 != Types.integer)
SemErr("integer type expected");
((Node)op).addChildren(node);
((Node)op).addChildren(secondTerm);
node = op;
}
}
void RelOp(out ASTNode op) {
op = new Node(Labels.Lt);
switch (la.kind) {
case 30: {
Get();
break;
}
case 31: {
Get();
op = new Node(Labels.Gt);
break;
}
case 32: {
Get();
op = new Node(Labels.Eq);
break;
}
case 33: {
Get();
op = new Node(Labels.NotEq);
break;
}
case 34: {
Get();
op = new Node(Labels.Lte);
break;
}
case 35: {
Get();
op = new Node(Labels.Gte);
break;
}
default: SynErr(54); break;
}
}
void Term(out Types type, out ASTNode node) {
Types type1; ASTNode op, secondfactor;
Factor(out type, out node);
while (la.kind == 38 || la.kind == 39) {
MulOp(out op);
Factor(out type1,out secondfactor);
controlForProcedurs(secondfactor);
if(type == Types.fun)
type = Types.integer;
if(type1 == Types.fun)
type1 = Types.integer;
if ( type != Types.integer || type1 != Types.integer)
SemErr("integer type expected");
((Node)op).addChildren(node);
((Node)op).addChildren(secondfactor);
node = op;
}
}
void AddOp(out ASTNode op) {
op = new Node(Labels.Plus);
if (la.kind == 29) {
Get();
} else if (la.kind == 23) {
Get();
op = new Node(Labels.Minus);
} else SynErr(55);
}
void Factor(out Types type, out ASTNode node) {
int n; Obj obj,robj; string name; Types type1; bool control = false;
Queue<Types> actualTypes = new Queue<Types>(); ASTNode node1;
type = Types.undef;
node = null;
switch (la.kind) {
case 1: {
Ident(out name);
obj = tab.Find(name);
node = new Term(obj);
type = obj.type;
if (la.kind == 6) {
control = true;
node = new Node(Labels.FunCall, obj);
Obj owner = tab.getOwner();
if(owner != null){
if (owner.name == obj.name){
owner.recursive = true;
}
}
Get();
while (StartOf(6)) {
if (StartOf(3)) {
CompleteExpr(out type1, out node1);
actualTypes.Enqueue(type1);
((Node)node).addChildren(node1);
} else {
AProcDecl(out robj, out node1);
actualTypes.Enqueue(Types.fun);
((Node)node).addChildren(node1);
}
while (la.kind == 7) {
Get();
if (StartOf(3)) {
CompleteExpr(out type1, out node1);
actualTypes.Enqueue(type1);
((Node)node).addChildren(node1);
} else if (la.kind == 5) {
AProcDecl(out robj, out node1);
actualTypes.Enqueue(Types.fun);
((Node)node).addChildren(node1);
} else SynErr(56);
}
}
Expect(8);
if (!(obj.type == Types.fun || obj.kind == Kinds.fundec) )
SemErr(name+" is not a function");
else
tab.checkActualFormalTypes(obj, actualTypes);
}
if (!control && obj.kind != Kinds.var)
SemErr("variable expected");
break;
}
case 3: {
Get();
n = Convert.ToInt32(t.val);
node = new Term(n);
type = Types.integer;
break;
}
case 23: {
Get();
Factor(out type,out node1);
node = new Node(Labels.Negativ);
((Node)node).addChildren(node1);
if (type != Types.integer)
SemErr("integer type expected");
type = Types.integer;
break;
}
case 24: {
Get();
node = new Term(true);
type = Types.boolean;
break;
}
case 25: {
Get();
node = new Term(false);
type = Types.boolean;
break;
}
case 6: {
Get();
CompleteExpr(out type1, out node1);
Expect(8);
controlForProcedurs(node1);
node = new Node(Labels.Bracket);
((Node)node).addChildren(node1);
type = type1;
break;
}
default: SynErr(57); break;
}
}
void MulOp(out ASTNode op) {
op = new Node(Labels.Mul);
if (la.kind == 38) {
Get();
} else if (la.kind == 39) {
Get();
op = new Node(Labels.Div);
} else SynErr(58);
}
public void Parse() {
la = new Token();
la.val = "";
Get();
Fun();
Expect(0);
}
static readonly bool[,] set = {
{T,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x},
{x,T,x,x, x,x,x,x, x,x,x,x, x,x,T,x, x,x,T,x, T,T,T,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x},
{x,x,x,x, x,T,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,T,T, T,x,x,x, x,x,x,x, x,x,x,x, x,x},
{x,T,x,T, x,x,T,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,T, T,T,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x},
{x,T,x,x, x,x,x,x, x,x,x,x, x,x,T,x, x,x,T,x, T,T,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x},
{x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,T,T, T,T,T,T, x,x,x,x, x,x},
{x,T,x,T, x,T,T,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,T, T,T,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x}
};
} // end Parser
public class Errors {
public int count = 0; // number of errors detected
public System.IO.TextWriter errorStream = Console.Out; // error messages go to this stream
public string errMsgFormat = "-- line {0} col {1}: {2}"; // 0=line, 1=column, 2=text
public virtual void SynErr (int line, int col, int n) {
string s;
switch (n) {
case 0: s = "EOF expected"; break;
case 1: s = "ident expected"; break;
case 2: s = "url expected"; break;
case 3: s = "number expected"; break;
case 4: s = "string expected"; break;
case 5: s = "\"fun\" expected"; break;
case 6: s = "\"(\" expected"; break;
case 7: s = "\",\" expected"; break;
case 8: s = "\")\" expected"; break;
case 9: s = "\"{\" expected"; break;
case 10: s = "\"}\" expected"; break;
case 11: s = "\"main\" expected"; break;
case 12: s = "\"=\" expected"; break;
case 13: s = "\"async\" expected"; break;
case 14: s = "\"return\" expected"; break;
case 15: s = "\";\" expected"; break;
case 16: s = "\"dasync\" expected"; break;
case 17: s = "\"readln\" expected"; break;
case 18: s = "\"if\" expected"; break;
case 19: s = "\"else\" expected"; break;
case 20: s = "\"while\" expected"; break;
case 21: s = "\"println\" expected"; break;
case 22: s = "\"var\" expected"; break;
case 23: s = "\"-\" expected"; break;
case 24: s = "\"true\" expected"; break;
case 25: s = "\"false\" expected"; break;
case 26: s = "\"int\" expected"; break;
case 27: s = "\"bool\" expected"; break;
case 28: s = "\"url\" expected"; break;
case 29: s = "\"+\" expected"; break;
case 30: s = "\"<\" expected"; break;
case 31: s = "\">\" expected"; break;
case 32: s = "\"==\" expected"; break;
case 33: s = "\"!=\" expected"; break;
case 34: s = "\"<=\" expected"; break;
case 35: s = "\">=\" expected"; break;
case 36: s = "\"&&\" expected"; break;
case 37: s = "\"||\" expected"; break;
case 38: s = "\"*\" expected"; break;
case 39: s = "\"/\" expected"; break;
case 40: s = "??? expected"; break;
case 41: s = "invalid ProcDecl"; break;
case 42: s = "invalid Type"; break;
case 43: s = "invalid FRType"; break;
case 44: s = "invalid VarDecl"; break;
case 45: s = "invalid VarDecl"; break;
case 46: s = "invalid VarDecl"; break;
case 47: s = "invalid VarDecl"; break;
case 48: s = "invalid Stat"; break;
case 49: s = "invalid Stat"; break;
case 50: s = "invalid Stat"; break;
case 51: s = "invalid Stat"; break;
case 52: s = "invalid Return"; break;
case 53: s = "invalid BoolOp"; break;
case 54: s = "invalid RelOp"; break;
case 55: s = "invalid AddOp"; break;
case 56: s = "invalid Factor"; break;
case 57: s = "invalid Factor"; break;
case 58: s = "invalid MulOp"; break;
default: s = "error " + n; break;
}
errorStream.WriteLine(errMsgFormat, line, col, s);
count++;
}
public virtual void SemErr (int line, int col, string s) {
errorStream.WriteLine(errMsgFormat, line, col, s);
count++;
}
public virtual void SemErr (string s) {
errorStream.WriteLine(s);
count++;
}
public virtual void Warning (int line, int col, string s) {
errorStream.WriteLine(errMsgFormat, line, col, s);
}
public virtual void Warning(string s) {
errorStream.WriteLine(s);
}
} // Errors
public class FatalError: Exception {
public FatalError(string m): base(m) {}
}
}
| |
// MbUnit Test Framework
//
// Copyright (c) 2004 Jonathan de Halleux
//
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from
// the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment in the product
// documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must
// not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
// MbUnit HomePage: http://www.mbunit.com
// Author: Jonathan de Halleux
using System;
using System.IO;
using System.Collections;
using System.Collections.Specialized;
using System.Windows.Forms;
using MbUnit.Core.Reports.Serialization;
using MbUnit.Core.Config;
namespace MbUnit.Core.Remoting
{
public class TreeTestDomainCollection : ICollection, IDisposable
{
private IUnitTreeNodeFactory factory;
private AssemblyWatcher watcher = new AssemblyWatcher();
private IDictionary identifierDomains = new SortedList();
private ArrayList list=new ArrayList();
private volatile object syncRoot = new object();
private volatile bool pendingStop = false;
public TreeTestDomainCollection(IUnitTreeNodeFactory factory)
{
if (factory==null)
throw new ArgumentNullException("factory");
this.factory=factory;
this.watcher.Start();
}
public void Stop()
{
lock (this.syncRoot)
{
this.pendingStop = true;
}
}
/// <summary>
/// Gets the assembly watcher
/// </summary>
public AssemblyWatcher Watcher
{
get
{
return this.watcher;
}
}
public TreeTestDomain Add(string testFilePath)
{
if (testFilePath==null)
throw new ArgumentNullException("testFilePath");
if (!File.Exists(testFilePath))
throw new FileNotFoundException("File not found",testFilePath);
// check if already in collection
if (this.ContainsTestAssembly(testFilePath))
throw new ArgumentException("File "+testFilePath+" already loaded");
TreeTestDomain domain = new TreeTestDomain(testFilePath,this.factory);
domain.ShadowCopyFiles = true;
this.identifierDomains.Add(domain.Identifier, domain);
this.list.Add(domain);
this.watcher.Add(testFilePath);
return domain;
}
public void Remove(TreeTestDomain testDomain)
{
if (testDomain==null)
throw new ArgumentNullException("testDomain");
testDomain.Unload();
this.identifierDomains.Remove(testDomain.Identifier);
this.watcher.Remove(testDomain.TestFilePath);
this.list.Remove(testDomain);
testDomain.Dispose();
}
public bool Remove(string testFilePath)
{
if (testFilePath==null)
throw new ArgumentNullException("testFilePath");
foreach(TreeTestDomain td in this)
{
if (td.TestFilePath==testFilePath)
{
this.Remove(td);
return true;
}
}
return false;
}
public bool Contains(TreeTestDomain domain)
{
if (domain==null)
throw new ArgumentNullException("domain");
return this.list.Contains(domain);
}
public bool ContainsTestAssembly(string testFilePath)
{
foreach(TreeTestDomain domain in this.list)
{
if (domain.TestFilePath==testFilePath)
return true;
}
return false;
}
public void Clear()
{
this.Unload();
foreach(TreeTestDomain td in this)
{
td.Dispose();
}
this.Watcher.Clear();
this.identifierDomains.Clear();
this.list.Clear();
this.pendingStop = false;
// delete cache folder
String cachePath = Environment.ExpandEnvironmentVariables("%TEMP%/Cache");
CacheFolderHelper.DeleteDir(cachePath);
}
public void RunPipes()
{
try
{
this.pendingStop = false;
this.Watcher.Stop();
foreach(TreeTestDomain domain in this.list)
{
if (this.pendingStop)
return;
domain.TestEngine.RunPipes();
}
}
finally
{
this.Watcher.Start();
}
}
public void RunPipes(UnitTreeNode node)
{
if (node==null)
throw new ArgumentNullException("node");
try
{
this.Watcher.Stop();
TreeTestDomain domain = GetDomain(node.DomainIdentifier);
domain.TestTree.RunPipes(node);
}
finally
{
this.Watcher.Start();
}
}
public ReportRun GetResult(UnitTreeNode node)
{
if (node == null)
throw new ArgumentNullException("node");
TreeTestDomain domain = this.GetDomain(node.DomainIdentifier);
return domain.TestTree.GetResult(node.TestIdentifier);
}
public ReportCounter GetTestCount()
{
ReportCounter count = new ReportCounter();;
foreach(TreeTestDomain domain in this.list)
{
if (domain.TestEngine == null)
continue;
count.AddCounts(domain.TestEngine.GetTestCount());
}
return count;
}
public StringCollection TestFilePaths
{
get
{
StringCollection paths= new StringCollection();
foreach(TreeTestDomain domain in this)
paths.Add(domain.TestFilePath);
return paths;
}
}
public void Reload()
{
foreach(TreeTestDomain td in this.list)
{
td.Reload();
}
}
public void Unload()
{
foreach(TreeTestDomain td in this.list)
{
td.Unload();
}
}
public ReportResult GetReport()
{
ReportResult result = new ReportResult();
result.Date = DateTime.Now;
foreach(TreeTestDomain td in this.list)
{
if (td.TestEngine == null)
continue;
if (td.TestEngine.Report == null)
continue;
if (td.TestEngine.Report.Result == null)
continue;
result.Merge(td.TestEngine.Report.Result);
}
result.UpdateCounts();
return result;
}
public void PopulateFacade(TestTreeNodeFacade facade)
{
if (facade==null)
throw new ArgumentNullException("facade");
foreach(TreeTestDomain td in this.list)
{
td.TestTree.PopulateFacade(facade);
}
}
public delegate int AddNodeDelegate(System.Windows.Forms.TreeNode node);
public void PopulateChildTree(TreeView tree,TestTreeNodeFacade facade)
{
foreach(TreeTestDomain td in this.list)
{
UnitTreeNode node = this.factory.CreateUnitTreeNode(
td.TestTree.ParentNode.Name,
TestNodeType.Populator,
td.Identifier,
td.TestTree.ParentNode.Identifier
);
tree.Invoke(new AddNodeDelegate(tree.Nodes.Add),new Object[]{node});
td.PopulateChildTree(node,facade);
}
}
protected TreeTestDomain GetDomain(Guid identifier)
{
TreeTestDomain domain = this.identifierDomains[identifier] as TreeTestDomain;
if (domain==null)
throw new InvalidOperationException("Could not find domain");
return domain;
}
public int Count
{
get
{
return this.list.Count;
}
}
public IEnumerator GetEnumerator()
{
return this.list.GetEnumerator();
}
public void CopyTo(Array array, int index)
{
this.list.CopyTo(array,index);
}
public Object SyncRoot
{
get
{
return null;
}
}
public bool IsSynchronized
{
get
{
return false;
}
}
#region IDisposable Members
public void Dispose()
{
this.Unload();
this.Clear();
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Newtonsoft.Json.Linq;
using NUnit.Framework;
using ReactNative.Bridge;
using ReactNative.Bridge.Queue;
using ReactNative.Modules.Core;
using ReactNative.UIManager;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Threading;
namespace ReactNative.Tests.UIManager
{
[TestFixture, Apartment(ApartmentState.STA)]
public class UIManagerModuleTests
{
[Test]
public void UIManagerModule_ArgumentChecks()
{
var context = new ReactContext();
var viewManagers = new List<IViewManager>();
var uiImplementationProvider = new UIImplementationProvider();
using (var actionQueue = new ActionQueue(ex => { }))
{
ArgumentNullException ex1 = Assert.Throws<ArgumentNullException>(
() => new UIManagerModule(context, null, uiImplementationProvider, actionQueue, UIManagerModuleOptions.None));
Assert.AreEqual("viewManagers", ex1.ParamName);
ArgumentNullException ex2 = Assert.Throws<ArgumentNullException>(
() => new UIManagerModule(context, viewManagers, null, actionQueue, UIManagerModuleOptions.None));
Assert.AreEqual("uiImplementationProvider", ex2.ParamName);
ArgumentNullException ex3 = Assert.Throws<ArgumentNullException>(
() => new UIManagerModule(context, viewManagers, uiImplementationProvider, null, UIManagerModuleOptions.None));
Assert.AreEqual("layoutActionQueue", ex3.ParamName);
}
}
[Test]
public async Task UIManagerModule_CustomEvents_Constants()
{
var context = new ReactContext();
var viewManagers = new List<IViewManager> { new NoEventsViewManager() };
ReactNative.Bridge.DispatcherHelpers.MainDispatcher = Dispatcher.CurrentDispatcher;
await DispatcherHelpers.RunOnDispatcherAsync(ReactChoreographer.Initialize);
var uiImplementationProvider = new UIImplementationProvider();
using (var actionQueue = new ActionQueue(ex => { }))
{
var module = await DispatcherHelpers.CallOnDispatcherAsync(
() => new UIManagerModule(context, viewManagers, uiImplementationProvider, actionQueue, UIManagerModuleOptions.None));
var constants = ((INativeModule)module).Constants;
Assert.AreEqual("onSelect", constants.GetMap("genericBubblingEventTypes").GetMap("topSelect").GetMap("phasedRegistrationNames").GetValue("bubbled").Value<string>());
Assert.AreEqual("onSelectCapture", constants.GetMap("genericBubblingEventTypes").GetMap("topSelect").GetMap("phasedRegistrationNames").GetValue("captured").Value<string>());
Assert.AreEqual("onChange", constants.GetMap("genericBubblingEventTypes").GetMap("topChange").GetMap("phasedRegistrationNames").GetValue("bubbled").Value<string>());
Assert.AreEqual("onChangeCapture", constants.GetMap("genericBubblingEventTypes").GetMap("topChange").GetMap("phasedRegistrationNames").GetValue("captured").Value<string>());
Assert.AreEqual("onTouchStart", constants.GetMap("genericBubblingEventTypes").GetMap("topTouchStart").GetMap("phasedRegistrationNames").GetValue("bubbled").Value<string>());
Assert.AreEqual("onTouchStartCapture", constants.GetMap("genericBubblingEventTypes").GetMap("topTouchStart").GetMap("phasedRegistrationNames").GetValue("captured").Value<string>());
Assert.AreEqual("onTouchMove", constants.GetMap("genericBubblingEventTypes").GetMap("topTouchMove").GetMap("phasedRegistrationNames").GetValue("bubbled").Value<string>());
Assert.AreEqual("onTouchMoveCapture", constants.GetMap("genericBubblingEventTypes").GetMap("topTouchMove").GetMap("phasedRegistrationNames").GetValue("captured").Value<string>());
Assert.AreEqual("onTouchEnd", constants.GetMap("genericBubblingEventTypes").GetMap("topTouchEnd").GetMap("phasedRegistrationNames").GetValue("bubbled").Value<string>());
Assert.AreEqual("onTouchEndCapture", constants.GetMap("genericBubblingEventTypes").GetMap("topTouchEnd").GetMap("phasedRegistrationNames").GetValue("captured").Value<string>());
Assert.AreEqual("onMouseOver", constants.GetMap("genericBubblingEventTypes").GetMap("topMouseOver").GetMap("phasedRegistrationNames").GetValue("bubbled").Value<string>());
Assert.AreEqual("onMouseOverCapture", constants.GetMap("genericBubblingEventTypes").GetMap("topMouseOver").GetMap("phasedRegistrationNames").GetValue("captured").Value<string>());
Assert.AreEqual("onMouseOut", constants.GetMap("genericBubblingEventTypes").GetMap("topMouseOut").GetMap("phasedRegistrationNames").GetValue("bubbled").Value<string>());
Assert.AreEqual("onMouseOutCapture", constants.GetMap("genericBubblingEventTypes").GetMap("topMouseOut").GetMap("phasedRegistrationNames").GetValue("captured").Value<string>());
Assert.AreEqual("onSelectionChange", constants.GetMap("genericDirectEventTypes").GetMap("topSelectionChange").GetValue("registrationName").Value<string>());
Assert.AreEqual("onLoadingStart", constants.GetMap("genericDirectEventTypes").GetMap("topLoadingStart").GetValue("registrationName").Value<string>());
Assert.AreEqual("onLoadingFinish", constants.GetMap("genericDirectEventTypes").GetMap("topLoadingFinish").GetValue("registrationName").Value<string>());
Assert.AreEqual("onLoadingError", constants.GetMap("genericDirectEventTypes").GetMap("topLoadingError").GetValue("registrationName").Value<string>());
Assert.AreEqual("onLayout", constants.GetMap("genericDirectEventTypes").GetMap("topLayout").GetValue("registrationName").Value<string>());
Assert.AreEqual("onMouseEnter", constants.GetMap("genericDirectEventTypes").GetMap("topMouseEnter").GetValue("registrationName").Value<string>());
Assert.AreEqual("onMouseLeave", constants.GetMap("genericDirectEventTypes").GetMap("topMouseLeave").GetValue("registrationName").Value<string>());
Assert.AreEqual("onMessage", constants.GetMap("genericDirectEventTypes").GetMap("topMessage").GetValue("registrationName").Value<string>());
}
// Ideally we should dispose, but the original dispatcher is somehow lost/etc.
// await DispatcherHelpers.RunOnDispatcherAsync(ReactChoreographer.Dispose);
}
[Test]
public async Task UIManagerModule_Constants_ViewManager_CustomEvents()
{
var context = new ReactContext();
var viewManagers = new List<IViewManager> { new TestViewManager() };
ReactNative.Bridge.DispatcherHelpers.MainDispatcher = Dispatcher.CurrentDispatcher;
await DispatcherHelpers.RunOnDispatcherAsync(ReactChoreographer.Initialize);
var uiImplementationProvider = new UIImplementationProvider();
using (var actionQueue = new ActionQueue(ex => { }))
{
var module = await DispatcherHelpers.CallOnDispatcherAsync(
() => new UIManagerModule(context, viewManagers, uiImplementationProvider, actionQueue, UIManagerModuleOptions.None));
var constants = ((INativeModule)module).Constants.GetMap("Test");
Assert.AreEqual(42, constants.GetMap("directEventTypes").GetValue("otherSelectionChange").Value<int>());
Assert.AreEqual(42, constants.GetMap("directEventTypes").GetMap("topSelectionChange").GetValue("registrationName").Value<int>());
Assert.AreEqual(42, constants.GetMap("directEventTypes").GetMap("topLoadingStart").GetValue("foo").Value<int>());
Assert.AreEqual(42, constants.GetMap("directEventTypes").GetValue("topLoadingError").Value<int>());
}
// Ideally we should dispose, but the original dispatcher is somehow lost/etc.
// await DispatcherHelpers.RunOnDispatcherAsync(ReactChoreographer.Dispose);
}
[Test]
public async Task UIManagerModule_Constants_ViewManager_LazyConstants()
{
var context = new ReactContext();
var viewManagers = new List<IViewManager> { new TestViewManager() };
ReactNative.Bridge.DispatcherHelpers.MainDispatcher = Dispatcher.CurrentDispatcher;
await DispatcherHelpers.RunOnDispatcherAsync(ReactChoreographer.Initialize);
var uiImplementationProvider = new UIImplementationProvider();
using (var actionQueue = new ActionQueue(ex => { }))
{
var module = await DispatcherHelpers.CallOnDispatcherAsync(
() => new UIManagerModule(context, viewManagers, uiImplementationProvider, actionQueue, UIManagerModuleOptions.LazyViewManagers));
var obj = ((INativeModule)module).Constants.GetValue("ViewManagerNames");
var viewManagerNames = obj as JArray;
Assert.IsNotNull(viewManagerNames);
Assert.AreEqual(1, viewManagerNames.Count());
Assert.AreEqual("Test", viewManagerNames.Single().Value<string>());
}
// Ideally we should dispose, but the original dispatcher is somehow lost/etc.
// await DispatcherHelpers.RunOnDispatcherAsync(ReactChoreographer.Dispose);
}
[Test]
public async Task UIManagerModule_getConstantsForViewManager()
{
var context = new ReactContext();
var viewManagers = new List<IViewManager> { new TestViewManager() };
ReactNative.Bridge.DispatcherHelpers.MainDispatcher = Dispatcher.CurrentDispatcher;
await DispatcherHelpers.RunOnDispatcherAsync(ReactChoreographer.Initialize);
var uiImplementationProvider = new UIImplementationProvider();
using (var actionQueue = new ActionQueue(ex => { }))
{
var module = await DispatcherHelpers.CallOnDispatcherAsync(
() => new UIManagerModule(context, viewManagers, uiImplementationProvider, actionQueue, UIManagerModuleOptions.LazyViewManagers));
var constants = module.getConstantsForViewManager("Test");
Assert.AreEqual(42, constants.GetMap("directEventTypes").GetValue("otherSelectionChange").Value<int>());
Assert.AreEqual(42, constants.GetMap("directEventTypes").GetMap("topSelectionChange").GetValue("registrationName").Value<int>());
Assert.AreEqual(42, constants.GetMap("directEventTypes").GetMap("topLoadingStart").GetValue("foo").Value<int>());
Assert.AreEqual(42, constants.GetMap("directEventTypes").GetValue("topLoadingError").Value<int>());
}
// Ideally we should dispose, but the original dispatcher is somehow lost/etc.
// await DispatcherHelpers.RunOnDispatcherAsync(ReactChoreographer.Dispose);
}
class NoEventsViewManager : MockViewManager
{
public override JObject CommandsMap
{
get
{
return null;
}
}
public override JObject ExportedCustomBubblingEventTypeConstants
{
get
{
return null;
}
}
public override JObject ExportedCustomDirectEventTypeConstants
{
get
{
return null;
}
}
public override JObject ExportedViewConstants
{
get
{
return null;
}
}
public override JObject NativeProps
{
get
{
return null;
}
}
public override string Name
{
get
{
return "Test";
}
}
public override Type ShadowNodeType
{
get
{
return typeof(ReactShadowNode);
}
}
}
class TestViewManager : NoEventsViewManager
{
public override JObject ExportedCustomDirectEventTypeConstants
{
get
{
return new JObject
{
{ "otherSelectionChange", 42 },
{ "topSelectionChange", new JObject { { "registrationName", 42 } } },
{ "topLoadingStart", new JObject { { "foo", 42 } } },
{ "topLoadingError", 42 },
};
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using EnvDTE;
using EnvDTE80;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.IO;
using log4net;
using Knowledge.Editor.Model;
using Knowledge.Editor.Controller;
namespace Knowledge.Editor.View
{
/*
*
*/
class TextEditorHelper
{
private static readonly ILog log = LogManager.GetLogger(typeof(TextEditorHelper));
public static void navigate(KnowledgeController controller, Object tag, String sourceFile)
{
try
{
log.Debug(" navigation ... ");
string regExpression = getRegExpr(tag);
if (regExpression == null) { return; }
string actualString = getActualString(sourceFile, regExpression);
if (actualString == null) { return; }
Window textEditor = controller.environment.ApplicationObject.OpenFile(Constants.vsViewKindCode, sourceFile);
TextSelection textSelection = (TextSelection)textEditor.Document.Selection;
textSelection.StartOfDocument(false);
textSelection.EndOfDocument(false);
// TODO: textSelection.findPattern doesn't work for some reason
if (textSelection.FindText(actualString, (int)vsFindOptions.vsFindOptionsFromStart)){
textSelection.SelectLine();
}else{
log.Debug("log. actualString is not found in text file, actualString="+actualString);
}
textEditor.Visible = true;
textEditor.Activate();
// TODO: save of the document
}
catch (Exception e0)
{
MessageBox.Show(e0.Message);
}
}
private static string getRegExpr(Object tag)
{
string pattern;
string spaces = "\\s+";
if (KnowledgeAdapter.isClassFrame(tag))
{
string name = KnowledgeAdapter.getFrameName(tag);
pattern = "frame" + spaces + "class" + spaces + name;
}
else if (KnowledgeAdapter.isInstanceFrame(tag))
{
string name = KnowledgeAdapter.getFrameName(tag);
pattern = "frame" + spaces + "instance" + spaces + name;
}
else if (KnowledgeAdapter.isRuleFrame(tag))
{
string name = KnowledgeAdapter.getFrameName(tag);
pattern = "frame" + spaces + "ruleset" + spaces + name;
}
else
{
pattern = null;
}
// TODO: slots
log.Debug(" regular expression = "+pattern);
return pattern;
}
/*
public void update(ChangeEvent ce, string sourceFile)
{
try
{
// ADD for Frames is not implemented
if (ce.getChangeID() == ChangeEvent.REMOVE &&
// it's frame knowledges
ce.getSource().getID() >= 10 &&
ce.getSource().getID() >= 20){
writer.WriteLine("log. ADD for Frames is not implemented");
return;
}
string regExpression = getRegExpr(ce);
if (regExpression == null) { return; }
string actualString = getActualString(sourceFile, regExpression);
if (actualString == null) { return; }
Window textEditor = Manager.getInstance().getEnvironment().ApplicationObject.OpenFile(Constants.vsViewKindCode, sourceFile);
TextSelection textSelection = (TextSelection)textEditor.Document.Selection;
textSelection.StartOfDocument(false);
textSelection.EndOfDocument(false);
// TODO: textSelection.findPattern doesn't work for some reason
if (textSelection.FindText(actualString, (int)vsFindOptions.vsFindOptionsFromStart))
{
textSelection.Cut();
}
else
{
writer.WriteLine("log. actualString is not found in text file, actualString=" + actualString);
}
// TODO: save of the document
}
catch (Exception e0)
{
MessageBox.Show(e0.Message);
}
}
*/
private static string getActualString(string sourceFile, string regExpression) {
FileStream file = new FileStream(sourceFile, FileMode.Open);
StreamReader reader = new StreamReader(file);
string str = reader.ReadToEnd();
MatchCollection Matches = Regex.Matches(str, regExpression, RegexOptions.None);
string matchText = null;
foreach (Match match in Matches)
{
matchText = match.Value;
}
reader.Close();
file.Close();
if (matchText == null){
log.Debug("log. actual text is not found, regExpr="+regExpression);
}
return matchText;
}
/*
private static string getRegExpr(Object tag)
{
KnowledgeNode source = ne.getSource();
int id = source.getID();
string name = source.getName();
string pattern;
string spaces = "\\s+";
if (id == KnowledgeNode.EMPTY)
{
writer.WriteLine("log. empty knowledge -> event skipped");
return null;
}
else if (id == KnowledgeNode.FRAME_CLASS)
{
pattern = "frame" + spaces + "class" + spaces + name;
}
else if (id == KnowledgeNode.FRAME_INSTANCE)
{
pattern = "frame" + spaces + "instance" + spaces + name;
}
else if (id == KnowledgeNode.FRAME_RULESET)
{
pattern = "frame" + spaces + "ruleset" + spaces + name;
}
else if (id == KnowledgeNode.SLOT_OWN)
{
// TODO: not implemented yet
// since class hierarchy is not implemented yet
return null;
}
else if (id == KnowledgeNode.SLOT_INSTANCE)
{
// TODO: not implemented yet
// since class hierarchy is not implemented yet
return null;
}
else
{
writer.WriteLine("log. knowledge is not found, id=" + id);
return null;
}
return pattern;
}
// TODO: text "{}" (for REMOVE) should be removed also !!!
// NOTE: ADD for Frames won't be implemented
/*
private string getRegExpr(ChangeEvent ce) {
KnowledgeNode source = ce.getSource();
int id = source.getID();
string name = source.getName();
string pattern;
string spaces = "\\s+";
if (id == KnowledgeNode.EMPTY)
{
writer.WriteLine("log. empty knowledge -> event skipped");
writer.WriteLine("log. name = "+name);
return null;
}
else if (id == KnowledgeNode.FRAME_CLASS)
{
pattern = "frame" + spaces + "class" + spaces + name;
}
else if (id == KnowledgeNode.FRAME_INSTANCE)
{
pattern = "frame" + spaces + "instance" + spaces + name;
}
else if (id == KnowledgeNode.FRAME_RULESET)
{
pattern = "frame" + spaces + "ruleset" + spaces + name;
}
else if (id == KnowledgeNode.SLOT_OWN)
{
// TODO: not implemented yet
// since class hierarchy is not implemented yet
return null;
}
else if (id == KnowledgeNode.SLOT_INSTANCE)
{
// TODO: not implemented yet
// since class hierarchy is not implemented yet
return null;
}
else
{
writer.WriteLine("log. knowledge is not found, id=" + id);
return null;
}
// TODO: implement the same thing about other types
if (id == KnowledgeNode.FRAME_CLASS ||
id == KnowledgeNode.FRAME_INSTANCE ||
id == KnowledgeNode.FRAME_RULESET)
{
pattern = pattern + spaces + "{" + "[^}]+" + "}";
}
return pattern;
}
* */
}
}
| |
using System.Collections.Generic;
using Umbraco.Core.Models;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.Querying;
using Umbraco.Core.Persistence.UnitOfWork;
namespace Umbraco.Core.Services
{
/// <summary>
/// Tag service to query for tags in the tags db table. The tags returned are only relevant for published content & saved media or members
/// </summary>
/// <remarks>
/// If there is unpublished content with tags, those tags will not be contained
/// </remarks>
public class TagService : ITagService
{
private readonly RepositoryFactory _repositoryFactory;
private readonly IDatabaseUnitOfWorkProvider _uowProvider;
public TagService()
: this(new RepositoryFactory())
{}
public TagService(RepositoryFactory repositoryFactory)
: this(new PetaPocoUnitOfWorkProvider(), repositoryFactory)
{
}
public TagService(IDatabaseUnitOfWorkProvider provider)
: this(provider, new RepositoryFactory())
{
}
public TagService(IDatabaseUnitOfWorkProvider provider, RepositoryFactory repositoryFactory)
{
_repositoryFactory = repositoryFactory;
_uowProvider = provider;
}
/// <summary>
/// Gets tagged Content by a specific 'Tag Group'.
/// </summary>
/// <remarks>The <see cref="TaggedEntity"/> contains the Id and Tags of the Content, not the actual Content item.</remarks>
/// <param name="tagGroup">Name of the 'Tag Group'</param>
/// <returns>An enumerable list of <see cref="TaggedEntity"/></returns>
public IEnumerable<TaggedEntity> GetTaggedContentByTagGroup(string tagGroup)
{
using (var repository = _repositoryFactory.CreateTagRepository(_uowProvider.GetUnitOfWork()))
{
return repository.GetTaggedEntitiesByTagGroup(TaggableObjectTypes.Content, tagGroup);
}
}
/// <summary>
/// Gets tagged Content by a specific 'Tag' and optional 'Tag Group'.
/// </summary>
/// <remarks>The <see cref="TaggedEntity"/> contains the Id and Tags of the Content, not the actual Content item.</remarks>
/// <param name="tag">Tag</param>
/// <param name="tagGroup">Optional name of the 'Tag Group'</param>
/// <returns>An enumerable list of <see cref="TaggedEntity"/></returns>
public IEnumerable<TaggedEntity> GetTaggedContentByTag(string tag, string tagGroup = null)
{
using (var repository = _repositoryFactory.CreateTagRepository(_uowProvider.GetUnitOfWork()))
{
return repository.GetTaggedEntitiesByTag(TaggableObjectTypes.Content, tag, tagGroup);
}
}
/// <summary>
/// Gets tagged Media by a specific 'Tag Group'.
/// </summary>
/// <remarks>The <see cref="TaggedEntity"/> contains the Id and Tags of the Media, not the actual Media item.</remarks>
/// <param name="tagGroup">Name of the 'Tag Group'</param>
/// <returns>An enumerable list of <see cref="TaggedEntity"/></returns>
public IEnumerable<TaggedEntity> GetTaggedMediaByTagGroup(string tagGroup)
{
using (var repository = _repositoryFactory.CreateTagRepository(_uowProvider.GetUnitOfWork()))
{
return repository.GetTaggedEntitiesByTagGroup(TaggableObjectTypes.Media, tagGroup);
}
}
/// <summary>
/// Gets tagged Media by a specific 'Tag' and optional 'Tag Group'.
/// </summary>
/// <remarks>The <see cref="TaggedEntity"/> contains the Id and Tags of the Media, not the actual Media item.</remarks>
/// <param name="tag">Tag</param>
/// <param name="tagGroup">Optional name of the 'Tag Group'</param>
/// <returns>An enumerable list of <see cref="TaggedEntity"/></returns>
public IEnumerable<TaggedEntity> GetTaggedMediaByTag(string tag, string tagGroup = null)
{
using (var repository = _repositoryFactory.CreateTagRepository(_uowProvider.GetUnitOfWork()))
{
return repository.GetTaggedEntitiesByTag(TaggableObjectTypes.Media, tag, tagGroup);
}
}
/// <summary>
/// Gets tagged Members by a specific 'Tag Group'.
/// </summary>
/// <remarks>The <see cref="TaggedEntity"/> contains the Id and Tags of the Member, not the actual Member item.</remarks>
/// <param name="tagGroup">Name of the 'Tag Group'</param>
/// <returns>An enumerable list of <see cref="TaggedEntity"/></returns>
public IEnumerable<TaggedEntity> GetTaggedMembersByTagGroup(string tagGroup)
{
using (var repository = _repositoryFactory.CreateTagRepository(_uowProvider.GetUnitOfWork()))
{
return repository.GetTaggedEntitiesByTagGroup(TaggableObjectTypes.Member, tagGroup);
}
}
/// <summary>
/// Gets tagged Members by a specific 'Tag' and optional 'Tag Group'.
/// </summary>
/// <remarks>The <see cref="TaggedEntity"/> contains the Id and Tags of the Member, not the actual Member item.</remarks>
/// <param name="tag">Tag</param>
/// <param name="tagGroup">Optional name of the 'Tag Group'</param>
/// <returns>An enumerable list of <see cref="TaggedEntity"/></returns>
public IEnumerable<TaggedEntity> GetTaggedMembersByTag(string tag, string tagGroup = null)
{
using (var repository = _repositoryFactory.CreateTagRepository(_uowProvider.GetUnitOfWork()))
{
return repository.GetTaggedEntitiesByTag(TaggableObjectTypes.Member, tag, tagGroup);
}
}
/// <summary>
/// Gets every tag stored in the database
/// </summary>
/// <param name="tagGroup">Optional name of the 'Tag Group'</param>
/// <returns>An enumerable list of <see cref="ITag"/></returns>
public IEnumerable<ITag> GetAllTags(string tagGroup = null)
{
using (var repository = _repositoryFactory.CreateTagRepository(_uowProvider.GetUnitOfWork()))
{
if (tagGroup.IsNullOrWhiteSpace())
{
return repository.GetAll();
}
var query = Query<ITag>.Builder.Where(x => x.Group == tagGroup);
var definitions = repository.GetByQuery(query);
return definitions;
}
}
/// <summary>
/// Gets all tags for content items
/// </summary>
/// <remarks>Use the optional tagGroup parameter to limit the
/// result to a specific 'Tag Group'.</remarks>
/// <param name="tagGroup">Optional name of the 'Tag Group'</param>
/// <returns>An enumerable list of <see cref="ITag"/></returns>
public IEnumerable<ITag> GetAllContentTags(string tagGroup = null)
{
using (var repository = _repositoryFactory.CreateTagRepository(_uowProvider.GetUnitOfWork()))
{
return repository.GetTagsForEntityType(TaggableObjectTypes.Content, tagGroup);
}
}
/// <summary>
/// Gets all tags for media items
/// </summary>
/// <remarks>Use the optional tagGroup parameter to limit the
/// result to a specific 'Tag Group'.</remarks>
/// <param name="tagGroup">Optional name of the 'Tag Group'</param>
/// <returns>An enumerable list of <see cref="ITag"/></returns>
public IEnumerable<ITag> GetAllMediaTags(string tagGroup = null)
{
using (var repository = _repositoryFactory.CreateTagRepository(_uowProvider.GetUnitOfWork()))
{
return repository.GetTagsForEntityType(TaggableObjectTypes.Media, tagGroup);
}
}
/// <summary>
/// Gets all tags for member items
/// </summary>
/// <remarks>Use the optional tagGroup parameter to limit the
/// result to a specific 'Tag Group'.</remarks>
/// <param name="tagGroup">Optional name of the 'Tag Group'</param>
/// <returns>An enumerable list of <see cref="ITag"/></returns>
public IEnumerable<ITag> GetAllMemberTags(string tagGroup = null)
{
using (var repository = _repositoryFactory.CreateTagRepository(_uowProvider.GetUnitOfWork()))
{
return repository.GetTagsForEntityType(TaggableObjectTypes.Member, tagGroup);
}
}
/// <summary>
/// Gets all tags attached to a property by entity id
/// </summary>
/// <remarks>Use the optional tagGroup parameter to limit the
/// result to a specific 'Tag Group'.</remarks>
/// <param name="contentId">The content item id to get tags for</param>
/// <param name="propertyTypeAlias">Property type alias</param>
/// <param name="tagGroup">Optional name of the 'Tag Group'</param>
/// <returns>An enumerable list of <see cref="ITag"/></returns>
public IEnumerable<ITag> GetTagsForProperty(int contentId, string propertyTypeAlias, string tagGroup = null)
{
using (var repository = _repositoryFactory.CreateTagRepository(_uowProvider.GetUnitOfWork()))
{
return repository.GetTagsForProperty(contentId, propertyTypeAlias, tagGroup);
}
}
/// <summary>
/// Gets all tags attached to an entity (content, media or member) by entity id
/// </summary>
/// <remarks>Use the optional tagGroup parameter to limit the
/// result to a specific 'Tag Group'.</remarks>
/// <param name="contentId">The content item id to get tags for</param>
/// <param name="tagGroup">Optional name of the 'Tag Group'</param>
/// <returns>An enumerable list of <see cref="ITag"/></returns>
public IEnumerable<ITag> GetTagsForEntity(int contentId, string tagGroup = null)
{
using (var repository = _repositoryFactory.CreateTagRepository(_uowProvider.GetUnitOfWork()))
{
return repository.GetTagsForEntity(contentId, tagGroup);
}
}
}
}
| |
using System;
using System.IO;
using System.Collections;
using CommonAST = antlr.CommonAST;
using AST = antlr.collections.AST;
using CharBuffer = antlr.CharBuffer;
using RecognitionException = antlr.RecognitionException;
using TokenStreamException = antlr.TokenStreamException;
namespace eduLang
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class TinyC_eval
{
/// <summary>
/// The main entry point for the application.
/// </summary>
///
static void CheckTypes(Value A, Value B, ValueType typ)
{
if(A.Type != typ) throw new Exception("Type Mismatch");
if(B.Type != typ) throw new Exception("Type Mismatch");
}
static Value performBinaryOperator(Value A, string op, Value B, Environment Env)
{
if(A.Type == ValueType.tString)
{
string Left = A.vString;
string Right = B.vStr();
Env.Record("STRING_" + ("" + B.Type).Substring(1).ToUpper() + "_convert");
Env.Record("STRING_left_append" , Left.Length);
Env.Record("STRING_right_append", Right.Length);
return new Value(Left + Right);
}
if(A.Type == ValueType.tReal)
{
Env.Record("FLOAT_binary" + op.ToUpper());
if(op.Equals("+")) { CheckTypes(A,B,ValueType.tReal); return new Value(A.vReal+B.vReal); }
if(op.Equals("*")) { CheckTypes(A,B,ValueType.tReal); return new Value(A.vReal*B.vReal); }
if(op.Equals("-")) { CheckTypes(A,B,ValueType.tReal); return new Value(A.vReal-B.vReal); }
if(op.Equals("/")) { CheckTypes(A,B,ValueType.tReal); return new Value(A.vReal/B.vReal); }
if(op.Equals("%")) { CheckTypes(A,B,ValueType.tReal); return new Value(A.vReal%B.vReal); }
if(op.Equals("<")) { CheckTypes(A,B,ValueType.tReal); return new Value(A.vReal<B.vReal); }
if(op.Equals("<=")) { CheckTypes(A,B,ValueType.tReal); return new Value(A.vReal<=B.vReal); }
if(op.Equals(">=")) { CheckTypes(A,B,ValueType.tReal); return new Value(A.vReal>=B.vReal); }
if(op.Equals(">")) { CheckTypes(A,B,ValueType.tReal); return new Value(A.vReal>B.vReal); }
}
if(A.Type == ValueType.tInt)
{
Env.Record("INT_binary" + op.ToUpper());
if(op.Equals("+")) { CheckTypes(A,B,ValueType.tInt); return new Value(A.vInteger+B.vInteger); }
if(op.Equals("*")) { CheckTypes(A,B,ValueType.tInt); return new Value(A.vInteger*B.vInteger); }
if(op.Equals("-")) { CheckTypes(A,B,ValueType.tInt); return new Value(A.vInteger-B.vInteger); }
if(op.Equals("/")) { CheckTypes(A,B,ValueType.tInt); return new Value(A.vInteger/B.vInteger); }
if(op.Equals("%")) { CheckTypes(A,B,ValueType.tInt); return new Value(A.vInteger%B.vInteger); }
if(op.Equals("<")) { CheckTypes(A,B,ValueType.tInt); return new Value(A.vInteger<B.vInteger); }
if(op.Equals("<=")) { CheckTypes(A,B,ValueType.tInt); return new Value(A.vInteger<=B.vInteger); }
if(op.Equals(">=")) { CheckTypes(A,B,ValueType.tInt); return new Value(A.vInteger>=B.vInteger); }
if(op.Equals(">")) { CheckTypes(A,B,ValueType.tInt); return new Value(A.vInteger>B.vInteger); }
if(op.Equals("<<")) { CheckTypes(A,B,ValueType.tInt); return new Value(A.vInteger<<B.vInteger); }
if(op.Equals(">>")) { CheckTypes(A,B,ValueType.tInt); return new Value(A.vInteger>>B.vInteger); }
}
if(op.Equals("=="))
{
Env.Record(("" + A.Type).Substring(1).ToUpper() + "_binary" + op.ToUpper());
if(A.Type == ValueType.tInt) { CheckTypes(A,B,ValueType.tInt); return new Value(A.vInteger==B.vInteger); }
if(A.Type == ValueType.tChar) { CheckTypes(A,B,ValueType.tChar); return new Value(A.vChar==B.vChar); }
if(A.Type == ValueType.tString) { CheckTypes(A,B,ValueType.tChar); return new Value(A.vString.Equals(B.vString)); }
if(A.Type == ValueType.tBool) { CheckTypes(A,B,ValueType.tBool); return new Value(A.vBoolean == B.vBoolean); }
if(A.Type == ValueType.tReal) { CheckTypes(A,B,ValueType.tBool); return new Value(A.vReal == B.vReal); }
if(A.Type == ValueType.tRef) { CheckTypes(A,B,ValueType.tRef); return new Value(A.rRef == B.rRef); }
}
if(op.Equals("!="))
{
Env.Record(("" + A.Type).Substring(1).ToUpper() + "_binary" + op.ToUpper());
if(A.Type == ValueType.tInt) { CheckTypes(A,B,ValueType.tInt); return new Value(A.vInteger!=B.vInteger); }
if(A.Type == ValueType.tChar) { CheckTypes(A,B,ValueType.tChar); return new Value(A.vChar!=B.vChar); }
if(A.Type == ValueType.tString) { CheckTypes(A,B,ValueType.tChar); return new Value(!A.vString.Equals(B.vString)); }
if(A.Type == ValueType.tBool) { CheckTypes(A,B,ValueType.tBool); return new Value(A.vBoolean != B.vBoolean); }
if(A.Type == ValueType.tReal) { CheckTypes(A,B,ValueType.tBool); return new Value(A.vReal != B.vReal); }
if(A.Type == ValueType.tRef) { CheckTypes(A,B,ValueType.tRef); return new Value(A.rRef != B.rRef); }
}
if(op.Equals("and")) { CheckTypes(A,B,ValueType.tBool); return new Value(A.vBoolean && B.vBoolean); }
if(op.Equals("or")) { CheckTypes(A,B,ValueType.tBool); return new Value(A.vBoolean || B.vBoolean); }
return new Value();
}
public static bool RunTrace;
public static bool ForceTrace = true;
public static LispNode Root;
public static int ListingIdx;
public static string ListingSource;
public static string LastListingData;
public static string LastListingName;
public static string LastListingEnv;
public static string LastListingHeap;
public static string optional(string C, string O)
{
if(C.Equals("\"\"")) return "";
return O;
}
public static string FixConsole(string X)
{
return X.Replace("\"","\\\"").Replace("\n","<br/>").Replace("\t"," ").Replace(" "," ");
}
public enum DiffType {Copy, Original};
public class DiffToken
{
public DiffType Type;
public int CopyStart;
public int CopyLength;
public string CopyGoal;
public string Original;
public DiffToken(string Copy, int Start, int Length)
{
CopyGoal = Copy;
CopyStart = Start;
CopyLength = Length;
Type = DiffType.Copy;
}
public DiffToken(string Offender)
{
Original = Offender;
Type = DiffType.Original;
}
};
static DiffToken[] BuildDiff(string Prior, string Current)
{
ArrayList Tokens = new ArrayList();
string Cur = Current;
while(Cur.Length > 0)
{
bool Search = true;
int ScanLength = Cur.Length;
while(ScanLength > 0 && Search)
{
if(Prior.IndexOf(Cur.Substring(0,ScanLength)) >= 0)
{
Search = false; // found a sub string
}
else
{
ScanLength/=2;
}
}
if(ScanLength == 0)
{
Tokens.Add(new DiffToken(Cur.Substring(0,1)));
Cur = Cur.Substring(1);
}
else if(Search == false)
{
int Start = Prior.IndexOf(Cur.Substring(0,ScanLength));
Tokens.Add( new DiffToken(Cur.Substring(0,ScanLength),Start, ScanLength));
Cur = Cur.Substring(ScanLength);
}
}
DiffToken[] DT = new DiffToken[Tokens.Count];
int idx = 0;
foreach(DiffToken T in Tokens)
{
DT[idx] = T;
idx++;
}
return DT;
}
public static string FixCompress(string C)
{
return C.Replace("\\","\\\\").Replace("\"","\\\"");
}
public static string PrePost_FixCompress(string Last, string Cur, string V)
{
// \" => "
// \\ => \
string L = Last.Replace("\\\"","\"").Replace("\\\\","\\");
string C = Cur.Replace("\\\"","\"").Replace("\\\\","\\");
DiffToken[] DT = BuildDiff(L, C);
string NextString = "";
bool Busted = false;
bool BuildingString = false;
string BuiltString = "";
for(int i = 0; i < DT.Length; i++)
{
if(DT[i].Type == DiffType.Copy)
{
string Code = V.Substring(0,1) + "(" + (ListingIdx-1) +","+ DT[i].CopyStart +","+ DT[i].CopyLength + ")";
if(DT[i].CopyLength <= Code.Length)
{
BuildingString = true;
BuiltString += DT[i].CopyGoal;
}
else
{
if(BuildingString)
{
if(Busted) NextString += "+";
NextString += "\"" + FixCompress(BuiltString) + "\"";
BuiltString = "";
BuildingString = false;
Busted = true;
}
if(Busted) NextString += "+";
//NextString += V + "[" +(ListingIdx-1)+ "].substring("+ DT[i].CopyStart + "," + DT[i].CopyLength +")";
NextString += V.Substring(0,1) + "(" + (ListingIdx-1) +","+ DT[i].CopyStart +","+ DT[i].CopyLength + ")";
/// V + "[" +(ListingIdx-1)+ "].substring("+ DT[i].CopyStart + "," + DT[i].CopyLength +")";
Busted = true;
}
}
else
{
BuildingString = true;
BuiltString += DT[i].Original;
}
}
if(BuildingString)
{
if(Busted) NextString += "+";
NextString += "\"" + FixCompress(BuiltString) + "\"";
}
if(NextString.Equals(""))
NextString = "\"\"";
return NextString;
/*
int DropLeft = 0;
int DropRight = 0;
for(int leftSame = 0; leftSame < Math.Min(L.Length,C.Length) &&
L[leftSame]==C[leftSame]; leftSame++)
{
DropLeft = leftSame + 1;
}
for(int rightSame = 0; rightSame < Math.Min(L.Length,C.Length) - DropLeft &&
L[L.Length-1-rightSame]==C[C.Length-1-rightSame]; rightSame++)
{
DropRight = rightSame + 1;
}
string LeftTerm = "";
if(DropLeft > 0)
{
// LeftTerm = "sL(" + (ListingIdx-1) + "," + DropLeft + ")";
LeftTerm = V + "[" +(ListingIdx-1)+ "].substring(0,"+(DropLeft)+")";
}
else
{
LeftTerm = "\"\"";
}
string RightTerm = "";
if(DropRight > 0)
{
// RightTerm = "sR(" + (ListingIdx-1) + "," + (L.Length - DropRight) + ")";
RightTerm = V + "[" +(ListingIdx-1)+ "].substring("+(L.Length - DropRight)+")";
}
else
{
RightTerm = "\"\"";
}
string MiddleTerm = FixCompress(C.Substring(DropLeft,C.Length - DropLeft - DropRight));
//string MiddleTerm = FixCompress(C.Substring(DropLeft,C.Length - DropLeft));
MiddleTerm = "\"" + MiddleTerm + "\"";
return optional(LeftTerm, LeftTerm + "+") + MiddleTerm + optional(RightTerm,"+" + RightTerm);
*/
}
public static string Fix(string x, string name)
{
string V = x;
V = V.Replace("\n","<br/>");
V = V.Replace("\"","\\\"");
V = V.Replace("\t"," ");
if(ListingIdx == 0)
{
if(name.Equals("data")) LastListingData = V;
if(name.Equals("name")) LastListingName = V;
if(name.Equals("env")) LastListingEnv = V;
if(name.Equals("heap")) LastListingHeap = V;
V = "\"" + V + "\"";
}
else
{
string FixStr = "\"" + V + "\"";
if(name.Equals("data"))
{
FixStr = PrePost_FixCompress(LastListingData, V, name);
LastListingData = V;
}
if(name.Equals("name"))
{
FixStr = PrePost_FixCompress(LastListingName, V, name);
LastListingName = V;
}
if(name.Equals("env"))
{
FixStr = PrePost_FixCompress(LastListingEnv, V, name);
LastListingEnv = V;
}
if(name.Equals("heap"))
{
FixStr = PrePost_FixCompress(LastListingHeap, V, name);
LastListingHeap = V;
}
V = FixStr;
}
return V;
}
public static Value Eval(LispNode N, Environment Env)
{
bool WasOn = ForceTrace;
int CapturedListingIdx = ListingIdx;
if(RunTrace && ForceTrace)
{
MachineTrace.ActiveNode = N;
MachineTrace.reset();
ListingSource += "da[" + ListingIdx + "]=" + Fix(MachineTrace.Next(Root),"data") + ";\n";
ListingSource += "na[" + ListingIdx + "]=" + Fix(Env.GetTotalFrameName(),"name") + ";\n";
ListingSource += "en[" + ListingIdx + "]=" + Fix(Env.GetLocalRepresentation(),"env") + ";\n";
ListingSource += "he[" + ListingIdx + "]=" + Fix(Env.GetHeapRep(),"heap") + ";\n";
if(ListingIdx == 0) ListingSource += "co[" + ListingIdx + "]=\"\";\n";
else ListingSource += "cn(" + ListingIdx + "," + (ListingIdx-1) + ");\n";
//else ListingSource += "co[" + ListingIdx + "]=co[" + (ListingIdx-1) + "];\n";
ListingIdx ++;
}
try
{
Value V = EvalStep(N,Env);
if(RunTrace && WasOn)
{
MachineTrace.ActiveNode = N;
MachineTrace.reset();
string Hack = Fix(MachineTrace.Next(Root),"data");
Hack = Fix(Env.GetTotalFrameName(),"name");
Hack = Fix(Env.GetLocalRepresentation(),"env");
ListingSource += "cp(" + ListingIdx + "," + CapturedListingIdx + ");\n";
ListingSource += "he[" + ListingIdx + "]=" + Fix(Env.GetHeapRep(),"heap") + ";\n";
// ListingSource += "da[" + ListingIdx + "]=da[" + CapturedListingIdx + "];\n";
// ListingSource += "na[" + ListingIdx + "]=na[" + CapturedListingIdx + "];\n";
// ListingSource += "en[" + ListingIdx + "]=en[" + CapturedListingIdx + "];\n";
// ListingSource += "data[" + ListingIdx + "] = " + Fix(MachineTrace.Next(Root),"data") + "; \n\n";
// ListingSource += "name[" + ListingIdx + "] = " + Fix(Env.GetTotalFrameName(),"name") + "; \n\n";
// ListingSource += " env[" + ListingIdx + "] = " + Fix(Env.GetLocalRepresentation(),"env") + "; \n\n";
if(ListingIdx == 0) ListingSource += "co[" + ListingIdx + "]=\"\";\n";
else ListingSource += "cn(" + ListingIdx + "," + (ListingIdx-1) + ");\n";
// else ListingSource += "co[" + ListingIdx + "]=co[" + (ListingIdx-1) + "];\n";
ListingIdx ++;
}
return V;
}
catch(FuncReturn FR)
{
if(RunTrace && WasOn)
{
MachineTrace.ActiveNode = N;
MachineTrace.reset();
string Hack = Fix(MachineTrace.Next(Root),"data");
Hack = Fix(Env.GetTotalFrameName(),"name");
Hack = Fix(Env.GetLocalRepresentation(),"env");
ListingSource += "cp(" + ListingIdx + "," + CapturedListingIdx + ");\n";
ListingSource += "he[" + ListingIdx + "]=" + Fix(Env.GetHeapRep(),"heap") + ";\n";
// ListingSource += "da[" + ListingIdx + "]=da[" + CapturedListingIdx + "];\n";
// ListingSource += "na[" + ListingIdx + "]=na[" + CapturedListingIdx + "];\n";
// ListingSource += "en[" + ListingIdx + "]=en[" + CapturedListingIdx + "];\n";
// ListingSource += "data[" + ListingIdx + "] = " + Fix(MachineTrace.Next(Root),"data") + "; \n\n";
// ListingSource += "name[" + ListingIdx + "] = " + Fix(Env.GetTotalFrameName(),"name") + "; \n\n";
// ListingSource += " env[" + ListingIdx + "] = " + Fix(Env.GetLocalRepresentation(),"env") + "; \n\n";
if(ListingIdx == 0) ListingSource += "co[" + ListingIdx + "]=\"\";\n";
else ListingSource += "cn(" + ListingIdx + "," + (ListingIdx-1) + ");\n";
//else ListingSource += "co[" + ListingIdx + "]=co[" + (ListingIdx-1) + "];\n";
ListingIdx ++;
}
throw FR;
}
}
public static Random RndFunc = new Random();
public static Value EvalStep(LispNode N, Environment Env)
{
if(N.node.Equals("real"))
{
string DS = N.children[0].node + "." + N.children[2].node;
return new Value(Double.Parse(DS));
}
if(N.node.Equals("null"))
{
Value v1 = new Value();
v1.Type = ValueType.tRef;
v1.rRef = 0;
return v1;
}
if(N.node.Equals("integer"))
{
Value vI = new Value(Int32.Parse(N.children[0].node));
return vI;
}
if(N.node.Equals("char"))
{
if(N.children[0].node.Equals("\\n")) return new Value('\n');
if(N.children[0].node.Equals("\\r")) return new Value('\r');
if(N.children[0].node.Equals("\\t")) return new Value('\t');
if(N.children[0].node.Equals("\\b")) return new Value('\b');
if(N.children[0].node.Equals("\\f")) return new Value('\f');
if(N.children[0].node.Equals("\\\"")) return new Value('\"');
if(N.children[0].node.Equals("\\\\")) return new Value('\\');
Value vI = new Value(N.children[0].node[0]);
return vI;
}
if(N.node.Equals("string"))
{
Value vI = new Value(N.children[0].node);
return vI;
}
if(N.node.Equals("lookup"))
{
Value[] Idx = new Value[N.children.Length-1];
Value Arr = Eval(N.children[0],Env);
for(int k = 0; k < N.children.Length-1; k++)
{
Idx[k] = Eval(N.children[k+1],Env);
}
return Env.LookupRef(Arr, Idx);
}
if(N.node.Equals("."))
{
Value Ref = Eval(N.children[0],Env);
string Field = N.children[1].node;
return Env.LookupRef(Ref, Field);
}
if(N.node.Equals("return"))
{
Value V = Eval(N.children[0], Env);
throw new FuncReturn(V);
}
if(N.node.Equals("delete"))
{
Value V = Eval(N.children[0], Env);
Env.ClearRef(V);
return new Value();
}
if(N.node.Equals("assigneval"))
{
if(!N.children[0].node.Equals("lookup") && !N.children[0].node.Equals(".") ) throw new Exception("Error, assign is either variable or (expr)[v] or (expr).field");
if(N.children[0].node.Equals("lookup"))
{
Value V = Eval(N.children[1], Env);
if(N.children[0].children.Length > 1)
{
Value[] Idx = new Value[N.children[0].children.Length-2];
Value Arr = Eval(N.children[0].children[0],Env);
for(int k = 0; k < N.children[0].children.Length-2; k++)
Idx[k] = Eval(N.children[0].children[k+1],Env);
Value Ref = Env.LookupRef(Arr, Idx);
Value Loc = Eval(N.children[0].children[N.children[0].children.Length - 1],Env);
Env.UpdateRef(Ref, V, Loc.vInteger);
}
else
{
Value Ref = Eval(N.children[0].children[0], Env);
Value Loc = Eval(N.children[0].children[1], Env);
Env.UpdateRef(Ref, V, Loc.vInteger);
}
}
if(N.children[0].node.Equals("."))
{
Value Str = Eval(N.children[0].children[0], Env);
string Field = N.children[0].children[1].node;
Value V = Eval(N.children[1], Env);
Env.UpdateRef(Str, V, Field);
}
return new Value();
}
if(N.node.Equals("="))
{
string VarName = N.children[0].node;
Value V = Eval(N.children[1], Env);
Env.Assign(VarName, V);
return new Value();
}
if(N.node.Equals("null_init") || N.node.Equals("null_incr"))
{
return new Value();
}
if(N.node.Equals("null_cond"))
{
return new Value(true);
}
if(N.node.Equals("while"))
{
LispNode Cond = N.children[0];
LispNode Body = N.children[1];
Value CndEval = Eval(Cond, Env);
while(CndEval.vBoolean && CndEval.Type == ValueType.tBool)
{
Env.Record("BranchTrue");
Eval(Body,Env);
CndEval = Eval(Cond, Env);
}
Env.Record("BranchFalse");
if(CndEval.Type != ValueType.tBool)
throw new Exception("Must result in bool!");
}
if(N.node.Equals("for"))
{
Env.PushScope();
LispNode Init = N.children[0];
LispNode Cond = N.children[1];
LispNode Inc = N.children[2];
LispNode Body = N.children[3];
Eval(Init, Env);
Value CndEval = Eval(Cond, Env);
while(CndEval.vBoolean && CndEval.Type == ValueType.tBool)
{
Env.Record("BranchTrue");
Eval(Body,Env);
Eval(Inc, Env);
CndEval = Eval(Cond, Env);
}
Env.Record("BranchFalse");
if(CndEval.Type != ValueType.tBool)
throw new Exception("Must result in bool!");
//Eval(Init, Env);
Env.PopScope();
return new Value();
}
if(N.node.Equals("if"))
{
Value B = Eval(N.children[0],Env);
if(B.Type != ValueType.tBool) throw new Exception("need boolean");
if(B.vBoolean)
{
Env.Record("BranchTrue");
return Eval(N.children[1],Env);
}
Env.Record("BranchFalse");
if(N.children.Length == 3 && ! B.vBoolean )
{
return Eval(N.children[2],Env);
}
}
if(N.node.Equals("news"))
{
Type Typ = new Type(N.children[0], Env);
Value[] V = new Value[N.children.Length - 1];
for(int k = 0; k < V.Length; k++)
V[k] = Eval(N.children[k+1],Env);
return Env.NewStruct(Typ, V);
}
if(N.node.Equals("newa"))
{
Type SubTyp = new Type(N.children[0],Env);
Value V = Eval(N.children[1],Env);
if(V.Type != ValueType.tInt) throw new Exception("value must be integer");
return Env.NewArray(SubTyp, V.vInteger);
//Env.NewArray(
}
if(N.node.Equals("decl"))
{
Type typ = new Type(N.children[0],Env);
for(int k = 1; k < N.children.Length; k++)
{
string name = N.children[k].node;
Env.LocalDeclare(name, typ);
}
return new Value();
}
if(N.node.Equals("decla"))
{
Type typ = new Type(N.children[0],Env);
string name = N.children[1].node;
Value V = Eval(N.children[2], Env);
Env.LocalDeclare(name, typ);
Env.Assign(name, V);
return new Value();
}
if(N.node.Equals("var"))
{
return Env.LookUP(N.children[0].node);
}
if(N.node.Equals("block"))
{
if(N.children != null)
{
foreach(LispNode Statement in N.children)
{
Value R = Eval(Statement, Env);
}
}
return new Value();
}
if(N.node.Equals("fun_app"))
{
// Value[] P = new Value[N.children.Length -1];
if(!N.children[0].node.Equals("var")) throw new Exception("need a function");
string FunctionName = N.children[0].children[0].node;
Env.Record(FunctionName);
EnvFunc EV = Env.GetFunction(FunctionName);
if(EV == null)
{
if(FunctionName.Equals("length"))
{
if(N.children.Length == 2)
{
Value Ref = Eval(N.children[1],Env);
if(Ref.Type != ValueType.tRef) throw new Exception("length expecting an array");
return Env.RefMax(Ref);
}
}
if(FunctionName.Equals("rnd"))
{
return new Value(RndFunc.Next());
}
if(FunctionName.Equals("tr_off"))
{
ForceTrace = false;
return new Value();
}
if(FunctionName.Equals("tr_on"))
{
ForceTrace = true;
return new Value();
}
if(FunctionName.Equals("display"))
{
if(N.children.Length == 2)
{
Value Vle = Eval(N.children[1],Env);
string output = Vle.vStr();
output = output.Replace("\\t","\t");
output = output.Replace("\\b","\b");
output = output.Replace("\\r","\r");
output = output.Replace("\\n","\n");
if(RunTrace)
{
ListingSource += "co[" + (ListingIdx-1) + "]+=\""+FixConsole(output)+"\";\n";
}
else
{
Console.Write(output);
}
return new Value();
}
}
}
else
{
if(EV.parameter_names == null)
{
Env.PushFrame("" + EV.name + "()");
Value R = new Value(EV.return_type, Env);
try
{
Eval(EV.body, Env);
}
catch ( FuncReturn ret )
{
R = ret.ReturnVal;
}
Env.PopFrame();
return R;
}
else
{
Value[] P = new Value[N.children.Length - 1];
if(P.Length != EV.parameter_names.Length)
throw new Exception("parameter mismath");
for(int k = 0; k < P.Length; k++)
{
P[k] = Eval(N.children[k+1],Env);
}
string FrameName = EV.name + "(";
for(int k = 0; k < P.Length; k++)
{
if(k!=0) FrameName += ",";
FrameName += ((P[k].Type == ValueType.tRef) ? ("REF" + P[k].rRef) : P[k].str2());
}
Env.PushFrame(FrameName + ")");
for(int k = 0; k < P.Length; k++)
{
Env.LocalDeclare(EV.parameter_names[k],EV.parameter_types[k]);
Env.Assign(EV.parameter_names[k], P[k]);
}
//Env.LocalDeclare(
Value R = new Value(EV.return_type, Env);
try
{
Eval(EV.body, Env);
}
catch ( FuncReturn ret )
{
R = ret.ReturnVal;
}
for(int k = 0; k < P.Length; k++)
{
if(P[k].Type == ValueType.tRef)
{
Value vNULL = new Value();
vNULL.Type = ValueType.tRef;
vNULL.rRef = 0;
Env.Assign(EV.parameter_names[k], vNULL);
}
}
Env.PopFrame();
return R;
}
}
}
if(N.node.Equals("-"))
{
if(N.children.Length == 1)
{
Value S = Eval(N.children[0],Env);
if(S.Type != ValueType.tInt) throw new Exception("error: unary minus type mismatch");
S.vInteger *= -1;
Env.Record("unary-");
return S;
}
}
if(N.node.Equals("not"))
{
if(N.children.Length == 1)
{
Value S = Eval(N.children[0],Env);
if(S.Type != ValueType.tBool) throw new Exception("error: unary negation type mismatch");
S.vBoolean = !S.vBoolean;
Env.Record("unaryNOT");
return S;
}
}
if( N.node.Equals("+") || N.node.Equals("*") || N.node.Equals("-") || N.node.Equals("/") || N.node.Equals("%") ||
N.node.Equals("<") || N.node.Equals("<=") || N.node.Equals(">=") || N.node.Equals(">") ||
N.node.Equals("or") || N.node.Equals("and") ||
N.node.Equals("!=") || N.node.Equals("==") || N.node.Equals("<<") || N.node.Equals(">>") )
{
if(N.children.Length != 2) throw new Exception(N.node + " err!");
Value A = Eval(N.children[0],Env);
Value B = Eval(N.children[1],Env);
return performBinaryOperator(A, N.node, B, Env);
}
if(N.node.Equals("*"))
{
Value S = new Value(1);
foreach(LispNode T in N.children)
{
Value P = Eval(T, Env);
if(S.Type != ValueType.tInt) throw new Exception("run-time type mismatch!");
S.vInteger *= P.vInteger;
}
return S;
}
if(N.node.Equals("prog"))
{
foreach(LispNode LN in N.children) Eval(LN, Env);
return new Value();
}
if(N.node.Equals("struct"))
{
if(N.children.Length != 2) throw new Exception("struct: err");
string structName = N.children[0].node;
LispNode structParam = N.children[1];
Env.CreateNewStructureType(structName, structParam);
return new Value();
}
if(N.node.Equals("func_decl"))
{
if(N.children.Length != 2) throw new Exception("func_decl: err");
LispNode Decl = N.children[0];
LispNode Body = N.children[1];
Env.CreateNewFunction(Decl, Body);
// return new Value();
}
if(N.node.Equals("glob_assign"))
{
if(N.children.Length != 3) throw new Exception("glob_assign: err");
// get the type
Type Typ = new Type(N.children[0],Env);
// get the name
string Nme = N.children[1].node;
// evaluate it
Value R = Eval(N.children[2], Env);
// map it
Env.GlobalMap(Nme,Typ,R);
return new Value();
}
if(N.node.Equals("glob_decl"))
{
if(N.children.Length != 2) throw new Exception("glob_decl: err");
// get the type
Type Typ = new Type(N.children[0],Env);
// get the name
string Nme = N.children[1].node;
// evaluate it
Value R = new Value(Typ, Env);
// map it
Env.GlobalMap(Nme,Typ,R);
return new Value();
}
return new Value();
}
[STAThread]
static void Main(string[] args)
{
StreamReader SR = new StreamReader("e:\\projects\\eduLang\\input.c");
TinyCLexer lex = new TinyCLexer( SR );
TinyCParser par = new TinyCParser(lex);
par.program();
if(par.getAST() != null)
{
string Lisp = par.getAST().ToStringTree();
LispLexer LispLex = new LispLexer(Lisp);
LispNode Program = LispNode.Parse(LispLex);
Root = Program;
Console.WriteLine("//// PROGRAM: " + Root.str() + "\n////----------------------------------------\n\n");
RunTrace = true;
ListingIdx = 0;
Eval(Program, new Environment());
string ListingSourceHeader = "";
ListingSourceHeader += "var da = new Array(" + ListingIdx + ");\n";
ListingSourceHeader += "var na = new Array(" + ListingIdx + ");\n";
ListingSourceHeader += "var en = new Array(" + ListingIdx + ");\n";
ListingSourceHeader += "var he = new Array(" + ListingIdx + ");\n";
ListingSourceHeader += "var co = new Array(" + ListingIdx + ");\n";
ListingSourceHeader += "function d(idx, s, l) { return da[idx].substring(s,s+l); }\n";
ListingSourceHeader += "function n(idx, s, l) { return na[idx].substring(s,s+l); }\n";
ListingSourceHeader += "function e(idx, s, l) { return en[idx].substring(s,s+l); }\n";
ListingSourceHeader += "function h(idx, s, l) { return he[idx].substring(s,s+l); }\n";
ListingSourceHeader += "function cp(idxD, idxS) { da[idxD] = da[idxS]; na[idxD] = na[idxS]; en[idxD] = en[idxS]; }\n";
ListingSourceHeader += "function cn(idxD, idxS) { co[idxD] = co[idxS]; }\n";
if(RunTrace) Console.WriteLine(ListingSourceHeader + ListingSource);
//Console.WriteLine("\n----------------------------------------\nLISTING:\n");
//MachineTrace.reset();
//Console.WriteLine(MachineTrace.ProduceListing(Program));
}
}
}
}
| |
// <copyright file="DelimitedReaderTests.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
//
// Copyright (c) 2009-2013 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using System;
using System.Globalization;
using System.IO;
using System.Numerics;
using System.Text;
using NUnit.Framework;
using MathNet.Numerics.Data.Text;
namespace MathNet.Numerics.Data.UnitTests.Text
{
/// <summary>
/// Delimited reader tests.
/// </summary>
[TestFixture]
public class DelimitedReaderTests
{
/// <summary>
/// Can parse comma delimited data.
/// </summary>
[Test]
public void CanParseCommaDelimitedData()
{
var data = "a,b,c" + Environment.NewLine
+ "1" + Environment.NewLine
+ "\"2.2\",0.3e1" + Environment.NewLine
+ "'4',5,6" + Environment.NewLine;
var reader = new DelimitedReader
{
Delimiter = ",",
HasHeaderRow = true,
FormatProvider = CultureInfo.InvariantCulture
};
var matrix = reader.ReadMatrix<double>(new MemoryStream(Encoding.UTF8.GetBytes(data)));
Assert.AreEqual(3, matrix.RowCount);
Assert.AreEqual(3, matrix.ColumnCount);
Assert.AreEqual(1.0, matrix[0, 0]);
Assert.AreEqual(0.0, matrix[0, 1]);
Assert.AreEqual(0.0, matrix[0, 2]);
Assert.AreEqual(2.2, matrix[1, 0]);
Assert.AreEqual(3.0, matrix[1, 1]);
Assert.AreEqual(0.0, matrix[1, 2]);
Assert.AreEqual(4.0, matrix[2, 0]);
Assert.AreEqual(5.0, matrix[2, 1]);
Assert.AreEqual(6.0, matrix[2, 2]);
}
/// <summary>
/// Can parse tab delimited data.
/// </summary>
[Test]
public void CanParseTabDelimitedData()
{
var data = "1" + Environment.NewLine
+ "\"2.2\"\t\t0.3e1" + Environment.NewLine
+ "'4'\t5\t6";
var matrix = DelimitedReader.ReadStream<float>(new MemoryStream(Encoding.UTF8.GetBytes(data)), delimiter: "\t", formatProvider: CultureInfo.InvariantCulture);
Assert.AreEqual(3, matrix.RowCount);
Assert.AreEqual(3, matrix.ColumnCount);
Assert.AreEqual(1.0f, matrix[0, 0]);
Assert.AreEqual(0.0f, matrix[0, 1]);
Assert.AreEqual(0.0f, matrix[0, 2]);
Assert.AreEqual(2.2f, matrix[1, 0]);
Assert.AreEqual(3.0f, matrix[1, 1]);
Assert.AreEqual(0.0f, matrix[1, 2]);
Assert.AreEqual(4.0f, matrix[2, 0]);
Assert.AreEqual(5.0f, matrix[2, 1]);
Assert.AreEqual(6.0f, matrix[2, 2]);
}
/// <summary>
/// Can parse white space delimited data.
/// </summary>
[Test]
public void CanParseWhiteSpaceDelimitedData()
{
var data = "1" + Environment.NewLine
+ "\"2.2\" 0.3e1" + Environment.NewLine
+ "'4' 5 6" + Environment.NewLine;
var reader = new DelimitedReader
{
FormatProvider = CultureInfo.InvariantCulture
};
var matrix = reader.ReadMatrix<float>(new MemoryStream(Encoding.UTF8.GetBytes(data)));
Assert.AreEqual(3, matrix.RowCount);
Assert.AreEqual(3, matrix.ColumnCount);
Assert.AreEqual(1.0f, matrix[0, 0]);
Assert.AreEqual(0.0f, matrix[0, 1]);
Assert.AreEqual(0.0f, matrix[0, 2]);
Assert.AreEqual(2.2f, matrix[1, 0]);
Assert.AreEqual(3.0f, matrix[1, 1]);
Assert.AreEqual(0.0f, matrix[1, 2]);
Assert.AreEqual(4.0f, matrix[2, 0]);
Assert.AreEqual(5.0f, matrix[2, 1]);
Assert.AreEqual(6.0f, matrix[2, 2]);
}
/// <summary>
/// Can parse period delimited data.
/// </summary>
[Test]
public void CanParsePeriodDelimitedData()
{
var data = "a.b.c" + Environment.NewLine
+ "1" + Environment.NewLine
+ "\"2,2\".0,3e1" + Environment.NewLine
+ "'4,0'.5,0.6,0" + Environment.NewLine;
var reader = new DelimitedReader
{
Delimiter = ".",
HasHeaderRow = true,
FormatProvider = new CultureInfo("tr-TR")
};
var matrix = reader.ReadMatrix<double>(new MemoryStream(Encoding.UTF8.GetBytes(data)));
Assert.AreEqual(3, matrix.RowCount);
Assert.AreEqual(3, matrix.ColumnCount);
Assert.AreEqual(1.0, matrix[0, 0]);
Assert.AreEqual(0.0, matrix[0, 1]);
Assert.AreEqual(0.0, matrix[0, 2]);
Assert.AreEqual(2.2, matrix[1, 0]);
Assert.AreEqual(3.0, matrix[1, 1]);
Assert.AreEqual(0.0, matrix[1, 2]);
Assert.AreEqual(4.0, matrix[2, 0]);
Assert.AreEqual(5.0, matrix[2, 1]);
Assert.AreEqual(6.0, matrix[2, 2]);
}
/// <summary>
/// Can parse comma delimited complex data.
/// </summary>
[Test]
public void CanParseComplexCommaDelimitedData()
{
var data = "a,b,c" + Environment.NewLine
+ "(1,2)" + Environment.NewLine
+ "\"2.2\",0.3e1" + Environment.NewLine
+ "'(4,-5)',5,6" + Environment.NewLine;
var matrix = DelimitedReader.Read<Complex>(new StringReader(data), delimiter: ",", hasHeaders: true, formatProvider: CultureInfo.InvariantCulture);
Assert.AreEqual(3, matrix.RowCount);
Assert.AreEqual(3, matrix.ColumnCount);
Assert.AreEqual(1.0, matrix[0, 0].Real);
Assert.AreEqual(2.0, matrix[0, 0].Imaginary);
Assert.AreEqual((Complex) 0.0, matrix[0, 1]);
Assert.AreEqual((Complex) 0.0, matrix[0, 2]);
Assert.AreEqual((Complex) 2.2, matrix[1, 0]);
Assert.AreEqual((Complex) 3.0, matrix[1, 1]);
Assert.AreEqual((Complex) 0.0, matrix[1, 2]);
Assert.AreEqual(4.0, matrix[2, 0].Real);
Assert.AreEqual(-5.0, matrix[2, 0].Imaginary);
Assert.AreEqual((Complex) 5.0, matrix[2, 1]);
Assert.AreEqual((Complex) 6.0, matrix[2, 2]);
}
/// <summary>
/// Can parse comma delimited complex data.
/// </summary>
[Test]
public void CanParseComplex32CommaDelimitedData()
{
var data = "a,b,c" + Environment.NewLine
+ "(1,2)" + Environment.NewLine
+ "\"2.2\",0.3e1" + Environment.NewLine
+ "'(4,-5)',5,6" + Environment.NewLine;
var reader = new DelimitedReader
{
Delimiter = ",",
HasHeaderRow = true,
FormatProvider = CultureInfo.InvariantCulture
};
var matrix = reader.ReadMatrix<Complex32>(new MemoryStream(Encoding.UTF8.GetBytes(data)));
Assert.AreEqual(3, matrix.RowCount);
Assert.AreEqual(3, matrix.ColumnCount);
Assert.AreEqual(1.0f, matrix[0, 0].Real);
Assert.AreEqual(2.0f, matrix[0, 0].Imaginary);
Assert.AreEqual((Complex32)0.0f, matrix[0, 1]);
Assert.AreEqual((Complex32)0.0f, matrix[0, 2]);
Assert.AreEqual((Complex32)2.2f, matrix[1, 0]);
Assert.AreEqual((Complex32)3.0f, matrix[1, 1]);
Assert.AreEqual((Complex32)0.0f, matrix[1, 2]);
Assert.AreEqual(4.0f, matrix[2, 0].Real);
Assert.AreEqual(-5.0f, matrix[2, 0].Imaginary);
Assert.AreEqual((Complex32)5.0f, matrix[2, 1]);
Assert.AreEqual((Complex32)6.0f, matrix[2, 2]);
}
/// <summary>
/// Can parse comma delimited sparse data.
/// </summary>
[Test]
public void CanParseSparseCommaDelimitedData()
{
var data = "a,b,c" + Environment.NewLine
+ "1" + Environment.NewLine
+ "\"2.2\",0.3e1" + Environment.NewLine
+ "'4',0,6" + Environment.NewLine;
var matrix = DelimitedReader.Read<double>(new StringReader(data), true, ",", true, CultureInfo.InvariantCulture);
Assert.IsTrue(matrix is LinearAlgebra.Double.SparseMatrix);
Assert.AreEqual(3, matrix.RowCount);
Assert.AreEqual(3, matrix.ColumnCount);
Assert.AreEqual(1.0, matrix[0, 0]);
Assert.AreEqual(0.0, matrix[0, 1]);
Assert.AreEqual(0.0, matrix[0, 2]);
Assert.AreEqual(2.2, matrix[1, 0]);
Assert.AreEqual(3.0, matrix[1, 1]);
Assert.AreEqual(0.0, matrix[1, 2]);
Assert.AreEqual(4.0, matrix[2, 0]);
Assert.AreEqual(0.0, matrix[2, 1]);
Assert.AreEqual(6.0, matrix[2, 2]);
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the email-2010-12-01.normal.json service model.
*/
using System;
using System.IO;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Amazon.SimpleEmail;
using Amazon.SimpleEmail.Model;
using Amazon.SimpleEmail.Model.Internal.MarshallTransformations;
using Amazon.Runtime.Internal.Transform;
using ServiceClientGenerator;
using AWSSDK_DotNet35.UnitTests.TestTools;
namespace AWSSDK_DotNet35.UnitTests.Marshalling
{
[TestClass]
public class SimpleEmailServiceMarshallingTests
{
static readonly ServiceModel service_model = Utils.LoadServiceModel("email-2010-12-01.normal.json", "email.customizations.json");
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void CloneReceiptRuleSetMarshallTest()
{
var operation = service_model.FindOperation("CloneReceiptRuleSet");
var request = InstantiateClassGenerator.Execute<CloneReceiptRuleSetRequest>();
var marshaller = new CloneReceiptRuleSetRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = CloneReceiptRuleSetResponseUnmarshaller.Instance.Unmarshall(context)
as CloneReceiptRuleSetResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void CreateReceiptFilterMarshallTest()
{
var operation = service_model.FindOperation("CreateReceiptFilter");
var request = InstantiateClassGenerator.Execute<CreateReceiptFilterRequest>();
var marshaller = new CreateReceiptFilterRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = CreateReceiptFilterResponseUnmarshaller.Instance.Unmarshall(context)
as CreateReceiptFilterResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void CreateReceiptRuleMarshallTest()
{
var operation = service_model.FindOperation("CreateReceiptRule");
var request = InstantiateClassGenerator.Execute<CreateReceiptRuleRequest>();
var marshaller = new CreateReceiptRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = CreateReceiptRuleResponseUnmarshaller.Instance.Unmarshall(context)
as CreateReceiptRuleResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void CreateReceiptRuleSetMarshallTest()
{
var operation = service_model.FindOperation("CreateReceiptRuleSet");
var request = InstantiateClassGenerator.Execute<CreateReceiptRuleSetRequest>();
var marshaller = new CreateReceiptRuleSetRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = CreateReceiptRuleSetResponseUnmarshaller.Instance.Unmarshall(context)
as CreateReceiptRuleSetResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void DeleteIdentityMarshallTest()
{
var operation = service_model.FindOperation("DeleteIdentity");
var request = InstantiateClassGenerator.Execute<DeleteIdentityRequest>();
var marshaller = new DeleteIdentityRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = DeleteIdentityResponseUnmarshaller.Instance.Unmarshall(context)
as DeleteIdentityResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void DeleteIdentityPolicyMarshallTest()
{
var operation = service_model.FindOperation("DeleteIdentityPolicy");
var request = InstantiateClassGenerator.Execute<DeleteIdentityPolicyRequest>();
var marshaller = new DeleteIdentityPolicyRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = DeleteIdentityPolicyResponseUnmarshaller.Instance.Unmarshall(context)
as DeleteIdentityPolicyResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void DeleteReceiptFilterMarshallTest()
{
var operation = service_model.FindOperation("DeleteReceiptFilter");
var request = InstantiateClassGenerator.Execute<DeleteReceiptFilterRequest>();
var marshaller = new DeleteReceiptFilterRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = DeleteReceiptFilterResponseUnmarshaller.Instance.Unmarshall(context)
as DeleteReceiptFilterResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void DeleteReceiptRuleMarshallTest()
{
var operation = service_model.FindOperation("DeleteReceiptRule");
var request = InstantiateClassGenerator.Execute<DeleteReceiptRuleRequest>();
var marshaller = new DeleteReceiptRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = DeleteReceiptRuleResponseUnmarshaller.Instance.Unmarshall(context)
as DeleteReceiptRuleResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void DeleteReceiptRuleSetMarshallTest()
{
var operation = service_model.FindOperation("DeleteReceiptRuleSet");
var request = InstantiateClassGenerator.Execute<DeleteReceiptRuleSetRequest>();
var marshaller = new DeleteReceiptRuleSetRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = DeleteReceiptRuleSetResponseUnmarshaller.Instance.Unmarshall(context)
as DeleteReceiptRuleSetResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void DeleteVerifiedEmailAddressMarshallTest()
{
var operation = service_model.FindOperation("DeleteVerifiedEmailAddress");
var request = InstantiateClassGenerator.Execute<DeleteVerifiedEmailAddressRequest>();
var marshaller = new DeleteVerifiedEmailAddressRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void DescribeActiveReceiptRuleSetMarshallTest()
{
var operation = service_model.FindOperation("DescribeActiveReceiptRuleSet");
var request = InstantiateClassGenerator.Execute<DescribeActiveReceiptRuleSetRequest>();
var marshaller = new DescribeActiveReceiptRuleSetRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = DescribeActiveReceiptRuleSetResponseUnmarshaller.Instance.Unmarshall(context)
as DescribeActiveReceiptRuleSetResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void DescribeReceiptRuleMarshallTest()
{
var operation = service_model.FindOperation("DescribeReceiptRule");
var request = InstantiateClassGenerator.Execute<DescribeReceiptRuleRequest>();
var marshaller = new DescribeReceiptRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = DescribeReceiptRuleResponseUnmarshaller.Instance.Unmarshall(context)
as DescribeReceiptRuleResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void DescribeReceiptRuleSetMarshallTest()
{
var operation = service_model.FindOperation("DescribeReceiptRuleSet");
var request = InstantiateClassGenerator.Execute<DescribeReceiptRuleSetRequest>();
var marshaller = new DescribeReceiptRuleSetRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = DescribeReceiptRuleSetResponseUnmarshaller.Instance.Unmarshall(context)
as DescribeReceiptRuleSetResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void GetIdentityDkimAttributesMarshallTest()
{
var operation = service_model.FindOperation("GetIdentityDkimAttributes");
var request = InstantiateClassGenerator.Execute<GetIdentityDkimAttributesRequest>();
var marshaller = new GetIdentityDkimAttributesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = GetIdentityDkimAttributesResponseUnmarshaller.Instance.Unmarshall(context)
as GetIdentityDkimAttributesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void GetIdentityNotificationAttributesMarshallTest()
{
var operation = service_model.FindOperation("GetIdentityNotificationAttributes");
var request = InstantiateClassGenerator.Execute<GetIdentityNotificationAttributesRequest>();
var marshaller = new GetIdentityNotificationAttributesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = GetIdentityNotificationAttributesResponseUnmarshaller.Instance.Unmarshall(context)
as GetIdentityNotificationAttributesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void GetIdentityPoliciesMarshallTest()
{
var operation = service_model.FindOperation("GetIdentityPolicies");
var request = InstantiateClassGenerator.Execute<GetIdentityPoliciesRequest>();
var marshaller = new GetIdentityPoliciesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = GetIdentityPoliciesResponseUnmarshaller.Instance.Unmarshall(context)
as GetIdentityPoliciesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void GetIdentityVerificationAttributesMarshallTest()
{
var operation = service_model.FindOperation("GetIdentityVerificationAttributes");
var request = InstantiateClassGenerator.Execute<GetIdentityVerificationAttributesRequest>();
var marshaller = new GetIdentityVerificationAttributesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = GetIdentityVerificationAttributesResponseUnmarshaller.Instance.Unmarshall(context)
as GetIdentityVerificationAttributesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void GetSendQuotaMarshallTest()
{
var operation = service_model.FindOperation("GetSendQuota");
var request = InstantiateClassGenerator.Execute<GetSendQuotaRequest>();
var marshaller = new GetSendQuotaRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = GetSendQuotaResponseUnmarshaller.Instance.Unmarshall(context)
as GetSendQuotaResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void GetSendStatisticsMarshallTest()
{
var operation = service_model.FindOperation("GetSendStatistics");
var request = InstantiateClassGenerator.Execute<GetSendStatisticsRequest>();
var marshaller = new GetSendStatisticsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = GetSendStatisticsResponseUnmarshaller.Instance.Unmarshall(context)
as GetSendStatisticsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void ListIdentitiesMarshallTest()
{
var operation = service_model.FindOperation("ListIdentities");
var request = InstantiateClassGenerator.Execute<ListIdentitiesRequest>();
var marshaller = new ListIdentitiesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = ListIdentitiesResponseUnmarshaller.Instance.Unmarshall(context)
as ListIdentitiesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void ListIdentityPoliciesMarshallTest()
{
var operation = service_model.FindOperation("ListIdentityPolicies");
var request = InstantiateClassGenerator.Execute<ListIdentityPoliciesRequest>();
var marshaller = new ListIdentityPoliciesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = ListIdentityPoliciesResponseUnmarshaller.Instance.Unmarshall(context)
as ListIdentityPoliciesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void ListReceiptFiltersMarshallTest()
{
var operation = service_model.FindOperation("ListReceiptFilters");
var request = InstantiateClassGenerator.Execute<ListReceiptFiltersRequest>();
var marshaller = new ListReceiptFiltersRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = ListReceiptFiltersResponseUnmarshaller.Instance.Unmarshall(context)
as ListReceiptFiltersResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void ListReceiptRuleSetsMarshallTest()
{
var operation = service_model.FindOperation("ListReceiptRuleSets");
var request = InstantiateClassGenerator.Execute<ListReceiptRuleSetsRequest>();
var marshaller = new ListReceiptRuleSetsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = ListReceiptRuleSetsResponseUnmarshaller.Instance.Unmarshall(context)
as ListReceiptRuleSetsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void ListVerifiedEmailAddressesMarshallTest()
{
var operation = service_model.FindOperation("ListVerifiedEmailAddresses");
var request = InstantiateClassGenerator.Execute<ListVerifiedEmailAddressesRequest>();
var marshaller = new ListVerifiedEmailAddressesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = ListVerifiedEmailAddressesResponseUnmarshaller.Instance.Unmarshall(context)
as ListVerifiedEmailAddressesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void PutIdentityPolicyMarshallTest()
{
var operation = service_model.FindOperation("PutIdentityPolicy");
var request = InstantiateClassGenerator.Execute<PutIdentityPolicyRequest>();
var marshaller = new PutIdentityPolicyRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = PutIdentityPolicyResponseUnmarshaller.Instance.Unmarshall(context)
as PutIdentityPolicyResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void ReorderReceiptRuleSetMarshallTest()
{
var operation = service_model.FindOperation("ReorderReceiptRuleSet");
var request = InstantiateClassGenerator.Execute<ReorderReceiptRuleSetRequest>();
var marshaller = new ReorderReceiptRuleSetRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = ReorderReceiptRuleSetResponseUnmarshaller.Instance.Unmarshall(context)
as ReorderReceiptRuleSetResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void SendBounceMarshallTest()
{
var operation = service_model.FindOperation("SendBounce");
var request = InstantiateClassGenerator.Execute<SendBounceRequest>();
var marshaller = new SendBounceRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = SendBounceResponseUnmarshaller.Instance.Unmarshall(context)
as SendBounceResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void SendEmailMarshallTest()
{
var operation = service_model.FindOperation("SendEmail");
var request = InstantiateClassGenerator.Execute<SendEmailRequest>();
var marshaller = new SendEmailRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = SendEmailResponseUnmarshaller.Instance.Unmarshall(context)
as SendEmailResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void SendRawEmailMarshallTest()
{
var operation = service_model.FindOperation("SendRawEmail");
var request = InstantiateClassGenerator.Execute<SendRawEmailRequest>();
var marshaller = new SendRawEmailRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = SendRawEmailResponseUnmarshaller.Instance.Unmarshall(context)
as SendRawEmailResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void SetActiveReceiptRuleSetMarshallTest()
{
var operation = service_model.FindOperation("SetActiveReceiptRuleSet");
var request = InstantiateClassGenerator.Execute<SetActiveReceiptRuleSetRequest>();
var marshaller = new SetActiveReceiptRuleSetRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = SetActiveReceiptRuleSetResponseUnmarshaller.Instance.Unmarshall(context)
as SetActiveReceiptRuleSetResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void SetIdentityDkimEnabledMarshallTest()
{
var operation = service_model.FindOperation("SetIdentityDkimEnabled");
var request = InstantiateClassGenerator.Execute<SetIdentityDkimEnabledRequest>();
var marshaller = new SetIdentityDkimEnabledRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = SetIdentityDkimEnabledResponseUnmarshaller.Instance.Unmarshall(context)
as SetIdentityDkimEnabledResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void SetIdentityFeedbackForwardingEnabledMarshallTest()
{
var operation = service_model.FindOperation("SetIdentityFeedbackForwardingEnabled");
var request = InstantiateClassGenerator.Execute<SetIdentityFeedbackForwardingEnabledRequest>();
var marshaller = new SetIdentityFeedbackForwardingEnabledRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = SetIdentityFeedbackForwardingEnabledResponseUnmarshaller.Instance.Unmarshall(context)
as SetIdentityFeedbackForwardingEnabledResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void SetIdentityNotificationTopicMarshallTest()
{
var operation = service_model.FindOperation("SetIdentityNotificationTopic");
var request = InstantiateClassGenerator.Execute<SetIdentityNotificationTopicRequest>();
var marshaller = new SetIdentityNotificationTopicRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = SetIdentityNotificationTopicResponseUnmarshaller.Instance.Unmarshall(context)
as SetIdentityNotificationTopicResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void SetReceiptRulePositionMarshallTest()
{
var operation = service_model.FindOperation("SetReceiptRulePosition");
var request = InstantiateClassGenerator.Execute<SetReceiptRulePositionRequest>();
var marshaller = new SetReceiptRulePositionRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = SetReceiptRulePositionResponseUnmarshaller.Instance.Unmarshall(context)
as SetReceiptRulePositionResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void UpdateReceiptRuleMarshallTest()
{
var operation = service_model.FindOperation("UpdateReceiptRule");
var request = InstantiateClassGenerator.Execute<UpdateReceiptRuleRequest>();
var marshaller = new UpdateReceiptRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = UpdateReceiptRuleResponseUnmarshaller.Instance.Unmarshall(context)
as UpdateReceiptRuleResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void VerifyDomainDkimMarshallTest()
{
var operation = service_model.FindOperation("VerifyDomainDkim");
var request = InstantiateClassGenerator.Execute<VerifyDomainDkimRequest>();
var marshaller = new VerifyDomainDkimRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = VerifyDomainDkimResponseUnmarshaller.Instance.Unmarshall(context)
as VerifyDomainDkimResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void VerifyDomainIdentityMarshallTest()
{
var operation = service_model.FindOperation("VerifyDomainIdentity");
var request = InstantiateClassGenerator.Execute<VerifyDomainIdentityRequest>();
var marshaller = new VerifyDomainIdentityRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = VerifyDomainIdentityResponseUnmarshaller.Instance.Unmarshall(context)
as VerifyDomainIdentityResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void VerifyEmailAddressMarshallTest()
{
var operation = service_model.FindOperation("VerifyEmailAddress");
var request = InstantiateClassGenerator.Execute<VerifyEmailAddressRequest>();
var marshaller = new VerifyEmailAddressRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("SimpleEmailService")]
public void VerifyEmailIdentityMarshallTest()
{
var operation = service_model.FindOperation("VerifyEmailIdentity");
var request = InstantiateClassGenerator.Execute<VerifyEmailIdentityRequest>();
var marshaller = new VerifyEmailIdentityRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = VerifyEmailIdentityResponseUnmarshaller.Instance.Unmarshall(context)
as VerifyEmailIdentityResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using SPD.CommonObjects;
namespace SPD.GUI {
/// <summary>
///
/// </summary>
public delegate void VisitChangeEventHandler(object sender,
VisitChangeEventArgs e);
/// <summary>
///
/// </summary>
public partial class VisitsControl : UserControl {
/// <summary>
/// Gets or sets the list view visits.
/// </summary>
/// <value>The list view visits.</value>
public System.Windows.Forms.ListView ListViewVisits {
get { return listViewVisits; }
set { listViewVisits = value; }
}
private IList<VisitData> visits;
private PatientData patient;
/// <summary>
/// Occurs when [change].
/// </summary>
public event VisitChangeEventHandler Change;
/// <summary>
/// Initializes a new instance of the <see cref="VisitsControl"/> class.
/// </summary>
public VisitsControl() {
InitializeComponent();
listViewVisits.View = View.Details;
listViewVisits.LabelEdit = false;
listViewVisits.AllowColumnReorder = true;
listViewVisits.FullRowSelect = true;
// Create columns for the items and subitems.
listViewVisits.Columns.Add("VID", 50);
listViewVisits.Columns.Add("Diagnosis", 190);
listViewVisits.Columns.Add("Procedure", 190);
listViewVisits.Columns.Add("Cause", 100);
listViewVisits.Columns.Add("Localis", 100);
listViewVisits.Columns.Add("Date", 70);
}
//public IList<VisitData> Visits{
// set { visits = value; }
//}
//public PatientData Patient{
// set { patient = value; }
//}
/// <summary>
/// Clears the specified with visits list.
/// </summary>
/// <param name="withVisitsList">if set to <c>true</c> [with visits list].</param>
public void Clear(bool withVisitsList){
if (withVisitsList)
listViewVisits.Items.Clear();
textBoxCause.Text = "";
textBoxDateYear.Text = "";
textBoxDateMonth.Text = "";
textBoxDateDay.Text = "";
textBoxExtraDiagnosis.Text = "";
textBoxExtraTherapy.Text = "";
textBoxLocalis.Text = "";
textBoxPatientNr.Text = "";
textBoxProcedure.Text = "";
textBoxAnesthesiology.Text = "";
textBoxUltrasound.Text = "";
textBoxBlooddiagnostic.Text = "";
textBoxTodo.Text = "";
textBoxRadiodiagnostics.Text = "";
}
private void fillVisitList(){
Clear(true);
if (visits != null) {
foreach (VisitData vd in visits) {
ListViewItem item = new ListViewItem(vd.Id.ToString());
item.SubItems.Add(vd.ExtraDiagnosis);
item.SubItems.Add(vd.Procedure);
item.SubItems.Add(vd.Cause);
item.SubItems.Add(vd.Localis);
item.SubItems.Add(vd.VisitDate.ToShortDateString());
listViewVisits.Items.Add(item);
}
if (listViewVisits.Items.Count > 0) {
listViewVisits.SelectedIndices.Add(listViewVisits.Items.Count-1);
}
}
}
private void VisitsControl_Load(object sender, EventArgs e) {
}
/// <summary>
/// Inits the specified patient.
/// </summary>
/// <param name="patient">The patient.</param>
/// <param name="visits">The visits.</param>
public void Init(PatientData patient, IList<VisitData> visits) {
this.patient = patient;
this.visits = CommonUtilities.StaticUtilities.SortVisitsListByDate(visits);
fillVisitList();
labelHeadlineAndPatientData.Text = "Visits: " + patient.ToString();
if (patient != null && patient.Id == 313) {
this.pictureBoxEasterEgg.Visible = true;
} else {
this.pictureBoxEasterEgg.Visible = false;
}
}
private void listViewVisits_SelectedIndexChanged(object sender, EventArgs e) {
showDetailsBelow();
}
private void showDetailsBelow() {
foreach (VisitData visit in visits) {
if (listViewVisits.SelectedItems.Count > 0) {
if (visit.Id == Int64.Parse(listViewVisits.SelectedItems[0].Text)) {
textBoxCause.Text = visit.Cause;
textBoxDateYear.Text = visit.VisitDate.Year.ToString();
textBoxDateMonth.Text = visit.VisitDate.Month.ToString();
textBoxDateDay.Text = visit.VisitDate.Day.ToString();
textBoxExtraDiagnosis.Text = visit.ExtraDiagnosis;
textBoxExtraTherapy.Text = visit.ExtraTherapy;
textBoxLocalis.Text = visit.Localis;
textBoxPatientNr.Text = visit.PatientId.ToString();
textBoxProcedure.Text = visit.Procedure;
textBoxAnesthesiology.Text = visit.Anesthesiology;
textBoxUltrasound.Text = visit.Ultrasound;
textBoxBlooddiagnostic.Text = visit.Blooddiagnostic;
textBoxTodo.Text = visit.Todo;
textBoxRadiodiagnostics.Text = visit.Radiodiagnostics;
}
}
}
}
private void buttonChange_Click(object sender, EventArgs e){
if (listViewVisits.SelectedItems.Count > 0) {
foreach(VisitData visit in visits){
if (visit.Id == Int64.Parse(listViewVisits.SelectedItems[0].Text)){
VisitChangeEventArgs e2 = new VisitChangeEventArgs(visit);
Change(this, e2);
}
}
}
}
private VisitData getSelectedVisit(){
long vId = 0;
foreach (ListViewItem lvi in this.listViewVisits.SelectedItems) {
vId = Int64.Parse(lvi.Text);
}
foreach (VisitData vd in this.visits) {
if (vd.Id == vId) {
return vd;
}
}
return null;
}
private bool isVisitSelected() {
return (listViewVisits.SelectedItems.Count > 0);
}
}
/// <summary>
///
/// </summary>
public class VisitChangeEventArgs : EventArgs {
private VisitData visit;
/// <summary>
/// Initializes a new instance of the <see cref="VisitChangeEventArgs"/> class.
/// </summary>
/// <param name="visit">The visit.</param>
public VisitChangeEventArgs(VisitData visit) {
this.visit = visit;
}
/// <summary>
/// Gets the visit.
/// </summary>
/// <value>The visit.</value>
public VisitData Visit {
get {
return visit;
}
}
}
}
| |
// 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.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
//
// This file was autogenerated by a tool.
// Do not modify it.
//
namespace Microsoft.Azure.Batch
{
using Models = Microsoft.Azure.Batch.Protocol.Models;
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// A task which is run when a compute node joins a pool in the Azure Batch service, or when the compute node is rebooted
/// or reimaged.
/// </summary>
public partial class StartTask : ITransportObjectProvider<Models.StartTask>, IPropertyMetadata
{
private class PropertyContainer : PropertyCollection
{
public readonly PropertyAccessor<string> CommandLineProperty;
public readonly PropertyAccessor<IList<EnvironmentSetting>> EnvironmentSettingsProperty;
public readonly PropertyAccessor<int?> MaxTaskRetryCountProperty;
public readonly PropertyAccessor<IList<ResourceFile>> ResourceFilesProperty;
public readonly PropertyAccessor<bool?> RunElevatedProperty;
public readonly PropertyAccessor<bool?> WaitForSuccessProperty;
public PropertyContainer() : base(BindingState.Unbound)
{
this.CommandLineProperty = this.CreatePropertyAccessor<string>("CommandLine", BindingAccess.Read | BindingAccess.Write);
this.EnvironmentSettingsProperty = this.CreatePropertyAccessor<IList<EnvironmentSetting>>("EnvironmentSettings", BindingAccess.Read | BindingAccess.Write);
this.MaxTaskRetryCountProperty = this.CreatePropertyAccessor<int?>("MaxTaskRetryCount", BindingAccess.Read | BindingAccess.Write);
this.ResourceFilesProperty = this.CreatePropertyAccessor<IList<ResourceFile>>("ResourceFiles", BindingAccess.Read | BindingAccess.Write);
this.RunElevatedProperty = this.CreatePropertyAccessor<bool?>("RunElevated", BindingAccess.Read | BindingAccess.Write);
this.WaitForSuccessProperty = this.CreatePropertyAccessor<bool?>("WaitForSuccess", BindingAccess.Read | BindingAccess.Write);
}
public PropertyContainer(Models.StartTask protocolObject) : base(BindingState.Bound)
{
this.CommandLineProperty = this.CreatePropertyAccessor(
protocolObject.CommandLine,
"CommandLine",
BindingAccess.Read | BindingAccess.Write);
this.EnvironmentSettingsProperty = this.CreatePropertyAccessor(
EnvironmentSetting.ConvertFromProtocolCollection(protocolObject.EnvironmentSettings),
"EnvironmentSettings",
BindingAccess.Read | BindingAccess.Write);
this.MaxTaskRetryCountProperty = this.CreatePropertyAccessor(
protocolObject.MaxTaskRetryCount,
"MaxTaskRetryCount",
BindingAccess.Read | BindingAccess.Write);
this.ResourceFilesProperty = this.CreatePropertyAccessor(
ResourceFile.ConvertFromProtocolCollection(protocolObject.ResourceFiles),
"ResourceFiles",
BindingAccess.Read | BindingAccess.Write);
this.RunElevatedProperty = this.CreatePropertyAccessor(
protocolObject.RunElevated,
"RunElevated",
BindingAccess.Read | BindingAccess.Write);
this.WaitForSuccessProperty = this.CreatePropertyAccessor(
protocolObject.WaitForSuccess,
"WaitForSuccess",
BindingAccess.Read | BindingAccess.Write);
}
}
private readonly PropertyContainer propertyContainer;
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="StartTask"/> class.
/// </summary>
/// <param name='commandLine'>The command line of the task.</param>
public StartTask(
string commandLine)
{
this.propertyContainer = new PropertyContainer();
this.CommandLine = commandLine;
}
internal StartTask(Models.StartTask protocolObject)
{
this.propertyContainer = new PropertyContainer(protocolObject);
}
#endregion Constructors
#region StartTask
/// <summary>
/// Gets or sets the command line of the task.
/// </summary>
/// <remarks>
/// The command line does not run under a shell, and therefore cannot take advantage of shell features such as environment
/// variable expansion. If you want to take advantage of such features, you should invoke the shell in the command
/// line, for example using "cmd /c MyCommand" in Windows or "/bin/sh -c MyCommand" in Linux.
/// </remarks>
public string CommandLine
{
get { return this.propertyContainer.CommandLineProperty.Value; }
set { this.propertyContainer.CommandLineProperty.Value = value; }
}
/// <summary>
/// Gets or sets a set of environment settings for the start task.
/// </summary>
public IList<EnvironmentSetting> EnvironmentSettings
{
get { return this.propertyContainer.EnvironmentSettingsProperty.Value; }
set
{
this.propertyContainer.EnvironmentSettingsProperty.Value = ConcurrentChangeTrackedModifiableList<EnvironmentSetting>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets the maximum number of retries for the task.
/// </summary>
public int? MaxTaskRetryCount
{
get { return this.propertyContainer.MaxTaskRetryCountProperty.Value; }
set { this.propertyContainer.MaxTaskRetryCountProperty.Value = value; }
}
/// <summary>
/// Gets or sets a list of files that the Batch service will download to the compute node before running the command
/// line.
/// </summary>
public IList<ResourceFile> ResourceFiles
{
get { return this.propertyContainer.ResourceFilesProperty.Value; }
set
{
this.propertyContainer.ResourceFilesProperty.Value = ConcurrentChangeTrackedModifiableList<ResourceFile>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets whether to run the task in elevated mode.
/// </summary>
public bool? RunElevated
{
get { return this.propertyContainer.RunElevatedProperty.Value; }
set { this.propertyContainer.RunElevatedProperty.Value = value; }
}
/// <summary>
/// Gets or sets a value indicating whether the Batch service should wait for the start task to complete before scheduling
/// any tasks on the compute node.
/// </summary>
/// <remarks>
/// If this is not specified, the default is false.
/// </remarks>
public bool? WaitForSuccess
{
get { return this.propertyContainer.WaitForSuccessProperty.Value; }
set { this.propertyContainer.WaitForSuccessProperty.Value = value; }
}
#endregion // StartTask
#region IPropertyMetadata
bool IModifiable.HasBeenModified
{
get { return this.propertyContainer.HasBeenModified; }
}
bool IReadOnly.IsReadOnly
{
get { return this.propertyContainer.IsReadOnly; }
set { this.propertyContainer.IsReadOnly = value; }
}
#endregion //IPropertyMetadata
#region Internal/private methods
/// <summary>
/// Return a protocol object of the requested type.
/// </summary>
/// <returns>The protocol object of the requested type.</returns>
Models.StartTask ITransportObjectProvider<Models.StartTask>.GetTransportObject()
{
Models.StartTask result = new Models.StartTask()
{
CommandLine = this.CommandLine,
EnvironmentSettings = UtilitiesInternal.ConvertToProtocolCollection(this.EnvironmentSettings),
MaxTaskRetryCount = this.MaxTaskRetryCount,
ResourceFiles = UtilitiesInternal.ConvertToProtocolCollection(this.ResourceFiles),
RunElevated = this.RunElevated,
WaitForSuccess = this.WaitForSuccess,
};
return result;
}
#endregion // Internal/private methods
}
}
| |
// 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.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace System.Net.WebSockets
{
/// <summary>
/// Static class containing the WinHttp global callback and associated routines.
/// </summary>
internal static class WinHttpWebSocketCallback
{
public static Interop.WinHttp.WINHTTP_STATUS_CALLBACK s_StaticCallbackDelegate =
new Interop.WinHttp.WINHTTP_STATUS_CALLBACK(WinHttpCallback);
public static void WinHttpCallback(
IntPtr handle,
IntPtr context,
uint internetStatus,
IntPtr statusInformation,
uint statusInformationLength)
{
if (Environment.HasShutdownStarted)
{
return;
}
if (context == IntPtr.Zero)
{
Debug.Assert(internetStatus != Interop.WinHttp.WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING);
return;
}
try
{
WinHttpWebSocketState state = WinHttpWebSocketState.FromIntPtr(context);
Debug.Assert(state != null, "WinHttpWebSocketCallback: state should not be null");
if ((state.RequestHandle != null) &&
(state.RequestHandle.DangerousGetHandle() == handle))
{
RequestCallback(handle, state, internetStatus, statusInformation, statusInformationLength);
return;
}
if ((state.WebSocketHandle != null) &&
(state.WebSocketHandle.DangerousGetHandle() == handle))
{
WebSocketCallback(handle, state, internetStatus, statusInformation, statusInformationLength);
return;
}
}
catch (Exception ex)
{
Debug.Fail("Unhandled exception in WinHTTP callback: " + ex);
}
}
#region RequestCallback
private static void RequestCallback(
IntPtr handle,
WinHttpWebSocketState state,
uint internetStatus,
IntPtr statusInformation,
uint statusInformationLength)
{
switch (internetStatus)
{
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE:
OnRequestSendRequestComplete(state);
return;
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE:
OnRequestHeadersAvailable(state);
return;
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING:
OnRequestHandleClosing(state);
return;
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REQUEST_ERROR:
Debug.Assert(
statusInformationLength == Marshal.SizeOf<Interop.WinHttp.WINHTTP_ASYNC_RESULT>(),
"RequestCallback: statusInformationLength=" + statusInformationLength +
" must be sizeof(WINHTTP_ASYNC_RESULT)=" + Marshal.SizeOf<Interop.WinHttp.WINHTTP_ASYNC_RESULT>());
var asyncResult = Marshal.PtrToStructure<Interop.WinHttp.WINHTTP_ASYNC_RESULT>(statusInformation);
OnRequestError(state, asyncResult);
return;
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_SECURE_FAILURE:
Debug.Assert(
statusInformationLength == sizeof(uint),
"RequestCallback: statusInformationLength must be sizeof(uint).");
// statusInformation contains a flag: WINHTTP_CALLBACK_STATUS_FLAG_*
uint flags = 0;
unchecked
{
flags = (uint)Marshal.ReadInt32(statusInformation);
}
OnRequestSecureFailure(state, flags);
return;
}
}
private static void OnRequestSendRequestComplete(WinHttpWebSocketState state)
{
Debug.Assert(state != null, "OnRequestSendRequestComplete: state is null");
Debug.Assert(state.TcsUpgrade != null, "OnRequestSendRequestComplete: task completion source is null");
state.TcsUpgrade.TrySetResult(true);
}
private static void OnRequestHeadersAvailable(WinHttpWebSocketState state)
{
Debug.Assert(state != null, "OnRequestHeadersAvailable: state is null");
Debug.Assert(state.TcsUpgrade != null, "OnRequestHeadersAvailable: task completion source is null");
state.TcsUpgrade.TrySetResult(true);
}
private static void OnRequestHandleClosing(WinHttpWebSocketState state)
{
Debug.Assert(state != null, "OnRequestError: state is null");
Debug.Assert(state.RequestHandle != null, "OnRequestError: RequestHandle is null");
Debug.Assert(!state.RequestHandle.IsInvalid, "OnRequestError: RequestHandle is invalid");
state.RequestHandle.DetachCallback();
state.RequestHandle = null;
// Unpin the state object if there are no more open handles that are wired to the callback.
if (state.DecrementHandlesOpenWithCallback() == 0)
{
state.Unpin();
}
}
private static void OnRequestError(
WinHttpWebSocketState state,
Interop.WinHttp.WINHTTP_ASYNC_RESULT asyncResult)
{
Debug.Assert(state != null, "OnRequestError: state is null");
var innerException = WinHttpException.CreateExceptionUsingError(unchecked((int)asyncResult.dwError));
switch (unchecked((uint)asyncResult.dwResult.ToInt32()))
{
case Interop.WinHttp.API_SEND_REQUEST:
case Interop.WinHttp.API_RECEIVE_RESPONSE:
{
var exception = new WebSocketException(SR.net_webstatus_ConnectFailure, innerException);
state.UpdateState(WebSocketState.Closed);
state.TcsUpgrade.TrySetException(exception);
}
break;
default:
{
Debug.Fail(
"OnRequestError: Result (" + asyncResult.dwResult + ") is not expected.",
"Error code: " + asyncResult.dwError + " (" + innerException.Message + ")");
}
break;
}
}
private static void OnRequestSecureFailure(WinHttpWebSocketState state, uint flags)
{
Debug.Assert(state != null, "OnRequestSecureFailure: state is null");
var innerException = WinHttpException.CreateExceptionUsingError(unchecked((int)Interop.WinHttp.ERROR_WINHTTP_SECURE_FAILURE));
var exception = new WebSocketException(
WebSocketError.Success,
SR.net_webstatus_ConnectFailure,
innerException);
// TODO (#2509): handle SSL related exceptions.
state.UpdateState(WebSocketState.Closed);
// TODO (#2509): Create exception from WINHTTP_CALLBACK_STATUS_SECURE_FAILURE flags.
state.TcsUpgrade.TrySetException(exception);
}
#endregion
#region WebSocketCallback
private static void WebSocketCallback(
IntPtr handle,
WinHttpWebSocketState state,
uint internetStatus,
IntPtr statusInformation,
uint statusInformationLength)
{
switch (internetStatus)
{
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE:
OnWebSocketWriteComplete(state);
return;
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_READ_COMPLETE:
Debug.Assert(
statusInformationLength == Marshal.SizeOf<Interop.WinHttp.WINHTTP_WEB_SOCKET_STATUS>(),
"WebSocketCallback: statusInformationLength must be sizeof(WINHTTP_WEB_SOCKET_STATUS).");
var info = Marshal.PtrToStructure<Interop.WinHttp.WINHTTP_WEB_SOCKET_STATUS>(statusInformation);
OnWebSocketReadComplete(state, info);
return;
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_CLOSE_COMPLETE:
OnWebSocketCloseComplete(state);
return;
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_SHUTDOWN_COMPLETE:
OnWebSocketShutdownComplete(state);
return;
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING:
OnWebSocketHandleClosing(state);
return;
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REQUEST_ERROR:
Debug.Assert(
statusInformationLength == Marshal.SizeOf<Interop.WinHttp.WINHTTP_WEB_SOCKET_ASYNC_RESULT>(),
"WebSocketCallback: statusInformationLength must be sizeof(WINHTTP_WEB_SOCKET_ASYNC_RESULT).");
var asyncResult = Marshal.PtrToStructure<Interop.WinHttp.WINHTTP_WEB_SOCKET_ASYNC_RESULT>(statusInformation);
OnWebSocketError(state, asyncResult);
return;
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_SECURE_FAILURE:
Debug.Assert(
statusInformationLength == sizeof(uint),
"WebSocketCallback: statusInformationLength must be sizeof(uint).");
// statusInformation contains a flag: WINHTTP_CALLBACK_STATUS_FLAG_*
uint flags = unchecked((uint)statusInformation);
OnRequestSecureFailure(state, flags);
return;
}
}
private static void OnWebSocketWriteComplete(WinHttpWebSocketState state)
{
Debug.Assert(state != null, "OnWebSocketWriteComplete: state is null");
state.PendingWriteOperation = false;
state.TcsSend.TrySetResult(true);
}
private static void OnWebSocketReadComplete(
WinHttpWebSocketState state,
Interop.WinHttp.WINHTTP_WEB_SOCKET_STATUS info)
{
Debug.Assert(state != null, "OnWebSocketReadComplete: state is null");
if (info.eBufferType == Interop.WinHttp.WINHTTP_WEB_SOCKET_BUFFER_TYPE.WINHTTP_WEB_SOCKET_CLOSE_BUFFER_TYPE)
{
state.UpdateState(WebSocketState.CloseReceived);
}
state.BufferType = info.eBufferType;
state.BytesTransferred = info.dwBytesTransferred;
state.PendingReadOperation = false;
state.TcsReceive.TrySetResult(true);
}
private static void OnWebSocketCloseComplete(WinHttpWebSocketState state)
{
Debug.Assert(state != null, "OnWebSocketCloseComplete: state is null");
state.UpdateState(WebSocketState.Closed);
state.TcsClose.TrySetResult(true);
}
private static void OnWebSocketShutdownComplete(WinHttpWebSocketState state)
{
Debug.Assert(state != null, "OnWebSocketShutdownComplete: state is null");
state.UpdateState(WebSocketState.CloseSent);
state.TcsCloseOutput.TrySetResult(true);
}
private static void OnWebSocketHandleClosing(WinHttpWebSocketState state)
{
Debug.Assert(state != null, "OnWebSocketHandleClosing: state is null");
Debug.Assert(state.WebSocketHandle != null, "OnWebSocketHandleClosing: WebSocketHandle is null");
Debug.Assert(!state.WebSocketHandle.IsInvalid, "OnWebSocketHandleClosing: WebSocketHandle is invalid");
state.WebSocketHandle.DetachCallback();
state.WebSocketHandle = null;
// Unpin the state object if there are no more open handles that are wired to the callback.
if (state.DecrementHandlesOpenWithCallback() == 0)
{
state.Unpin();
}
}
private static void OnWebSocketError(
WinHttpWebSocketState state,
Interop.WinHttp.WINHTTP_WEB_SOCKET_ASYNC_RESULT asyncResult)
{
Debug.Assert(state != null, "OnWebSocketError: state is null");
var innerException = WinHttpException.CreateExceptionUsingError(unchecked((int)(asyncResult.AsyncResult.dwError)));
if (asyncResult.AsyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED)
{
state.UpdateState(WebSocketState.Aborted);
if (state.TcsReceive != null)
{
state.TcsReceive.TrySetCanceled();
}
if (state.TcsSend != null)
{
state.TcsSend.TrySetCanceled();
}
return;
}
switch (asyncResult.Operation)
{
case Interop.WinHttp.WINHTTP_WEB_SOCKET_OPERATION.WINHTTP_WEB_SOCKET_SEND_OPERATION:
state.PendingWriteOperation = false;
state.TcsSend.TrySetException(innerException);
break;
case Interop.WinHttp.WINHTTP_WEB_SOCKET_OPERATION.WINHTTP_WEB_SOCKET_RECEIVE_OPERATION:
state.PendingReadOperation = false;
state.TcsReceive.TrySetException(innerException);
break;
case Interop.WinHttp.WINHTTP_WEB_SOCKET_OPERATION.WINHTTP_WEB_SOCKET_CLOSE_OPERATION:
state.TcsClose.TrySetException(innerException);
break;
case Interop.WinHttp.WINHTTP_WEB_SOCKET_OPERATION.WINHTTP_WEB_SOCKET_SHUTDOWN_OPERATION:
state.TcsCloseOutput.TrySetException(innerException);
break;
default:
Debug.Fail(
"OnWebSocketError: Operation (" + asyncResult.Operation + ") is not expected.",
"Error code: " + asyncResult.AsyncResult.dwError + " (" + innerException.Message + ")");
break;
}
}
private static void OnWebSocketSecureFailure(WinHttpWebSocketState state, uint flags)
{
Debug.Assert(state != null, "OnWebSocketSecureFailure: state is null");
var innerException = WinHttpException.CreateExceptionUsingError(unchecked((int)Interop.WinHttp.ERROR_WINHTTP_SECURE_FAILURE));
var exception = new WebSocketException(WebSocketError.ConnectionClosedPrematurely, innerException);
// TODO (Issue 2509): handle SSL related exceptions.
state.UpdateState(WebSocketState.Aborted);
// TODO (Issue 2509): Create exception from WINHTTP_CALLBACK_STATUS_SECURE_FAILURE flags.
state.TcsUpgrade.TrySetException(exception);
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="StateManagedCollection.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.UI {
using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing.Design;
using System.Reflection;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Util;
/// <devdoc>
/// Manages state for an arbitrary collection of items that implement IStateManager.
/// The collection differentiates between known types and unknown types.
/// Known types take up less space in ViewState because only an index needs to be stored instead of a fully qualified type name.
/// Unknown types need to have their fully qualified type name stored in ViewState so they take up more space.
/// </devdoc>
public abstract class StateManagedCollection : IList, IStateManager {
private ArrayList _collectionItems;
private bool _tracking;
private bool _saveAll;
// We want to know if the collection had items to begin with
// so we don't put empty collections in the ViewState unnecessarily
private bool _hadItems;
/// <devdoc>
/// Creates a new instance of StateManagedCollection.
/// </devdoc>
protected StateManagedCollection() {
_collectionItems = new ArrayList();
}
/// <devdoc>
/// Returns the number of items in the collection.
/// </devdoc>
public int Count {
get {
return _collectionItems.Count;
}
}
/// <devdoc>
/// Removes all the items from the collection.
/// </devdoc>
public void Clear() {
OnClear();
_collectionItems.Clear();
OnClearComplete();
if (_tracking) {
_saveAll = true;
}
}
public void CopyTo(Array array, int index) {
_collectionItems.CopyTo(array, index);
}
/// <devdoc>
/// Creates an object of a known type based on an index into an array of types.
/// Indexes passed into CreateKnownType() must mach the indexes of the ArrayList returned
/// by GetKnownTypes().
/// </devdoc>
protected virtual object CreateKnownType(int index) {
throw new InvalidOperationException(SR.GetString(SR.StateManagedCollection_NoKnownTypes));
}
/// <devdoc>
/// Returns the IEnumerator for the collection.
/// </devdoc>
public IEnumerator GetEnumerator() {
return _collectionItems.GetEnumerator();
}
/// <devdoc>
/// Returns an ordered list of known types.
/// </devdoc>
protected virtual Type[] GetKnownTypes() {
return null;
}
/// <devdoc>
/// Returns the number of known types.
/// </devdoc>
private int GetKnownTypeCount() {
Type[] types = GetKnownTypes();
if (types == null)
return 0;
return types.Length;
}
/// <devdoc>
/// Inserts a new object into the collection at a given index.
/// If the index is -1 then the object is appended to the end of the collection.
/// </devdoc>
private void InsertInternal(int index, object o) {
Debug.Assert(index >= -1 && index <= Count, "Expected index to be at least -1 and less than or equal to Count.");
if (o == null) {
throw new ArgumentNullException("o");
}
if (((IStateManager)this).IsTrackingViewState) {
((IStateManager)o).TrackViewState();
SetDirtyObject(o);
}
OnInsert(index, o);
int trueIndex;
if (index == -1) {
trueIndex = _collectionItems.Add(o);
}
else {
trueIndex = index;
_collectionItems.Insert(index, o);
}
try {
OnInsertComplete(index, o);
}
catch {
_collectionItems.RemoveAt(trueIndex);
throw;
}
}
/// <devdoc>
/// Loads all items from view state.
/// </devdoc>
private void LoadAllItemsFromViewState(object savedState) {
Debug.Assert(savedState != null);
Debug.Assert(savedState is Pair);
Pair p1 = (Pair)savedState;
if (p1.Second is Pair) {
Pair p2 = (Pair)p1.Second;
// save all mode; some objects are typed
object[] states = (object[])p1.First;
int[] typeIndices = (int[])p2.First;
ArrayList typedObjectTypeNames = (ArrayList)p2.Second;
Clear();
for (int i = 0; i < states.Length; i++) {
object o;
// If there is only one known type, we don't need type indices
if (typeIndices == null) {
// Create known type
o = CreateKnownType(0);
}
else {
int typeIndex = typeIndices[i];
if (typeIndex < GetKnownTypeCount()) {
// Create known type
o = CreateKnownType(typeIndex);
}
else {
string typeName = (string)typedObjectTypeNames[typeIndex - GetKnownTypeCount()];
Type type = Type.GetType(typeName);
o = Activator.CreateInstance(type);
}
}
((IStateManager)o).TrackViewState();
((IStateManager)o).LoadViewState(states[i]);
((IList)this).Add(o);
}
}
else {
Debug.Assert(p1.First is object[]);
// save all mode; all objects are instances of known types
object[] states = (object[])p1.First;
int[] typeIndices = (int[])p1.Second;
Clear();
for (int i = 0; i < states.Length; i++) {
// Create known type
int typeIndex = 0;
if (typeIndices != null) {
typeIndex = (int)typeIndices[i];
}
object o = CreateKnownType(typeIndex);
((IStateManager)o).TrackViewState();
((IStateManager)o).LoadViewState(states[i]);
((IList)this).Add(o);
}
}
}
/// <devdoc>
/// Loads only changed items from view state.
/// </devdoc>
private void LoadChangedItemsFromViewState(object savedState) {
Debug.Assert(savedState != null);
Debug.Assert(savedState is Triplet);
Triplet t = (Triplet)savedState;
if (t.Third is Pair) {
// save some mode; some new objects are typed
Pair p = (Pair)t.Third;
ArrayList indices = (ArrayList)t.First;
ArrayList states = (ArrayList)t.Second;
ArrayList typeIndices = (ArrayList)p.First;
ArrayList typedObjectTypeNames = (ArrayList)p.Second;
for (int i = 0; i < indices.Count; i++) {
int index = (int)indices[i];
if (index < Count) {
((IStateManager)((IList)this)[index]).LoadViewState(states[i]);
}
else {
object o;
// If there is only one known type, we don't need type indices
if (typeIndices == null) {
// Create known type
o = CreateKnownType(0);
}
else {
int typeIndex = (int)typeIndices[i];
if (typeIndex < GetKnownTypeCount()) {
// Create known type
o = CreateKnownType(typeIndex);
}
else {
string typeName = (string)typedObjectTypeNames[typeIndex - GetKnownTypeCount()];
Type type = Type.GetType(typeName);
o = Activator.CreateInstance(type);
}
}
((IStateManager)o).TrackViewState();
((IStateManager)o).LoadViewState(states[i]);
((IList)this).Add(o);
}
}
}
else {
// save some mode; all new objects are instances of known types
ArrayList indices = (ArrayList)t.First;
ArrayList states = (ArrayList)t.Second;
ArrayList typeIndices = (ArrayList)t.Third;
for (int i = 0; i < indices.Count; i++) {
int index = (int)indices[i];
if (index < Count) {
((IStateManager)((IList)this)[index]).LoadViewState(states[i]);
}
else {
// Create known type
int typeIndex = 0;
if (typeIndices != null) {
typeIndex = (int)typeIndices[i];
}
object o = CreateKnownType(typeIndex);
((IStateManager)o).TrackViewState();
((IStateManager)o).LoadViewState(states[i]);
((IList)this).Add(o);
}
}
}
}
/// <devdoc>
/// Called when the Clear() method is starting.
/// </devdoc>
protected virtual void OnClear() {
}
/// <devdoc>
/// Called when the Clear() method is complete.
/// </devdoc>
protected virtual void OnClearComplete() {
}
/// <devdoc>
/// Called when an object must be validated.
/// </devdoc>
protected virtual void OnValidate(object value) {
if (value == null) throw new ArgumentNullException("value");
}
/// <devdoc>
/// Called when the Insert() method is starting.
/// </devdoc>
protected virtual void OnInsert(int index, object value) {
}
/// <devdoc>
/// Called when the Insert() method is complete.
/// </devdoc>
protected virtual void OnInsertComplete(int index, object value) {
}
/// <devdoc>
/// Called when the Remove() method is starting.
/// </devdoc>
protected virtual void OnRemove(int index, object value) {
}
/// <devdoc>
/// Called when the Remove() method is complete.
/// </devdoc>
protected virtual void OnRemoveComplete(int index, object value) {
}
/// <devdoc>
/// Saves all items in the collection to view state.
/// </devdoc>
private object SaveAllItemsToViewState() {
Debug.Assert(_saveAll);
bool hasState = false;
int count = _collectionItems.Count;
int[] typeIndices = new int[count];
object[] states = new object[count];
ArrayList typedObjectTypeNames = null;
IDictionary typedObjectTracker = null;
int knownTypeCount = GetKnownTypeCount();
for (int i = 0; i < count; i++) {
object o = _collectionItems[i];
SetDirtyObject(o);
states[i] = ((IStateManager)o).SaveViewState();
if (states[i] != null)
hasState = true;
Type objectType = o.GetType();
int knownTypeIndex = -1;
// If there are known types, find index
if (knownTypeCount != 0) {
knownTypeIndex = ((IList)GetKnownTypes()).IndexOf(objectType);
}
if (knownTypeIndex != -1) {
// Type is known
typeIndices[i] = knownTypeIndex;
}
else {
// Type is unknown
if (typedObjectTypeNames == null) {
typedObjectTypeNames = new ArrayList();
typedObjectTracker = new HybridDictionary();
}
// Get index of type
object index = typedObjectTracker[objectType];
// If type is not in list, add it to the list
if (index == null) {
typedObjectTypeNames.Add(objectType.AssemblyQualifiedName);
// Offset the index by the known type count
index = typedObjectTypeNames.Count + knownTypeCount - 1;
typedObjectTracker[objectType] = index;
}
typeIndices[i] = (int)index;
}
}
// If the collection didn't have items to begin with don't save the state
if (!_hadItems && !hasState) {
return null;
}
if (typedObjectTypeNames == null) {
// all objects are instances known types
// If there is only one known type, then all objects are of that type so the indices are not needed
if (knownTypeCount == 1)
typeIndices = null;
return new Pair(states, typeIndices);
}
else {
return new Pair(states, new Pair(typeIndices, typedObjectTypeNames));
}
}
/// <devdoc>
/// Saves changed items to view state.
/// </devdoc>
private object SaveChangedItemsToViewState() {
Debug.Assert(_saveAll == false);
bool hasState = false;
int count = _collectionItems.Count;
ArrayList indices = new ArrayList();
ArrayList states = new ArrayList();
ArrayList typeIndices = new ArrayList();
ArrayList typedObjectTypeNames = null;
IDictionary typedObjectTracker = null;
int knownTypeCount = GetKnownTypeCount();
for (int i = 0; i < count; i++) {
object o = _collectionItems[i];
object state = ((IStateManager)o).SaveViewState();
if (state != null) {
hasState = true;
indices.Add(i);
states.Add(state);
Type objectType = o.GetType();
int knownTypeIndex = -1;
// If there are known types, find index
if (knownTypeCount != 0) {
knownTypeIndex = ((IList)GetKnownTypes()).IndexOf(objectType);
}
if (knownTypeIndex != -1) {
// Type is known
typeIndices.Add(knownTypeIndex);
}
else {
// Type is unknown
if (typedObjectTypeNames == null) {
typedObjectTypeNames = new ArrayList();
typedObjectTracker = new HybridDictionary();
}
object index = typedObjectTracker[objectType];
if (index == null) {
typedObjectTypeNames.Add(objectType.AssemblyQualifiedName);
// Offset the index by the known type count
index = typedObjectTypeNames.Count + knownTypeCount - 1;
typedObjectTracker[objectType] = index;
}
typeIndices.Add(index);
}
}
}
// If the collection didn't have items to begin with don't save the state
if (!_hadItems && !hasState) {
return null;
}
if (typedObjectTypeNames == null) {
// all objects are instances known types
// If there is only one known type, then all objects are of that type so the indices are not needed
if (knownTypeCount == 1)
typeIndices = null;
return new Triplet(indices, states, typeIndices);
}
else {
return new Triplet(indices, states, new Pair(typeIndices, typedObjectTypeNames));
}
}
/// <devdoc>
/// Forces the entire collection to be serialized into viewstate, not just
/// the change-information. This is useful when a collection has changed in
/// a significant way and change information would be insufficient to
/// recreate the object.
/// </devdoc>
public void SetDirty() {
_saveAll = true;
}
/// <devdoc>
/// Flags an object to record its entire state instead of just changed parts.
/// </devdoc>
protected abstract void SetDirtyObject(object o);
/// <internalonly/>
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
/// <internalonly/>
int ICollection.Count {
get {
return Count;
}
}
/// <internalonly/>
bool ICollection.IsSynchronized {
get {
return false;
}
}
/// <internalonly/>
object ICollection.SyncRoot {
get {
return null;
}
}
/// <internalonly/>
bool IList.IsFixedSize {
get {
return false;
}
}
/// <internalonly/>
bool IList.IsReadOnly {
get {
return _collectionItems.IsReadOnly;
}
}
/// <internalonly/>
object IList.this[int index] {
get {
return _collectionItems[index];
}
set {
if (index < 0 || index >= Count) {
throw new ArgumentOutOfRangeException("index", SR.GetString(SR.StateManagedCollection_InvalidIndex));
}
((IList)this).RemoveAt(index);
((IList)this).Insert(index, value);
}
}
/// <internalonly/>
int IList.Add(object value) {
OnValidate(value);
InsertInternal(-1, value);
return _collectionItems.Count - 1;
}
/// <internalonly/>
void IList.Clear() {
Clear();
}
/// <internalonly/>
bool IList.Contains(object value) {
if (value == null) {
return false;
}
OnValidate(value);
return _collectionItems.Contains(value);
}
/// <internalonly/>
int IList.IndexOf(object value) {
if (value == null) {
return -1;
}
OnValidate(value);
return _collectionItems.IndexOf(value);
}
/// <internalonly/>
void IList.Insert(int index, object value) {
if (value == null) {
throw new ArgumentNullException("value");
}
if (index < 0 || index > Count) {
throw new ArgumentOutOfRangeException("index", SR.GetString(SR.StateManagedCollection_InvalidIndex));
}
OnValidate(value);
InsertInternal(index, value);
if (_tracking) {
_saveAll = true;
}
}
/// <internalonly/>
void IList.Remove(object value) {
if (value == null) {
return;
}
OnValidate(value);
((IList)this).RemoveAt(((IList)this).IndexOf(value));
}
/// <internalonly/>
void IList.RemoveAt(int index) {
object o = _collectionItems[index];
OnRemove(index, o);
_collectionItems.RemoveAt(index);
try {
OnRemoveComplete(index, o);
}
catch {
_collectionItems.Insert(index, o);
throw;
}
if (_tracking) {
_saveAll = true;
}
}
/// <internalonly/>
bool IStateManager.IsTrackingViewState {
get {
return _tracking;
}
}
/// <internalonly/>
void IStateManager.LoadViewState(object savedState) {
if (savedState != null) {
if (savedState is Triplet) {
LoadChangedItemsFromViewState(savedState);
}
else {
LoadAllItemsFromViewState(savedState);
}
}
}
/// <internalonly/>
object IStateManager.SaveViewState() {
if (_saveAll) {
return SaveAllItemsToViewState();
}
else {
return SaveChangedItemsToViewState();
}
}
/// <internalonly/>
void IStateManager.TrackViewState() {
if (!((IStateManager)this).IsTrackingViewState) {
_hadItems = Count > 0;
_tracking = true;
foreach (IStateManager o in _collectionItems) {
o.TrackViewState();
}
}
}
}
}
| |
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using SharpDX.Direct3D;
using SharpDX.Direct3D11;
namespace SharpDX.Toolkit.Graphics
{
/// <summary>
/// Abstract class front end to <see cref="SharpDX.Direct3D11.Texture2D"/>.
/// </summary>
public abstract class Texture2DBase : Texture
{
protected readonly new Direct3D11.Texture2D Resource;
private DXGI.Surface dxgiSurface;
/// <summary>
/// Initializes a new instance of the <see cref="Texture2DBase" /> class.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="description2D">The description.</param>
/// <msdn-id>ff476521</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short>
protected internal Texture2DBase(GraphicsDevice device, Texture2DDescription description2D)
: base(device, description2D)
{
Resource = new Direct3D11.Texture2D(device, description2D);
}
/// <summary>
/// Initializes a new instance of the <see cref="Texture2DBase" /> class.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="description2D">The description.</param>
/// <param name="dataBoxes">A variable-length parameters list containing data rectangles.</param>
/// <msdn-id>ff476521</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short>
protected internal Texture2DBase(GraphicsDevice device, Texture2DDescription description2D, DataBox[] dataBoxes)
: base(device ,description2D)
{
Resource = new Direct3D11.Texture2D(device, description2D, dataBoxes);
}
/// <summary>
/// Specialised constructor for use only by derived classes.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="texture">The texture.</param>
/// <msdn-id>ff476521</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short>
protected internal Texture2DBase(GraphicsDevice device, Direct3D11.Texture2D texture)
: base(device, texture.Description)
{
Resource = texture;
}
/// <summary>
/// Return an equivalent staging texture CPU read-writable from this instance.
/// </summary>
/// <returns></returns>
public override Texture ToStaging()
{
return new Texture2D(this.GraphicsDevice, this.Description.ToStagingDescription());
}
protected virtual DXGI.Format GetDefaultViewFormat()
{
return this.Description.Format;
}
internal override ShaderResourceView GetShaderResourceView(ViewType viewType, int arrayOrDepthSlice, int mipIndex)
{
if ((this.Description.BindFlags & BindFlags.ShaderResource) == 0)
return null;
int arrayCount;
int mipCount;
GetViewSliceBounds(viewType, ref arrayOrDepthSlice, ref mipIndex, out arrayCount, out mipCount);
var srvIndex = GetViewIndex(viewType, arrayOrDepthSlice, mipIndex);
lock (this.shaderResourceViews)
{
var srv = this.shaderResourceViews[srvIndex];
// Creates the shader resource view
if (srv == null)
{
// Create the view
var srvDescription = new ShaderResourceViewDescription() { Format = GetDefaultViewFormat() };
// Initialize for texture arrays or texture cube
if (this.Description.ArraySize > 1)
{
// If texture cube
if ((this.Description.OptionFlags & ResourceOptionFlags.TextureCube) != 0)
{
srvDescription.Dimension = ShaderResourceViewDimension.TextureCube;
srvDescription.TextureCube.MipLevels = mipCount;
srvDescription.TextureCube.MostDetailedMip = mipIndex;
}
else
{
// Else regular Texture2D
srvDescription.Dimension = this.Description.SampleDescription.Count > 1 ? ShaderResourceViewDimension.Texture2DMultisampledArray : ShaderResourceViewDimension.Texture2DArray;
// Multisample?
if (this.Description.SampleDescription.Count > 1)
{
srvDescription.Texture2DMSArray.ArraySize = arrayCount;
srvDescription.Texture2DMSArray.FirstArraySlice = arrayOrDepthSlice;
}
else
{
srvDescription.Texture2DArray.ArraySize = arrayCount;
srvDescription.Texture2DArray.FirstArraySlice = arrayOrDepthSlice;
srvDescription.Texture2DArray.MipLevels = mipCount;
srvDescription.Texture2DArray.MostDetailedMip = mipIndex;
}
}
}
else
{
srvDescription.Dimension = this.Description.SampleDescription.Count > 1 ? ShaderResourceViewDimension.Texture2DMultisampled : ShaderResourceViewDimension.Texture2D;
if (this.Description.SampleDescription.Count <= 1)
{
srvDescription.Texture2D.MipLevels = mipCount;
srvDescription.Texture2D.MostDetailedMip = mipIndex;
}
}
srv = new ShaderResourceView(this.GraphicsDevice, this.Resource, srvDescription);
this.shaderResourceViews[srvIndex] = ToDispose(srv);
}
// Associate this instance
srv.Tag = this;
return srv;
}
}
internal override UnorderedAccessView GetUnorderedAccessView(int arrayOrDepthSlice, int mipIndex)
{
if ((this.Description.BindFlags & BindFlags.UnorderedAccess) == 0)
return null;
int arrayCount = 1;
// Use Full although we are binding to a single array/mimap slice, just to get the correct index
var uavIndex = GetViewIndex(ViewType.Full, arrayOrDepthSlice, mipIndex);
lock (this.unorderedAccessViews)
{
var uav = this.unorderedAccessViews[uavIndex];
// Creates the unordered access view
if (uav == null)
{
var uavDescription = new UnorderedAccessViewDescription() {
Format = this.Description.Format,
Dimension = this.Description.ArraySize > 1 ? UnorderedAccessViewDimension.Texture2DArray : UnorderedAccessViewDimension.Texture2D
};
if (this.Description.ArraySize > 1)
{
uavDescription.Texture2DArray.ArraySize = arrayCount;
uavDescription.Texture2DArray.FirstArraySlice = arrayOrDepthSlice;
uavDescription.Texture2DArray.MipSlice = mipIndex;
}
else
{
uavDescription.Texture2D.MipSlice = mipIndex;
}
uav = new UnorderedAccessView(GraphicsDevice, Resource, uavDescription);
this.unorderedAccessViews[uavIndex] = ToDispose(uav);
}
// Associate this instance
uav.Tag = this;
return uav;
}
}
/// <summary>
/// <see cref="SharpDX.DXGI.Surface"/> casting operator.
/// </summary>
/// <param name="from">From the Texture1D.</param>
public static implicit operator SharpDX.DXGI.Surface(Texture2DBase from)
{
// Don't bother with multithreading here
return from == null ? null : from.dxgiSurface ?? (from.dxgiSurface = from.ToDispose(from.Resource.QueryInterface<DXGI.Surface>()));
}
protected override void InitializeViews()
{
// Creates the shader resource view
if ((this.Description.BindFlags & BindFlags.ShaderResource) != 0)
{
this.shaderResourceViews = new ShaderResourceView[GetViewCount()];
// Pre initialize by default the view on the first array/mipmap
GetShaderResourceView(ViewType.Full, 0, 0);
}
// Creates the unordered access view
if ((this.Description.BindFlags & BindFlags.UnorderedAccess) != 0)
{
// Initialize the unordered access views
this.unorderedAccessViews = new UnorderedAccessView[GetViewCount()];
// Pre initialize by default the view on the first array/mipmap
GetUnorderedAccessView(0, 0);
}
}
protected static Texture2DDescription NewDescription(int width, int height, PixelFormat format, TextureFlags textureFlags, int mipCount, int arraySize, ResourceUsage usage)
{
if ((textureFlags & TextureFlags.UnorderedAccess) != 0)
usage = ResourceUsage.Default;
var desc = new Texture2DDescription()
{
Width = width,
Height = height,
ArraySize = arraySize,
SampleDescription = new DXGI.SampleDescription(1, 0),
BindFlags = GetBindFlagsFromTextureFlags(textureFlags),
Format = format,
MipLevels = CalculateMipMapCount(mipCount, width, height),
Usage = usage,
CpuAccessFlags = GetCputAccessFlagsFromUsage(usage),
OptionFlags = ResourceOptionFlags.None
};
// If the texture is a RenderTarget + ShaderResource + MipLevels > 1, then allow for GenerateMipMaps method
if ((desc.BindFlags & BindFlags.RenderTarget) != 0 && (desc.BindFlags & BindFlags.ShaderResource) != 0 && desc.MipLevels > 1)
{
desc.OptionFlags |= ResourceOptionFlags.GenerateMipMaps;
}
return desc;
}
}
}
| |
// 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.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using Microsoft.Internal.Collections;
namespace System.ComponentModel.Composition.ReflectionModel
{
internal class ReflectionComposablePartDefinition : ComposablePartDefinition, ICompositionElement
{
private readonly IReflectionPartCreationInfo _creationInfo;
private volatile ImportDefinition[] _imports;
private volatile ExportDefinition[] _exports;
private volatile IDictionary<string, object> _metadata;
private volatile ConstructorInfo _constructor;
private object _lock = new object();
public ReflectionComposablePartDefinition(IReflectionPartCreationInfo creationInfo)
{
if (creationInfo == null)
{
throw new ArgumentNullException(nameof(creationInfo));
}
_creationInfo = creationInfo;
}
public Type GetPartType()
{
return _creationInfo.GetPartType();
}
public Lazy<Type> GetLazyPartType()
{
return _creationInfo.GetLazyPartType();
}
public ConstructorInfo GetConstructor()
{
if (_constructor == null)
{
ConstructorInfo constructor = _creationInfo.GetConstructor();
lock (_lock)
{
if (_constructor == null)
{
_constructor = constructor;
}
}
}
return _constructor;
}
private ExportDefinition[] ExportDefinitionsInternal
{
get
{
if (_exports == null)
{
ExportDefinition[] exports = _creationInfo.GetExports().ToArray();
lock (_lock)
{
if (_exports == null)
{
_exports = exports;
}
}
}
return _exports;
}
}
public override IEnumerable<ExportDefinition> ExportDefinitions
{
get
{
return ExportDefinitionsInternal;
}
}
public override IEnumerable<ImportDefinition> ImportDefinitions
{
get
{
if (_imports == null)
{
ImportDefinition[] imports = _creationInfo.GetImports().ToArray();
lock (_lock)
{
if (_imports == null)
{
_imports = imports;
}
}
}
return _imports;
}
}
public override IDictionary<string, object> Metadata
{
get
{
if (_metadata == null)
{
IDictionary<string, object> metadata = _creationInfo.GetMetadata().AsReadOnly();
lock (_lock)
{
if (_metadata == null)
{
_metadata = metadata;
}
}
}
return _metadata;
}
}
internal bool IsDisposalRequired
{
get
{
return _creationInfo.IsDisposalRequired;
}
}
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
public override ComposablePart CreatePart()
{
if (IsDisposalRequired)
{
return new DisposableReflectionComposablePart(this);
}
else
{
return new ReflectionComposablePart(this);
}
}
internal override ComposablePartDefinition GetGenericPartDefinition()
{
GenericSpecializationPartCreationInfo genericCreationInfo = _creationInfo as GenericSpecializationPartCreationInfo;
if (genericCreationInfo != null)
{
return genericCreationInfo.OriginalPart;
}
return null;
}
internal override bool TryGetExports(ImportDefinition definition, out Tuple<ComposablePartDefinition, ExportDefinition> singleMatch, out IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> multipleMatches)
{
if (this.IsGeneric())
{
singleMatch = null;
multipleMatches = null;
List<Tuple<ComposablePartDefinition, ExportDefinition>> exports = null;
var genericParameters = (definition.Metadata.Count > 0) ? definition.Metadata.GetValue<IEnumerable<object>>(CompositionConstants.GenericParametersMetadataName) : null;
// if and only if generic parameters have been supplied can we attempt to "close" the generic
if (genericParameters != null)
{
Type[] genericTypeParameters = null;
// we only understand types
if (TryGetGenericTypeParameters(genericParameters, out genericTypeParameters))
{
HashSet<ComposablePartDefinition> candidates = null;
ComposablePartDefinition candidatePart = null;
ComposablePartDefinition previousPart = null;
// go through all orders of generic parameters that part exports allows
foreach (Type[] candidateParameters in GetCandidateParameters(genericTypeParameters))
{
if (TryMakeGenericPartDefinition(candidateParameters, out candidatePart))
{
bool alreadyProcessed = false;
if (candidates == null)
{
if (previousPart != null)
{
if (candidatePart.Equals(previousPart))
{
alreadyProcessed = true;
}
else
{
candidates = new HashSet<ComposablePartDefinition>();
candidates.Add(previousPart);
candidates.Add(candidatePart);
}
}
else
{
previousPart = candidatePart;
}
}
else
{
if (candidates.Contains(candidatePart))
{
alreadyProcessed = true;
}
else
{
candidates.Add(candidatePart);
}
}
if (!alreadyProcessed)
{
Tuple<ComposablePartDefinition, ExportDefinition> candidateSingleMatch;
IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> candidateMultipleMatches;
if (candidatePart.TryGetExports(definition, out candidateSingleMatch, out candidateMultipleMatches))
{
exports = exports.FastAppendToListAllowNulls(candidateSingleMatch, candidateMultipleMatches);
}
}
}
}
}
}
if (exports != null)
{
multipleMatches = exports;
return true;
}
else
{
return false;
}
}
else
{
return TryGetNonGenericExports(definition, out singleMatch, out multipleMatches);
}
}
// Optimised for local as array case
private bool TryGetNonGenericExports(ImportDefinition definition, out Tuple<ComposablePartDefinition, ExportDefinition> singleMatch, out IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> multipleMatches)
{
singleMatch = null;
multipleMatches = null;
List<Tuple<ComposablePartDefinition, ExportDefinition>> multipleExports = null;
Tuple<ComposablePartDefinition, ExportDefinition> singleExport = null;
bool matchesFound = false;
foreach (var export in ExportDefinitionsInternal)
{
if (definition.IsConstraintSatisfiedBy(export))
{
matchesFound = true;
if (singleExport == null)
{
singleExport = new Tuple<ComposablePartDefinition, ExportDefinition>(this, export);
}
else
{
if (multipleExports == null)
{
multipleExports = new List<Tuple<ComposablePartDefinition, ExportDefinition>>();
multipleExports.Add(singleExport);
}
multipleExports.Add(new Tuple<ComposablePartDefinition, ExportDefinition>(this, export));
}
}
}
if (!matchesFound)
{
return false;
}
if (multipleExports != null)
{
multipleMatches = multipleExports;
}
else
{
singleMatch = singleExport;
}
return true;
}
private IEnumerable<Type[]> GetCandidateParameters(Type[] genericParameters)
{
// we iterate over all exports and find only generic ones. Assuming the arity matches, we reorder the original parameters
foreach (ExportDefinition export in ExportDefinitionsInternal)
{
var genericParametersOrder = export.Metadata.GetValue<int[]>(CompositionConstants.GenericExportParametersOrderMetadataName);
if ((genericParametersOrder != null) && (genericParametersOrder.Length == genericParameters.Length))
{
yield return GenericServices.Reorder(genericParameters, genericParametersOrder);
}
}
}
private static bool TryGetGenericTypeParameters(IEnumerable<object> genericParameters, out Type[] genericTypeParameters)
{
genericTypeParameters = genericParameters as Type[];
if (genericTypeParameters == null)
{
object[] genericParametersAsArray = genericParameters.AsArray();
genericTypeParameters = new Type[genericParametersAsArray.Length];
for (int i = 0; i < genericParametersAsArray.Length; i++)
{
genericTypeParameters[i] = genericParametersAsArray[i] as Type;
if (genericTypeParameters[i] == null)
{
return false;
}
}
}
return true;
}
internal bool TryMakeGenericPartDefinition(Type[] genericTypeParameters, out ComposablePartDefinition genericPartDefinition)
{
genericPartDefinition = null;
if (!GenericSpecializationPartCreationInfo.CanSpecialize(Metadata, genericTypeParameters))
{
return false;
}
genericPartDefinition = new ReflectionComposablePartDefinition(new GenericSpecializationPartCreationInfo(_creationInfo, this, genericTypeParameters));
return true;
}
string ICompositionElement.DisplayName
{
get { return _creationInfo.DisplayName; }
}
ICompositionElement ICompositionElement.Origin
{
get { return _creationInfo.Origin; }
}
public override string ToString()
{
return _creationInfo.DisplayName;
}
public override bool Equals(object obj)
{
if (_creationInfo.IsIdentityComparison)
{
return object.ReferenceEquals(this, obj);
}
else
{
ReflectionComposablePartDefinition that = obj as ReflectionComposablePartDefinition;
if (that == null)
{
return false;
}
return _creationInfo.Equals(that._creationInfo);
}
}
public override int GetHashCode()
{
if (_creationInfo.IsIdentityComparison)
{
return base.GetHashCode();
}
else
{
return _creationInfo.GetHashCode();
}
}
}
}
| |
/********************************************************************++
* Copyright (c) Microsoft Corporation. All rights reserved.
* --********************************************************************/
using System.Collections;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
namespace System.Management.Automation
{
/// <summary>
/// Base class for items in the PSInformationalBuffers.
///
/// A PSInformationalRecord consists of a string Message and the InvocationInfo and pipeline state corresponding
/// to the command that created the record.
/// </summary>
[DataContract()]
public abstract class InformationalRecord
{
/// <remarks>
/// This class can be instantiated only by its derived classes
/// </remarks>
internal InformationalRecord(string message)
{
_message = message;
_invocationInfo = null;
_pipelineIterationInfo = null;
_serializeExtendedInfo = false;
}
/// <summary>
/// Creates an InformationalRecord object from a record serialized as a PSObject by ToPSObjectForRemoting.
/// </summary>
internal InformationalRecord(PSObject serializedObject)
{
_message = (string)SerializationUtilities.GetPropertyValue(serializedObject, "InformationalRecord_Message");
_serializeExtendedInfo = (bool)SerializationUtilities.GetPropertyValue(serializedObject, "InformationalRecord_SerializeInvocationInfo");
if (_serializeExtendedInfo)
{
_invocationInfo = new InvocationInfo(serializedObject);
ArrayList pipelineIterationInfo = (ArrayList)SerializationUtilities.GetPsObjectPropertyBaseObject(serializedObject, "InformationalRecord_PipelineIterationInfo");
_pipelineIterationInfo = new ReadOnlyCollection<int>((int[])pipelineIterationInfo.ToArray(typeof(int)));
}
else
{
_invocationInfo = null;
}
}
/// <summary>
/// The message written by the command that created this record
/// </summary>
public string Message
{
get
{
return _message;
}
set { _message = value; }
}
/// <summary>
/// The InvocationInfo of the command that created this record
/// </summary>
/// <remarks>
/// The InvocationInfo can be null if the record was not created by a command.
/// </remarks>
public InvocationInfo InvocationInfo
{
get
{
return _invocationInfo;
}
}
/// <summary>
/// The status of the pipeline when this record was created.
/// </summary>
/// <remarks>
/// The PipelineIterationInfo can be null if the record was not created by a command.
/// </remarks>
public ReadOnlyCollection<int> PipelineIterationInfo
{
get
{
return _pipelineIterationInfo;
}
}
/// <summary>
/// Sets the InvocationInfo (and PipelineIterationInfo) for this record
/// </summary>
internal void SetInvocationInfo(InvocationInfo invocationInfo)
{
_invocationInfo = invocationInfo;
//
// Copy a snapshot of the PipelineIterationInfo from the InvocationInfo to this InformationalRecord
//
if (invocationInfo.PipelineIterationInfo != null)
{
int[] snapshot = (int[])invocationInfo.PipelineIterationInfo.Clone();
_pipelineIterationInfo = new ReadOnlyCollection<int>(snapshot);
}
}
/// <summary>
/// Whether to serialize the InvocationInfo and PipelineIterationInfo during remote calls
/// </summary>
internal bool SerializeExtendedInfo
{
get
{
return _serializeExtendedInfo;
}
set
{
_serializeExtendedInfo = value;
}
}
/// <summary>
/// Returns the record's message
/// </summary>
public override string ToString()
{
return this.Message;
}
/// <summary>
/// Adds the information about this informational record to a PSObject as note properties.
/// The PSObject is used to serialize the record during remote operations.
/// </summary>
internal virtual void ToPSObjectForRemoting(PSObject psObject)
{
RemotingEncoder.AddNoteProperty<string>(psObject, "InformationalRecord_Message", () => this.Message);
//
// The invocation info may be null if the record was created via WriteVerbose/Warning/DebugLine instead of WriteVerbose/Warning/Debug, in that case
// we set InformationalRecord_SerializeInvocationInfo to false.
//
if (!this.SerializeExtendedInfo || _invocationInfo == null)
{
RemotingEncoder.AddNoteProperty(psObject, "InformationalRecord_SerializeInvocationInfo", () => false);
}
else
{
RemotingEncoder.AddNoteProperty(psObject, "InformationalRecord_SerializeInvocationInfo", () => true);
_invocationInfo.ToPSObjectForRemoting(psObject);
RemotingEncoder.AddNoteProperty<object>(psObject, "InformationalRecord_PipelineIterationInfo", () => this.PipelineIterationInfo);
}
}
[DataMember()]
private string _message;
private InvocationInfo _invocationInfo;
private ReadOnlyCollection<int> _pipelineIterationInfo;
private bool _serializeExtendedInfo;
}
/// <summary>
/// A warning record in the PSInformationalBuffers.
/// </summary>
[DataContract()]
public class WarningRecord : InformationalRecord
{
/// <summary>
///
/// </summary>
/// <param name="message"></param>
public WarningRecord(string message)
: base(message)
{ }
/// <summary>
///
/// </summary>
/// <param name="record"></param>
public WarningRecord(PSObject record)
: base(record)
{ }
/// <summary>
/// Constructor for Fully qualified warning Id.
/// </summary>
/// <param name="fullyQualifiedWarningId">Fully qualified warning Id</param>
/// <param name="message">Warning message</param>
public WarningRecord(string fullyQualifiedWarningId, string message)
: base(message)
{
_fullyQualifiedWarningId = fullyQualifiedWarningId;
}
/// <summary>
/// Constructor for Fully qualified warning Id.
/// </summary>
/// <param name="fullyQualifiedWarningId">Fully qualified warning Id</param>
/// <param name="record">Warning serialized object</param>
public WarningRecord(string fullyQualifiedWarningId, PSObject record)
: base(record)
{
_fullyQualifiedWarningId = fullyQualifiedWarningId;
}
/// <summary>
/// String which uniquely identifies this warning condition.
/// </summary>
public string FullyQualifiedWarningId
{
get
{
return _fullyQualifiedWarningId ?? string.Empty;
}
}
private string _fullyQualifiedWarningId;
}
/// <summary>
/// A debug record in the PSInformationalBuffers.
/// </summary>
[DataContract()]
public class DebugRecord : InformationalRecord
{
/// <summary>
///
/// </summary>
/// <param name="message"></param>
public DebugRecord(string message)
: base(message)
{ }
/// <summary>
///
/// </summary>
/// <param name="record"></param>
public DebugRecord(PSObject record)
: base(record)
{ }
}
/// <summary>
/// A verbose record in the PSInformationalBuffers.
/// </summary>
[DataContract()]
public class VerboseRecord : InformationalRecord
{
/// <summary>
///
/// </summary>
/// <param name="message"></param>
public VerboseRecord(string message)
: base(message)
{ }
/// <summary>
///
/// </summary>
/// <param name="record"></param>
public VerboseRecord(PSObject record)
: base(record)
{ }
}
}
| |
// Copyright (c) 1995-2009 held by the author(s). 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 names of the Naval Postgraduate School (NPS)
// Modeling Virtual Environments and Simulation (MOVES) Institute
// (http://www.nps.edu and http://www.MovesInstitute.org)
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All
// rights reserved. This work is licensed under the BSD open source license,
// available at https://www.movesinstitute.org/licenses/bsd.html
//
// Author: DMcG
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Xml.Serialization;
using OpenDis.Core;
namespace OpenDis.Dis1995
{
/// <summary>
/// Section 5.2.4.2. Used when the antenna pattern type field has a value of 1. Specifies the direction, patter, and polarization of radiation from an antenna.
/// </summary>
[Serializable]
[XmlRoot]
[XmlInclude(typeof(Orientation))]
public partial class BeamAntennaPattern
{
/// <summary>
/// The rotation that transformst he reference coordinate sytem into the beam coordinate system. Either world coordinates or entity coordinates may be used as the reference coordinate system, as specified by teh reference system field of the antenna pattern record.
/// </summary>
private Orientation _beamDirection = new Orientation();
private float _azimuthBeamwidth;
private float _referenceSystem;
private short _padding1;
private byte _padding2;
/// <summary>
/// Magnigute of the z-component in beam coordinates at some arbitrary single point in the mainbeam and in the far field of the antenna.
/// </summary>
private float _ez;
/// <summary>
/// Magnigute of the x-component in beam coordinates at some arbitrary single point in the mainbeam and in the far field of the antenna.
/// </summary>
private float _ex;
/// <summary>
/// THe phase angle between Ez and Ex in radians.
/// </summary>
private float _phase;
/// <summary>
/// Initializes a new instance of the <see cref="BeamAntennaPattern"/> class.
/// </summary>
public BeamAntennaPattern()
{
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(BeamAntennaPattern left, BeamAntennaPattern right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(BeamAntennaPattern left, BeamAntennaPattern right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
public virtual int GetMarshalledSize()
{
int marshalSize = 0;
marshalSize += this._beamDirection.GetMarshalledSize(); // this._beamDirection
marshalSize += 4; // this._azimuthBeamwidth
marshalSize += 4; // this._referenceSystem
marshalSize += 2; // this._padding1
marshalSize += 1; // this._padding2
marshalSize += 4; // this._ez
marshalSize += 4; // this._ex
marshalSize += 4; // this._phase
return marshalSize;
}
/// <summary>
/// Gets or sets the The rotation that transformst he reference coordinate sytem into the beam coordinate system. Either world coordinates or entity coordinates may be used as the reference coordinate system, as specified by teh reference system field of the antenna pattern record.
/// </summary>
[XmlElement(Type = typeof(Orientation), ElementName = "beamDirection")]
public Orientation BeamDirection
{
get
{
return this._beamDirection;
}
set
{
this._beamDirection = value;
}
}
/// <summary>
/// Gets or sets the azimuthBeamwidth
/// </summary>
[XmlElement(Type = typeof(float), ElementName = "azimuthBeamwidth")]
public float AzimuthBeamwidth
{
get
{
return this._azimuthBeamwidth;
}
set
{
this._azimuthBeamwidth = value;
}
}
/// <summary>
/// Gets or sets the referenceSystem
/// </summary>
[XmlElement(Type = typeof(float), ElementName = "referenceSystem")]
public float ReferenceSystem
{
get
{
return this._referenceSystem;
}
set
{
this._referenceSystem = value;
}
}
/// <summary>
/// Gets or sets the padding1
/// </summary>
[XmlElement(Type = typeof(short), ElementName = "padding1")]
public short Padding1
{
get
{
return this._padding1;
}
set
{
this._padding1 = value;
}
}
/// <summary>
/// Gets or sets the padding2
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "padding2")]
public byte Padding2
{
get
{
return this._padding2;
}
set
{
this._padding2 = value;
}
}
/// <summary>
/// Gets or sets the Magnigute of the z-component in beam coordinates at some arbitrary single point in the mainbeam and in the far field of the antenna.
/// </summary>
[XmlElement(Type = typeof(float), ElementName = "ez")]
public float Ez
{
get
{
return this._ez;
}
set
{
this._ez = value;
}
}
/// <summary>
/// Gets or sets the Magnigute of the x-component in beam coordinates at some arbitrary single point in the mainbeam and in the far field of the antenna.
/// </summary>
[XmlElement(Type = typeof(float), ElementName = "ex")]
public float Ex
{
get
{
return this._ex;
}
set
{
this._ex = value;
}
}
/// <summary>
/// Gets or sets the THe phase angle between Ez and Ex in radians.
/// </summary>
[XmlElement(Type = typeof(float), ElementName = "phase")]
public float Phase
{
get
{
return this._phase;
}
set
{
this._phase = value;
}
}
/// <summary>
/// Occurs when exception when processing PDU is caught.
/// </summary>
public event EventHandler<PduExceptionEventArgs> ExceptionOccured;
/// <summary>
/// Called when exception occurs (raises the <see cref="Exception"/> event).
/// </summary>
/// <param name="e">The exception.</param>
protected void RaiseExceptionOccured(Exception e)
{
if (Pdu.FireExceptionEvents && this.ExceptionOccured != null)
{
this.ExceptionOccured(this, new PduExceptionEventArgs(e));
}
}
/// <summary>
/// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public virtual void Marshal(DataOutputStream dos)
{
if (dos != null)
{
try
{
this._beamDirection.Marshal(dos);
dos.WriteFloat((float)this._azimuthBeamwidth);
dos.WriteFloat((float)this._referenceSystem);
dos.WriteShort((short)this._padding1);
dos.WriteByte((byte)this._padding2);
dos.WriteFloat((float)this._ez);
dos.WriteFloat((float)this._ex);
dos.WriteFloat((float)this._phase);
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public virtual void Unmarshal(DataInputStream dis)
{
if (dis != null)
{
try
{
this._beamDirection.Unmarshal(dis);
this._azimuthBeamwidth = dis.ReadFloat();
this._referenceSystem = dis.ReadFloat();
this._padding1 = dis.ReadShort();
this._padding2 = dis.ReadByte();
this._ez = dis.ReadFloat();
this._ex = dis.ReadFloat();
this._phase = dis.ReadFloat();
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
/// <summary>
/// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging.
/// This will be modified in the future to provide a better display. Usage:
/// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb });
/// where pdu is an object representing a single pdu and sb is a StringBuilder.
/// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality
/// </summary>
/// <param name="sb">The StringBuilder instance to which the PDU is written to.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public virtual void Reflection(StringBuilder sb)
{
sb.AppendLine("<BeamAntennaPattern>");
try
{
sb.AppendLine("<beamDirection>");
this._beamDirection.Reflection(sb);
sb.AppendLine("</beamDirection>");
sb.AppendLine("<azimuthBeamwidth type=\"float\">" + this._azimuthBeamwidth.ToString(CultureInfo.InvariantCulture) + "</azimuthBeamwidth>");
sb.AppendLine("<referenceSystem type=\"float\">" + this._referenceSystem.ToString(CultureInfo.InvariantCulture) + "</referenceSystem>");
sb.AppendLine("<padding1 type=\"short\">" + this._padding1.ToString(CultureInfo.InvariantCulture) + "</padding1>");
sb.AppendLine("<padding2 type=\"byte\">" + this._padding2.ToString(CultureInfo.InvariantCulture) + "</padding2>");
sb.AppendLine("<ez type=\"float\">" + this._ez.ToString(CultureInfo.InvariantCulture) + "</ez>");
sb.AppendLine("<ex type=\"float\">" + this._ex.ToString(CultureInfo.InvariantCulture) + "</ex>");
sb.AppendLine("<phase type=\"float\">" + this._phase.ToString(CultureInfo.InvariantCulture) + "</phase>");
sb.AppendLine("</BeamAntennaPattern>");
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return this == obj as BeamAntennaPattern;
}
/// <summary>
/// Compares for reference AND value equality.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public bool Equals(BeamAntennaPattern obj)
{
bool ivarsEqual = true;
if (obj.GetType() != this.GetType())
{
return false;
}
if (!this._beamDirection.Equals(obj._beamDirection))
{
ivarsEqual = false;
}
if (this._azimuthBeamwidth != obj._azimuthBeamwidth)
{
ivarsEqual = false;
}
if (this._referenceSystem != obj._referenceSystem)
{
ivarsEqual = false;
}
if (this._padding1 != obj._padding1)
{
ivarsEqual = false;
}
if (this._padding2 != obj._padding2)
{
ivarsEqual = false;
}
if (this._ez != obj._ez)
{
ivarsEqual = false;
}
if (this._ex != obj._ex)
{
ivarsEqual = false;
}
if (this._phase != obj._phase)
{
ivarsEqual = false;
}
return ivarsEqual;
}
/// <summary>
/// HashCode Helper
/// </summary>
/// <param name="hash">The hash value.</param>
/// <returns>The new hash value.</returns>
private static int GenerateHash(int hash)
{
hash = hash << (5 + hash);
return hash;
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int result = 0;
result = GenerateHash(result) ^ this._beamDirection.GetHashCode();
result = GenerateHash(result) ^ this._azimuthBeamwidth.GetHashCode();
result = GenerateHash(result) ^ this._referenceSystem.GetHashCode();
result = GenerateHash(result) ^ this._padding1.GetHashCode();
result = GenerateHash(result) ^ this._padding2.GetHashCode();
result = GenerateHash(result) ^ this._ez.GetHashCode();
result = GenerateHash(result) ^ this._ex.GetHashCode();
result = GenerateHash(result) ^ this._phase.GetHashCode();
return result;
}
}
}
| |
#region Copyright notice and license
// Copyright 2015-2016, Google Inc.
// 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Grpc.Core.Internal;
using NUnit.Framework;
namespace Grpc.Core.Internal.Tests
{
public class AsyncCallTest
{
Channel channel;
FakeNativeCall fakeCall;
AsyncCall<string, string> asyncCall;
[SetUp]
public void Init()
{
channel = new Channel("localhost", ChannelCredentials.Insecure);
fakeCall = new FakeNativeCall();
var callDetails = new CallInvocationDetails<string, string>(channel, "someMethod", null, Marshallers.StringMarshaller, Marshallers.StringMarshaller, new CallOptions());
asyncCall = new AsyncCall<string, string>(callDetails, fakeCall);
}
[TearDown]
public void Cleanup()
{
channel.ShutdownAsync().Wait();
}
[Test]
public void AsyncUnary_CompletionSuccess()
{
var resultTask = asyncCall.UnaryCallAsync("abc");
fakeCall.UnaryResponseClientHandler(true, new ClientSideStatus(Status.DefaultSuccess, new Metadata()), new byte[] { 1, 2, 3 }, new Metadata());
Assert.IsTrue(resultTask.IsCompleted);
Assert.IsTrue(fakeCall.IsDisposed);
Assert.AreEqual(Status.DefaultSuccess, asyncCall.GetStatus());
}
[Test]
public void AsyncUnary_CompletionFailure()
{
var resultTask = asyncCall.UnaryCallAsync("abc");
fakeCall.UnaryResponseClientHandler(false, new ClientSideStatus(new Status(StatusCode.Internal, ""), null), new byte[] { 1, 2, 3 }, new Metadata());
Assert.IsTrue(resultTask.IsCompleted);
Assert.IsTrue(fakeCall.IsDisposed);
Assert.AreEqual(StatusCode.Internal, asyncCall.GetStatus().StatusCode);
Assert.IsNull(asyncCall.GetTrailers());
var ex = Assert.Throws<RpcException>(() => resultTask.GetAwaiter().GetResult());
Assert.AreEqual(StatusCode.Internal, ex.Status.StatusCode);
}
internal class FakeNativeCall : INativeCall
{
public UnaryResponseClientHandler UnaryResponseClientHandler
{
get;
set;
}
public ReceivedStatusOnClientHandler ReceivedStatusOnClientHandler
{
get;
set;
}
public ReceivedMessageHandler ReceivedMessageHandler
{
get;
set;
}
public ReceivedResponseHeadersHandler ReceivedResponseHeadersHandler
{
get;
set;
}
public SendCompletionHandler SendCompletionHandler
{
get;
set;
}
public ReceivedCloseOnServerHandler ReceivedCloseOnServerHandler
{
get;
set;
}
public bool IsCancelled
{
get;
set;
}
public bool IsDisposed
{
get;
set;
}
public void Cancel()
{
IsCancelled = true;
}
public void CancelWithStatus(Status status)
{
IsCancelled = true;
}
public string GetPeer()
{
return "PEER";
}
public void StartUnary(UnaryResponseClientHandler callback, byte[] payload, MetadataArraySafeHandle metadataArray, WriteFlags writeFlags)
{
UnaryResponseClientHandler = callback;
}
public void StartUnary(BatchContextSafeHandle ctx, byte[] payload, MetadataArraySafeHandle metadataArray, WriteFlags writeFlags)
{
throw new NotImplementedException();
}
public void StartClientStreaming(UnaryResponseClientHandler callback, MetadataArraySafeHandle metadataArray)
{
UnaryResponseClientHandler = callback;
}
public void StartServerStreaming(ReceivedStatusOnClientHandler callback, byte[] payload, MetadataArraySafeHandle metadataArray, WriteFlags writeFlags)
{
ReceivedStatusOnClientHandler = callback;
}
public void StartDuplexStreaming(ReceivedStatusOnClientHandler callback, MetadataArraySafeHandle metadataArray)
{
ReceivedStatusOnClientHandler = callback;
}
public void StartReceiveMessage(ReceivedMessageHandler callback)
{
ReceivedMessageHandler = callback;
}
public void StartReceiveInitialMetadata(ReceivedResponseHeadersHandler callback)
{
ReceivedResponseHeadersHandler = callback;
}
public void StartSendInitialMetadata(SendCompletionHandler callback, MetadataArraySafeHandle metadataArray)
{
SendCompletionHandler = callback;
}
public void StartSendMessage(SendCompletionHandler callback, byte[] payload, WriteFlags writeFlags, bool sendEmptyInitialMetadata)
{
SendCompletionHandler = callback;
}
public void StartSendCloseFromClient(SendCompletionHandler callback)
{
SendCompletionHandler = callback;
}
public void StartSendStatusFromServer(SendCompletionHandler callback, Status status, MetadataArraySafeHandle metadataArray, bool sendEmptyInitialMetadata)
{
SendCompletionHandler = callback;
}
public void StartServerSide(ReceivedCloseOnServerHandler callback)
{
ReceivedCloseOnServerHandler = callback;
}
public void Dispose()
{
IsDisposed = true;
}
}
}
}
| |
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 Exam_Service.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) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//------------------------------------------------------------------------------
using System.Collections.Generic;
using System.Data.Common;
using System.Diagnostics;
namespace System.Data.SqlClient
{
internal class TdsParserSessionPool
{
// NOTE: This is a very simplistic, lightweight pooler. It wasn't
// intended to handle huge number of items, just to keep track
// of the session objects to ensure that they're cleaned up in
// a timely manner, to avoid holding on to an unacceptible
// amount of server-side resources in the event that consumers
// let their data readers be GC'd, instead of explicitly
// closing or disposing of them
private const int MaxInactiveCount = 10; // pick something, preferably small...
private readonly TdsParser _parser; // parser that owns us
private readonly List<TdsParserStateObject> _cache; // collection of all known sessions
private int _cachedCount; // lock-free _cache.Count
private TdsParserStateObject[] _freeStateObjects; // collection of all sessions available for reuse
private int _freeStateObjectCount; // Number of available free sessions
internal TdsParserSessionPool(TdsParser parser)
{
_parser = parser;
_cache = new List<TdsParserStateObject>();
_freeStateObjects = new TdsParserStateObject[MaxInactiveCount];
_freeStateObjectCount = 0;
}
private bool IsDisposed
{
get
{
return (null == _freeStateObjects);
}
}
internal void Deactivate()
{
// When being deactivated, we check all the sessions in the
// cache to make sure they're cleaned up and then we dispose of
// sessions that are past what we want to keep around.
lock (_cache)
{
// NOTE: The PutSession call below may choose to remove the
// session from the cache, which will throw off our
// enumerator. We avoid that by simply indexing backward
// through the array.
for (int i = _cache.Count - 1; i >= 0; i--)
{
TdsParserStateObject session = _cache[i];
if (null != session)
{
if (session.IsOrphaned)
{
// TODO: consider adding a performance counter for the number of sessions we reclaim
PutSession(session);
}
}
}
// TODO: re-enable this assert when the connection isn't doomed.
//Debug.Assert (_cachedCount < MaxInactiveCount, "non-orphaned connection past initial allocation?");
}
}
// This is called from a ThreadAbort - ensure that it can be run from a CER Catch
internal void BestEffortCleanup()
{
for (int i = 0; i < _cache.Count; i++)
{
TdsParserStateObject session = _cache[i];
if (null != session)
{
var sessionHandle = session.Handle;
if (sessionHandle != null)
{
sessionHandle.Dispose();
}
}
}
}
internal void Dispose()
{
lock (_cache)
{
// Dispose free sessions
for (int i = 0; i < _freeStateObjectCount; i++)
{
if (_freeStateObjects[i] != null)
{
_freeStateObjects[i].Dispose();
}
}
_freeStateObjects = null;
_freeStateObjectCount = 0;
// Dispose orphaned sessions
for (int i = 0; i < _cache.Count; i++)
{
if (_cache[i] != null)
{
if (_cache[i].IsOrphaned)
{
_cache[i].Dispose();
}
else
{
// Remove the "initial" callback (this will allow the stateObj to be GC collected if need be)
_cache[i].DecrementPendingCallbacks(false);
}
}
}
_cache.Clear();
_cachedCount = 0;
// Any active sessions will take care of themselves
// (It's too dangerous to dispose them, as this can cause AVs)
}
}
internal TdsParserStateObject GetSession(object owner)
{
TdsParserStateObject session;
lock (_cache)
{
if (IsDisposed)
{
throw ADP.ClosedConnectionError();
}
else if (_freeStateObjectCount > 0)
{
// Free state object - grab it
_freeStateObjectCount--;
session = _freeStateObjects[_freeStateObjectCount];
_freeStateObjects[_freeStateObjectCount] = null;
Debug.Assert(session != null, "There was a null session in the free session list?");
}
else
{
// No free objects, create a new one
session = _parser.CreateSession();
_cache.Add(session);
_cachedCount = _cache.Count;
}
session.Activate(owner);
}
return session;
}
internal void PutSession(TdsParserStateObject session)
{
Debug.Assert(null != session, "null session?");
//Debug.Assert(null != session.Owner, "session without owner?");
bool okToReuse = session.Deactivate();
lock (_cache)
{
if (IsDisposed)
{
// We're diposed - just clean out the session
Debug.Assert(_cachedCount == 0, "SessionPool is disposed, but there are still sessions in the cache?");
session.Dispose();
}
else if ((okToReuse) && (_freeStateObjectCount < MaxInactiveCount))
{
// Session is good to re-use and our cache has space
Debug.Assert(!session._pendingData, "pending data on a pooled session?");
_freeStateObjects[_freeStateObjectCount] = session;
_freeStateObjectCount++;
}
else
{
// Either the session is bad, or we have no cache space - so dispose the session and remove it
bool removed = _cache.Remove(session);
Debug.Assert(removed, "session not in pool?");
_cachedCount = _cache.Count;
session.Dispose();
}
session.RemoveOwner();
}
}
internal int ActiveSessionsCount
{
get
{
return _cachedCount - _freeStateObjectCount;
}
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.HSLF.Record
{
using System;
using System.IO;
using NPOI.Util;
using System.Text;
using System.Collections;
/**
* The special info Runs Contained in this text.
* Special info Runs consist of character properties which don?t follow styles.
*
* @author Yegor Kozlov
*/
public class TextSpecInfoAtom : RecordAtom
{
/**
* Record header.
*/
private byte[] _header;
/**
* Record data.
*/
private byte[] _data;
/**
* Constructs the link related atom record from its
* source data.
*
* @param source the source data as a byte array.
* @param start the start offset into the byte array.
* @param len the length of the slice in the byte array.
*/
protected TextSpecInfoAtom(byte[] source, int start, int len)
{
// Get the header.
_header = new byte[8];
Array.Copy(source, start, _header, 0, 8);
// Get the record data.
_data = new byte[len - 8];
Array.Copy(source, start + 8, _data, 0, len - 8);
}
/**
* Gets the record type.
* @return the record type.
*/
public override long RecordType
{
get { return RecordTypes.TextSpecInfoAtom.typeID; }
}
/**
* Write the contents of the record back, so it can be written
* to disk
*
* @param out the output stream to write to.
* @throws java.io.IOException if an error occurs.
*/
public override void WriteOut(Stream out1)
{
out1.Write(_header, (int)out1.Position, _header.Length);
out1.Write(_data, (int)out1.Position, _data.Length);
}
/**
* Update the text length
*
* @param size the text length
*/
public void SetTextSize(int size)
{
LittleEndian.PutInt(_data, 0, size);
}
/**
* Reset the content to one info run with the default values
* @param size the site of parent text
*/
public void Reset(int size)
{
_data = new byte[10];
// 01 00 00 00
LittleEndian.PutInt(_data, 0, size);
// 01 00 00 00
LittleEndian.PutInt(_data, 4, 1); //mask
// 00 00
LittleEndian.PutShort(_data, 8, (short)0); //langId
// Update the size (header bytes 5-8)
LittleEndian.PutInt(_header, 4, _data.Length);
}
/**
* Get the number of characters covered by this records
*
* @return the number of characters covered by this records
*/
public int GetCharactersCovered()
{
int covered = 0;
TextSpecInfoRun[] Runs = GetTextSpecInfoRuns();
for (int i = 0; i < Runs.Length; i++) covered += Runs[i].len;
return covered;
}
public TextSpecInfoRun[] GetTextSpecInfoRuns()
{
ArrayList lst = new ArrayList();
int pos = 0;
int[] bits = { 1, 0, 2 };
while (pos < _data.Length)
{
TextSpecInfoRun run = new TextSpecInfoRun();
run.len = LittleEndian.GetInt(_data, pos); pos += 4;
run.mask = LittleEndian.GetInt(_data, pos); pos += 4;
for (int i = 0; i < bits.Length; i++)
{
if ((run.mask & 1 << bits[i]) != 0)
{
switch (bits[i])
{
case 0:
run.spellInfo = LittleEndian.GetShort(_data, pos); pos += 2;
break;
case 1:
run.langId = LittleEndian.GetShort(_data, pos); pos += 2;
break;
case 2:
run.altLangId = LittleEndian.GetShort(_data, pos); pos += 2;
break;
}
}
}
lst.Add(run);
}
return (TextSpecInfoRun[])lst.ToArray(typeof(TextSpecInfoRun));
}
public class TextSpecInfoRun
{
//Length of special info Run.
internal int len;
//Special info mask of this Run;
internal int mask;
// info fields as indicated by the mask.
// -1 means the bit is not set
internal short spellInfo = -1;
internal short langId = -1;
internal short altLangId = -1;
/**
* Spelling status of this text. See Spell Info table below.
*
* <p>Spell Info Types:</p>
* <li>0 UnChecked
* <li>1 Previously incorrect, needs reChecking
* <li>2 Correct
* <li>3 Incorrect
*
* @return Spelling status of this text
*/
public short SpellInfo
{
get
{
return spellInfo;
}
}
/**
* Windows LANGID for this text.
*
* @return Windows LANGID for this text.
*/
public short LangId
{
get
{
return spellInfo;
}
}
/**
* Alternate Windows LANGID of this text;
* must be a valid non-East Asian LANGID if the text has an East Asian language,
* otherwise may be an East Asian LANGID or language neutral (zero).
*
* @return Alternate Windows LANGID of this text
*/
public short AltLangId
{
get
{
return altLangId;
}
}
/**
* @return Length of special info Run.
*/
public int Length
{
get
{
return len;
}
}
}
}
}
| |
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 WinterIsComing.WebApi.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System;
namespace Lucene.Net.Util.junitcompat
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using After = org.junit.After;
using AfterClass = org.junit.AfterClass;
using Assert = org.junit.Assert;
using Before = org.junit.Before;
using BeforeClass = org.junit.BeforeClass;
using Rule = org.junit.Rule;
using Test = org.junit.Test;
using TestRule = org.junit.rules.TestRule;
using Description = org.junit.runner.Description;
using JUnitCore = org.junit.runner.JUnitCore;
using Statement = org.junit.runners.model.Statement;
/// <summary>
/// Test reproduce message is right.
/// </summary>
public class TestReproduceMessage : WithNestedTests
{
public static SorePoint @where;
public static SoreType Type;
public class Nested : AbstractNestedTest
{
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @BeforeClass public static void beforeClass()
public static void BeforeClass()
{
if (RunningNested)
{
TriggerOn(SorePoint.BEFORE_CLASS);
}
}
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Rule public org.junit.rules.TestRule rule = new TestRuleAnonymousInnerClassHelper();
public TestRule rule = new TestRuleAnonymousInnerClassHelper();
private class TestRuleAnonymousInnerClassHelper : TestRule
{
public TestRuleAnonymousInnerClassHelper()
{
}
public override Statement Apply(Statement @base, Description description)
{
return new StatementAnonymousInnerClassHelper(this, @base);
}
private class StatementAnonymousInnerClassHelper : Statement
{
private readonly TestRuleAnonymousInnerClassHelper OuterInstance;
private Statement @base;
public StatementAnonymousInnerClassHelper(TestRuleAnonymousInnerClassHelper outerInstance, Statement @base)
{
this.outerInstance = outerInstance;
this.@base = @base;
}
public override void Evaluate()
{
TriggerOn(SorePoint.RULE);
@base.evaluate();
}
}
}
/// <summary>
/// Class initializer block/ default constructor. </summary>
public Nested()
{
TriggerOn(SorePoint.INITIALIZER);
}
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Before public void before()
public virtual void Before()
{
TriggerOn(SorePoint.BEFORE);
}
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void test()
public virtual void Test()
{
TriggerOn(SorePoint.TEST);
}
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @After public void after()
public virtual void After()
{
TriggerOn(SorePoint.AFTER);
}
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @AfterClass public static void afterClass()
public static void AfterClass()
{
if (RunningNested)
{
TriggerOn(SorePoint.AFTER_CLASS);
}
}
internal static void TriggerOn(SorePoint pt)
{
if (pt == @where)
{
switch (Type)
{
case Lucene.Net.Util.junitcompat.SoreType.ASSUMPTION:
LuceneTestCase.assumeTrue(pt.ToString(), false);
throw new Exception("unreachable");
case Lucene.Net.Util.junitcompat.SoreType.ERROR:
throw new Exception(pt.ToString());
case Lucene.Net.Util.junitcompat.SoreType.FAILURE:
Assert.IsTrue(pt.ToString(), false);
throw new Exception("unreachable");
}
}
}
}
/*
* ASSUMPTIONS.
*/
public TestReproduceMessage() : base(true)
{
}
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void testAssumeBeforeClass() throws Exception
public virtual void TestAssumeBeforeClass()
{
Type = SoreType.ASSUMPTION;
@where = SorePoint.BEFORE_CLASS;
Assert.IsTrue(RunAndReturnSyserr().Length == 0);
}
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void testAssumeInitializer() throws Exception
public virtual void TestAssumeInitializer()
{
Type = SoreType.ASSUMPTION;
@where = SorePoint.INITIALIZER;
Assert.IsTrue(RunAndReturnSyserr().Length == 0);
}
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void testAssumeRule() throws Exception
public virtual void TestAssumeRule()
{
Type = SoreType.ASSUMPTION;
@where = SorePoint.RULE;
Assert.AreEqual("", RunAndReturnSyserr());
}
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void testAssumeBefore() throws Exception
public virtual void TestAssumeBefore()
{
Type = SoreType.ASSUMPTION;
@where = SorePoint.BEFORE;
Assert.IsTrue(RunAndReturnSyserr().Length == 0);
}
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void testAssumeTest() throws Exception
public virtual void TestAssumeTest()
{
Type = SoreType.ASSUMPTION;
@where = SorePoint.TEST;
Assert.IsTrue(RunAndReturnSyserr().Length == 0);
}
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void testAssumeAfter() throws Exception
public virtual void TestAssumeAfter()
{
Type = SoreType.ASSUMPTION;
@where = SorePoint.AFTER;
Assert.IsTrue(RunAndReturnSyserr().Length == 0);
}
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void testAssumeAfterClass() throws Exception
public virtual void TestAssumeAfterClass()
{
Type = SoreType.ASSUMPTION;
@where = SorePoint.AFTER_CLASS;
Assert.IsTrue(RunAndReturnSyserr().Length == 0);
}
/*
* FAILURES
*/
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void testFailureBeforeClass() throws Exception
public virtual void TestFailureBeforeClass()
{
Type = SoreType.FAILURE;
@where = SorePoint.BEFORE_CLASS;
Assert.IsTrue(RunAndReturnSyserr().Contains("NOTE: reproduce with:"));
}
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void testFailureInitializer() throws Exception
public virtual void TestFailureInitializer()
{
Type = SoreType.FAILURE;
@where = SorePoint.INITIALIZER;
Assert.IsTrue(RunAndReturnSyserr().Contains("NOTE: reproduce with:"));
}
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void testFailureRule() throws Exception
public virtual void TestFailureRule()
{
Type = SoreType.FAILURE;
@where = SorePoint.RULE;
string syserr = RunAndReturnSyserr();
Assert.IsTrue(syserr.Contains("NOTE: reproduce with:"));
Assert.IsTrue(Arrays.AsList(syserr.Split("\\s", true)).Contains("-Dtests.method=test"));
Assert.IsTrue(Arrays.AsList(syserr.Split("\\s", true)).Contains("-Dtestcase=" + typeof(Nested).SimpleName));
}
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void testFailureBefore() throws Exception
public virtual void TestFailureBefore()
{
Type = SoreType.FAILURE;
@where = SorePoint.BEFORE;
string syserr = RunAndReturnSyserr();
Assert.IsTrue(syserr.Contains("NOTE: reproduce with:"));
Assert.IsTrue(Arrays.AsList(syserr.Split("\\s", true)).Contains("-Dtests.method=test"));
Assert.IsTrue(Arrays.AsList(syserr.Split("\\s", true)).Contains("-Dtestcase=" + typeof(Nested).SimpleName));
}
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void testFailureTest() throws Exception
public virtual void TestFailureTest()
{
Type = SoreType.FAILURE;
@where = SorePoint.TEST;
string syserr = RunAndReturnSyserr();
Assert.IsTrue(syserr.Contains("NOTE: reproduce with:"));
Assert.IsTrue(Arrays.AsList(syserr.Split("\\s", true)).Contains("-Dtests.method=test"));
Assert.IsTrue(Arrays.AsList(syserr.Split("\\s", true)).Contains("-Dtestcase=" + typeof(Nested).SimpleName));
}
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void testFailureAfter() throws Exception
public virtual void TestFailureAfter()
{
Type = SoreType.FAILURE;
@where = SorePoint.AFTER;
string syserr = RunAndReturnSyserr();
Assert.IsTrue(syserr.Contains("NOTE: reproduce with:"));
Assert.IsTrue(Arrays.AsList(syserr.Split("\\s", true)).Contains("-Dtests.method=test"));
Assert.IsTrue(Arrays.AsList(syserr.Split("\\s", true)).Contains("-Dtestcase=" + typeof(Nested).SimpleName));
}
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void testFailureAfterClass() throws Exception
public virtual void TestFailureAfterClass()
{
Type = SoreType.FAILURE;
@where = SorePoint.AFTER_CLASS;
Assert.IsTrue(RunAndReturnSyserr().Contains("NOTE: reproduce with:"));
}
/*
* ERRORS
*/
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void testErrorBeforeClass() throws Exception
public virtual void TestErrorBeforeClass()
{
Type = SoreType.ERROR;
@where = SorePoint.BEFORE_CLASS;
Assert.IsTrue(RunAndReturnSyserr().Contains("NOTE: reproduce with:"));
}
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void testErrorInitializer() throws Exception
public virtual void TestErrorInitializer()
{
Type = SoreType.ERROR;
@where = SorePoint.INITIALIZER;
Assert.IsTrue(RunAndReturnSyserr().Contains("NOTE: reproduce with:"));
}
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void testErrorRule() throws Exception
public virtual void TestErrorRule()
{
Type = SoreType.ERROR;
@where = SorePoint.RULE;
string syserr = RunAndReturnSyserr();
Assert.IsTrue(syserr.Contains("NOTE: reproduce with:"));
Assert.IsTrue(Arrays.AsList(syserr.Split("\\s", true)).Contains("-Dtests.method=test"));
Assert.IsTrue(Arrays.AsList(syserr.Split("\\s", true)).Contains("-Dtestcase=" + typeof(Nested).SimpleName));
}
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void testErrorBefore() throws Exception
public virtual void TestErrorBefore()
{
Type = SoreType.ERROR;
@where = SorePoint.BEFORE;
string syserr = RunAndReturnSyserr();
Assert.IsTrue(syserr.Contains("NOTE: reproduce with:"));
Assert.IsTrue(Arrays.AsList(syserr.Split("\\s", true)).Contains("-Dtests.method=test"));
Assert.IsTrue(Arrays.AsList(syserr.Split("\\s", true)).Contains("-Dtestcase=" + typeof(Nested).SimpleName));
}
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void testErrorTest() throws Exception
public virtual void TestErrorTest()
{
Type = SoreType.ERROR;
@where = SorePoint.TEST;
string syserr = RunAndReturnSyserr();
Assert.IsTrue(syserr.Contains("NOTE: reproduce with:"));
Assert.IsTrue(Arrays.AsList(syserr.Split("\\s", true)).Contains("-Dtests.method=test"));
Assert.IsTrue(Arrays.AsList(syserr.Split("\\s", true)).Contains("-Dtestcase=" + typeof(Nested).SimpleName));
}
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void testErrorAfter() throws Exception
public virtual void TestErrorAfter()
{
Type = SoreType.ERROR;
@where = SorePoint.AFTER;
string syserr = RunAndReturnSyserr();
Assert.IsTrue(syserr.Contains("NOTE: reproduce with:"));
Assert.IsTrue(Arrays.AsList(syserr.Split("\\s", true)).Contains("-Dtests.method=test"));
Assert.IsTrue(Arrays.AsList(syserr.Split("\\s", true)).Contains("-Dtestcase=" + typeof(Nested).SimpleName));
}
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void testErrorAfterClass() throws Exception
public virtual void TestErrorAfterClass()
{
Type = SoreType.ERROR;
@where = SorePoint.AFTER_CLASS;
Assert.IsTrue(RunAndReturnSyserr().Contains("NOTE: reproduce with:"));
}
private string RunAndReturnSyserr()
{
JUnitCore.runClasses(typeof(Nested));
string err = SysErr;
// super.prevSysErr.println("Type: " + type + ", point: " + where + " resulted in:\n" + err);
// super.prevSysErr.println("---");
return err;
}
}
}
| |
// 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.WebSecurityScanner.V1.Snippets
{
using Google.Api.Gax;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class AllGeneratedWebSecurityScannerClientSnippets
{
/// <summary>Snippet for CreateScanConfig</summary>
public void CreateScanConfigRequestObject()
{
// Snippet: CreateScanConfig(CreateScanConfigRequest, CallSettings)
// Create client
WebSecurityScannerClient webSecurityScannerClient = WebSecurityScannerClient.Create();
// Initialize request argument(s)
CreateScanConfigRequest request = new CreateScanConfigRequest
{
Parent = "",
ScanConfig = new ScanConfig(),
};
// Make the request
ScanConfig response = webSecurityScannerClient.CreateScanConfig(request);
// End snippet
}
/// <summary>Snippet for CreateScanConfigAsync</summary>
public async Task CreateScanConfigRequestObjectAsync()
{
// Snippet: CreateScanConfigAsync(CreateScanConfigRequest, CallSettings)
// Additional: CreateScanConfigAsync(CreateScanConfigRequest, CancellationToken)
// Create client
WebSecurityScannerClient webSecurityScannerClient = await WebSecurityScannerClient.CreateAsync();
// Initialize request argument(s)
CreateScanConfigRequest request = new CreateScanConfigRequest
{
Parent = "",
ScanConfig = new ScanConfig(),
};
// Make the request
ScanConfig response = await webSecurityScannerClient.CreateScanConfigAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteScanConfig</summary>
public void DeleteScanConfigRequestObject()
{
// Snippet: DeleteScanConfig(DeleteScanConfigRequest, CallSettings)
// Create client
WebSecurityScannerClient webSecurityScannerClient = WebSecurityScannerClient.Create();
// Initialize request argument(s)
DeleteScanConfigRequest request = new DeleteScanConfigRequest { Name = "", };
// Make the request
webSecurityScannerClient.DeleteScanConfig(request);
// End snippet
}
/// <summary>Snippet for DeleteScanConfigAsync</summary>
public async Task DeleteScanConfigRequestObjectAsync()
{
// Snippet: DeleteScanConfigAsync(DeleteScanConfigRequest, CallSettings)
// Additional: DeleteScanConfigAsync(DeleteScanConfigRequest, CancellationToken)
// Create client
WebSecurityScannerClient webSecurityScannerClient = await WebSecurityScannerClient.CreateAsync();
// Initialize request argument(s)
DeleteScanConfigRequest request = new DeleteScanConfigRequest { Name = "", };
// Make the request
await webSecurityScannerClient.DeleteScanConfigAsync(request);
// End snippet
}
/// <summary>Snippet for GetScanConfig</summary>
public void GetScanConfigRequestObject()
{
// Snippet: GetScanConfig(GetScanConfigRequest, CallSettings)
// Create client
WebSecurityScannerClient webSecurityScannerClient = WebSecurityScannerClient.Create();
// Initialize request argument(s)
GetScanConfigRequest request = new GetScanConfigRequest { Name = "", };
// Make the request
ScanConfig response = webSecurityScannerClient.GetScanConfig(request);
// End snippet
}
/// <summary>Snippet for GetScanConfigAsync</summary>
public async Task GetScanConfigRequestObjectAsync()
{
// Snippet: GetScanConfigAsync(GetScanConfigRequest, CallSettings)
// Additional: GetScanConfigAsync(GetScanConfigRequest, CancellationToken)
// Create client
WebSecurityScannerClient webSecurityScannerClient = await WebSecurityScannerClient.CreateAsync();
// Initialize request argument(s)
GetScanConfigRequest request = new GetScanConfigRequest { Name = "", };
// Make the request
ScanConfig response = await webSecurityScannerClient.GetScanConfigAsync(request);
// End snippet
}
/// <summary>Snippet for ListScanConfigs</summary>
public void ListScanConfigsRequestObject()
{
// Snippet: ListScanConfigs(ListScanConfigsRequest, CallSettings)
// Create client
WebSecurityScannerClient webSecurityScannerClient = WebSecurityScannerClient.Create();
// Initialize request argument(s)
ListScanConfigsRequest request = new ListScanConfigsRequest { Parent = "", };
// Make the request
PagedEnumerable<ListScanConfigsResponse, ScanConfig> response = webSecurityScannerClient.ListScanConfigs(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (ScanConfig 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 (ListScanConfigsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ScanConfig 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<ScanConfig> 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 (ScanConfig 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 ListScanConfigsAsync</summary>
public async Task ListScanConfigsRequestObjectAsync()
{
// Snippet: ListScanConfigsAsync(ListScanConfigsRequest, CallSettings)
// Create client
WebSecurityScannerClient webSecurityScannerClient = await WebSecurityScannerClient.CreateAsync();
// Initialize request argument(s)
ListScanConfigsRequest request = new ListScanConfigsRequest { Parent = "", };
// Make the request
PagedAsyncEnumerable<ListScanConfigsResponse, ScanConfig> response = webSecurityScannerClient.ListScanConfigsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((ScanConfig 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((ListScanConfigsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ScanConfig 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<ScanConfig> 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 (ScanConfig 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 UpdateScanConfig</summary>
public void UpdateScanConfigRequestObject()
{
// Snippet: UpdateScanConfig(UpdateScanConfigRequest, CallSettings)
// Create client
WebSecurityScannerClient webSecurityScannerClient = WebSecurityScannerClient.Create();
// Initialize request argument(s)
UpdateScanConfigRequest request = new UpdateScanConfigRequest
{
ScanConfig = new ScanConfig(),
UpdateMask = new FieldMask(),
};
// Make the request
ScanConfig response = webSecurityScannerClient.UpdateScanConfig(request);
// End snippet
}
/// <summary>Snippet for UpdateScanConfigAsync</summary>
public async Task UpdateScanConfigRequestObjectAsync()
{
// Snippet: UpdateScanConfigAsync(UpdateScanConfigRequest, CallSettings)
// Additional: UpdateScanConfigAsync(UpdateScanConfigRequest, CancellationToken)
// Create client
WebSecurityScannerClient webSecurityScannerClient = await WebSecurityScannerClient.CreateAsync();
// Initialize request argument(s)
UpdateScanConfigRequest request = new UpdateScanConfigRequest
{
ScanConfig = new ScanConfig(),
UpdateMask = new FieldMask(),
};
// Make the request
ScanConfig response = await webSecurityScannerClient.UpdateScanConfigAsync(request);
// End snippet
}
/// <summary>Snippet for StartScanRun</summary>
public void StartScanRunRequestObject()
{
// Snippet: StartScanRun(StartScanRunRequest, CallSettings)
// Create client
WebSecurityScannerClient webSecurityScannerClient = WebSecurityScannerClient.Create();
// Initialize request argument(s)
StartScanRunRequest request = new StartScanRunRequest { Name = "", };
// Make the request
ScanRun response = webSecurityScannerClient.StartScanRun(request);
// End snippet
}
/// <summary>Snippet for StartScanRunAsync</summary>
public async Task StartScanRunRequestObjectAsync()
{
// Snippet: StartScanRunAsync(StartScanRunRequest, CallSettings)
// Additional: StartScanRunAsync(StartScanRunRequest, CancellationToken)
// Create client
WebSecurityScannerClient webSecurityScannerClient = await WebSecurityScannerClient.CreateAsync();
// Initialize request argument(s)
StartScanRunRequest request = new StartScanRunRequest { Name = "", };
// Make the request
ScanRun response = await webSecurityScannerClient.StartScanRunAsync(request);
// End snippet
}
/// <summary>Snippet for GetScanRun</summary>
public void GetScanRunRequestObject()
{
// Snippet: GetScanRun(GetScanRunRequest, CallSettings)
// Create client
WebSecurityScannerClient webSecurityScannerClient = WebSecurityScannerClient.Create();
// Initialize request argument(s)
GetScanRunRequest request = new GetScanRunRequest { Name = "", };
// Make the request
ScanRun response = webSecurityScannerClient.GetScanRun(request);
// End snippet
}
/// <summary>Snippet for GetScanRunAsync</summary>
public async Task GetScanRunRequestObjectAsync()
{
// Snippet: GetScanRunAsync(GetScanRunRequest, CallSettings)
// Additional: GetScanRunAsync(GetScanRunRequest, CancellationToken)
// Create client
WebSecurityScannerClient webSecurityScannerClient = await WebSecurityScannerClient.CreateAsync();
// Initialize request argument(s)
GetScanRunRequest request = new GetScanRunRequest { Name = "", };
// Make the request
ScanRun response = await webSecurityScannerClient.GetScanRunAsync(request);
// End snippet
}
/// <summary>Snippet for ListScanRuns</summary>
public void ListScanRunsRequestObject()
{
// Snippet: ListScanRuns(ListScanRunsRequest, CallSettings)
// Create client
WebSecurityScannerClient webSecurityScannerClient = WebSecurityScannerClient.Create();
// Initialize request argument(s)
ListScanRunsRequest request = new ListScanRunsRequest { Parent = "", };
// Make the request
PagedEnumerable<ListScanRunsResponse, ScanRun> response = webSecurityScannerClient.ListScanRuns(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (ScanRun 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 (ListScanRunsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ScanRun 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<ScanRun> 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 (ScanRun 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 ListScanRunsAsync</summary>
public async Task ListScanRunsRequestObjectAsync()
{
// Snippet: ListScanRunsAsync(ListScanRunsRequest, CallSettings)
// Create client
WebSecurityScannerClient webSecurityScannerClient = await WebSecurityScannerClient.CreateAsync();
// Initialize request argument(s)
ListScanRunsRequest request = new ListScanRunsRequest { Parent = "", };
// Make the request
PagedAsyncEnumerable<ListScanRunsResponse, ScanRun> response = webSecurityScannerClient.ListScanRunsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((ScanRun 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((ListScanRunsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ScanRun 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<ScanRun> 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 (ScanRun 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 StopScanRun</summary>
public void StopScanRunRequestObject()
{
// Snippet: StopScanRun(StopScanRunRequest, CallSettings)
// Create client
WebSecurityScannerClient webSecurityScannerClient = WebSecurityScannerClient.Create();
// Initialize request argument(s)
StopScanRunRequest request = new StopScanRunRequest { Name = "", };
// Make the request
ScanRun response = webSecurityScannerClient.StopScanRun(request);
// End snippet
}
/// <summary>Snippet for StopScanRunAsync</summary>
public async Task StopScanRunRequestObjectAsync()
{
// Snippet: StopScanRunAsync(StopScanRunRequest, CallSettings)
// Additional: StopScanRunAsync(StopScanRunRequest, CancellationToken)
// Create client
WebSecurityScannerClient webSecurityScannerClient = await WebSecurityScannerClient.CreateAsync();
// Initialize request argument(s)
StopScanRunRequest request = new StopScanRunRequest { Name = "", };
// Make the request
ScanRun response = await webSecurityScannerClient.StopScanRunAsync(request);
// End snippet
}
/// <summary>Snippet for ListCrawledUrls</summary>
public void ListCrawledUrlsRequestObject()
{
// Snippet: ListCrawledUrls(ListCrawledUrlsRequest, CallSettings)
// Create client
WebSecurityScannerClient webSecurityScannerClient = WebSecurityScannerClient.Create();
// Initialize request argument(s)
ListCrawledUrlsRequest request = new ListCrawledUrlsRequest { Parent = "", };
// Make the request
PagedEnumerable<ListCrawledUrlsResponse, CrawledUrl> response = webSecurityScannerClient.ListCrawledUrls(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (CrawledUrl 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 (ListCrawledUrlsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (CrawledUrl 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<CrawledUrl> 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 (CrawledUrl 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 ListCrawledUrlsAsync</summary>
public async Task ListCrawledUrlsRequestObjectAsync()
{
// Snippet: ListCrawledUrlsAsync(ListCrawledUrlsRequest, CallSettings)
// Create client
WebSecurityScannerClient webSecurityScannerClient = await WebSecurityScannerClient.CreateAsync();
// Initialize request argument(s)
ListCrawledUrlsRequest request = new ListCrawledUrlsRequest { Parent = "", };
// Make the request
PagedAsyncEnumerable<ListCrawledUrlsResponse, CrawledUrl> response = webSecurityScannerClient.ListCrawledUrlsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((CrawledUrl 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((ListCrawledUrlsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (CrawledUrl 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<CrawledUrl> 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 (CrawledUrl 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 GetFinding</summary>
public void GetFindingRequestObject()
{
// Snippet: GetFinding(GetFindingRequest, CallSettings)
// Create client
WebSecurityScannerClient webSecurityScannerClient = WebSecurityScannerClient.Create();
// Initialize request argument(s)
GetFindingRequest request = new GetFindingRequest { Name = "", };
// Make the request
Finding response = webSecurityScannerClient.GetFinding(request);
// End snippet
}
/// <summary>Snippet for GetFindingAsync</summary>
public async Task GetFindingRequestObjectAsync()
{
// Snippet: GetFindingAsync(GetFindingRequest, CallSettings)
// Additional: GetFindingAsync(GetFindingRequest, CancellationToken)
// Create client
WebSecurityScannerClient webSecurityScannerClient = await WebSecurityScannerClient.CreateAsync();
// Initialize request argument(s)
GetFindingRequest request = new GetFindingRequest { Name = "", };
// Make the request
Finding response = await webSecurityScannerClient.GetFindingAsync(request);
// End snippet
}
/// <summary>Snippet for ListFindings</summary>
public void ListFindingsRequestObject()
{
// Snippet: ListFindings(ListFindingsRequest, CallSettings)
// Create client
WebSecurityScannerClient webSecurityScannerClient = WebSecurityScannerClient.Create();
// Initialize request argument(s)
ListFindingsRequest request = new ListFindingsRequest
{
Parent = "",
Filter = "",
};
// Make the request
PagedEnumerable<ListFindingsResponse, Finding> response = webSecurityScannerClient.ListFindings(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Finding 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 (ListFindingsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Finding 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<Finding> 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 (Finding 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 ListFindingsAsync</summary>
public async Task ListFindingsRequestObjectAsync()
{
// Snippet: ListFindingsAsync(ListFindingsRequest, CallSettings)
// Create client
WebSecurityScannerClient webSecurityScannerClient = await WebSecurityScannerClient.CreateAsync();
// Initialize request argument(s)
ListFindingsRequest request = new ListFindingsRequest
{
Parent = "",
Filter = "",
};
// Make the request
PagedAsyncEnumerable<ListFindingsResponse, Finding> response = webSecurityScannerClient.ListFindingsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Finding 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((ListFindingsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Finding 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<Finding> 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 (Finding 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 ListFindingTypeStats</summary>
public void ListFindingTypeStatsRequestObject()
{
// Snippet: ListFindingTypeStats(ListFindingTypeStatsRequest, CallSettings)
// Create client
WebSecurityScannerClient webSecurityScannerClient = WebSecurityScannerClient.Create();
// Initialize request argument(s)
ListFindingTypeStatsRequest request = new ListFindingTypeStatsRequest { Parent = "", };
// Make the request
ListFindingTypeStatsResponse response = webSecurityScannerClient.ListFindingTypeStats(request);
// End snippet
}
/// <summary>Snippet for ListFindingTypeStatsAsync</summary>
public async Task ListFindingTypeStatsRequestObjectAsync()
{
// Snippet: ListFindingTypeStatsAsync(ListFindingTypeStatsRequest, CallSettings)
// Additional: ListFindingTypeStatsAsync(ListFindingTypeStatsRequest, CancellationToken)
// Create client
WebSecurityScannerClient webSecurityScannerClient = await WebSecurityScannerClient.CreateAsync();
// Initialize request argument(s)
ListFindingTypeStatsRequest request = new ListFindingTypeStatsRequest { Parent = "", };
// Make the request
ListFindingTypeStatsResponse response = await webSecurityScannerClient.ListFindingTypeStatsAsync(request);
// End snippet
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.HSSF.Record.Aggregates
{
using NPOI.HSSF.Model;
using NPOI.HSSF.Record;
using NPOI.POIFS.Crypt;
using NPOI.Util;
using System;
/**
* Groups the sheet protection records for a worksheet.
* <p/>
*
* See OOO excelfileformat.pdf sec 4.18.2 'Sheet Protection in a Workbook
* (BIFF5-BIFF8)'
*
* @author Josh Micich
*/
public class WorksheetProtectionBlock : RecordAggregate
{
// Every one of these component records is optional
// (The whole WorksheetProtectionBlock may not be present)
private ProtectRecord _protectRecord;
private ObjectProtectRecord _objectProtectRecord;
private ScenarioProtectRecord _scenarioProtectRecord;
private PasswordRecord _passwordRecord;
/**
* Creates an empty WorksheetProtectionBlock
*/
public WorksheetProtectionBlock()
{
// all fields emptyv
}
/**
* @return <c>true</c> if the specified Record sid is one belonging to
* the 'Page Settings Block'.
*/
public static bool IsComponentRecord(int sid)
{
switch (sid)
{
case ProtectRecord.sid:
case ObjectProtectRecord.sid:
case ScenarioProtectRecord.sid:
case PasswordRecord.sid:
return true;
}
return false;
}
private bool ReadARecord(RecordStream rs)
{
switch (rs.PeekNextSid())
{
case ProtectRecord.sid:
CheckNotPresent(_protectRecord);
_protectRecord = rs.GetNext() as ProtectRecord;
break;
case ObjectProtectRecord.sid:
CheckNotPresent(_objectProtectRecord);
_objectProtectRecord = rs.GetNext() as ObjectProtectRecord;
break;
case ScenarioProtectRecord.sid:
CheckNotPresent(_scenarioProtectRecord);
_scenarioProtectRecord = rs.GetNext() as ScenarioProtectRecord;
break;
case PasswordRecord.sid:
CheckNotPresent(_passwordRecord);
_passwordRecord = rs.GetNext() as PasswordRecord;
break;
default:
// all other record types are not part of the PageSettingsBlock
return false;
}
return true;
}
private void CheckNotPresent(Record rec)
{
if (rec != null)
{
throw new RecordFormatException("Duplicate WorksheetProtectionBlock record (sid=0x"
+ StringUtil.ToHexString(rec.Sid) + ")");
}
}
public override void VisitContainedRecords(RecordVisitor rv)
{
// Replicates record order from Excel 2007, though this is not critical
VisitIfPresent(_protectRecord, rv);
VisitIfPresent(_objectProtectRecord, rv);
VisitIfPresent(_scenarioProtectRecord, rv);
VisitIfPresent(_passwordRecord, rv);
}
private static void VisitIfPresent(Record r, RecordVisitor rv)
{
if (r != null)
{
rv.VisitRecord(r);
}
}
public PasswordRecord GetPasswordRecord()
{
return _passwordRecord;
}
public ScenarioProtectRecord GetHCenter()
{
return _scenarioProtectRecord;
}
/**
* This method Reads {@link WorksheetProtectionBlock} records from the supplied RecordStream
* until the first non-WorksheetProtectionBlock record is encountered. As each record is Read,
* it is incorporated into this WorksheetProtectionBlock.
* <p/>
* As per the OOO documentation, the protection block records can be expected to be written
* toGether (with no intervening records), but earlier versions of POI (prior to Jun 2009)
* didn't do this. Workbooks with sheet protection Created by those earlier POI versions
* seemed to be valid (Excel opens them OK). So PO allows continues to support Reading of files
* with non continuous worksheet protection blocks.
*
* <p/>
* <b>Note</b> - when POI Writes out this WorksheetProtectionBlock, the records will always be
* written in one consolidated block (in the standard ordering) regardless of how scattered the
* records were when they were originally Read.
*/
public void AddRecords(RecordStream rs)
{
while (true)
{
if (!ReadARecord(rs))
{
break;
}
}
}
/// <summary>
/// the ProtectRecord. If one is not contained in the sheet, then one is created.
/// </summary>
private ProtectRecord Protect
{
get
{
if (_protectRecord == null)
{
_protectRecord = new ProtectRecord(false);
}
return _protectRecord;
}
}
/// <summary>
/// the PasswordRecord. If one is not Contained in the sheet, then one is Created.
/// </summary>
public PasswordRecord Password
{
get
{
if (_passwordRecord == null)
{
_passwordRecord = CreatePassword();
}
return _passwordRecord;
}
}
/// <summary>
/// protect a spreadsheet with a password (not encrypted, just sets protect flags and the password.)
/// </summary>
/// <param name="password">password to set;Pass <code>null</code> to remove all protection</param>
/// <param name="shouldProtectObjects">shouldProtectObjects are protected</param>
/// <param name="shouldProtectScenarios">shouldProtectScenarios are protected</param>
public void ProtectSheet(String password, bool shouldProtectObjects,
bool shouldProtectScenarios)
{
if (password == null)
{
_passwordRecord = null;
_protectRecord = null;
_objectProtectRecord = null;
_scenarioProtectRecord = null;
return;
}
ProtectRecord prec = this.Protect;
PasswordRecord pass = this.Password;
prec.Protect = true;
pass.Password = (short)CryptoFunctions.CreateXorVerifier1(password);
if (_objectProtectRecord == null && shouldProtectObjects)
{
ObjectProtectRecord rec = CreateObjectProtect();
rec.Protect = (true);
_objectProtectRecord = rec;
}
if (_scenarioProtectRecord == null && shouldProtectScenarios)
{
ScenarioProtectRecord srec = CreateScenarioProtect();
srec.Protect = (true);
_scenarioProtectRecord = srec;
}
}
public bool IsSheetProtected
{
get
{
return _protectRecord != null && _protectRecord.Protect;
}
}
public bool IsObjectProtected
{
get{
return _objectProtectRecord != null && _objectProtectRecord.Protect;
}
}
public bool IsScenarioProtected
{
get
{
return _scenarioProtectRecord != null && _scenarioProtectRecord.Protect;
}
}
/// <summary>
/// Creates an ObjectProtect record with protect set to false.
/// </summary>
/// <returns></returns>
private static ObjectProtectRecord CreateObjectProtect() {
ObjectProtectRecord retval = new ObjectProtectRecord();
retval.Protect = (false);
return retval;
}
/// <summary>
/// Creates a ScenarioProtect record with protect set to false.
/// </summary>
/// <returns></returns>
private static ScenarioProtectRecord CreateScenarioProtect() {
ScenarioProtectRecord retval = new ScenarioProtectRecord();
retval.Protect = (false);
return retval;
}
/// <summary>
///Creates a Password record with password set to 0x0000.
/// </summary>
/// <returns></returns>
private static PasswordRecord CreatePassword()
{
return new PasswordRecord(0x0000);
}
public int PasswordHash
{
get
{
if (_passwordRecord == null)
{
return 0;
}
return _passwordRecord.Password;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.PerformanceData;
using System.Globalization;
using System.Management.Automation.Tracing;
namespace System.Management.Automation.PerformanceData
{
/// <summary>
/// An abstract class that forms the base class for any Counter Set type.
/// A Counter Set Instance is required to register a given performance counter category
/// with PSPerfCountersMgr.
/// </summary>
public abstract class CounterSetInstanceBase : IDisposable
{
private readonly PowerShellTraceSource _tracer = PowerShellTraceSourceFactory.GetTraceSource();
#region Protected Members
/// <summary>
/// An instance of counterSetRegistrarBase type encapsulates all the information
/// about a counter set and its associated counters.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")]
protected CounterSetRegistrarBase _counterSetRegistrarBase;
// NOTE: Check whether the following dictionaries need to be concurrent
// because there would be only 1 thread creating the instance,
// and that instance would then be shared by multiple threads for data access.
// Those threads won't modify/manipulate the dictionary, but they would only access it.
/// <summary>
/// Dictionary mapping counter name to id.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")]
protected ConcurrentDictionary<string, int> _counterNameToIdMapping;
/// <summary>
/// Dictionary mapping counter id to counter type.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")]
protected ConcurrentDictionary<int, CounterType> _counterIdToTypeMapping;
#region Constructors
/// <summary>
/// Constructor.
/// </summary>
protected CounterSetInstanceBase(CounterSetRegistrarBase counterSetRegistrarInst)
{
this._counterSetRegistrarBase = counterSetRegistrarInst;
_counterNameToIdMapping = new ConcurrentDictionary<string, int>();
_counterIdToTypeMapping = new ConcurrentDictionary<int, CounterType>();
CounterInfo[] counterInfoArray = this._counterSetRegistrarBase.CounterInfoArray;
for (int i = 0; i < counterInfoArray.Length; i++)
{
this._counterIdToTypeMapping.TryAdd(counterInfoArray[i].Id, counterInfoArray[i].Type);
if (!string.IsNullOrWhiteSpace(counterInfoArray[i].Name))
{
this._counterNameToIdMapping.TryAdd(counterInfoArray[i].Name, counterInfoArray[i].Id);
}
}
}
#endregion
/// <summary>
/// Method that retrieves the target counter id.
/// NOTE: If isNumerator is true, then input counter id is returned.
/// But, if isNumerator is false, then a check is made on the input
/// counter's type to ensure that denominator is indeed value for such a counter.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2233:OperationsShouldNotOverflow", Justification = "countId is validated as known denominator before it is incremented.")]
protected bool RetrieveTargetCounterIdIfValid(int counterId, bool isNumerator, out int targetCounterId)
{
targetCounterId = counterId;
if (isNumerator == false)
{
bool isDenominatorValid = false;
CounterType counterType = this._counterIdToTypeMapping[counterId];
switch (counterType)
{
case CounterType.MultiTimerPercentageActive:
case CounterType.MultiTimerPercentageActive100Ns:
case CounterType.MultiTimerPercentageNotActive:
case CounterType.MultiTimerPercentageNotActive100Ns:
case CounterType.RawFraction32:
case CounterType.RawFraction64:
case CounterType.SampleFraction:
case CounterType.AverageCount64:
case CounterType.AverageTimer32:
isDenominatorValid = true;
break;
}
if (isDenominatorValid == false)
{
InvalidOperationException invalidOperationException =
new InvalidOperationException(
string.Format(
CultureInfo.InvariantCulture,
"Denominator for update not valid for the given counter id {0}",
counterId));
_tracer.TraceException(invalidOperationException);
return false;
}
targetCounterId = counterId + 1;
}
return true;
}
#endregion
#region Public Methods
/// <summary>
/// If isNumerator is true, then updates the numerator component
/// of target counter 'counterId' by a value given by 'stepAmount'.
/// Otherwise, updates the denominator component by 'stepAmount'.
/// </summary>
public abstract bool UpdateCounterByValue(
int counterId,
long stepAmount,
bool isNumerator);
/// <summary>
/// If isNumerator is true, then updates the numerator component
/// of target counter 'counterName' by a value given by 'stepAmount'.
/// Otherwise, updates the denominator component by 'stepAmount'.
/// </summary>
public abstract bool UpdateCounterByValue(
string counterName,
long stepAmount,
bool isNumerator);
/// <summary>
/// If isNumerator is true, then sets the numerator component of target
/// counter 'counterId' to 'counterValue'.
/// Otherwise, sets the denominator component to 'counterValue'.
/// </summary>
public abstract bool SetCounterValue(
int counterId,
long counterValue,
bool isNumerator);
/// <summary>
/// If isNumerator is true, then sets the numerator component of target
/// Counter 'counterName' to 'counterValue'.
/// Otherwise, sets the denominator component to 'counterValue'.
/// </summary>
public abstract bool SetCounterValue(
string counterName,
long counterValue,
bool isNumerator);
/// <summary>
/// This method retrieves the counter value associated with counter 'counterId'
/// based on isNumerator parameter.
/// </summary>
public abstract bool GetCounterValue(int counterId, bool isNumerator, out long counterValue);
/// <summary>
/// This method retrieves the counter value associated with counter 'counterName'
/// based on isNumerator parameter.
/// </summary>
public abstract bool GetCounterValue(string counterName, bool isNumerator, out long counterValue);
/// <summary>
/// An abstract method that will be implemented by the derived type
/// so as to dispose the appropriate counter set instance.
/// </summary>
public abstract void Dispose();
/*
/// <summary>
/// Resets the target counter 'counterId' to 0. If the given
/// counter has both numerator and denominator components, then
/// they both are set to 0.
/// </summary>
public bool ResetCounter(
int counterId)
{
this.SetCounterValue(counterId, 0, true);
this.SetCounterValue(counterId, 0, false);
}
/// <summary>
/// Resets the target counter 'counterName' to 0. If the given
/// counter has both numerator and denominator components, then
/// they both are set to 0.
/// </summary>
public void ResetCounter(string counterName)
{
this.SetCounterValue(counterName, 0, true);
this.SetCounterValue(counterName, 0, false);
}
*/
#endregion
}
/// <summary>
/// PSCounterSetInstance is a thin wrapper
/// on System.Diagnostics.PerformanceData.CounterSetInstance.
/// </summary>
public class PSCounterSetInstance : CounterSetInstanceBase
{
#region Private Members
private bool _Disposed;
private CounterSet _CounterSet;
private CounterSetInstance _CounterSetInstance;
private readonly PowerShellTraceSource _tracer = PowerShellTraceSourceFactory.GetTraceSource();
#region Private Methods
private void CreateCounterSetInstance()
{
_CounterSet =
new CounterSet(
base._counterSetRegistrarBase.ProviderId,
base._counterSetRegistrarBase.CounterSetId,
base._counterSetRegistrarBase.CounterSetInstType);
// Add the counters to the counter set definition.
foreach (CounterInfo counterInfo in base._counterSetRegistrarBase.CounterInfoArray)
{
if (counterInfo.Name == null)
{
_CounterSet.AddCounter(counterInfo.Id, counterInfo.Type);
}
else
{
_CounterSet.AddCounter(counterInfo.Id, counterInfo.Type, counterInfo.Name);
}
}
string instanceName = PSPerfCountersMgr.Instance.GetCounterSetInstanceName();
// Create an instance of the counter set (contains the counter data).
_CounterSetInstance = _CounterSet.CreateCounterSetInstance(instanceName);
}
private void UpdateCounterByValue(CounterData TargetCounterData, long stepAmount)
{
Debug.Assert(TargetCounterData != null);
if (stepAmount == -1)
{
TargetCounterData.Decrement();
}
else if (stepAmount == 1)
{
TargetCounterData.Increment();
}
else
{
TargetCounterData.IncrementBy(stepAmount);
}
}
#endregion
#endregion
#region Constructors
/// <summary>
/// Constructor for creating an instance of PSCounterSetInstance.
/// </summary>
public PSCounterSetInstance(CounterSetRegistrarBase counterSetRegBaseObj)
: base(counterSetRegBaseObj)
{
CreateCounterSetInstance();
}
#endregion
#region Destructor
/// <summary>
/// This destructor will run only if the Dispose method
/// does not get called.
/// It gives the base class opportunity to finalize.
/// </summary>
~PSCounterSetInstance()
{
Dispose(false);
}
#endregion
#region Protected Methods
/// <summary>
/// Dispose(bool disposing) executes in two distinct scenarios.
/// If disposing equals true, the method has been called directly
/// or indirectly by a user's code. Managed and unmanaged resources
/// can be disposed.
/// If disposing equals false, the method has been called by the
/// runtime from inside the finalizer and you should not reference
/// other objects. Only unmanaged resources can be disposed.
/// </summary>
protected virtual void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if (!_Disposed)
{
// If disposing equals true, dispose all managed
// and unmanaged resources.
if (disposing)
{
// Dispose managed resources.
_CounterSetInstance.Dispose();
_CounterSet.Dispose();
}
// Note disposing has been done.
_Disposed = true;
}
}
#endregion
#region IDisposable Overrides
/// <summary>
/// Dispose Method implementation for IDisposable interface.
/// </summary>
public override void Dispose()
{
this.Dispose(true);
// This object will be cleaned up by the Dispose method.
// Therefore, you should call GC.SuppressFinalize to
// take this object off the finalization queue
// and prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
#endregion
#region CounterSetInstanceBase Overrides
#region Public Methods
/// <summary>
/// If isNumerator is true, then updates the numerator component
/// of target counter 'counterId' by a value given by 'stepAmount'.
/// Otherwise, updates the denominator component by 'stepAmount'.
/// </summary>
public override bool UpdateCounterByValue(int counterId, long stepAmount, bool isNumerator)
{
if (_Disposed)
{
ObjectDisposedException objectDisposedException =
new ObjectDisposedException("PSCounterSetInstance");
_tracer.TraceException(objectDisposedException);
return false;
}
int targetCounterId;
if (base.RetrieveTargetCounterIdIfValid(counterId, isNumerator, out targetCounterId))
{
CounterData targetCounterData = _CounterSetInstance.Counters[targetCounterId];
if (targetCounterData != null)
{
this.UpdateCounterByValue(targetCounterData, stepAmount);
return true;
}
else
{
InvalidOperationException invalidOperationException =
new InvalidOperationException(
string.Format(
CultureInfo.InvariantCulture,
"Lookup for counter corresponding to counter id {0} failed",
counterId));
_tracer.TraceException(invalidOperationException);
return false;
}
}
else
{
return false;
}
}
/// <summary>
/// If isNumerator is true, then updates the numerator component
/// of target counter 'counterName' by a value given by 'stepAmount'.
/// Otherwise, updates the denominator component by 'stepAmount'.
/// </summary>
public override bool UpdateCounterByValue(string counterName, long stepAmount, bool isNumerator)
{
if (_Disposed)
{
ObjectDisposedException objectDisposedException =
new ObjectDisposedException("PSCounterSetInstance");
_tracer.TraceException(objectDisposedException);
return false;
}
// retrieve counter id associated with the counter name
if (counterName == null)
{
ArgumentNullException argNullException = new ArgumentNullException(nameof(counterName));
_tracer.TraceException(argNullException);
return false;
}
try
{
int targetCounterId = this._counterNameToIdMapping[counterName];
return this.UpdateCounterByValue(targetCounterId, stepAmount, isNumerator);
}
catch (KeyNotFoundException)
{
InvalidOperationException invalidOperationException =
new InvalidOperationException(
string.Format(
CultureInfo.InvariantCulture,
"Lookup for counter corresponding to counter name {0} failed",
counterName));
_tracer.TraceException(invalidOperationException);
return false;
}
}
/// <summary>
/// If isNumerator is true, then sets the numerator component
/// of target counter 'counterId' to 'counterValue'.
/// Otherwise, sets the denominator component to 'counterValue'.
/// </summary>
public override bool SetCounterValue(int counterId, long counterValue, bool isNumerator)
{
if (_Disposed)
{
ObjectDisposedException objectDisposedException =
new ObjectDisposedException("PSCounterSetInstance");
_tracer.TraceException(objectDisposedException);
return false;
}
int targetCounterId;
if (base.RetrieveTargetCounterIdIfValid(counterId, isNumerator, out targetCounterId))
{
CounterData targetCounterData = _CounterSetInstance.Counters[targetCounterId];
if (targetCounterData != null)
{
targetCounterData.Value = counterValue;
return true;
}
else
{
InvalidOperationException invalidOperationException =
new InvalidOperationException(
string.Format(
CultureInfo.InvariantCulture,
"Lookup for counter corresponding to counter id {0} failed",
counterId));
_tracer.TraceException(invalidOperationException);
return false;
}
}
else
{
return false;
}
}
/// <summary>
/// If isNumerator is true, then updates the numerator component
/// of target counter 'counterName' by a value given by 'counterValue'.
/// Otherwise, sets the denominator component to 'counterValue'.
/// </summary>
public override bool SetCounterValue(string counterName, long counterValue, bool isNumerator)
{
if (_Disposed)
{
ObjectDisposedException objectDisposedException =
new ObjectDisposedException("PSCounterSetInstance");
_tracer.TraceException(objectDisposedException);
return false;
}
// retrieve counter id associated with the counter name
if (counterName == null)
{
ArgumentNullException argNullException = new ArgumentNullException(nameof(counterName));
_tracer.TraceException(argNullException);
return false;
}
try
{
int targetCounterId = this._counterNameToIdMapping[counterName];
return this.SetCounterValue(targetCounterId, counterValue, isNumerator);
}
catch (KeyNotFoundException)
{
InvalidOperationException invalidOperationException =
new InvalidOperationException(
string.Format(
CultureInfo.InvariantCulture,
"Lookup for counter corresponding to counter name {0} failed",
counterName));
_tracer.TraceException(invalidOperationException);
return false;
}
}
/// <summary>
/// This method retrieves the counter value associated with counter 'counterId'
/// based on isNumerator parameter.
/// </summary>
public override bool GetCounterValue(int counterId, bool isNumerator, out long counterValue)
{
counterValue = -1;
if (_Disposed)
{
ObjectDisposedException objectDisposedException =
new ObjectDisposedException("PSCounterSetInstance");
_tracer.TraceException(objectDisposedException);
return false;
}
int targetCounterId;
if (base.RetrieveTargetCounterIdIfValid(counterId, isNumerator, out targetCounterId))
{
CounterData targetCounterData = _CounterSetInstance.Counters[targetCounterId];
if (targetCounterData != null)
{
counterValue = targetCounterData.Value;
return true;
}
else
{
InvalidOperationException invalidOperationException =
new InvalidOperationException(
string.Format(
CultureInfo.InvariantCulture,
"Lookup for counter corresponding to counter id {0} failed",
counterId));
_tracer.TraceException(invalidOperationException);
return false;
}
}
else
{
return false;
}
}
/// <summary>
/// This method retrieves the counter value associated with counter 'counterName'
/// based on isNumerator parameter.
/// </summary>
public override bool GetCounterValue(string counterName, bool isNumerator, out long counterValue)
{
counterValue = -1;
if (_Disposed)
{
ObjectDisposedException objectDisposedException =
new ObjectDisposedException("PSCounterSetInstance");
_tracer.TraceException(objectDisposedException);
return false;
}
// retrieve counter id associated with the counter name
if (counterName == null)
{
ArgumentNullException argNullException = new ArgumentNullException(nameof(counterName));
_tracer.TraceException(argNullException);
return false;
}
try
{
int targetCounterId = this._counterNameToIdMapping[counterName];
return this.GetCounterValue(targetCounterId, isNumerator, out counterValue);
}
catch (KeyNotFoundException)
{
InvalidOperationException invalidOperationException =
new InvalidOperationException(
string.Format(
CultureInfo.InvariantCulture,
"Lookup for counter corresponding to counter name {0} failed",
counterName));
_tracer.TraceException(invalidOperationException);
return false;
}
}
#endregion
#endregion
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// WebChannelResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
using Twilio.Types;
namespace Twilio.Rest.FlexApi.V1
{
public class WebChannelResource : Resource
{
public sealed class ChatStatusEnum : StringEnum
{
private ChatStatusEnum(string value) : base(value) {}
public ChatStatusEnum() {}
public static implicit operator ChatStatusEnum(string value)
{
return new ChatStatusEnum(value);
}
public static readonly ChatStatusEnum Inactive = new ChatStatusEnum("inactive");
}
private static Request BuildReadRequest(ReadWebChannelOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.FlexApi,
"/v1/WebChannels",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read WebChannel parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of WebChannel </returns>
public static ResourceSet<WebChannelResource> Read(ReadWebChannelOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<WebChannelResource>.FromJson("flex_chat_channels", response.Content);
return new ResourceSet<WebChannelResource>(page, options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read WebChannel parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of WebChannel </returns>
public static async System.Threading.Tasks.Task<ResourceSet<WebChannelResource>> ReadAsync(ReadWebChannelOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<WebChannelResource>.FromJson("flex_chat_channels", response.Content);
return new ResourceSet<WebChannelResource>(page, options, client);
}
#endif
/// <summary>
/// read
/// </summary>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of WebChannel </returns>
public static ResourceSet<WebChannelResource> Read(int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadWebChannelOptions(){PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of WebChannel </returns>
public static async System.Threading.Tasks.Task<ResourceSet<WebChannelResource>> ReadAsync(int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadWebChannelOptions(){PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<WebChannelResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<WebChannelResource>.FromJson("flex_chat_channels", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<WebChannelResource> NextPage(Page<WebChannelResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.FlexApi)
);
var response = client.Request(request);
return Page<WebChannelResource>.FromJson("flex_chat_channels", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<WebChannelResource> PreviousPage(Page<WebChannelResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.FlexApi)
);
var response = client.Request(request);
return Page<WebChannelResource>.FromJson("flex_chat_channels", response.Content);
}
private static Request BuildFetchRequest(FetchWebChannelOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.FlexApi,
"/v1/WebChannels/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch WebChannel parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of WebChannel </returns>
public static WebChannelResource Fetch(FetchWebChannelOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch WebChannel parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of WebChannel </returns>
public static async System.Threading.Tasks.Task<WebChannelResource> FetchAsync(FetchWebChannelOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// fetch
/// </summary>
/// <param name="pathSid"> The SID of the WebChannel resource to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of WebChannel </returns>
public static WebChannelResource Fetch(string pathSid, ITwilioRestClient client = null)
{
var options = new FetchWebChannelOptions(pathSid);
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="pathSid"> The SID of the WebChannel resource to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of WebChannel </returns>
public static async System.Threading.Tasks.Task<WebChannelResource> FetchAsync(string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchWebChannelOptions(pathSid);
return await FetchAsync(options, client);
}
#endif
private static Request BuildCreateRequest(CreateWebChannelOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.FlexApi,
"/v1/WebChannels",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create WebChannel parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of WebChannel </returns>
public static WebChannelResource Create(CreateWebChannelOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create WebChannel parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of WebChannel </returns>
public static async System.Threading.Tasks.Task<WebChannelResource> CreateAsync(CreateWebChannelOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// create
/// </summary>
/// <param name="flexFlowSid"> The SID of the Flex Flow </param>
/// <param name="identity"> The chat identity </param>
/// <param name="customerFriendlyName"> The chat participant's friendly name </param>
/// <param name="chatFriendlyName"> The chat channel's friendly name </param>
/// <param name="chatUniqueName"> The chat channel's unique name </param>
/// <param name="preEngagementData"> The pre-engagement data </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of WebChannel </returns>
public static WebChannelResource Create(string flexFlowSid,
string identity,
string customerFriendlyName,
string chatFriendlyName,
string chatUniqueName = null,
string preEngagementData = null,
ITwilioRestClient client = null)
{
var options = new CreateWebChannelOptions(flexFlowSid, identity, customerFriendlyName, chatFriendlyName){ChatUniqueName = chatUniqueName, PreEngagementData = preEngagementData};
return Create(options, client);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="flexFlowSid"> The SID of the Flex Flow </param>
/// <param name="identity"> The chat identity </param>
/// <param name="customerFriendlyName"> The chat participant's friendly name </param>
/// <param name="chatFriendlyName"> The chat channel's friendly name </param>
/// <param name="chatUniqueName"> The chat channel's unique name </param>
/// <param name="preEngagementData"> The pre-engagement data </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of WebChannel </returns>
public static async System.Threading.Tasks.Task<WebChannelResource> CreateAsync(string flexFlowSid,
string identity,
string customerFriendlyName,
string chatFriendlyName,
string chatUniqueName = null,
string preEngagementData = null,
ITwilioRestClient client = null)
{
var options = new CreateWebChannelOptions(flexFlowSid, identity, customerFriendlyName, chatFriendlyName){ChatUniqueName = chatUniqueName, PreEngagementData = preEngagementData};
return await CreateAsync(options, client);
}
#endif
private static Request BuildUpdateRequest(UpdateWebChannelOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.FlexApi,
"/v1/WebChannels/" + options.PathSid + "",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// update
/// </summary>
/// <param name="options"> Update WebChannel parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of WebChannel </returns>
public static WebChannelResource Update(UpdateWebChannelOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// update
/// </summary>
/// <param name="options"> Update WebChannel parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of WebChannel </returns>
public static async System.Threading.Tasks.Task<WebChannelResource> UpdateAsync(UpdateWebChannelOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// update
/// </summary>
/// <param name="pathSid"> The SID that identifies the resource to update </param>
/// <param name="chatStatus"> The chat status </param>
/// <param name="postEngagementData"> The post-engagement data </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of WebChannel </returns>
public static WebChannelResource Update(string pathSid,
WebChannelResource.ChatStatusEnum chatStatus = null,
string postEngagementData = null,
ITwilioRestClient client = null)
{
var options = new UpdateWebChannelOptions(pathSid){ChatStatus = chatStatus, PostEngagementData = postEngagementData};
return Update(options, client);
}
#if !NET35
/// <summary>
/// update
/// </summary>
/// <param name="pathSid"> The SID that identifies the resource to update </param>
/// <param name="chatStatus"> The chat status </param>
/// <param name="postEngagementData"> The post-engagement data </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of WebChannel </returns>
public static async System.Threading.Tasks.Task<WebChannelResource> UpdateAsync(string pathSid,
WebChannelResource.ChatStatusEnum chatStatus = null,
string postEngagementData = null,
ITwilioRestClient client = null)
{
var options = new UpdateWebChannelOptions(pathSid){ChatStatus = chatStatus, PostEngagementData = postEngagementData};
return await UpdateAsync(options, client);
}
#endif
private static Request BuildDeleteRequest(DeleteWebChannelOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Delete,
Rest.Domain.FlexApi,
"/v1/WebChannels/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// delete
/// </summary>
/// <param name="options"> Delete WebChannel parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of WebChannel </returns>
public static bool Delete(DeleteWebChannelOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#if !NET35
/// <summary>
/// delete
/// </summary>
/// <param name="options"> Delete WebChannel parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of WebChannel </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteWebChannelOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#endif
/// <summary>
/// delete
/// </summary>
/// <param name="pathSid"> The SID that identifies the resource to delete </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of WebChannel </returns>
public static bool Delete(string pathSid, ITwilioRestClient client = null)
{
var options = new DeleteWebChannelOptions(pathSid);
return Delete(options, client);
}
#if !NET35
/// <summary>
/// delete
/// </summary>
/// <param name="pathSid"> The SID that identifies the resource to delete </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of WebChannel </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathSid, ITwilioRestClient client = null)
{
var options = new DeleteWebChannelOptions(pathSid);
return await DeleteAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a WebChannelResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> WebChannelResource object represented by the provided JSON </returns>
public static WebChannelResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<WebChannelResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The SID of the Account that created the resource and owns this Workflow
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The SID of the Flex Flow
/// </summary>
[JsonProperty("flex_flow_sid")]
public string FlexFlowSid { get; private set; }
/// <summary>
/// The unique string that identifies the WebChannel resource
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// The absolute URL of the WebChannel resource
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
/// <summary>
/// The ISO 8601 date and time in GMT when the resource was created
/// </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
/// <summary>
/// The ISO 8601 date and time in GMT when the resource was last updated
/// </summary>
[JsonProperty("date_updated")]
public DateTime? DateUpdated { get; private set; }
private WebChannelResource()
{
}
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Avalonia.Collections;
using Avalonia.Controls.Generators;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Input;
using Avalonia.UnitTests;
using Xunit;
namespace Avalonia.Controls.UnitTests.Presenters
{
public class ItemsPresenterTests_Virtualization_Simple
{
[Fact]
public void Should_Return_Items_Count_For_Extent_Vertical()
{
var target = CreateTarget();
target.ApplyTemplate();
Assert.Equal(new Size(0, 20), ((ILogicalScrollable)target).Extent);
}
[Fact]
public void Should_Return_Items_Count_For_Extent_Horizontal()
{
var target = CreateTarget(orientation: Orientation.Horizontal);
target.ApplyTemplate();
Assert.Equal(new Size(20, 0), ((ILogicalScrollable)target).Extent);
}
[Fact]
public void Should_Have_Number_Of_Visible_Items_As_Viewport_Vertical()
{
var target = CreateTarget();
target.ApplyTemplate();
target.Measure(new Size(100, 100));
target.Arrange(new Rect(0, 0, 100, 100));
Assert.Equal(new Size(0, 10), ((ILogicalScrollable)target).Viewport);
}
[Fact]
public void Should_Have_Number_Of_Visible_Items_As_Viewport_Horizontal()
{
var target = CreateTarget(orientation: Orientation.Horizontal);
target.ApplyTemplate();
target.Measure(new Size(100, 100));
target.Arrange(new Rect(0, 0, 100, 100));
Assert.Equal(new Size(10, 0), ((ILogicalScrollable)target).Viewport);
}
[Fact]
public void Should_Add_Containers_When_Panel_Is_Not_Full()
{
var target = CreateTarget(itemCount: 5);
var items = (IList<string>)target.Items;
target.ApplyTemplate();
target.Measure(new Size(100, 100));
target.Arrange(new Rect(0, 0, 100, 100));
Assert.Equal(5, target.Panel.Children.Count);
items.Add("New Item");
Assert.Equal(6, target.Panel.Children.Count);
}
[Fact]
public void Should_Remove_Items_When_Control_Is_Shrank()
{
var target = CreateTarget();
var items = (IList<string>)target.Items;
target.ApplyTemplate();
target.Measure(new Size(100, 100));
target.Arrange(new Rect(0, 0, 100, 100));
Assert.Equal(10, target.Panel.Children.Count);
target.Measure(new Size(100, 80));
target.Arrange(new Rect(0, 0, 100, 80));
Assert.Equal(8, target.Panel.Children.Count);
}
[Fact]
public void Should_Add_New_Containers_At_Top_When_Control_Is_Scrolled_To_Bottom_And_Enlarged()
{
var target = CreateTarget();
var items = (IList<string>)target.Items;
target.ApplyTemplate();
target.Measure(new Size(100, 100));
target.Arrange(new Rect(0, 0, 100, 100));
Assert.Equal(10, target.Panel.Children.Count);
((IScrollable)target).Offset = new Vector(0, 10);
target.Measure(new Size(120, 120));
target.Arrange(new Rect(0, 0, 100, 120));
Assert.Equal(12, target.Panel.Children.Count);
for (var i = 0; i < target.Panel.Children.Count; ++i)
{
Assert.Equal(items[i + 8], target.Panel.Children[i].DataContext);
}
}
[Fact]
public void Should_Update_Containers_When_Items_Changes()
{
var target = CreateTarget();
target.ApplyTemplate();
target.Measure(new Size(100, 100));
target.Arrange(new Rect(0, 0, 100, 100));
target.Items = new[] { "foo", "bar", "baz" };
Assert.Equal(3, target.Panel.Children.Count);
}
[Fact]
public void Should_Decrease_The_Viewport_Size_By_One_If_There_Is_A_Partial_Item()
{
var target = CreateTarget();
target.ApplyTemplate();
target.Measure(new Size(100, 95));
target.Arrange(new Rect(0, 0, 100, 95));
Assert.Equal(new Size(0, 9), ((ILogicalScrollable)target).Viewport);
}
[Fact]
public void Moving_To_And_From_The_End_With_Partial_Item_Should_Set_Panel_PixelOffset()
{
var target = CreateTarget();
target.ApplyTemplate();
target.Measure(new Size(100, 95));
target.Arrange(new Rect(0, 0, 100, 95));
((ILogicalScrollable)target).Offset = new Vector(0, 11);
var minIndex = target.ItemContainerGenerator.Containers.Min(x => x.Index);
Assert.Equal(new Vector(0, 11), ((ILogicalScrollable)target).Offset);
Assert.Equal(10, minIndex);
Assert.Equal(10, ((IVirtualizingPanel)target.Panel).PixelOffset);
((ILogicalScrollable)target).Offset = new Vector(0, 10);
minIndex = target.ItemContainerGenerator.Containers.Min(x => x.Index);
Assert.Equal(new Vector(0, 10), ((ILogicalScrollable)target).Offset);
Assert.Equal(10, minIndex);
Assert.Equal(0, ((IVirtualizingPanel)target.Panel).PixelOffset);
((ILogicalScrollable)target).Offset = new Vector(0, 11);
minIndex = target.ItemContainerGenerator.Containers.Min(x => x.Index);
Assert.Equal(new Vector(0, 11), ((ILogicalScrollable)target).Offset);
Assert.Equal(10, minIndex);
Assert.Equal(10, ((IVirtualizingPanel)target.Panel).PixelOffset);
}
[Fact]
public void Inserting_Items_Should_Update_Containers()
{
var target = CreateTarget();
target.ApplyTemplate();
target.Measure(new Size(100, 100));
target.Arrange(new Rect(0, 0, 100, 100));
((ILogicalScrollable)target).Offset = new Vector(0, 5);
var expected = Enumerable.Range(5, 10).Select(x => $"Item {x}").ToList();
var items = (ObservableCollection<string>)target.Items;
var actual = target.Panel.Children.Select(x => x.DataContext).ToList();
Assert.Equal(expected, actual);
items.Insert(6, "Inserted");
expected.Insert(1, "Inserted");
expected.RemoveAt(expected.Count - 1);
actual = target.Panel.Children.Select(x => x.DataContext).ToList();
Assert.Equal(expected, actual);
}
[Fact]
public void Removing_First_Materialized_Item_Should_Update_Containers()
{
var target = CreateTarget();
target.ApplyTemplate();
target.Measure(new Size(100, 100));
target.Arrange(new Rect(0, 0, 100, 100));
var expected = Enumerable.Range(0, 10).Select(x => $"Item {x}").ToList();
var items = (ObservableCollection<string>)target.Items;
var actual = target.Panel.Children.Select(x => x.DataContext).ToList();
Assert.Equal(expected, actual);
items.RemoveAt(0);
expected = Enumerable.Range(1, 10).Select(x => $"Item {x}").ToList();
actual = target.Panel.Children.Select(x => x.DataContext).ToList();
Assert.Equal(expected, actual);
}
[Fact]
public void Removing_Items_From_Middle_Should_Update_Containers_When_All_Items_Visible()
{
var target = CreateTarget();
target.ApplyTemplate();
target.Measure(new Size(100, 200));
target.Arrange(new Rect(0, 0, 100, 200));
var items = (ObservableCollection<string>)target.Items;
var actual = target.Panel.Children.Select(x => x.DataContext).ToList();
Assert.Equal(items, actual);
items.RemoveAt(2);
actual = target.Panel.Children.Select(x => x.DataContext).ToList();
Assert.Equal(items, actual);
items.RemoveAt(items.Count - 2);
actual = target.Panel.Children.Select(x => x.DataContext).ToList();
Assert.Equal(items, actual);
}
[Fact]
public void Removing_Last_Item_Should_Update_Containers_When_All_Items_Visible()
{
var target = CreateTarget();
target.ApplyTemplate();
target.Measure(new Size(100, 200));
target.Arrange(new Rect(0, 0, 100, 200));
((ILogicalScrollable)target).Offset = new Vector(0, 5);
var expected = Enumerable.Range(0, 20).Select(x => $"Item {x}").ToList();
var items = (ObservableCollection<string>)target.Items;
var actual = target.Panel.Children.Select(x => x.DataContext).ToList();
Assert.Equal(expected, actual);
items.Remove(items.Last());
expected.Remove(expected.Last());
actual = target.Panel.Children.Select(x => x.DataContext).ToList();
Assert.Equal(expected, actual);
}
[Fact]
public void Removing_Items_When_Scrolled_To_End_Should_Recyle_Containers_At_Top()
{
var target = CreateTarget(useAvaloniaList: true);
target.ApplyTemplate();
target.Measure(new Size(100, 100));
target.Arrange(new Rect(0, 0, 100, 100));
((ILogicalScrollable)target).Offset = new Vector(0, 10);
var expected = Enumerable.Range(10, 10).Select(x => $"Item {x}").ToList();
var items = (AvaloniaList<string>)target.Items;
var actual = target.Panel.Children.Select(x => x.DataContext).ToList();
Assert.Equal(expected, actual);
items.RemoveRange(18, 2);
expected = Enumerable.Range(8, 10).Select(x => $"Item {x}").ToList();
actual = target.Panel.Children.Select(x => x.DataContext).ToList();
Assert.Equal(expected, actual);
}
[Fact]
public void Removing_Items_When_Scrolled_To_Near_End_Should_Recycle_Containers_At_Bottom_And_Top()
{
var target = CreateTarget(useAvaloniaList: true);
target.ApplyTemplate();
target.Measure(new Size(100, 100));
target.Arrange(new Rect(0, 0, 100, 100));
((ILogicalScrollable)target).Offset = new Vector(0, 9);
var expected = Enumerable.Range(9, 10).Select(x => $"Item {x}").ToList();
var items = (AvaloniaList<string>)target.Items;
var actual = target.Panel.Children.Select(x => x.DataContext).ToList();
Assert.Equal(expected, actual);
items.RemoveRange(15, 3);
expected = Enumerable.Range(7, 8).Select(x => $"Item {x}")
.Concat(Enumerable.Range(18, 2).Select(x => $"Item {x}"))
.ToList();
actual = target.Panel.Children.Select(x => x.DataContext).ToList();
Assert.Equal(expected, actual);
}
[Fact]
public void Replacing_Items_Should_Update_Containers()
{
var target = CreateTarget();
target.ApplyTemplate();
target.Measure(new Size(100, 100));
target.Arrange(new Rect(0, 0, 100, 100));
var expected = Enumerable.Range(0, 10).Select(x => $"Item {x}").ToList();
var items = (ObservableCollection<string>)target.Items;
var actual = target.Panel.Children.Select(x => x.DataContext).ToList();
Assert.Equal(expected, actual);
items[4] = expected[4] = "Replaced";
actual = target.Panel.Children.Select(x => x.DataContext).ToList();
Assert.Equal(expected, actual);
}
[Fact]
public void Moving_Items_Should_Update_Containers()
{
var target = CreateTarget();
target.ApplyTemplate();
target.Measure(new Size(100, 100));
target.Arrange(new Rect(0, 0, 100, 100));
var expected = Enumerable.Range(0, 10).Select(x => $"Item {x}").ToList();
var items = (ObservableCollection<string>)target.Items;
var actual = target.Panel.Children.Select(x => x.DataContext).ToList();
Assert.Equal(expected, actual);
items.Move(4, 8);
var i = expected[4];
expected.RemoveAt(4);
expected.Insert(8, i);
actual = target.Panel.Children.Select(x => x.DataContext).ToList();
Assert.Equal(expected, actual);
}
[Fact]
public void Setting_Items_To_Null_Should_Remove_Containers()
{
var target = CreateTarget();
target.ApplyTemplate();
target.Measure(new Size(100, 100));
target.Arrange(new Rect(0, 0, 100, 100));
var expected = Enumerable.Range(0, 10).Select(x => $"Item {x}").ToList();
var items = (ObservableCollection<string>)target.Items;
var actual = target.Panel.Children.Select(x => x.DataContext).ToList();
Assert.Equal(expected, actual);
target.Items = null;
Assert.Empty(target.Panel.Children);
}
[Fact]
public void Reassigning_Items_Should_Create_Containers()
{
var target = CreateTarget(itemCount: 5);
target.ApplyTemplate();
target.Measure(new Size(100, 100));
target.Arrange(new Rect(0, 0, 100, 100));
var expected = Enumerable.Range(0, 5).Select(x => $"Item {x}").ToList();
var items = (ObservableCollection<string>)target.Items;
var actual = target.Panel.Children.Select(x => x.DataContext).ToList();
Assert.Equal(expected, actual);
expected = Enumerable.Range(0, 6).Select(x => $"Item {x}").ToList();
target.Items = expected;
actual = target.Panel.Children.Select(x => x.DataContext).ToList();
Assert.Equal(expected, actual);
}
[Fact]
public void Reassigning_Items_Should_Remove_Containers()
{
var target = CreateTarget(itemCount: 6);
target.ApplyTemplate();
target.Measure(new Size(100, 100));
target.Arrange(new Rect(0, 0, 100, 100));
var expected = Enumerable.Range(0, 6).Select(x => $"Item {x}").ToList();
var items = (ObservableCollection<string>)target.Items;
var actual = target.Panel.Children.Select(x => x.DataContext).ToList();
Assert.Equal(expected, actual);
expected = Enumerable.Range(0, 5).Select(x => $"Item {x}").ToList();
target.Items = expected;
actual = target.Panel.Children.Select(x => x.DataContext).ToList();
Assert.Equal(expected, actual);
}
[Fact]
public void Clearing_Items_And_ReAdding_Should_Remove_Containers()
{
var target = CreateTarget(itemCount: 6);
target.ApplyTemplate();
target.Measure(new Size(100, 100));
target.Arrange(new Rect(0, 0, 100, 100));
var expected = Enumerable.Range(0, 6).Select(x => $"Item {x}").ToList();
var items = (ObservableCollection<string>)target.Items;
var actual = target.Panel.Children.Select(x => x.DataContext).ToList();
Assert.Equal(expected, actual);
expected = Enumerable.Range(0, 5).Select(x => $"Item {x}").ToList();
target.Items = null;
target.Items = expected;
actual = target.Panel.Children.Select(x => x.DataContext).ToList();
Assert.Equal(expected, actual);
}
[Fact]
public void Scrolling_To_Partial_Last_Item_Then_Adding_Item_Updates_Containers()
{
var target = CreateTarget(itemCount: 10);
var items = (IList<string>)target.Items;
target.ApplyTemplate();
target.Measure(new Size(100, 95));
target.Arrange(new Rect(0, 0, 100, 95));
((ILogicalScrollable)target).Offset = new Vector(0, 1);
Assert.Equal(new Vector(0, 1), ((ILogicalScrollable)target).Offset);
var expected = Enumerable.Range(0, 10).Select(x => $"Item {x}").ToList();
var actual = target.Panel.Children.Select(x => x.DataContext).ToList();
Assert.Equal(expected, actual);
Assert.Equal(10, ((IVirtualizingPanel)target.Panel).PixelOffset);
items.Add("Item 10");
expected = Enumerable.Range(1, 10).Select(x => $"Item {x}").ToList();
actual = target.Panel.Children.Select(x => x.DataContext).ToList();
Assert.Equal(expected, actual);
Assert.Equal(0, ((IVirtualizingPanel)target.Panel).PixelOffset);
}
public class Vertical
{
[Fact]
public void GetControlInDirection_Down_Should_Return_Existing_Container_If_Materialized()
{
var target = CreateTarget();
target.ApplyTemplate();
target.Measure(new Size(100, 100));
target.Arrange(new Rect(0, 0, 100, 100));
var from = target.Panel.Children[5];
var result = ((ILogicalScrollable)target).GetControlInDirection(
NavigationDirection.Down,
from);
Assert.Same(target.Panel.Children[6], result);
}
[Fact]
public void GetControlInDirection_Down_Should_Scroll_If_Necessary()
{
var target = CreateTarget();
target.ApplyTemplate();
target.Measure(new Size(100, 100));
target.Arrange(new Rect(0, 0, 100, 100));
var from = target.Panel.Children[9];
var result = ((ILogicalScrollable)target).GetControlInDirection(
NavigationDirection.Down,
from);
Assert.Equal(new Vector(0, 1), ((ILogicalScrollable)target).Offset);
Assert.Same(target.Panel.Children[9], result);
}
[Fact]
public void GetControlInDirection_Down_Should_Scroll_If_Partially_Visible()
{
using (UnitTestApplication.Start(TestServices.RealLayoutManager))
{
var target = CreateTarget();
var scroller = (ScrollContentPresenter)target.Parent;
scroller.Measure(new Size(100, 95));
scroller.Arrange(new Rect(0, 0, 100, 95));
var from = target.Panel.Children[8];
var result = ((ILogicalScrollable)target).GetControlInDirection(
NavigationDirection.Down,
from);
Assert.Equal(new Vector(0, 1), ((ILogicalScrollable)target).Offset);
Assert.Same(target.Panel.Children[8], result);
}
}
[Fact]
public void GetControlInDirection_Up_Should_Scroll_If_Partially_Visible_Item_Is_Currently_Shown()
{
using (UnitTestApplication.Start(TestServices.RealLayoutManager))
{
var target = CreateTarget();
var scroller = (ScrollContentPresenter)target.Parent;
scroller.Measure(new Size(100, 95));
scroller.Arrange(new Rect(0, 0, 100, 95));
((ILogicalScrollable)target).Offset = new Vector(0, 11);
var from = target.Panel.Children[1];
var result = ((ILogicalScrollable)target).GetControlInDirection(
NavigationDirection.Up,
from);
Assert.Equal(new Vector(0, 10), ((ILogicalScrollable)target).Offset);
Assert.Same(target.Panel.Children[0], result);
}
}
}
public class Horizontal
{
[Fact]
public void GetControlInDirection_Right_Should_Return_Existing_Container_If_Materialized()
{
var target = CreateTarget(orientation: Orientation.Horizontal);
target.ApplyTemplate();
target.Measure(new Size(100, 100));
target.Arrange(new Rect(0, 0, 100, 100));
var from = target.Panel.Children[5];
var result = ((ILogicalScrollable)target).GetControlInDirection(
NavigationDirection.Right,
from);
Assert.Same(target.Panel.Children[6], result);
}
[Fact]
public void GetControlInDirection_Right_Should_Scroll_If_Necessary()
{
var target = CreateTarget(orientation: Orientation.Horizontal);
target.ApplyTemplate();
target.Measure(new Size(100, 100));
target.Arrange(new Rect(0, 0, 100, 100));
var from = target.Panel.Children[9];
var result = ((ILogicalScrollable)target).GetControlInDirection(
NavigationDirection.Right,
from);
Assert.Equal(new Vector(1, 0), ((ILogicalScrollable)target).Offset);
Assert.Same(target.Panel.Children[9], result);
}
[Fact]
public void GetControlInDirection_Right_Should_Scroll_If_Partially_Visible()
{
using (UnitTestApplication.Start(TestServices.RealLayoutManager))
{
var target = CreateTarget(orientation: Orientation.Horizontal);
var scroller = (ScrollContentPresenter)target.Parent;
scroller.Measure(new Size(95, 100));
scroller.Arrange(new Rect(0, 0, 95, 100));
var from = target.Panel.Children[8];
var result = ((ILogicalScrollable)target).GetControlInDirection(
NavigationDirection.Right,
from);
Assert.Equal(new Vector(1, 0), ((ILogicalScrollable)target).Offset);
Assert.Same(target.Panel.Children[8], result);
}
}
[Fact]
public void GetControlInDirection_Left_Should_Scroll_If_Partially_Visible_Item_Is_Currently_Shown()
{
var target = CreateTarget(orientation: Orientation.Horizontal);
target.ApplyTemplate();
target.Measure(new Size(95, 100));
target.Arrange(new Rect(0, 0, 95, 100));
((ILogicalScrollable)target).Offset = new Vector(11, 0);
var from = target.Panel.Children[1];
var result = ((ILogicalScrollable)target).GetControlInDirection(
NavigationDirection.Left,
from);
Assert.Equal(new Vector(10, 0), ((ILogicalScrollable)target).Offset);
Assert.Same(target.Panel.Children[0], result);
}
}
public class WithContainers
{
[Fact]
public void Scrolling_Less_Than_A_Page_Should_Move_Recycled_Items()
{
var target = CreateTarget();
var items = (IList<string>)target.Items;
target.ApplyTemplate();
target.Measure(new Size(100, 100));
target.Arrange(new Rect(0, 0, 100, 100));
var containers = target.Panel.Children.ToList();
var scroller = (ScrollContentPresenter)target.Parent;
scroller.Offset = new Vector(0, 5);
var scrolledContainers = containers
.Skip(5)
.Take(5)
.Concat(containers.Take(5)).ToList();
Assert.Equal(new Vector(0, 5), ((ILogicalScrollable)target).Offset);
Assert.Equal(scrolledContainers, target.Panel.Children);
for (var i = 0; i < target.Panel.Children.Count; ++i)
{
Assert.Equal(items[i + 5], target.Panel.Children[i].DataContext);
}
scroller.Offset = new Vector(0, 0);
Assert.Equal(new Vector(0, 0), ((ILogicalScrollable)target).Offset);
Assert.Equal(containers, target.Panel.Children);
var dcs = target.Panel.Children.Select(x => x.DataContext).ToList();
for (var i = 0; i < target.Panel.Children.Count; ++i)
{
Assert.Equal(items[i], target.Panel.Children[i].DataContext);
}
}
[Fact]
public void Scrolling_More_Than_A_Page_Should_Recycle_Items()
{
var target = CreateTarget(itemCount: 50);
var items = (IList<string>)target.Items;
target.ApplyTemplate();
target.Measure(new Size(100, 100));
target.Arrange(new Rect(0, 0, 100, 100));
var containers = target.Panel.Children.ToList();
var scroller = (ScrollContentPresenter)target.Parent;
scroller.Offset = new Vector(0, 20);
Assert.Equal(new Vector(0, 20), ((ILogicalScrollable)target).Offset);
Assert.Equal(containers, target.Panel.Children);
for (var i = 0; i < target.Panel.Children.Count; ++i)
{
Assert.Equal(items[i + 20], target.Panel.Children[i].DataContext);
}
scroller.Offset = new Vector(0, 0);
Assert.Equal(new Vector(0, 0), ((ILogicalScrollable)target).Offset);
Assert.Equal(containers, target.Panel.Children);
for (var i = 0; i < target.Panel.Children.Count; ++i)
{
Assert.Equal(items[i], target.Panel.Children[i].DataContext);
}
}
}
private static ItemsPresenter CreateTarget(
Orientation orientation = Orientation.Vertical,
bool useContainers = true,
int itemCount = 20,
bool useAvaloniaList = false)
{
ItemsPresenter result;
var itemsSource = Enumerable.Range(0, itemCount).Select(x => $"Item {x}");
var items = useAvaloniaList ?
(IEnumerable)new AvaloniaList<string>(itemsSource) :
(IEnumerable)new ObservableCollection<string>(itemsSource);
var scroller = new ScrollContentPresenter
{
Content = result = new TestItemsPresenter(useContainers)
{
Items = items,
ItemsPanel = VirtualizingPanelTemplate(orientation),
ItemTemplate = ItemTemplate(),
VirtualizationMode = ItemVirtualizationMode.Simple,
}
};
scroller.UpdateChild();
return result;
}
private static IDataTemplate ItemTemplate()
{
return new FuncDataTemplate<string>(x => new Canvas
{
Width = 10,
Height = 10,
});
}
private static ITemplate<IPanel> VirtualizingPanelTemplate(
Orientation orientation = Orientation.Vertical)
{
return new FuncTemplate<IPanel>(() => new VirtualizingStackPanel
{
Orientation = orientation,
});
}
private class TestItemsPresenter : ItemsPresenter
{
private bool _useContainers;
public TestItemsPresenter(bool useContainers)
{
_useContainers = useContainers;
}
protected override IItemContainerGenerator CreateItemContainerGenerator()
{
return _useContainers ?
new ItemContainerGenerator<TestContainer>(this, TestContainer.ContentProperty, null) :
new ItemContainerGenerator(this);
}
}
private class TestContainer : ContentControl
{
public TestContainer()
{
Width = 10;
Height = 10;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace MusicLife.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.