context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using Server.BuildConfig;
using Server.Commands;
using Server.Services;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using System.Text.RegularExpressions;
namespace Server.Runtime {
public class BuildServer {
public event Action<RequestContext> OnStatusRequest;
public event Action<RequestContext, string> OnCommonMessage;
public event Action<RequestContext, string> OnHelpRequest;
public event Action<RequestContext, BuildProcess> OnInitBuild;
public event Action<string, bool> OnCommonError;
public event Action OnStop;
public event Action<string> LogFileChanged;
public string Name { get; }
public Project Project { get; private set; }
public List<IService> Services { get; private set; }
public CommandSetup Commands { get; private set; }
public string ServiceName {
get {
var assembly = GetType().GetTypeInfo().Assembly;
var name = assembly.GetName();
return $"{name.Name} {name.Version}";
}
}
string[] _buildArgs;
Build _build;
Thread _thread;
BuildProcess _process;
List<ICommand> _curCommands = new List<ICommand>();
ConcurrentDictionary<string, string> _taskStates = new ConcurrentDictionary<string, string>();
DateTime _curTime => DateTime.Now;
CommandFactory _commandFactory;
LoggerFactory _loggerFactory;
ILogger _logger;
public BuildServer(CommandFactory commandFactory, LoggerFactory loggerFactory, string name) {
_commandFactory = commandFactory;
_loggerFactory = loggerFactory;
_logger = _loggerFactory.CreateLogger<BuildServer>();
_logger.LogDebug($"ctor: name: \"{name}\"");
Name = name;
Commands = new CommandSetup();
}
static string ConvertToBuildName(FileSystemInfo file) {
var ext = file.Extension;
return file.Name.Substring(0, file.Name.Length - ext.Length);
}
public Dictionary<string, Build> FindBuilds() {
var tempDict = new Dictionary<string, Build>();
var buildsPath = Project.BuildsRoot;
if (!Directory.Exists(buildsPath)) {
return null;
}
var files = Directory.EnumerateFiles(buildsPath, "*.json");
foreach (var filePath in files) {
var file = new FileInfo(filePath);
var name = ConvertToBuildName(file);
var fullPath = file.FullName;
try {
var build = Build.Load(_loggerFactory, name, fullPath);
tempDict.Add(name, build);
} catch (Exception e) {
RaiseCommonError($"Failed to load build at \"{fullPath}\": \"{e}\"", true);
}
}
var resultDict = new Dictionary<string, Build>();
foreach (var buildPair in tempDict) {
try {
var build = buildPair.Value;
ProcessSubBuilds(build, tempDict);
ValidateBuild(build);
resultDict.Add(buildPair.Key, build);
} catch(Exception e) {
RaiseCommonError($"Failed to process build \"{buildPair.Key}\" : \"{e}\"", true);
}
}
return resultDict;
}
void ValidateBuild(Build build) {
foreach (var node in build.Nodes) {
ValidateNode(node);
}
}
void ValidateNode(BuildNode node) {
if (string.IsNullOrEmpty(node.Command) || !_commandFactory.ContainsHandler(node.Command)) {
throw new CommandNotFoundException(node.Command);
}
}
void ProcessSubBuilds(Build build, Dictionary<string, Build> builds) {
var nodes = build.Nodes;
for (int i = 0; i < nodes.Count; i++) {
var node = build.Nodes[i];
var subBuildNode = node as SubBuildNode;
if (subBuildNode == null) {
continue;
}
var subBuildName = subBuildNode.Name;
_logger.LogDebug($"ProcessSubBuilds: Process sub build node: \"{subBuildName}\"");
Build subBuild;
if (!builds.TryGetValue(subBuildName, out subBuild)) {
throw new SubBuildNotFoundException(subBuildName);
}
ProcessSubBuilds(subBuild, builds);
nodes.RemoveAt(i);
var subNodes = subBuild.Nodes;
var newNodes = new List<BuildNode>();
foreach (var subNode in subNodes) {
var newArgs = new Dictionary<string, string>();
foreach (var subBuildArg in subBuildNode.Args) {
var sbKey = subBuildArg.Key;
var sbValue = subBuildArg.Value;
foreach (var subNodeArg in subNode.Args) {
var subNodeValue = subNodeArg.Value;
string newValue = null;
if (!newArgs.ContainsKey(subNodeArg.Key)) {
newValue = TryReplace(subNodeValue, sbKey, sbValue);
newArgs.Add(subNodeArg.Key, newValue);
} else {
newValue = TryReplace(newArgs[subNodeArg.Key], sbKey, sbValue);
newArgs[subNodeArg.Key] = newValue;
}
_logger.LogDebug(
$"ProcessSubBuilds: Convert value: \"{subNodeValue}\" => \"\"{newValue}\"\"");
}
}
if ( newArgs.Count == 0 ) {
newArgs = subNode.Args;
}
newNodes.Add(new BuildNode(subNode.Name, subNode.Command, newArgs));
_logger.LogDebug(
$"ProcessSubBuilds: Converted node: \"{subNode.Name}\", args: {newArgs.Count}");
}
nodes.InsertRange(i, newNodes);
}
}
public bool TryInitialize(out string errorMessage, List<IService> services, List<string> projectPathes) {
_logger.LogDebug(
$"TryInitialize: services: {services.Count()}, pathes: {projectPathes.Count}");
try {
Project = Project.Load(_loggerFactory, Name, projectPathes);
} catch (Exception e) {
errorMessage = $"Failed to parse project settings: \"{e}\"";
return false;
}
InitServices(services, Project);
if (FindBuilds() == null) {
errorMessage = $"Failed to load builds directory!";
return false;
}
errorMessage = string.Empty;
return true;
}
void InitServices(IEnumerable<IService> services, Project project) {
Services = new List<IService>();
foreach (var service in services) {
_logger.LogDebug($"InitServices: \"{service.GetType().Name}\"");
var isInited = service.TryInit(this, project);
_logger.LogDebug($"InitServices: isInited: {isInited}");
if (isInited) {
Services.Add(service);
}
}
}
bool IsValidBuildArg(string arg, string checkRegex) {
if ( !string.IsNullOrWhiteSpace(checkRegex) ) {
var regex = new Regex(checkRegex);
return regex.IsMatch(arg);
}
return true;
}
public bool TryInitBuild(RequestContext context, Build build, string[] buildArgs) {
if (_process != null) {
RaiseCommonError("InitBuild: server is busy!", true);
return false;
}
for ( var i = 0; i < buildArgs.Length; i++ ) {
var curArg = buildArgs[i];
var argName = build.Args.ElementAtOrDefault(i);
var argCheck = build.Checks.ElementAtOrDefault(i);
if ( !IsValidBuildArg(curArg, argCheck) ) {
RaiseCommonError($"InitBuild: argument '{argName}' is invalid: '{curArg}' don't maches by '{argCheck}'!", true);
return false;
}
}
_logger.LogDebug($"InitBuild: \"{build.Name}\"");
_build = build;
_process = new BuildProcess(_loggerFactory, build);
var convertedLogFile = ConvertArgValue(Project, _build, null, build.LogFile);
LogFileChanged?.Invoke(convertedLogFile);
OnInitBuild?.Invoke(context, _process);
return true;
}
public void StartBuild(string[] args) {
if (_process == null) {
_logger.LogError("StartBuild: No build to start!");
return;
}
if (_process.IsStarted) {
_logger.LogError("StartBuild: Build already started!");
return;
}
_logger.LogDebug($"StartBuild: args: {args.Length}");
_buildArgs = args;
_thread = new Thread(ProcessBuild);
_thread.Start();
}
void ProcessBuild() {
_logger.LogDebug("ProcessBuild");
var nodes = _build.Nodes;
_process.StartBuild(_curTime);
if (nodes.Count == 0) {
_logger.LogError("ProcessBuild: No build nodes!");
_process.Abort(_curTime);
}
var tasks = InitTasks(nodes);
foreach (var task in tasks) {
_logger.LogDebug($"ProcessBuild: task: {tasks.IndexOf(task)}/{tasks.Count}");
task.Start();
task.Wait();
var result = task.Result;
if (!result) {
_logger.LogDebug($"ProcessBuild: failed command!");
_process.Abort(_curTime);
}
if (_process.IsAborted) {
_logger.LogDebug($"ProcessBuild: aborted!");
break;
}
}
LogFileChanged?.Invoke(null);
_buildArgs = null;
_build = null;
_thread = null;
_process = null;
_taskStates = new ConcurrentDictionary<string, string>();
_logger.LogDebug("ProcessBuild: cleared");
}
List<Task<bool>> InitTasks(List<BuildNode> nodes) {
var tasks = new List<Task<bool>>();
Dictionary<BuildNode, Task<bool>> parallelAccum = null;
foreach ( var node in nodes ) {
_logger.LogDebug($"InitTasks: node: \"{node.Name}\" (\"{node.Command}\")");
var task = new Task<bool>(() => ProcessCommand(_build, _buildArgs, node));
if ( node.IsParallel ) {
if ( parallelAccum == null ) {
parallelAccum = new Dictionary<BuildNode, Task<bool>>();
}
parallelAccum.Add(node, task);
} else {
ProcessParallelTask(ref parallelAccum, nodes, tasks);
tasks.Add(task);
}
}
ProcessParallelTask(ref parallelAccum, nodes, tasks);
return tasks;
}
void ProcessParallelTask(ref Dictionary<BuildNode, Task<bool>> accum, List<BuildNode> nodes, List<Task<bool>> tasks) {
if ( accum != null ) {
tasks.Add(CreateParallelTask(accum, nodes));
accum = null;
}
}
Task<bool> CreateParallelTask(Dictionary<BuildNode, Task<bool>> accum, List<BuildNode> nodes) {
return new Task<bool>(() => ParallelProcess(accum, nodes));
}
Dictionary<int, List<Task<bool>>> CreateQueuedTaskDict(Dictionary<BuildNode, Task<bool>> rawAccum) {
var queuedTasks = new Dictionary<int, List<Task<bool>>>();
foreach ( var nodeTask in rawAccum ) {
var queue = nodeTask.Key.ParallelQueue;
if ( !queuedTasks.ContainsKey(queue) ) {
queuedTasks.Add(queue, new List<Task<bool>>());
}
queuedTasks[queue].Add(nodeTask.Value);
}
return queuedTasks;
}
bool SequenceProcess(List<Task<bool>> tasks) {
foreach ( var task in tasks ) {
_logger.LogDebug($"SequenceProcess: start task: {tasks.IndexOf(task) + 1}/{tasks.Count}");
task.Start();
task.Wait();
_logger.LogDebug($"SequenceProcess: done task: {tasks.IndexOf(task) + 1}/{tasks.Count}: {task.Result}");
if ( !task.Result ) {
return false;
}
}
return true;
}
bool ParallelProcess(Dictionary<BuildNode, Task<bool>> rawAccum, List<BuildNode> nodes) {
var queuedTasks = CreateQueuedTaskDict(rawAccum);
var accumTasks = new List<Task<bool>>();
foreach ( var parallelPack in queuedTasks ) {
if ( parallelPack.Key > 0 ) {
_logger.LogDebug($"ParallelProcess: queue: {parallelPack.Key}, tasks: {parallelPack.Value.Count}");
accumTasks.Add(new Task<bool>(() => SequenceProcess(parallelPack.Value)));
} else {
_logger.LogDebug($"ParallelProcess: non-queued tasks: {parallelPack.Value.Count}");
accumTasks.AddRange(parallelPack.Value);
}
}
foreach ( var task in accumTasks ) {
task.Start();
}
Task.WaitAll(accumTasks.ToArray());
bool result = true;
foreach ( var task in accumTasks ) {
result = result && task.Result;
}
return result;
}
string TryReplace(string message, string key, string value) {
var keyFormat = string.Format("{{{0}}}", key);
if (message.Contains(keyFormat)) {
return message.Replace(keyFormat, value);
}
return message;
}
string ConvertArgValue(Project project, Build build, string[] buildArgs, string value) {
if ( value == null ) {
return null;
}
var result = value;
foreach (var key in project.Keys) {
result = TryReplace(result, key.Key, key.Value);
}
if (buildArgs != null) {
for (var i = 0; i < build.Args.Count; i++) {
var argName = build.Args[i];
var argValue = buildArgs[i];
result = TryReplace(result, argName, argValue);
}
}
foreach (var state in _taskStates) {
result = TryReplace(result, state.Key, state.Value);
}
_logger.LogDebug($"ConvertArgValue: \"{value}\" => \"{result}\"");
return result;
}
public Dictionary<string, string> FindCurrentBuildArgs() {
if ((_buildArgs == null) || (_build == null)) {
return null;
}
var dict = new Dictionary<string, string>();
for (int i = 0; i < _build.Args.Count; i++) {
var argName = _build.Args[i];
var argValue = _buildArgs[i];
dict.Add(argName, argValue);
}
return dict;
}
Dictionary<string, string> CreateRuntimeArgs(Project project, Build build, string[] buildArgs, BuildNode node) {
var dict = new Dictionary<string, string>();
foreach (var arg in node.Args) {
var value = ConvertArgValue(project, build, buildArgs, arg.Value);
dict.Add(arg.Key, value);
}
return dict;
}
bool ProcessCommand(Build build, string[] buildArgs, BuildNode node) {
_logger.LogDebug($"ProcessCommand: \"{node.Name}\" (\"{node.Command}\")");
_process.StartTask(node);
var command = _commandFactory.Create(node);
lock ( _curCommands ) {
_curCommands.Add(command);
}
_logger.LogDebug($"ProcessCommand: command is \"{command.GetType().Name}\"");
var runtimeArgs = CreateRuntimeArgs(Project, build, buildArgs, node);
_logger.LogDebug($"ProcessCommand: runtimeArgs is {runtimeArgs.Count}");
var result = command.Execute(_loggerFactory, runtimeArgs);
lock ( _curCommands ) {
_curCommands.Remove(command);
}
_logger.LogDebug(
$"ProcessCommand: result is [{result.IsSuccess}, \"{result.Message}\", \"{result.Result}\"]");
_process.DoneTask(node, _curTime, result);
AddTaskState(node.Name, result);
return result.IsSuccess;
}
void AddTaskState(string taskName, CommandResult result) {
AddTaskState(taskName, "message", result.Message);
AddTaskState(taskName, "result", result.Result);
}
void AddTaskState(string taskName, string key, string value) {
var fullKey = $"{taskName}:{key}";
if ( _taskStates.ContainsKey(fullKey) ) {
var curValue = string.Empty;
var getSuccess = _taskStates.TryGetValue(fullKey, out curValue);
var updateSuccess = _taskStates.TryUpdate(fullKey, value, curValue);
_logger.LogDebug($"AddTaskState: Override \"{fullKey}\"=>\"{value}\" (get success: {getSuccess}, update success: {updateSuccess})");
} else {
var addSuccess = _taskStates.TryAdd(fullKey, value);
_logger.LogDebug($"AddTaskState: Add \"{fullKey}\"=>\"{value}\" (add success: {addSuccess})");
}
}
public void RequestStatus(RequestContext context) {
_logger.LogDebug("RequestStatus");
OnStatusRequest?.Invoke(context);
}
public void AbortBuild() {
_logger.LogDebug($"AbortBuild: hasProcess: {_process != null}");
var proc = _process;
if(proc != null ) {
_logger.LogDebug("AbortBuild: Abort running process");
proc.Abort(_curTime);
}
foreach ( var command in _curCommands ) {
if ( command is IAbortableCommand abortableCommand ) {
_logger.LogDebug("AbortBuild: Abort running command");
abortableCommand.Abort();
}
}
}
public void StopServer() {
_logger.LogDebug($"StopServer: hasProcess: {_process != null}");
AbortBuild();
while (_process != null) {}
OnStop?.Invoke();
_logger.LogDebug("StopServer: done");
}
public void RequestHelp(RequestContext context, string arg) {
_logger.LogDebug("RequestHelp");
OnHelpRequest?.Invoke(context, arg);
}
public void RaiseCommonError(string message, bool isFatal) {
_logger.LogError($"RaiseCommonError: \"{message}\", isFatal: {isFatal}");
OnCommonError?.Invoke(message, isFatal);
}
public void RaiseCommonMessage(RequestContext context, string message) {
_logger.LogDebug($"RaiseCommonMessage: \"{message}\"");
OnCommonMessage?.Invoke(context, message);
}
public void AddCommand(string name, string description, Action<RequestContext, RequestArgs> handler) {
_logger.LogDebug($"AddHandler: \"{name}\" => \"{handler.GetMethodInfo().Name}\"");
Commands.Add(name, new BuildCommand(description, handler));
}
public void AddCommand(string name, string description, Action<RequestContext> handler) {
_logger.LogDebug($"AddHandler: \"{name}\" => \"{handler.GetMethodInfo().Name}\"");
Commands.Add(name, new BuildCommand(description, (context, _) => handler.Invoke(context)));
}
public T FindService<T>() where T : class, IService {
return Services.Find(s => s is T) as T;
}
public void AddBuildHandler(Action<string, RequestContext, RequestArgs> handler) {
_logger.LogDebug($"AddBuildHandler: \"{handler.GetMethodInfo().Name}\"");
Commands.AddBuildHandler(handler);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.MarkdigMarkdownRewriters
{
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.DocAsCode.Dfm;
using Microsoft.DocAsCode.MarkdownLite;
public class MarkdigMarkdownRenderer : DfmMarkdownRenderer
{
private static readonly HttpClient _client = new HttpClient(new HttpClientHandler { CheckCertificateRevocationList = true });
private static readonly string _requestTemplate = "https://xref.docs.microsoft.com/query?uid={0}";
private static DfmRenderer _dfmHtmlRender = new DfmRenderer();
private static readonly Regex _headingRegex = new Regex(@"^(?<pre> *#{1,6}(?<whitespace> *))(?<text>[^\n]+?)(?<post>(?: +#*)? *(?:\n+|$))", RegexOptions.Compiled);
private static readonly Regex _lheading = new Regex(@"^(?<text>[^\n]+)(?<post>\n *(?:=|-){2,} *(?:\n+|$))", RegexOptions.Compiled);
public virtual StringBuffer Render(IMarkdownRenderer render, DfmXrefInlineToken token, MarkdownInlineContext context)
{
if (token.Rule is DfmXrefShortcutInlineRule)
{
if (TryResolveUid(token.Href))
{
return $"@\"{token.Href}\"";
}
}
return base.Render(render, token, context);
}
public override StringBuffer Render(IMarkdownRenderer render, MarkdownLinkInlineToken token, MarkdownInlineContext context)
{
switch (token.LinkType)
{
case MarkdownLinkType.AutoLink:
return RenderAutoLink(render, token, context);
case MarkdownLinkType.NormalLink:
return RenderLinkNormalLink(render, token, context);
default:
return base.Render(render, token, context);
}
}
private StringBuffer RenderAutoLink(IMarkdownRenderer render, MarkdownLinkInlineToken token, MarkdownInlineContext context)
{
var content = RenderInlineTokens(token.Content, render);
return $"<{content}>";
}
private StringBuffer RenderLinkNormalLink(IMarkdownRenderer render, MarkdownLinkInlineToken token, MarkdownInlineContext context)
{
var content = StringBuffer.Empty;
content += "[";
content += RenderInlineTokens(token.Content, render);
content += "](";
content += StringHelper.EscapeMarkdownHref(token.Href);
if (!string.IsNullOrEmpty(token.Title))
{
content += " \"";
content += token.Title;
content += "\"";
}
content += ")";
return content;
}
public override StringBuffer Render(IMarkdownRenderer render, MarkdownBlockquoteBlockToken token, MarkdownBlockContext context)
{
const string BlockQuoteStartString = "> ";
const string BlockQuoteJoinString = "\n" + BlockQuoteStartString;
var content = StringBuffer.Empty;
var tokens = (from t in token.Tokens
where !(t is MarkdownNewLineBlockToken)
select t).ToList();
for (var index = 0; index < tokens.Count; index++)
{
var t = tokens[index];
if (index == tokens.Count - 1 && t is DfmVideoBlockToken videoToken)
{
content += render.Render(t).ToString().TrimEnd();
}
else
{
content += render.Render(t);
}
}
var contents = content.ToString().Split('\n');
content = StringBuffer.Empty;
foreach (var item in contents)
{
if (content == StringBuffer.Empty)
{
content += BlockQuoteStartString;
content += item;
}
else
{
content += BlockQuoteJoinString;
content += item;
}
}
return content + "\n\n";
}
public override StringBuffer Render(IMarkdownRenderer render, MarkdownHtmlBlockToken token, MarkdownBlockContext context)
{
var result = StringBuffer.Empty;
var inside = false;
foreach (var inline in token.Content.Tokens)
{
if (inline is MarkdownTagInlineToken)
{
inside = !inside;
result += MarkupInlineToken(render, inline);
}
else
{
result += inside ? MarkupInlineToken(render, inline)
: Render(render, inline, inline.Context);
}
}
return result;
}
public override StringBuffer Render(IMarkdownRenderer render, MarkdownStrongInlineToken token, MarkdownInlineContext context)
{
var source = token.SourceInfo.Markdown;
var symbol = source.StartsWith("_", StringComparison.Ordinal) ? "__" : "**";
var content = StringBuffer.Empty;
content += symbol;
content += RenderInlineTokens(token.Content, render);
content += symbol;
return content;
}
public override StringBuffer Render(IMarkdownRenderer render, MarkdownEmInlineToken token, MarkdownInlineContext context)
{
var source = token.SourceInfo.Markdown;
var symbol = source.StartsWith("_") ? "_" : "*";
var content = StringBuffer.Empty;
content += symbol;
content += RenderInlineTokens(token.Content, render);
content += symbol;
return content;
}
public override StringBuffer Render(IMarkdownRenderer render, MarkdownHeadingBlockToken token, MarkdownBlockContext context)
{
if (token.Rule is MarkdownLHeadingBlockRule)
{
return RenderLHeadingToken(render, token, context);
}
else
{
return RenderHeadingToken(render, token, context);
}
}
private StringBuffer RenderHeadingToken(IMarkdownRenderer render, MarkdownHeadingBlockToken token, MarkdownBlockContext context)
{
var source = token.SourceInfo.Markdown;
var match = _headingRegex.Match(source);
if (match.Success)
{
var result = StringBuffer.Empty;
var whitespace = match.Groups["whitespace"].Value;
var content = RenderInlineTokens(token.Content.Tokens, render);
result += match.Groups["pre"].Value;
if (string.IsNullOrEmpty(whitespace))
{
result += " ";
}
result += content;
result += match.Groups["post"].Value;
return result;
}
return base.Render(render, token, context);
}
private StringBuffer RenderLHeadingToken(IMarkdownRenderer render, MarkdownHeadingBlockToken token, MarkdownBlockContext context)
{
var source = token.SourceInfo.Markdown;
var match = _lheading.Match(source);
if (match.Success)
{
var result = RenderInlineTokens(token.Content.Tokens, render);
result += match.Groups["post"].Value;
return result;
}
return base.Render(render, token, context);
}
public override StringBuffer Render(IMarkdownRenderer render, MarkdownTableBlockToken token, MarkdownBlockContext context)
{
const int SpaceCount = 2;
var rowCount = token.Cells.Length + 2;
var columnCount = token.Header.Length;
var maxLengths = new int[columnCount];
var matrix = new StringBuffer[rowCount, columnCount];
for (var column = 0; column < columnCount; column++)
{
var header = token.Header[column];
var content = RenderInlineTokens(header.Content.Tokens, render);
matrix[0, column] = content;
maxLengths[column] = Math.Max(1, content.GetLength()) + SpaceCount;
}
for (var row = 0; row < token.Cells.Length; row++)
{
var cell = token.Cells[row];
for (var column = 0; column < columnCount; column++)
{
var item = cell[column];
var content = RenderInlineTokens(item.Content.Tokens, render);
matrix[row + 2, column] = content;
maxLengths[column] = Math.Max(maxLengths[column], content.GetLength() + SpaceCount);
}
}
for (var column = 0; column < columnCount; column++)
{
var align = token.Align[column];
switch (align)
{
case Align.NotSpec:
matrix[1, column] = "---";
break;
case Align.Left:
matrix[1, column] = ":--";
break;
case Align.Right:
matrix[1, column] = "--:";
break;
case Align.Center:
matrix[1, column] = ":-:";
break;
default:
throw new NotSupportedException($"align:{align} doesn't support in GFM table");
}
}
return BuildTable(matrix, maxLengths, rowCount, columnCount);
}
private StringBuffer BuildTable(StringBuffer[,] matrix, int[] maxLenths, int rowCount, int nCol)
{
var content = StringBuffer.Empty;
for (var row = 0; row < rowCount; row++)
{
content += "|";
for (var j = 0; j < nCol; j++)
{
var align = matrix[1, j];
if (row == 1)
{
content += BuildAlign(align, maxLenths[j]);
}
else
{
content += BuildItem(align, matrix[row, j], maxLenths[j]);
}
content += "|";
}
content += "\n";
}
return content + "\n";
}
private string BuildAlign(StringBuffer align, int maxLength)
{
switch (align)
{
case "---":
return new string('-', maxLength);
case ":--":
return ":" + new string('-', maxLength - 1);
case "--:":
return new string('-', maxLength - 1) + ":";
case ":-:":
return ":" + new string('-', maxLength - 2) + ":";
default:
throw new NotSupportedException($"align:{align} doesn't support in GFM table");
}
}
private StringBuffer BuildItem(StringBuffer align, StringBuffer value, int maxLength)
{
var length = value.GetLength();
var totalPad = maxLength - value.GetLength();
switch (align)
{
case "---":
case ":-:":
var leftPad = totalPad / 2;
return BuildItem(value, leftPad, totalPad - leftPad);
case ":--":
return BuildItem(value, 1, totalPad - 1);
case "--:":
return BuildItem(value, totalPad - 1, 1);
default:
throw new NotSupportedException($"align:{align} doesn't support in GFM table");
}
}
private StringBuffer BuildItem(StringBuffer value, int leftPad, int rightPad)
{
var leftValue = leftPad == 1 ? " " : new string(' ', leftPad);
var rightValue = rightPad == 1 ? " " : new string(' ', rightPad);
return StringBuffer.Empty + leftValue + value + rightValue;
}
private StringBuffer MarkupInlineTokens(IMarkdownRenderer render, ImmutableArray<IMarkdownToken> tokens)
{
var result = StringBuffer.Empty;
if (tokens != null)
{
foreach (var t in tokens)
{
result += MarkupInlineToken(render, t);
}
}
return result;
}
private StringBuffer MarkupInlineToken(IMarkdownRenderer render, IMarkdownToken token)
{
return _dfmHtmlRender.Render((dynamic)render, (dynamic)token, (dynamic)token.Context);
}
private StringBuffer RenderInlineTokens(ImmutableArray<IMarkdownToken> tokens, IMarkdownRenderer render)
{
var result = StringBuffer.Empty;
if (tokens != null)
{
foreach (var t in tokens)
{
result += render.Render(t);
}
}
return result;
}
private bool TryResolveUid(string uid)
{
var task = CanResolveUidWithRetryAsync(uid);
return task.Result;
}
private async Task<bool> CanResolveUidWithRetryAsync(string uid)
{
var retryCount = 3;
var delay = TimeSpan.FromSeconds(3);
var count = 1;
while (true)
{
try
{
return await CanResolveUidAsync(uid);
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Error occured while resolving uid:{uid}: ${ex.Message}. Retry {count}");
if (count >= retryCount)
{
throw;
}
count++;
}
await Task.Delay(delay);
}
}
private async Task<bool> CanResolveUidAsync(string uid)
{
var requestUrl = string.Format(_requestTemplate, Uri.EscapeDataString(uid));
using (var response = await _client.GetAsync(requestUrl))
{
response.EnsureSuccessStatusCode();
using var content = response.Content;
var result = await content.ReadAsStringAsync();
if (!string.Equals("[]", result))
{
return true;
}
}
return false;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Web;
using ServiceStack.Common;
using ServiceStack.Common.Extensions;
using ServiceStack.Common.Utils;
using ServiceStack.Common.Web;
using ServiceStack.Logging;
using ServiceStack.ServiceHost;
using ServiceStack.Text;
using ServiceStack.WebHost.Endpoints.Support;
namespace ServiceStack.WebHost.Endpoints.Extensions
{
/**
*
Input: http://localhost:96/Cambia3/Temp/Test.aspx/path/info?q=item#fragment
Some HttpRequest path and URL properties:
Request.ApplicationPath: /Cambia3
Request.CurrentExecutionFilePath: /Cambia3/Temp/Test.aspx
Request.FilePath: /Cambia3/Temp/Test.aspx
Request.Path: /Cambia3/Temp/Test.aspx/path/info
Request.PathInfo: /path/info
Request.PhysicalApplicationPath: D:\Inetpub\wwwroot\CambiaWeb\Cambia3\
Request.QueryString: /Cambia3/Temp/Test.aspx/path/info?query=arg
Request.Url.AbsolutePath: /Cambia3/Temp/Test.aspx/path/info
Request.Url.AbsoluteUri: http://localhost:96/Cambia3/Temp/Test.aspx/path/info?query=arg
Request.Url.Fragment:
Request.Url.Host: localhost
Request.Url.LocalPath: /Cambia3/Temp/Test.aspx/path/info
Request.Url.PathAndQuery: /Cambia3/Temp/Test.aspx/path/info?query=arg
Request.Url.Port: 96
Request.Url.Query: ?query=arg
Request.Url.Scheme: http
Request.Url.Segments: /
Cambia3/
Temp/
Test.aspx/
path/
info
* */
public static class HttpRequestExtensions
{
private static readonly ILog Log = LogManager.GetLogger(typeof(HttpRequestExtensions));
private static string WebHostDirectoryName = "";
static HttpRequestExtensions()
{
WebHostDirectoryName = Path.GetFileName("~".MapHostAbsolutePath());
}
public static string GetOperationName(this HttpRequest request)
{
var pathInfo = request.GetLastPathInfo();
return GetOperationNameFromLastPathInfo(pathInfo);
}
public static string GetOperationNameFromLastPathInfo(string lastPathInfo)
{
if (String.IsNullOrEmpty(lastPathInfo)) return null;
var operationName = lastPathInfo.Substring("/".Length);
return operationName;
}
private static string GetLastPathInfoFromRawUrl(string rawUrl)
{
var pathInfo = rawUrl.IndexOf("?") != -1
? rawUrl.Substring(0, rawUrl.IndexOf("?"))
: rawUrl;
pathInfo = pathInfo.Substring(pathInfo.LastIndexOf("/"));
return pathInfo;
}
public static string GetLastPathInfo(this HttpRequest request)
{
var pathInfo = request.PathInfo;
if (String.IsNullOrEmpty(pathInfo))
{
pathInfo = GetLastPathInfoFromRawUrl(request.RawUrl);
}
//Log.DebugFormat("Request.PathInfo: {0}, Request.RawUrl: {1}, pathInfo:{2}",
// request.PathInfo, request.RawUrl, pathInfo);
return pathInfo;
}
public static string GetUrlHostName(this HttpRequest request)
{
//TODO: Fix bug in mono fastcgi, when trying to get 'Request.Url.Host'
try
{
return request.Url.Host;
}
catch (Exception ex)
{
Log.ErrorFormat("Error trying to get 'Request.Url.Host'", ex);
return request.UserHostName;
}
}
// http://localhost/ServiceStack.Examples.Host.Web/Public/Public/Soap12/Wsdl =>
// http://localhost/ServiceStack.Examples.Host.Web/Public/Soap12/
public static string GetParentBaseUrl(this HttpRequest request)
{
var rawUrl = request.RawUrl; // /Cambia3/Temp/Test.aspx/path/info
var endpointsPath = rawUrl.Substring(0, rawUrl.LastIndexOf('/') + 1); // /Cambia3/Temp/Test.aspx/path
return GetAuthority(request) + endpointsPath;
}
public static string GetParentBaseUrl(this IHttpRequest request){
var rawUrl = request.RawUrl;
var endpointsPath = rawUrl.Substring(0, rawUrl.LastIndexOf('/') + 1);
return new Uri(request.AbsoluteUri).GetLeftPart(UriPartial.Authority) + endpointsPath;
}
public static string GetBaseUrl(this HttpRequest request)
{
return GetAuthority(request) + request.RawUrl;
}
//=> http://localhost:96 ?? ex=> http://localhost
private static string GetAuthority(HttpRequest request)
{
try
{
return request.Url.GetLeftPart(UriPartial.Authority);
}
catch (Exception ex)
{
Log.Error("Error trying to get: request.Url.GetLeftPart(UriPartial.Authority): " + ex.Message, ex);
return "http://" + request.UserHostName;
}
}
public static string GetOperationName(this HttpListenerRequest request)
{
return request.Url.Segments[request.Url.Segments.Length - 1];
}
public static string GetLastPathInfo(this HttpListenerRequest request)
{
return GetLastPathInfoFromRawUrl(request.RawUrl);
}
public static string GetPathInfo(this HttpRequest request)
{
if (!String.IsNullOrEmpty(request.PathInfo)) return request.PathInfo.TrimEnd('/');
var mode = EndpointHost.Config.ServiceStackHandlerFactoryPath;
var appPath = String.IsNullOrEmpty(request.ApplicationPath)
? WebHostDirectoryName
: request.ApplicationPath.TrimStart('/');
//mod_mono: /CustomPath35/api//default.htm
var path = Env.IsMono ? request.Path.Replace("//", "/") : request.Path;
return GetPathInfo(path, mode, appPath);
}
public static string GetPathInfo(string fullPath, string mode, string appPath)
{
var pathInfo = ResolvePathInfoFromMappedPath(fullPath, mode);
if (!String.IsNullOrEmpty(pathInfo)) return pathInfo;
//Wildcard mode relies on this to work out the handlerPath
pathInfo = ResolvePathInfoFromMappedPath(fullPath, appPath);
if (!String.IsNullOrEmpty(pathInfo)) return pathInfo;
return fullPath;
}
public static string ResolvePathInfoFromMappedPath(string fullPath, string mappedPathRoot)
{
if (mappedPathRoot == null) return null;
var sbPathInfo = new StringBuilder();
var fullPathParts = fullPath.Split('/');
var mappedPathRootParts = mappedPathRoot.Split('/');
var fullPathIndexOffset = mappedPathRootParts.Length - 1;
var pathRootFound = false;
for (var fullPathIndex = 0; fullPathIndex < fullPathParts.Length; fullPathIndex++) {
if (pathRootFound) {
sbPathInfo.Append("/" + fullPathParts[fullPathIndex]);
} else if (fullPathIndex - fullPathIndexOffset >= 0) {
pathRootFound = true;
for (var mappedPathRootIndex = 0; mappedPathRootIndex < mappedPathRootParts.Length; mappedPathRootIndex++) {
if (!String.Equals(fullPathParts[fullPathIndex - fullPathIndexOffset + mappedPathRootIndex], mappedPathRootParts[mappedPathRootIndex], StringComparison.InvariantCultureIgnoreCase)) {
pathRootFound = false;
break;
}
}
}
}
if (!pathRootFound) return null;
var path = sbPathInfo.ToString();
return path.Length > 1 ? path.TrimEnd('/') : "/";
}
public static bool IsContentType(this IHttpRequest request, string contentType)
{
return request.ContentType.StartsWith(contentType, StringComparison.InvariantCultureIgnoreCase);
}
public static bool HasAnyOfContentTypes(this IHttpRequest request, params string[] contentTypes)
{
if (contentTypes == null || request.ContentType == null) return false;
foreach (var contentType in contentTypes)
{
if (IsContentType(request, contentType)) return true;
}
return false;
}
public static IHttpRequest GetHttpRequest(this HttpRequest request)
{
return new HttpRequestWrapper(null, request);
}
public static IHttpRequest GetHttpRequest(this HttpListenerRequest request)
{
return new HttpListenerRequestWrapper(null, request);
}
public static Dictionary<string, string> GetRequestParams(this IHttpRequest request)
{
var map = new Dictionary<string, string>();
foreach (var name in request.QueryString.AllKeys)
{
if (name == null) continue; //thank you ASP.NET
map[name] = request.QueryString[name];
}
if ((request.HttpMethod == HttpMethods.Post || request.HttpMethod == HttpMethods.Put)
&& request.FormData != null)
{
foreach (var name in request.FormData.AllKeys)
{
if (name == null) continue; //thank you ASP.NET
map[name] = request.FormData[name];
}
}
return map;
}
public static string GetQueryStringContentType(this IHttpRequest httpReq)
{
var callback = httpReq.QueryString["callback"];
if (!String.IsNullOrEmpty(callback)) return ContentType.Json;
var format = httpReq.QueryString["format"];
if (format == null)
{
const int formatMaxLength = 4;
var pi = httpReq.PathInfo;
if (pi == null || pi.Length <= formatMaxLength) return null;
if (pi[0] == '/') pi = pi.Substring(1);
format = pi.SplitOnFirst('/')[0];
if (format.Length > formatMaxLength) return null;
}
format = format.SplitOnFirst('.')[0].ToLower();
if (format.Contains("json")) return ContentType.Json;
if (format.Contains("xml")) return ContentType.Xml;
if (format.Contains("jsv")) return ContentType.Jsv;
string contentType;
EndpointHost.ContentTypeFilter.ContentTypeFormats.TryGetValue(format, out contentType);
return contentType;
}
public static string[] PreferredContentTypes = new[] {
ContentType.Html, ContentType.Json, ContentType.Xml, ContentType.Jsv
};
/// <summary>
/// Use this to treat Request.Items[] as a cache by returning pre-computed items to save
/// calculating them multiple times.
/// </summary>
public static object ResolveItem(this IHttpRequest httpReq,
string itemKey, Func<IHttpRequest, object> resolveFn)
{
object cachedItem;
if (httpReq.Items.TryGetValue(itemKey, out cachedItem))
return cachedItem;
var item = resolveFn(httpReq);
httpReq.Items[itemKey] = item;
return item;
}
public static string GetResponseContentType(this IHttpRequest httpReq)
{
var specifiedContentType = GetQueryStringContentType(httpReq);
if (!String.IsNullOrEmpty(specifiedContentType)) return specifiedContentType;
var acceptContentTypes = httpReq.AcceptTypes;
var defaultContentType = httpReq.ContentType;
if (httpReq.HasAnyOfContentTypes(ContentType.FormUrlEncoded, ContentType.MultiPartFormData))
{
defaultContentType = EndpointHost.Config.DefaultContentType;
}
var customContentTypes = EndpointHost.ContentTypeFilter.ContentTypeFormats.Values;
var acceptsAnything = false;
var hasDefaultContentType = !String.IsNullOrEmpty(defaultContentType);
if (acceptContentTypes != null)
{
var hasPreferredContentTypes = new bool[PreferredContentTypes.Length];
foreach (var contentType in acceptContentTypes)
{
acceptsAnything = acceptsAnything || contentType == "*/*";
for (var i = 0; i < PreferredContentTypes.Length; i++)
{
if (hasPreferredContentTypes[i]) continue;
var preferredContentType = PreferredContentTypes[i];
hasPreferredContentTypes[i] = contentType.StartsWith(preferredContentType);
//Prefer Request.ContentType if it is also a preferredContentType
if (hasPreferredContentTypes[i] && preferredContentType == defaultContentType)
return preferredContentType;
}
}
for (var i = 0; i < PreferredContentTypes.Length; i++)
{
if (hasPreferredContentTypes[i]) return PreferredContentTypes[i];
}
if (acceptsAnything && hasDefaultContentType) return defaultContentType;
foreach (var contentType in acceptContentTypes)
{
foreach (var customContentType in customContentTypes)
{
if (contentType.StartsWith(customContentType)) return customContentType;
}
}
}
//We could also send a '406 Not Acceptable', but this is allowed also
return EndpointHost.Config.DefaultContentType;
}
public static void SetView(this IHttpRequest httpReq, string viewName)
{
httpReq.SetItem("View", viewName);
}
public static string GetView(this IHttpRequest httpReq)
{
return httpReq.GetItem("View") as string;
}
public static void SetTemplate(this IHttpRequest httpReq, string templateName)
{
httpReq.SetItem("Template", templateName);
}
public static string GetTemplate(this IHttpRequest httpReq)
{
return httpReq.GetItem("Template") as string;
}
public static string ResolveAbsoluteUrl(this IHttpRequest httpReq, string url)
{
return EndpointHost.AppHost.ResolveAbsoluteUrl(url, httpReq);
}
public static string ResolveBaseUrl(this IHttpRequest httpReq)
{
return EndpointHost.AppHost.ResolveAbsoluteUrl("~/", httpReq);
}
public static string GetAbsoluteUrl(this IHttpRequest httpReq, string url)
{
if (url.SafeSubstring(0, 2) == "~/")
{
url = httpReq.GetBaseUrl().CombineWith(url.Substring(2));
}
return url;
}
public static string GetBaseUrl(this IHttpRequest httpReq)
{
var baseUrl = ServiceStackHttpHandlerFactory.GetBaseUrl();
if (baseUrl != null) return baseUrl;
var handlerPath = EndpointHost.Config.ServiceStackHandlerFactoryPath;
if (handlerPath != null)
{
var pos = httpReq.AbsoluteUri.IndexOf(handlerPath, StringComparison.InvariantCultureIgnoreCase);
if (pos >= 0)
{
baseUrl = httpReq.AbsoluteUri.Substring(0, pos + handlerPath.Length);
return baseUrl;
}
return "/" + handlerPath;
}
return "/"; //Can't infer Absolute Uri, fallback to root relative path
}
public static EndpointAttributes ToEndpointAttributes(string[] attrNames)
{
var attrs = EndpointAttributes.None;
foreach (var simulatedAttr in attrNames)
{
var attr = (EndpointAttributes)Enum.Parse(typeof(EndpointAttributes), simulatedAttr, true);
attrs |= attr;
}
return attrs;
}
public static EndpointAttributes GetAttributes(this IHttpRequest request)
{
if (EndpointHost.DebugMode
&& request.QueryString != null) //Mock<IHttpRequest>
{
var simulate = request.QueryString["simulate"];
if (simulate != null)
{
return ToEndpointAttributes(simulate.Split(','));
}
}
var portRestrictions = EndpointAttributes.None;
portRestrictions |= HttpMethods.GetEndpointAttribute(request.HttpMethod);
portRestrictions |= request.IsSecureConnection ? EndpointAttributes.Secure : EndpointAttributes.InSecure;
if (request.UserHostAddress != null)
{
var isIpv4Address = request.UserHostAddress.IndexOf('.') != -1
&& request.UserHostAddress.IndexOf("::", StringComparison.InvariantCulture) == -1;
string ipAddressNumber = null;
if (isIpv4Address)
{
ipAddressNumber = request.UserHostAddress.SplitOnFirst(":")[0];
}
else
{
if (request.UserHostAddress.Contains("]:"))
{
ipAddressNumber = request.UserHostAddress.SplitOnLast(":")[0];
}
else
{
ipAddressNumber = request.UserHostAddress.LastIndexOf("%", StringComparison.InvariantCulture) > 0 ?
request.UserHostAddress.SplitOnLast(":")[0] :
request.UserHostAddress;
}
}
try
{
ipAddressNumber = ipAddressNumber.SplitOnFirst(',')[0];
var ipAddress = ipAddressNumber.StartsWith("::1")
? IPAddress.IPv6Loopback
: IPAddress.Parse(ipAddressNumber);
portRestrictions |= GetAttributes(ipAddress);
}
catch (Exception ex)
{
throw new ArgumentException("Could not parse Ipv{0} Address: {1} / {2}"
.Fmt((isIpv4Address ? 4 : 6), request.UserHostAddress, ipAddressNumber), ex);
}
}
return portRestrictions;
}
public static EndpointAttributes GetAttributes(IPAddress ipAddress)
{
if (IPAddress.IsLoopback(ipAddress))
return EndpointAttributes.Localhost;
return IsInLocalSubnet(ipAddress)
? EndpointAttributes.LocalSubnet
: EndpointAttributes.External;
}
public static bool IsInLocalSubnet(IPAddress ipAddress)
{
var ipAddressBytes = ipAddress.GetAddressBytes();
switch (ipAddress.AddressFamily)
{
case AddressFamily.InterNetwork:
foreach (var localIpv4AddressAndMask in EndpointHandlerBase.NetworkInterfaceIpv4Addresses)
{
if (ipAddressBytes.IsInSameIpv4Subnet(localIpv4AddressAndMask.Key, localIpv4AddressAndMask.Value))
{
return true;
}
}
break;
case AddressFamily.InterNetworkV6:
foreach (var localIpv6Address in EndpointHandlerBase.NetworkInterfaceIpv6Addresses)
{
if (ipAddressBytes.IsInSameIpv6Subnet(localIpv6Address))
{
return true;
}
}
break;
}
return false;
}
public static IHttpRequest ToRequest(this HttpRequest aspnetHttpReq, string operationName=null)
{
return new HttpRequestWrapper(aspnetHttpReq) {
OperationName = operationName,
Container = AppHostBase.Instance != null ? AppHostBase.Instance.Container : null
};
}
public static IHttpRequest ToRequest(this HttpListenerRequest listenerHttpReq, string operationName = null)
{
return new HttpListenerRequestWrapper(listenerHttpReq) {
OperationName = operationName,
Container = AppHostBase.Instance != null ? AppHostBase.Instance.Container : null
};
}
public static IHttpResponse ToResponse(this HttpResponse aspnetHttpRes)
{
return new HttpResponseWrapper(aspnetHttpRes);
}
public static IHttpResponse ToResponse(this HttpListenerResponse listenerHttpRes)
{
return new HttpListenerResponseWrapper(listenerHttpRes);
}
public static void SetOperationName(this IHttpRequest httpReq, string operationName)
{
if (httpReq.OperationName == null)
{
var aspReq = httpReq as HttpRequestWrapper;
if (aspReq != null)
{
aspReq.OperationName = operationName;
return;
}
var listenerReq = httpReq as HttpListenerRequestWrapper;
if (listenerReq != null)
{
listenerReq.OperationName = operationName;
}
}
}
public static System.ServiceModel.Channels.Message GetSoapMessage(this IHttpRequest httpReq)
{
return httpReq.Items["SoapMessage"] as System.ServiceModel.Channels.Message;
}
}
}
| |
using Glass.Mapper.Pipelines.ConfigurationResolver.Tasks.OnDemandResolver;
using Glass.Mapper.Pipelines.DataMapperResolver;
using Glass.Mapper.Sc.Configuration;
using Glass.Mapper.Sc.Configuration.Attributes;
using Glass.Mapper.Sc.DataMappers;
using NSubstitute;
using NUnit.Framework;
using Sitecore.Data.Managers;
using Sitecore.FakeDb;
namespace Glass.Mapper.Sc.FakeDb.DataMappers
{
[TestFixture]
public class SitecoreNodeMapperFixture
{
protected const string FieldName = "Field";
#region Property - ReadOnly
[Test]
public void ReadOnly_ReturnsTrue()
{
//Assign
var mapper = new SitecoreNodeMapper();
//Act
var result = mapper.ReadOnly;
//Assert
Assert.IsTrue(result);
}
#endregion
#region Method - CanHandle
[Test]
public void CanHandle_ConfigIsNodeAndClassMapped_ReturnsTrue()
{
//Assign
var config = new SitecoreNodeConfiguration();
var mapper = new SitecoreNodeMapper();
//Act
var result = mapper.CanHandle(config, null);
//Assert
Assert.IsTrue(result);
}
[Test]
public void CanHandle_ConfigIsNotNodeAndClassMapped_ReturnsFalse()
{
//Assign
var config = new SitecoreFieldConfiguration();
var mapper = new SitecoreNodeMapper();
//Act
var result = mapper.CanHandle(config, null);
//Assert
Assert.IsFalse(result);
}
#endregion
#region Method - MapToProperty
[Test]
public void MapToProperty_GetItemByPath_ReturnsItem()
{
//Assign
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("Source"),
new Sitecore.FakeDb.DbItem("Target")
})
{
var config = new SitecoreNodeConfiguration();
var mapper = new SitecoreNodeMapper();
var language = LanguageManager.GetLanguage("en");
mapper.Setup(new DataMapperResolverArgs(null, config));
var obj = new Stub();
var source = database.Database.GetItem("/sitecore/content/Source", language);
var target = database.Database.GetItem("/sitecore/content/Target", language);
var service = Substitute.For<ISitecoreService>();
var expected = new StubMapped();
var options = new GetItemOptionsParams();
config.PropertyInfo = typeof(Stub).GetProperty("StubMapped");
config.Path = "/sitecore/content/Target";
service.GetItem(Arg.Is<GetItemByItemOptions>(x => x.Item.Uri == target.Uri)).Returns(expected);
var mappingContext = new SitecoreDataMappingContext(obj, source, service, options);
//Act
var result = mapper.MapToProperty(mappingContext);
//Assert
Assert.AreEqual(expected, result);
}
}
[Test]
public void MapToProperty_GetItemByPathDifferentLanguage_ReturnsItem()
{
//Assign
var language = LanguageManager.GetLanguage("af-ZA");
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("Source")
{
new Sitecore.FakeDb.DbField("Title")
{
{language.Name , language.Name }
}
},
new Sitecore.FakeDb.DbItem("Target")
{
new Sitecore.FakeDb.DbField("Title")
{
{language.Name , language.Name }
}
},
})
{
var config = new SitecoreNodeConfiguration();
var mapper = new SitecoreNodeMapper();
mapper.Setup(new DataMapperResolverArgs(null, config));
var obj = new Stub();
var source = database.Database.GetItem("/sitecore/content/Source", language);
var target = database.Database.GetItem("/sitecore/content/Target", language);
var service = Substitute.For<ISitecoreService>();
var expected = new StubMapped();
var options = new GetItemOptionsParams();
config.PropertyInfo = typeof(Stub).GetProperty("StubMapped");
config.Path = "/sitecore/content/Target";
service.GetItem(Arg.Is<GetItemByItemOptions>(x => x.Item.Uri == target.Uri)).Returns(expected);
var mappingContext = new SitecoreDataMappingContext(obj, source, service, options);
//Act
var result = mapper.MapToProperty(mappingContext);
//Assert
Assert.AreEqual(expected, result);
}
}
[Test]
public void MapToProperty_GetItemByPathDifferentLanguageTargetDoesNotExistInLanguage_ReturnsNull()
{
//Assign
var config = new SitecoreNodeConfiguration();
var mapper = new SitecoreNodeMapper();
var language = LanguageManager.GetLanguage("af-ZA");
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("Source")
{
new Sitecore.FakeDb.DbField("Title")
{
{language.Name, language.Name}
}
},
new Sitecore.FakeDb.DbItem("TargetOneLanguage")
{
},
})
{
mapper.Setup(new DataMapperResolverArgs(null, config));
var obj = new Stub();
var source = database.Database.GetItem("/sitecore/content/Source", language);
var target = database.Database.GetItem(
"/sitecore/content/Tests/DataMappers/SitecoreNodeMapper/TargetOneLanguage", language);
var service = Substitute.For<ISitecoreService>();
var expected = new StubMapped();
var options = new GetItemOptionsParams();
config.PropertyInfo = typeof(Stub).GetProperty("StubMapped");
config.Path = "/sitecore/content/Tests/DataMappers/SitecoreNodeMapper/Target";
service.GetItem(Arg.Is<GetItemByItemOptions>(x => x.Item.Uri == target.Uri && x.Item.Versions.Count == 0)).Returns(expected);
var mappingContext = new SitecoreDataMappingContext(obj, source, service,options);
//Act
var result = mapper.MapToProperty(mappingContext);
//Assert
Assert.IsNull(result);
}
}
[Test]
public void MapToProperty_GetItemByID_ReturnsItem()
{
//Assign
var config = new SitecoreNodeConfiguration();
var context = Context.Create(FakeDb.Utilities.CreateStandardResolver());
var mapper = new SitecoreNodeMapper();
var language = LanguageManager.GetLanguage("en");
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubMapped)));
mapper.Setup(new DataMapperResolverArgs(context, config));
var obj = new Stub();
using (Db database = new Db{
new Sitecore.FakeDb.DbItem("Source"),
new Sitecore.FakeDb.DbItem("Target")
})
{
var source = database.Database.GetItem("/sitecore/content/Source", language);
var target = database.Database.GetItem("/sitecore/content/Target", language);
var service = Substitute.For<ISitecoreService>();
var expected = new StubMapped();
var options = new GetItemOptionsParams();
config.PropertyInfo = typeof(Stub).GetProperty("StubMapped");
config.Id = target.ID.Guid.ToString();
service.GetItem(Arg.Is<GetItemByItemOptions>(x => x.Item.Uri == target.Uri )).Returns(expected);
var mappingContext = new SitecoreDataMappingContext(obj, source, service, options);
//Act
var result = mapper.MapToProperty(mappingContext);
//Assert
Assert.AreEqual(expected, result);
}
}
[Test]
public void MapToProperty_GetItemByIdDifferentLanguage_ReturnsItem()
{
//Assign
var config = new SitecoreNodeConfiguration();
var context = Context.Create(FakeDb.Utilities.CreateStandardResolver());
var mapper = new SitecoreNodeMapper();
var language = LanguageManager.GetLanguage("af-ZA");
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubMapped)));
mapper.Setup(new DataMapperResolverArgs(context, config));
var obj = new Stub();
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("Source"),
new Sitecore.FakeDb.DbItem("Target")
})
{
var source = database.Database.GetItem("/sitecore/content/Source", language);
var target = database.Database.GetItem("/sitecore/content/Target", language);
var service = Substitute.For<ISitecoreService>();
var expected = new StubMapped();
var options = new GetItemOptionsParams();
config.PropertyInfo = typeof(Stub).GetProperty("StubMapped");
config.Id = target.ID.Guid.ToString();
service.GetItem(Arg.Is<GetItemByItemOptions>(x => x.Item.Uri == target.Uri)).Returns(expected);
var mappingContext = new SitecoreDataMappingContext(obj, source, service, options);
//Act
var result = mapper.MapToProperty(mappingContext);
//Assert
Assert.AreEqual(expected, result);
}
}
[Test]
public void MapToProperty_GetItemByIdDifferentLanguageTargetDoesNotExistInLanguage_ReturnsNull()
{
//Assign
var config = new SitecoreNodeConfiguration();
var context = Context.Create(FakeDb.Utilities.CreateStandardResolver());
var mapper = new SitecoreNodeMapper();
var language = LanguageManager.GetLanguage("af-ZA");
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubMapped)));
mapper.Setup(new DataMapperResolverArgs(context, config));
var obj = new Stub();
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("Source"),
new Sitecore.FakeDb.DbItem("Target")
})
{
var source = database.Database.GetItem("/sitecore/content/Source", language);
var target = database.Database.GetItem("/sitecore/content/Target", language);
var service = new SitecoreService(database.Database, context);
var options = new GetItemOptionsParams();
config.PropertyInfo = typeof(Stub).GetProperty("StubMapped");
config.Id = target.ID.Guid.ToString();
var mappingContext = new SitecoreDataMappingContext(obj, source, service, options);
//Act
var result = mapper.MapToProperty(mappingContext);
//Assert
Assert.IsNull(result);
}
}
[Test]
public void MapToProperty_GetItemByPathIsLazy_ReturnsItem()
{
//Assign
var config = new SitecoreNodeConfiguration();
var context = Context.Create(FakeDb.Utilities.CreateStandardResolver());
var mapper = new SitecoreNodeMapper();
var language = LanguageManager.GetLanguage("en");
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubMapped)));
mapper.Setup(new DataMapperResolverArgs(context, config));
var obj = new Stub();
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("Source"),
new Sitecore.FakeDb.DbItem("Target")
})
{
var source = database.Database.GetItem("/sitecore/content/Source", language);
var target = database.Database.GetItem("/sitecore/content/Target", language);
var service = Substitute.For<ISitecoreService>();
var expected = new StubMapped();
var options = new GetItemOptionsParams
{
Lazy = LazyLoading.Enabled
};
config.PropertyInfo = typeof(Stub).GetProperty("StubMapped");
config.Path = "/sitecore/content/Target";
service.GetItem(Arg.Is<GetItemByItemOptions>(x => x.Item.Uri == target.Uri && x.Lazy == LazyLoading.Enabled)).Returns(expected);
var mappingContext = new SitecoreDataMappingContext(obj, source, service, options);
//Act
var result = mapper.MapToProperty(mappingContext);
//Assert
Assert.AreEqual(expected, result);
}
}
[Test]
public void MapToProperty_GetItemByPathInferType_ReturnsItem()
{
//Assign
var config = new SitecoreNodeConfiguration();
var context = Context.Create(FakeDb.Utilities.CreateStandardResolver());
var mapper = new SitecoreNodeMapper();
var language = LanguageManager.GetLanguage("en");
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubMapped)));
mapper.Setup(new DataMapperResolverArgs(context, config));
var obj = new Stub();
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("Source"),
new Sitecore.FakeDb.DbItem("Target")
})
{
var source = database.Database.GetItem("/sitecore/content/Source", language);
var target = database.Database.GetItem("/sitecore/content/Target", language);
var service = Substitute.For<ISitecoreService>();
var expected = new StubMapped();
var options = new GetItemOptionsParams();
config.PropertyInfo = typeof(Stub).GetProperty("StubMapped");
config.Path = "/sitecore/content/Target";
config.InferType = true;
service.GetItem(Arg.Is<GetItemByItemOptions>(x => x.Item.Uri == target.Uri)).Returns(expected);
var mappingContext = new SitecoreDataMappingContext(obj, source, service, options);
//Act
var result = mapper.MapToProperty(mappingContext);
//Assert
Assert.AreEqual(expected, result);
}
}
[Test]
public void MapToProperty_GetItemByPathIsLazyIntegrationTest_ReturnsItem()
{
//Assign
var config = new SitecoreNodeConfiguration();
var context = Context.Create(FakeDb.Utilities.CreateStandardResolver());
var mapper = new SitecoreNodeMapper();
var language = LanguageManager.GetLanguage("en");
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubMapped)));
mapper.Setup(new DataMapperResolverArgs(context, config));
var obj = new Stub();
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("Source"),
new Sitecore.FakeDb.DbItem("Target")
})
{
var source = database.Database.GetItem("/sitecore/content/Source", language);
var target = database.Database.GetItem("/sitecore/content/Target", language);
var service = new SitecoreService(database.Database);
var expected = new StubMapped();
var options = new GetItemOptionsParams
{
Lazy = LazyLoading.Enabled
};
config.PropertyInfo = typeof(Stub).GetProperty("StubMapped");
config.Path = "/sitecore/content/Target";
var mappingContext = new SitecoreDataMappingContext(obj, source, service, options);
//Act
var result = mapper.MapToProperty(mappingContext);
//Assert
Assert.True(result is StubMapped);
}
}
#endregion
#region Stubs
[SitecoreType]
public class StubMapped
{
}
public class StubNotMapped
{
}
public class Stub
{
public StubMapped StubMapped { get; set; }
public StubNotMapped StubNotMapped { get; set; }
}
#endregion
}
}
| |
using u8 = System.Byte;
using Pgno = System.UInt32;
#if SQLITE_OMIT_WAL
using Wal = System.Object;
#endif
namespace Community.CsharpSqlite
{
public partial class Sqlite3
{
/*
** 2010 February 1
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This header file defines the interface to the write-ahead logging
** system. Refer to the comments below and the header comment attached to
** the implementation of each function in log.c for further details.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
**
*************************************************************************
*/
//#if !_WAL_H_
//#define _WAL_H_
//#include "sqliteInt.h"
#if SQLITE_OMIT_WAL
//# define sqlite3WalOpen(x,y,z) 0
static int sqlite3WalOpen( sqlite3_vfs x, sqlite3_file y, string z )
{
return 0;
}
//# define sqlite3WalLimit(x,y)
static void sqlite3WalLimit( sqlite3_vfs x, long y )
{
}
//# define sqlite3WalClose(w,x,y,z) 0
static int sqlite3WalClose( Wal w, int x, int y, u8 z )
{
return 0;
}
//# define sqlite3WalBeginReadTransaction(y,z) 0
static int sqlite3WalBeginReadTransaction( Wal y, int z )
{
return 0;
}
//# define sqlite3WalEndReadTransaction(z)
static void sqlite3WalEndReadTransaction( Wal z )
{
}
//# define sqlite3WalRead(v,w,x,y,z) 0
static int sqlite3WalRead( Wal v, Pgno w, ref int x, int y, u8[] z )
{
return 0;
}
//# define sqlite3WalDbsize(y) 0
static Pgno sqlite3WalDbsize( Wal y )
{
return 0;
}
//# define sqlite3WalBeginWriteTransaction(y) 0
static int sqlite3WalBeginWriteTransaction( Wal y )
{
return 0;
}
//# define sqlite3WalEndWriteTransaction(x) 0
static int sqlite3WalEndWriteTransaction( Wal x )
{
return 0;
}
//# define sqlite3WalUndo(x,y,z) 0
static int sqlite3WalUndo( Wal x, int y, object z )
{
return 0;
}
//# define sqlite3WalSavepoint(y,z)
static void sqlite3WalSavepoint( Wal y, object z )
{
}
//# define sqlite3WalSavepointUndo(y,z) 0
static int sqlite3WalSavepointUndo( Wal y, object z )
{
return 0;
}
//# define sqlite3WalFrames(u,v,w,x,y,z) 0
static int sqlite3WalFrames( Wal u, int v, PgHdr w, Pgno x, int y, int z )
{
return 0;
}
//# define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
static int sqlite3WalCheckpoint( Wal r, int s, int t, u8[] u, int v, int w, u8[]x, ref int y, ref int z )//r,s,t,u,v,w,x,y,z
{
y = 0;
z = 0;
return 0;
}
//# define sqlite3WalCallback(z) 0
static int sqlite3WalCallback( Wal z )
{
return 0;
}
//# define sqlite3WalExclusiveMode(y,z) 0
static bool sqlite3WalExclusiveMode( Wal y, int z )
{
return false;
}
//# define sqlite3WalHeapMemory(z) 0
static bool sqlite3WalHeapMemory( Wal z )
{
return false;
}
#else
//#define WAL_SAVEPOINT_NDATA 4
const int WAL_SAVEPOINT_NDATA = 4;
/* Connection to a write-ahead log (WAL) file.
** There is one object of this type for each pager.
*/
typedef struct Wal Wal;
/* Open and close a connection to a write-ahead log. */
int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, string , int, i64, Wal*);
int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 );
/* Set the limiting size of a WAL file. */
void sqlite3WalLimit(Wal*, i64);
/* Used by readers to open (lock) and close (unlock) a snapshot. A
** snapshot is like a read-transaction. It is the state of the database
** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and
** preserves the current state even if the other threads or processes
** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the
** transaction and releases the lock.
*/
int sqlite3WalBeginReadTransaction(Wal *pWal, int );
void sqlite3WalEndReadTransaction(Wal *pWal);
/* Read a page from the write-ahead log, if it is present. */
int sqlite3WalRead(Wal *pWal, Pgno pgno, int *pInWal, int nOut, u8 *pOut);
/* If the WAL is not empty, return the size of the database. */
Pgno sqlite3WalDbsize(Wal *pWal);
/* Obtain or release the WRITER lock. */
int sqlite3WalBeginWriteTransaction(Wal *pWal);
int sqlite3WalEndWriteTransaction(Wal *pWal);
/* Undo any frames written (but not committed) to the log */
int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), object *pUndoCtx);
/* Return an integer that records the current (uncommitted) write
** position in the WAL */
void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
/* Move the write position of the WAL back to iFrame. Called in
** response to a ROLLBACK TO command. */
int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
/* Write a frame or frames to the log. */
int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
/* Copy pages from the log to the database file */
int sqlite3WalCheckpoint(
Wal *pWal, /* Write-ahead log connection */
int eMode, /* One of PASSIVE, FULL and RESTART */
int (*xBusy)(void), /* Function to call when busy */
void *pBusyArg, /* Context argument for xBusyHandler */
int sync_flags, /* Flags to sync db file with (or 0) */
int nBuf, /* Size of buffer nBuf */
u8 *zBuf, /* Temporary buffer to use */
int *pnLog, /* OUT: Number of frames in WAL */
int *pnCkpt /* OUT: Number of backfilled frames in WAL */
);
/* Return the value to pass to a sqlite3_wal_hook callback, the
** number of frames in the WAL at the point of the last commit since
** sqlite3WalCallback() was called. If no commits have occurred since
** the last call, then return 0.
*/
int sqlite3WalCallback(Wal *pWal);
/* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
** by the pager layer on the database file.
*/
int sqlite3WalExclusiveMode(Wal *pWal, int op);
/* Return true if the argument is non-NULL and the WAL module is using
** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
** WAL module is using shared-memory, return false.
*/
int sqlite3WalHeapMemory(Wal *pWal);
#endif //* ifndef SQLITE_OMIT_WAL */
//#endif //* _WAL_H_ */
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Reflection
{
[System.FlagsAttribute]
public enum CallingConventions
{
Any = 3,
ExplicitThis = 64,
HasThis = 32,
Standard = 1,
VarArgs = 2,
}
[System.FlagsAttribute]
public enum EventAttributes
{
None = 0,
RTSpecialName = 1024,
SpecialName = 512,
}
[System.FlagsAttribute]
public enum FieldAttributes
{
Assembly = 3,
FamANDAssem = 2,
Family = 4,
FamORAssem = 5,
FieldAccessMask = 7,
HasDefault = 32768,
HasFieldMarshal = 4096,
HasFieldRVA = 256,
InitOnly = 32,
Literal = 64,
NotSerialized = 128,
PinvokeImpl = 8192,
Private = 1,
PrivateScope = 0,
Public = 6,
RTSpecialName = 1024,
SpecialName = 512,
Static = 16,
}
[System.FlagsAttribute]
public enum GenericParameterAttributes
{
Contravariant = 2,
Covariant = 1,
DefaultConstructorConstraint = 16,
None = 0,
NotNullableValueTypeConstraint = 8,
ReferenceTypeConstraint = 4,
SpecialConstraintMask = 28,
VarianceMask = 3,
}
[System.FlagsAttribute]
public enum MethodAttributes
{
Abstract = 1024,
Assembly = 3,
CheckAccessOnOverride = 512,
FamANDAssem = 2,
Family = 4,
FamORAssem = 5,
Final = 32,
HasSecurity = 16384,
HideBySig = 128,
MemberAccessMask = 7,
NewSlot = 256,
PinvokeImpl = 8192,
Private = 1,
PrivateScope = 0,
Public = 6,
RequireSecObject = 32768,
ReuseSlot = 0,
RTSpecialName = 4096,
SpecialName = 2048,
Static = 16,
UnmanagedExport = 8,
Virtual = 64,
VtableLayoutMask = 256,
}
public enum MethodImplAttributes
{
AggressiveInlining = 256,
CodeTypeMask = 3,
ForwardRef = 16,
IL = 0,
InternalCall = 4096,
Managed = 0,
ManagedMask = 4,
Native = 1,
NoInlining = 8,
NoOptimization = 64,
OPTIL = 2,
PreserveSig = 128,
Runtime = 3,
Synchronized = 32,
Unmanaged = 4,
}
[System.FlagsAttribute]
public enum ParameterAttributes
{
HasDefault = 4096,
HasFieldMarshal = 8192,
In = 1,
Lcid = 4,
None = 0,
Optional = 16,
Out = 2,
Retval = 8,
}
[System.FlagsAttribute]
public enum PropertyAttributes
{
HasDefault = 4096,
None = 0,
RTSpecialName = 1024,
SpecialName = 512,
}
[System.FlagsAttribute]
public enum TypeAttributes
{
Abstract = 128,
AnsiClass = 0,
AutoClass = 131072,
AutoLayout = 0,
BeforeFieldInit = 1048576,
Class = 0,
ClassSemanticsMask = 32,
CustomFormatClass = 196608,
CustomFormatMask = 12582912,
ExplicitLayout = 16,
HasSecurity = 262144,
Import = 4096,
Interface = 32,
LayoutMask = 24,
NestedAssembly = 5,
NestedFamANDAssem = 6,
NestedFamily = 4,
NestedFamORAssem = 7,
NestedPrivate = 3,
NestedPublic = 2,
NotPublic = 0,
Public = 1,
RTSpecialName = 2048,
Sealed = 256,
SequentialLayout = 8,
Serializable = 8192,
SpecialName = 1024,
StringFormatMask = 196608,
UnicodeClass = 65536,
VisibilityMask = 7,
WindowsRuntime = 16384,
}
}
namespace System.Reflection.Emit
{
public enum FlowControl
{
Branch = 0,
Break = 1,
Call = 2,
Cond_Branch = 3,
Meta = 4,
Next = 5,
Return = 7,
Throw = 8,
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct OpCode
{
public System.Reflection.Emit.FlowControl FlowControl { get { return default(System.Reflection.Emit.FlowControl); } }
public string Name { get { return default(string); } }
public System.Reflection.Emit.OpCodeType OpCodeType { get { return default(System.Reflection.Emit.OpCodeType); } }
public System.Reflection.Emit.OperandType OperandType { get { return default(System.Reflection.Emit.OperandType); } }
public int Size { get { return default(int); } }
public System.Reflection.Emit.StackBehaviour StackBehaviourPop { get { return default(System.Reflection.Emit.StackBehaviour); } }
public System.Reflection.Emit.StackBehaviour StackBehaviourPush { get { return default(System.Reflection.Emit.StackBehaviour); } }
public short Value { get { return default(short); } }
public override bool Equals(object obj) { return default(bool); }
public bool Equals(System.Reflection.Emit.OpCode obj) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static bool operator ==(System.Reflection.Emit.OpCode a, System.Reflection.Emit.OpCode b) { return default(bool); }
public static bool operator !=(System.Reflection.Emit.OpCode a, System.Reflection.Emit.OpCode b) { return default(bool); }
public override string ToString() { return default(string); }
}
public partial class OpCodes
{
internal OpCodes() { }
public static readonly System.Reflection.Emit.OpCode Add;
public static readonly System.Reflection.Emit.OpCode Add_Ovf;
public static readonly System.Reflection.Emit.OpCode Add_Ovf_Un;
public static readonly System.Reflection.Emit.OpCode And;
public static readonly System.Reflection.Emit.OpCode Arglist;
public static readonly System.Reflection.Emit.OpCode Beq;
public static readonly System.Reflection.Emit.OpCode Beq_S;
public static readonly System.Reflection.Emit.OpCode Bge;
public static readonly System.Reflection.Emit.OpCode Bge_S;
public static readonly System.Reflection.Emit.OpCode Bge_Un;
public static readonly System.Reflection.Emit.OpCode Bge_Un_S;
public static readonly System.Reflection.Emit.OpCode Bgt;
public static readonly System.Reflection.Emit.OpCode Bgt_S;
public static readonly System.Reflection.Emit.OpCode Bgt_Un;
public static readonly System.Reflection.Emit.OpCode Bgt_Un_S;
public static readonly System.Reflection.Emit.OpCode Ble;
public static readonly System.Reflection.Emit.OpCode Ble_S;
public static readonly System.Reflection.Emit.OpCode Ble_Un;
public static readonly System.Reflection.Emit.OpCode Ble_Un_S;
public static readonly System.Reflection.Emit.OpCode Blt;
public static readonly System.Reflection.Emit.OpCode Blt_S;
public static readonly System.Reflection.Emit.OpCode Blt_Un;
public static readonly System.Reflection.Emit.OpCode Blt_Un_S;
public static readonly System.Reflection.Emit.OpCode Bne_Un;
public static readonly System.Reflection.Emit.OpCode Bne_Un_S;
public static readonly System.Reflection.Emit.OpCode Box;
public static readonly System.Reflection.Emit.OpCode Br;
public static readonly System.Reflection.Emit.OpCode Br_S;
public static readonly System.Reflection.Emit.OpCode Break;
public static readonly System.Reflection.Emit.OpCode Brfalse;
public static readonly System.Reflection.Emit.OpCode Brfalse_S;
public static readonly System.Reflection.Emit.OpCode Brtrue;
public static readonly System.Reflection.Emit.OpCode Brtrue_S;
public static readonly System.Reflection.Emit.OpCode Call;
public static readonly System.Reflection.Emit.OpCode Calli;
public static readonly System.Reflection.Emit.OpCode Callvirt;
public static readonly System.Reflection.Emit.OpCode Castclass;
public static readonly System.Reflection.Emit.OpCode Ceq;
public static readonly System.Reflection.Emit.OpCode Cgt;
public static readonly System.Reflection.Emit.OpCode Cgt_Un;
public static readonly System.Reflection.Emit.OpCode Ckfinite;
public static readonly System.Reflection.Emit.OpCode Clt;
public static readonly System.Reflection.Emit.OpCode Clt_Un;
public static readonly System.Reflection.Emit.OpCode Constrained;
public static readonly System.Reflection.Emit.OpCode Conv_I;
public static readonly System.Reflection.Emit.OpCode Conv_I1;
public static readonly System.Reflection.Emit.OpCode Conv_I2;
public static readonly System.Reflection.Emit.OpCode Conv_I4;
public static readonly System.Reflection.Emit.OpCode Conv_I8;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I_Un;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I1;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I1_Un;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I2;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I2_Un;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I4;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I4_Un;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I8;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I8_Un;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U_Un;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U1;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U1_Un;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U2;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U2_Un;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U4;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U4_Un;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U8;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U8_Un;
public static readonly System.Reflection.Emit.OpCode Conv_R_Un;
public static readonly System.Reflection.Emit.OpCode Conv_R4;
public static readonly System.Reflection.Emit.OpCode Conv_R8;
public static readonly System.Reflection.Emit.OpCode Conv_U;
public static readonly System.Reflection.Emit.OpCode Conv_U1;
public static readonly System.Reflection.Emit.OpCode Conv_U2;
public static readonly System.Reflection.Emit.OpCode Conv_U4;
public static readonly System.Reflection.Emit.OpCode Conv_U8;
public static readonly System.Reflection.Emit.OpCode Cpblk;
public static readonly System.Reflection.Emit.OpCode Cpobj;
public static readonly System.Reflection.Emit.OpCode Div;
public static readonly System.Reflection.Emit.OpCode Div_Un;
public static readonly System.Reflection.Emit.OpCode Dup;
public static readonly System.Reflection.Emit.OpCode Endfilter;
public static readonly System.Reflection.Emit.OpCode Endfinally;
public static readonly System.Reflection.Emit.OpCode Initblk;
public static readonly System.Reflection.Emit.OpCode Initobj;
public static readonly System.Reflection.Emit.OpCode Isinst;
public static readonly System.Reflection.Emit.OpCode Jmp;
public static readonly System.Reflection.Emit.OpCode Ldarg;
public static readonly System.Reflection.Emit.OpCode Ldarg_0;
public static readonly System.Reflection.Emit.OpCode Ldarg_1;
public static readonly System.Reflection.Emit.OpCode Ldarg_2;
public static readonly System.Reflection.Emit.OpCode Ldarg_3;
public static readonly System.Reflection.Emit.OpCode Ldarg_S;
public static readonly System.Reflection.Emit.OpCode Ldarga;
public static readonly System.Reflection.Emit.OpCode Ldarga_S;
public static readonly System.Reflection.Emit.OpCode Ldc_I4;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_0;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_1;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_2;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_3;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_4;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_5;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_6;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_7;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_8;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_M1;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_S;
public static readonly System.Reflection.Emit.OpCode Ldc_I8;
public static readonly System.Reflection.Emit.OpCode Ldc_R4;
public static readonly System.Reflection.Emit.OpCode Ldc_R8;
public static readonly System.Reflection.Emit.OpCode Ldelem;
public static readonly System.Reflection.Emit.OpCode Ldelem_I;
public static readonly System.Reflection.Emit.OpCode Ldelem_I1;
public static readonly System.Reflection.Emit.OpCode Ldelem_I2;
public static readonly System.Reflection.Emit.OpCode Ldelem_I4;
public static readonly System.Reflection.Emit.OpCode Ldelem_I8;
public static readonly System.Reflection.Emit.OpCode Ldelem_R4;
public static readonly System.Reflection.Emit.OpCode Ldelem_R8;
public static readonly System.Reflection.Emit.OpCode Ldelem_Ref;
public static readonly System.Reflection.Emit.OpCode Ldelem_U1;
public static readonly System.Reflection.Emit.OpCode Ldelem_U2;
public static readonly System.Reflection.Emit.OpCode Ldelem_U4;
public static readonly System.Reflection.Emit.OpCode Ldelema;
public static readonly System.Reflection.Emit.OpCode Ldfld;
public static readonly System.Reflection.Emit.OpCode Ldflda;
public static readonly System.Reflection.Emit.OpCode Ldftn;
public static readonly System.Reflection.Emit.OpCode Ldind_I;
public static readonly System.Reflection.Emit.OpCode Ldind_I1;
public static readonly System.Reflection.Emit.OpCode Ldind_I2;
public static readonly System.Reflection.Emit.OpCode Ldind_I4;
public static readonly System.Reflection.Emit.OpCode Ldind_I8;
public static readonly System.Reflection.Emit.OpCode Ldind_R4;
public static readonly System.Reflection.Emit.OpCode Ldind_R8;
public static readonly System.Reflection.Emit.OpCode Ldind_Ref;
public static readonly System.Reflection.Emit.OpCode Ldind_U1;
public static readonly System.Reflection.Emit.OpCode Ldind_U2;
public static readonly System.Reflection.Emit.OpCode Ldind_U4;
public static readonly System.Reflection.Emit.OpCode Ldlen;
public static readonly System.Reflection.Emit.OpCode Ldloc;
public static readonly System.Reflection.Emit.OpCode Ldloc_0;
public static readonly System.Reflection.Emit.OpCode Ldloc_1;
public static readonly System.Reflection.Emit.OpCode Ldloc_2;
public static readonly System.Reflection.Emit.OpCode Ldloc_3;
public static readonly System.Reflection.Emit.OpCode Ldloc_S;
public static readonly System.Reflection.Emit.OpCode Ldloca;
public static readonly System.Reflection.Emit.OpCode Ldloca_S;
public static readonly System.Reflection.Emit.OpCode Ldnull;
public static readonly System.Reflection.Emit.OpCode Ldobj;
public static readonly System.Reflection.Emit.OpCode Ldsfld;
public static readonly System.Reflection.Emit.OpCode Ldsflda;
public static readonly System.Reflection.Emit.OpCode Ldstr;
public static readonly System.Reflection.Emit.OpCode Ldtoken;
public static readonly System.Reflection.Emit.OpCode Ldvirtftn;
public static readonly System.Reflection.Emit.OpCode Leave;
public static readonly System.Reflection.Emit.OpCode Leave_S;
public static readonly System.Reflection.Emit.OpCode Localloc;
public static readonly System.Reflection.Emit.OpCode Mkrefany;
public static readonly System.Reflection.Emit.OpCode Mul;
public static readonly System.Reflection.Emit.OpCode Mul_Ovf;
public static readonly System.Reflection.Emit.OpCode Mul_Ovf_Un;
public static readonly System.Reflection.Emit.OpCode Neg;
public static readonly System.Reflection.Emit.OpCode Newarr;
public static readonly System.Reflection.Emit.OpCode Newobj;
public static readonly System.Reflection.Emit.OpCode Nop;
public static readonly System.Reflection.Emit.OpCode Not;
public static readonly System.Reflection.Emit.OpCode Or;
public static readonly System.Reflection.Emit.OpCode Pop;
public static readonly System.Reflection.Emit.OpCode Prefix1;
public static readonly System.Reflection.Emit.OpCode Prefix2;
public static readonly System.Reflection.Emit.OpCode Prefix3;
public static readonly System.Reflection.Emit.OpCode Prefix4;
public static readonly System.Reflection.Emit.OpCode Prefix5;
public static readonly System.Reflection.Emit.OpCode Prefix6;
public static readonly System.Reflection.Emit.OpCode Prefix7;
public static readonly System.Reflection.Emit.OpCode Prefixref;
public static readonly System.Reflection.Emit.OpCode Readonly;
public static readonly System.Reflection.Emit.OpCode Refanytype;
public static readonly System.Reflection.Emit.OpCode Refanyval;
public static readonly System.Reflection.Emit.OpCode Rem;
public static readonly System.Reflection.Emit.OpCode Rem_Un;
public static readonly System.Reflection.Emit.OpCode Ret;
public static readonly System.Reflection.Emit.OpCode Rethrow;
public static readonly System.Reflection.Emit.OpCode Shl;
public static readonly System.Reflection.Emit.OpCode Shr;
public static readonly System.Reflection.Emit.OpCode Shr_Un;
public static readonly System.Reflection.Emit.OpCode Sizeof;
public static readonly System.Reflection.Emit.OpCode Starg;
public static readonly System.Reflection.Emit.OpCode Starg_S;
public static readonly System.Reflection.Emit.OpCode Stelem;
public static readonly System.Reflection.Emit.OpCode Stelem_I;
public static readonly System.Reflection.Emit.OpCode Stelem_I1;
public static readonly System.Reflection.Emit.OpCode Stelem_I2;
public static readonly System.Reflection.Emit.OpCode Stelem_I4;
public static readonly System.Reflection.Emit.OpCode Stelem_I8;
public static readonly System.Reflection.Emit.OpCode Stelem_R4;
public static readonly System.Reflection.Emit.OpCode Stelem_R8;
public static readonly System.Reflection.Emit.OpCode Stelem_Ref;
public static readonly System.Reflection.Emit.OpCode Stfld;
public static readonly System.Reflection.Emit.OpCode Stind_I;
public static readonly System.Reflection.Emit.OpCode Stind_I1;
public static readonly System.Reflection.Emit.OpCode Stind_I2;
public static readonly System.Reflection.Emit.OpCode Stind_I4;
public static readonly System.Reflection.Emit.OpCode Stind_I8;
public static readonly System.Reflection.Emit.OpCode Stind_R4;
public static readonly System.Reflection.Emit.OpCode Stind_R8;
public static readonly System.Reflection.Emit.OpCode Stind_Ref;
public static readonly System.Reflection.Emit.OpCode Stloc;
public static readonly System.Reflection.Emit.OpCode Stloc_0;
public static readonly System.Reflection.Emit.OpCode Stloc_1;
public static readonly System.Reflection.Emit.OpCode Stloc_2;
public static readonly System.Reflection.Emit.OpCode Stloc_3;
public static readonly System.Reflection.Emit.OpCode Stloc_S;
public static readonly System.Reflection.Emit.OpCode Stobj;
public static readonly System.Reflection.Emit.OpCode Stsfld;
public static readonly System.Reflection.Emit.OpCode Sub;
public static readonly System.Reflection.Emit.OpCode Sub_Ovf;
public static readonly System.Reflection.Emit.OpCode Sub_Ovf_Un;
public static readonly System.Reflection.Emit.OpCode Switch;
public static readonly System.Reflection.Emit.OpCode Tailcall;
public static readonly System.Reflection.Emit.OpCode Throw;
public static readonly System.Reflection.Emit.OpCode Unaligned;
public static readonly System.Reflection.Emit.OpCode Unbox;
public static readonly System.Reflection.Emit.OpCode Unbox_Any;
public static readonly System.Reflection.Emit.OpCode Volatile;
public static readonly System.Reflection.Emit.OpCode Xor;
public static bool TakesSingleByteArgument(System.Reflection.Emit.OpCode inst) { return default(bool); }
}
public enum OpCodeType
{
Macro = 1,
Nternal = 2,
Objmodel = 3,
Prefix = 4,
Primitive = 5,
}
public enum OperandType
{
InlineBrTarget = 0,
InlineField = 1,
InlineI = 2,
InlineI8 = 3,
InlineMethod = 4,
InlineNone = 5,
InlineR = 7,
InlineSig = 9,
InlineString = 10,
InlineSwitch = 11,
InlineTok = 12,
InlineType = 13,
InlineVar = 14,
ShortInlineBrTarget = 15,
ShortInlineI = 16,
ShortInlineR = 17,
ShortInlineVar = 18,
}
public enum PackingSize
{
Size1 = 1,
Size128 = 128,
Size16 = 16,
Size2 = 2,
Size32 = 32,
Size4 = 4,
Size64 = 64,
Size8 = 8,
Unspecified = 0,
}
public enum StackBehaviour
{
Pop0 = 0,
Pop1 = 1,
Pop1_pop1 = 2,
Popi = 3,
Popi_pop1 = 4,
Popi_popi = 5,
Popi_popi_popi = 7,
Popi_popi8 = 6,
Popi_popr4 = 8,
Popi_popr8 = 9,
Popref = 10,
Popref_pop1 = 11,
Popref_popi = 12,
Popref_popi_pop1 = 28,
Popref_popi_popi = 13,
Popref_popi_popi8 = 14,
Popref_popi_popr4 = 15,
Popref_popi_popr8 = 16,
Popref_popi_popref = 17,
Push0 = 18,
Push1 = 19,
Push1_push1 = 20,
Pushi = 21,
Pushi8 = 22,
Pushr4 = 23,
Pushr8 = 24,
Pushref = 25,
Varpop = 26,
Varpush = 27,
}
}
| |
// 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 Xunit;
namespace System.Text.Tests
{
public class EncoderConvert2Encoder : Encoder
{
private Encoder _encoder = null;
public EncoderConvert2Encoder()
{
_encoder = Encoding.UTF8.GetEncoder();
}
public override int GetByteCount(char[] chars, int index, int count, bool flush)
{
if (index >= count)
throw new ArgumentException();
return _encoder.GetByteCount(chars, index, count, flush);
}
public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, bool flush)
{
return _encoder.GetBytes(chars, charIndex, charCount, bytes, byteIndex, flush);
}
}
// Convert(System.Char[],System.Int32,System.Int32,System.Byte[],System.Int32,System.Int32,System.Boolean,System.Int32@,System.Int32@,System.Boolean@)
public class EncoderConvert2
{
private const int c_SIZE_OF_ARRAY = 256;
private readonly RandomDataGenerator _generator = new RandomDataGenerator();
public static IEnumerable<object[]> Encoders_RandomInput()
{
yield return new object[] { Encoding.ASCII.GetEncoder() };
yield return new object[] { Encoding.UTF8.GetEncoder() };
yield return new object[] { Encoding.Unicode.GetEncoder() };
}
public static IEnumerable<object[]> Encoders_Convert()
{
yield return new object[] { Encoding.ASCII.GetEncoder(), 1 };
yield return new object[] { Encoding.UTF8.GetEncoder(), 1 };
yield return new object[] { Encoding.Unicode.GetEncoder(), 2 };
}
// Call Convert to convert a arbitrary character array encoders
[Theory]
[MemberData(nameof(Encoders_RandomInput))]
public void EncoderConvertRandomCharArray(Encoder encoder)
{
char[] chars = new char[c_SIZE_OF_ARRAY];
byte[] bytes = new byte[c_SIZE_OF_ARRAY];
for (int i = 0; i < chars.Length; ++i)
{
chars[i] = _generator.GetChar(-55);
}
int charsUsed;
int bytesUsed;
bool completed;
encoder.Convert(chars, 0, chars.Length, bytes, 0, bytes.Length, false, out charsUsed, out bytesUsed, out completed);
// set flush to true and try again
encoder.Convert(chars, 0, chars.Length, bytes, 0, bytes.Length, true, out charsUsed, out bytesUsed, out completed);
}
// Call Convert to convert a ASCII character array encoders
[Theory]
[MemberData(nameof(Encoders_Convert))]
public void EncoderConvertASCIICharArray(Encoder encoder, int multiplier)
{
char[] chars = "TestLibrary.TestFramework.BeginScenario".ToCharArray();
byte[] bytes = new byte[chars.Length * multiplier];
VerificationHelper(encoder, chars, 0, chars.Length, bytes, 0, bytes.Length, false, chars.Length, chars.Length * multiplier, expectedCompleted: true);
VerificationHelper(encoder, chars, 0, chars.Length, bytes, 0, bytes.Length, true, chars.Length, chars.Length * multiplier, expectedCompleted: true);
VerificationHelper(encoder, chars, 0, 0, bytes, 0, 0, true, 0, 0, expectedCompleted: true);
}
// Call Convert to convert a ASCII character array with user implemented encoder
[Fact]
public void EncoderCustomConvertASCIICharArray()
{
char[] chars = "TestLibrary.TestFramework.BeginScenario".ToCharArray();
byte[] bytes = new byte[chars.Length];
Encoder encoder = new EncoderConvert2Encoder();
VerificationHelper(encoder, chars, 0, chars.Length, bytes, 0, bytes.Length, false, chars.Length, chars.Length, expectedCompleted: true);
VerificationHelper(encoder, chars, 0, chars.Length, bytes, 0, bytes.Length, true, chars.Length, chars.Length, expectedCompleted: true);
}
// Call Convert to convert partial of a ASCII character array with UTF8 encoder
[Fact]
public void EncoderUTF8ConvertASCIICharArrayPartial()
{
char[] chars = "TestLibrary.TestFramework.BeginScenario".ToCharArray();
byte[] bytes = new byte[chars.Length];
Encoder encoder = Encoding.UTF8.GetEncoder();
VerificationHelper(encoder, chars, 0, 1, bytes, 0, 1, false, 1, 1, expectedCompleted: true);
VerificationHelper(encoder, chars, 0, 1, bytes, 0, 1, true, 1, 1, expectedCompleted: true);
VerificationHelper(encoder, chars, 1, 1, bytes, 0, 1, false, 1, 1, expectedCompleted: true);
VerificationHelper(encoder, chars, 1, 1, bytes, 0, 1, true, 1, 1, expectedCompleted: true);
VerificationHelper(encoder, chars, 1, 1, bytes, 1, 1, false, 1, 1, expectedCompleted: true);
VerificationHelper(encoder, chars, 1, 1, bytes, 1, 1, true, 1, 1, expectedCompleted: true);
// Verify maxBytes is large than character count
VerificationHelper(encoder, chars, 0, chars.Length - 1, bytes, 0, bytes.Length, false, chars.Length - 1, chars.Length - 1, expectedCompleted: true);
VerificationHelper(encoder, chars, 1, chars.Length - 1, bytes, 0, bytes.Length, true, chars.Length - 1, chars.Length - 1, expectedCompleted: true);
}
// Call Convert to convert partial of a ASCII character array with Unicode encoder
[Fact]
public void EncoderUnicodeConvertASCIICharArrayPartial()
{
char[] chars = "TestLibrary.TestFramework.BeginScenario".ToCharArray();
byte[] bytes = new byte[chars.Length * 2];
Encoder encoder = Encoding.Unicode.GetEncoder();
VerificationHelper(encoder, chars, 0, 1, bytes, 0, 2, false, 1, 2, expectedCompleted: true);
VerificationHelper(encoder, chars, 0, 1, bytes, 0, 2, true, 1, 2, expectedCompleted: true);
VerificationHelper(encoder, chars, 1, 1, bytes, 0, 2, false, 1, 2, expectedCompleted: true);
VerificationHelper(encoder, chars, 1, 1, bytes, 0, 2, true, 1, 2, expectedCompleted: true);
VerificationHelper(encoder, chars, 1, 1, bytes, 1, 2, false, 1, 2, expectedCompleted: true);
VerificationHelper(encoder, chars, 1, 1, bytes, 1, 2, true, 1, 2, expectedCompleted: true);
VerificationHelper(encoder, chars, 0, 1, bytes, 0, bytes.Length, false, 1, 2, expectedCompleted: true);
VerificationHelper(encoder, chars, 0, 1, bytes, 0, bytes.Length, true, 1, 2, expectedCompleted: true);
}
// Call Convert to convert a Unicode character array with Unicode encoder
[Fact]
public void EncoderUnicodeConvertUnicodeCharArray()
{
char[] chars = "\u8FD9\u4E2A\u4E00\u4E2A\u6D4B\u8BD5".ToCharArray();
byte[] bytes = new byte[chars.Length * 2];
Encoder encoder = Encoding.Unicode.GetEncoder();
VerificationHelper(encoder, chars, 0, chars.Length, bytes, 0, bytes.Length, false, chars.Length, bytes.Length, expectedCompleted: true);
VerificationHelper(encoder, chars, 0, chars.Length, bytes, 0, bytes.Length, true, chars.Length, bytes.Length, expectedCompleted: true);
}
// Call Convert to convert partial of a Unicode character array with Unicode encoder
[Fact]
public void EncoderUnicodeConvertUnicodeCharArrayPartial()
{
char[] chars = "\u8FD9\u4E2A\u4E00\u4E2A\u6D4B\u8BD5".ToCharArray();
byte[] bytes = new byte[chars.Length * 2];
Encoder encoder = Encoding.Unicode.GetEncoder();
VerificationHelper(encoder, chars, 0, 1, bytes, 0, 2, false, 1, 2, expectedCompleted: true);
VerificationHelper(encoder, chars, 0, 1, bytes, 0, 2, true, 1, 2, expectedCompleted: true);
VerificationHelper(encoder, chars, 1, 1, bytes, 0, 2, false, 1, 2, expectedCompleted: true);
VerificationHelper(encoder, chars, 1, 1, bytes, 0, 2, true, 1, 2, expectedCompleted: true);
VerificationHelper(encoder, chars, 1, 1, bytes, 1, 2, false, 1, 2, expectedCompleted: true);
VerificationHelper(encoder, chars, 1, 1, bytes, 1, 2, true, 1, 2, expectedCompleted: true);
VerificationHelper(encoder, chars, 0, 1, bytes, 0, bytes.Length, false, 1, 2, expectedCompleted: true);
VerificationHelper(encoder, chars, 0, 1, bytes, 0, bytes.Length, true, 1, 2, expectedCompleted: true);
}
// Call Convert to convert partial of a ASCII character array with ASCII encoder
[Fact]
public void EncoderASCIIConvertASCIICharArrayPartial()
{
char[] chars = "TestLibrary.TestFramework.BeginScenario".ToCharArray();
byte[] bytes = new byte[chars.Length];
Encoder encoder = Encoding.ASCII.GetEncoder();
VerificationHelper(encoder, chars, 0, 1, bytes, 0, 1, false, 1, 1, expectedCompleted: true);
VerificationHelper(encoder, chars, 0, 1, bytes, 0, 1, true, 1, 1, expectedCompleted: true);
VerificationHelper(encoder, chars, 1, 1, bytes, 0, 1, false, 1, 1, expectedCompleted: true);
VerificationHelper(encoder, chars, 1, 1, bytes, 0, 1, true, 1, 1, expectedCompleted: true);
VerificationHelper(encoder, chars, 1, 1, bytes, 1, 1, false, 1, 1, expectedCompleted: true);
VerificationHelper(encoder, chars, 1, 1, bytes, 1, 1, true, 1, 1, expectedCompleted: true);
// Verify maxBytes is large than character count
VerificationHelper(encoder, chars, 0, chars.Length - 1, bytes, 0, bytes.Length, false, chars.Length - 1, chars.Length - 1, expectedCompleted: true);
VerificationHelper(encoder, chars, 1, chars.Length - 1, bytes, 0, bytes.Length, true, chars.Length - 1, chars.Length - 1, expectedCompleted: true);
}
// Call Convert to convert partial of a Unicode character array with ASCII encoder
[Fact]
public void EncoderASCIIConvertUnicodeCharArrayPartial()
{
char[] chars = "\uD83D\uDE01Test".ToCharArray();
byte[] bytes = new byte[chars.Length * 2];
Encoder encoder = Encoding.ASCII.GetEncoder();
VerificationHelper(encoder, chars, 0, 1, bytes, 0, 1, true, 1, 1, expectedCompleted: true);
VerificationHelper(encoder, chars, 0, 1, bytes, 0, 1, false, 1, 1, expectedCompleted: true);
VerificationHelper(encoder, chars, 0, 2, bytes, 0, 2, false, 2, 2, expectedCompleted: true);
VerificationHelper(encoder, chars, 0, 4, bytes, 0, 4, false, 4, 4, expectedCompleted: true);
VerificationHelper(encoder, chars, 0, 4, bytes, 0, 4, true, 4, 4, expectedCompleted: true);
VerificationHelper(encoder, chars, 2, 2, bytes, 0, 2, true, 2, 2, expectedCompleted: true);
VerificationHelper(encoder, chars, 1, 3, bytes, 1, 3, false, 3, 3, expectedCompleted: true);
VerificationHelper(encoder, chars, 1, 3, bytes, 1, 5, true, 3, 3, expectedCompleted: true);
VerificationHelper(encoder, chars, 0, 1, bytes, 0, bytes.Length, false, 1, 1, expectedCompleted: true);
VerificationHelper(encoder, chars, 1, 1, bytes, 0, bytes.Length, true, 1, 1, expectedCompleted: true);
}
// Call Convert to convert partial of a Unicode character array with UTF8 encoder
[Fact]
public void EncoderUTF8ConvertUnicodeCharArrayPartial()
{
char[] chars = "\uD83D\uDE01Test".ToCharArray();
byte[] bytes = new byte[chars.Length * 2];
Encoder encoder = Encoding.UTF8.GetEncoder();
VerificationHelper(encoder, chars, 0, 1, bytes, 0, 0, true, 1, 0, expectedCompleted: true);
VerificationHelper(encoder, chars, 0, 1, bytes, 0, 3, false, 1, 3, expectedCompleted: true);
VerificationHelper(encoder, chars, 0, 2, bytes, 0, 7, false, 2, 7, expectedCompleted: true);
VerificationHelper(encoder, chars, 0, 4, bytes, 0, 6, false, 4, 6, expectedCompleted: true);
VerificationHelper(encoder, chars, 0, 4, bytes, 0, 6, true, 4, 6, expectedCompleted: true);
VerificationHelper(encoder, chars, 2, 2, bytes, 0, 2, true, 2, 2, expectedCompleted: true);
VerificationHelper(encoder, chars, 1, 3, bytes, 1, 3, false, 1, 3, expectedCompleted: false);
VerificationHelper(encoder, chars, 1, 3, bytes, 1, 5, true, 3, 5, expectedCompleted: true);
VerificationHelper(encoder, chars, 0, 1, bytes, 0, bytes.Length, false, 1, 0, expectedCompleted: true);
VerificationHelper(encoder, chars, 1, 1, bytes, 0, bytes.Length, true, 1, 4, expectedCompleted: true);
}
// Call Convert to convert partial of a ASCII+Unicode character array with ASCII encoder
[Fact]
public void EncoderASCIIConvertMixedASCIIUnicodeCharArrayPartial()
{
char[] chars = "T\uD83D\uDE01est".ToCharArray();
byte[] bytes = new byte[chars.Length * 2];
Encoder encoder = Encoding.ASCII.GetEncoder();
VerificationHelper(encoder, chars, 0, 1, bytes, 0, 1, true, 1, 1, expectedCompleted: true);
VerificationHelper(encoder, chars, 0, 2, bytes, 0, 1, false, 1, 1, expectedCompleted: false);
VerificationHelper(encoder, chars, 1, 2, bytes, 0, 2, false, 2, 2, expectedCompleted: true);
VerificationHelper(encoder, chars, 0, 5, bytes, 0, 5, false, 5, 5, expectedCompleted: true);
VerificationHelper(encoder, chars, 0, 4, bytes, 0, 4, true, 4, 4, expectedCompleted: true);
VerificationHelper(encoder, chars, 2, 2, bytes, 0, 2, true, 2, 2, expectedCompleted: true);
VerificationHelper(encoder, chars, 1, 3, bytes, 1, 5, false, 3, 3, expectedCompleted: true);
VerificationHelper(encoder, chars, 1, 3, bytes, 1, 3, true, 3, 3, expectedCompleted: true);
VerificationHelper(encoder, chars, 0, 2, bytes, 0, bytes.Length, false, 2, 2, expectedCompleted: true);
VerificationHelper(encoder, chars, 1, 1, bytes, 0, bytes.Length, true, 1, 1, expectedCompleted: true);
}
// Call Convert to convert partial of a ASCII+Unicode character array with UTF8 encoder
[Fact]
public void EncoderUTF8ConvertMixedASCIIUnicodeCharArrayPartial()
{
char[] chars = "T\uD83D\uDE01est".ToCharArray();
byte[] bytes = new byte[chars.Length * 2];
Encoder encoder = Encoding.UTF8.GetEncoder();
VerificationHelper(encoder, chars, 0, 1, bytes, 0, 1, true, 1, 1, expectedCompleted: true);
VerificationHelper(encoder, chars, 0, 2, bytes, 0, 1, false, 2, 1, expectedCompleted: true);
VerificationHelper(encoder, chars, 1, 2, bytes, 0, 7, false, 2, 7, expectedCompleted: true);
VerificationHelper(encoder, chars, 0, 5, bytes, 0, 7, false, 5, 7, expectedCompleted: true);
VerificationHelper(encoder, chars, 0, 4, bytes, 0, 6, true, 4, 6, expectedCompleted: true);
VerificationHelper(encoder, chars, 2, 2, bytes, 0, 3, true, 1, 3, expectedCompleted: false);
VerificationHelper(encoder, chars, 1, 3, bytes, 1, 5, false, 3, 5, expectedCompleted: true);
VerificationHelper(encoder, chars, 1, 3, bytes, 1, 5, true, 3, 5, expectedCompleted: true);
VerificationHelper(encoder, chars, 0, 2, bytes, 0, bytes.Length, false, 2, 1, expectedCompleted: true);
VerificationHelper(encoder, chars, 1, 1, bytes, 0, bytes.Length, true, 1, 3, expectedCompleted: true);
}
private void VerificationHelper(Encoder encoder, char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex, int byteCount, bool flush, int expectedCharsUsed, int expectedBytesUsed,
bool expectedCompleted)
{
int charsUsed;
int bytesUsed;
bool completed;
encoder.Convert(chars, charIndex, charCount, bytes, byteIndex, byteCount, false, out charsUsed, out bytesUsed, out completed);
Assert.Equal(expectedCharsUsed, charsUsed);
Assert.Equal(expectedBytesUsed, bytesUsed);
Assert.Equal(expectedCompleted, completed);
}
}
}
| |
/*
| Version 10.1.84
| Copyright 2013 Esri
|
| Licensed under the Apache License, Version 2.0 (the "License");
| you may not use this file except in compliance with the License.
| You may obtain a copy of the License at
|
| http://www.apache.org/licenses/LICENSE-2.0
|
| Unless required by applicable law or agreed to in writing, software
| distributed under the License is distributed on an "AS IS" BASIS,
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
| See the License for the specific language governing permissions and
| limitations under the License.
*/
using System;
using System.Collections.Generic;
using ESRI.ArcLogistics.Data;
using ESRI.ArcLogistics.DomainObjects;
using System.Collections.ObjectModel;
namespace ESRI.ArcLogistics.App
{
/// <summary>
/// ScheduleHelper class.
/// </summary>
internal class ScheduleHelper
{
#region Public methods
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Get schedule by day
/// </summary>
/// <param name="schedule"></param>
/// <returns></returns>
public static Schedule GetCurrentScheduleByDay(DateTime day)
{
IDataObjectCollection<Schedule> schedules = App.Current.Project.Schedules.Search(day);
Schedule selectedSchedule = null;
foreach (Schedule schedule in schedules)
{
if (ScheduleType.Current == schedule.Type)
{
selectedSchedule = schedule;
break;
}
}
return selectedSchedule;
}
/// <summary>
/// Shows does schedule have built routes
/// </summary>
/// <param name="schedule"></param>
/// <returns></returns>
public static bool DoesScheduleHaveBuiltRoutes(Schedule schedule)
{
bool isEmpty = true;
if (null != schedule)
{
foreach (Route route in schedule.Routes)
{
IDataObjectCollection<Stop> stops = route.Stops;
if ((null != stops) && (0 < stops.Count))
{
isEmpty = false;
break;
}
}
}
return !isEmpty;
}
/// <summary>
/// Get schedule list for dates range
/// </summary>
/// <param name="schedule"></param>
/// <returns></returns>
public static ICollection<Schedule> GetCurrentSchedulesByDates(DateTime dayStart, DateTime dayFinish,
bool excludeEmpty)
{
List<Schedule> schedules = new List<Schedule>();
DateTime day = dayStart;
while (day <= dayFinish)
{
Schedule schedule = GetCurrentScheduleByDay(day);
if (null != schedule)
{
if (!excludeEmpty || DoesScheduleHaveBuiltRoutes(schedule))
schedules.Add(schedule);
}
day = day.AddDays(1);
}
return schedules.AsReadOnly();
}
/// <summary>
/// Method returns common collection of assigned and unassigned orders
/// </summary>
/// <param name="schedule"></param>
/// <returns></returns>
public static ICollection<Order> GetScheduleOrders(Schedule schedule)
{
List<Order> orders = new List<Order>();
foreach (Order unassignedOrder in schedule.UnassignedOrders)
orders.Add(unassignedOrder);
foreach (Route route in schedule.Routes)
{
if (route.Stops.Count > 0)
{
foreach (Stop stop in route.Stops)
if (stop.AssociatedObject is Order)
orders.Add((Order)stop.AssociatedObject);
}
}
return orders.AsReadOnly();
}
/// <summary>
/// Method checks is any schedule in date bound with any order
/// </summary>
/// <param name="orders"></param>
/// <param name="targetDate"></param>
/// <returns></returns>
public static bool IsAnyOrderAssignedToSchedule(IList<Order> orders, DateTime targetDate)
{
bool ordersHaveBoundSchedule = false;
if (orders.Count == 0)
return false;
IList<Schedule> schedules = App.Current.Project.Schedules.Search(targetDate);
foreach (Schedule schedule in schedules)
{
if (schedule.UnassignedOrders != null)
{
if (schedule.UnassignedOrders.Count == 0)
ordersHaveBoundSchedule = true;
else
{
foreach (Order order in orders)
{
if (!schedule.UnassignedOrders.Contains(order))
{
ordersHaveBoundSchedule = true;
break;
}
}
}
}
else if (schedule.Routes != null && DoesScheduleHaveBuiltRoutes(schedule))
{
foreach (Route route in schedule.Routes)
{
if (route.Stops.Count > 0)
{
foreach (Stop stop in route.Stops)
if (stop.AssociatedObject is Order && orders.Contains((Order)stop.AssociatedObject))
{
ordersHaveBoundSchedule = true;
break;
}
}
if (ordersHaveBoundSchedule)
break;
}
}
if (ordersHaveBoundSchedule)
break;
}
return ordersHaveBoundSchedule;
}
/// <summary>
/// Method returns collection of locked orders and appropriate schedules
/// </summary>
/// <param name="orders"></param>
/// <param name="targetDate"></param>
/// <returns></returns>
public static Dictionary<Schedule, Collection<Order>> GetLockedOrdersSchedules(ICollection<Order> orders, DateTime targetDate)
{
Dictionary<Schedule, Collection<Order>> lockedOrderSchedules = new Dictionary<Schedule, Collection<Order>>();
IList<Schedule> schedules = App.Current.Project.Schedules.Search(targetDate);
foreach (Schedule schedule in schedules)
{
if (schedule.Routes != null)
foreach (Route route in schedule.Routes)
{
foreach (Stop stop in route.Stops)
if (stop.AssociatedObject is Order && orders.Contains((Order)stop.AssociatedObject) && (stop.IsLocked || route.IsLocked))
{
if (!lockedOrderSchedules.ContainsKey(schedule))
lockedOrderSchedules.Add(schedule, new Collection<Order>());
lockedOrderSchedules[schedule].Add((Order)stop.AssociatedObject);
}
}
}
return lockedOrderSchedules;
}
#endregion // Public methods
}
}
| |
//
// Encog(tm) Core v3.2 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using Encog.ML.Data;
using Encog.Neural.Networks.Training.Strategy;
using Encog.Util.Validate;
namespace Encog.Neural.Networks.Training.Propagation.Back
{
/// <summary>
/// This class implements a backpropagation training algorithm for feed forward
/// neural networks. It is used in the same manner as any other training class
/// that implements the Train interface.
/// Backpropagation is a common neural network training algorithm. It works by
/// analyzing the error of the output of the neural network. Each neuron in the
/// output layer's contribution, according to weight, to this error is
/// determined. These weights are then adjusted to minimize this error. This
/// process continues working its way backwards through the layers of the neural
/// network.
/// This implementation of the backpropagation algorithm uses both momentum and a
/// learning rate. The learning rate specifies the degree to which the weight
/// matrixes will be modified through each iteration. The momentum specifies how
/// much the previous learning iteration affects the current. To use no momentum
/// at all specify zero.
/// One primary problem with backpropagation is that the magnitude of the partial
/// derivative is often detrimental to the training of the neural network. The
/// other propagation methods of Manhatten and Resilient address this issue in
/// different ways. In general, it is suggested that you use the resilient
/// propagation technique for most Encog training tasks over back propagation.
/// </summary>
///
public class Backpropagation : Propagation, IMomentum,
ILearningRate
{
/// <summary>
/// The resume key for backpropagation.
/// </summary>
///
public const String PropertyLastDelta = "LAST_DELTA";
/// <summary>
/// The last delta values.
/// </summary>
///
private double[] _lastDelta;
/// <summary>
/// The learning rate.
/// </summary>
///
private double _learningRate;
/// <summary>
/// The momentum.
/// </summary>
///
private double _momentum;
/// <summary>
/// Create a class to train using backpropagation. Use auto learn rate and
/// momentum. Use the CPU to train.
/// </summary>
///
/// <param name="network">The network that is to be trained.</param>
/// <param name="training">The training data to be used for backpropagation.</param>
public Backpropagation(IContainsFlat network, IMLDataSet training) : this(network, training, 0, 0)
{
AddStrategy(new SmartLearningRate());
AddStrategy(new SmartMomentum());
}
/// <param name="network">The network that is to be trained</param>
/// <param name="training">The training set</param>
/// <param name="learnRate"></param>
/// <param name="momentum"></param>
public Backpropagation(IContainsFlat network,
IMLDataSet training, double learnRate,
double momentum) : base(network, training)
{
ValidateNetwork.ValidateMethodToData(network, training);
_momentum = momentum;
_learningRate = learnRate;
_lastDelta = new double[Network.Flat.Weights.Length];
}
/// <inheritdoc />
public override sealed bool CanContinue
{
get { return true; }
}
/// <value>Ther last delta values.</value>
public double[] LastDelta
{
get { return _lastDelta; }
}
#region ILearningRate Members
/// <summary>
/// Set the learning rate, this is value is essentially a percent. It is the
/// degree to which the gradients are applied to the weight matrix to allow
/// learning.
/// </summary>
public virtual double LearningRate
{
get { return _learningRate; }
set { _learningRate = value; }
}
#endregion
#region IMomentum Members
/// <summary>
/// Set the momentum for training. This is the degree to which changes from
/// which the previous training iteration will affect this training
/// iteration. This can be useful to overcome local minima.
/// </summary>
public virtual double Momentum
{
get { return _momentum; }
set { _momentum = value; }
}
#endregion
/// <summary>
/// Determine if the specified continuation object is valid to resume with.
/// </summary>
///
/// <param name="state">The continuation object to check.</param>
/// <returns>True if the specified continuation object is valid for this
/// training method and network.</returns>
public bool IsValidResume(TrainingContinuation state)
{
if (!state.Contents.ContainsKey(PropertyLastDelta))
{
return false;
}
if (!state.TrainingType.Equals(GetType().Name))
{
return false;
}
var d = (double[])state.Get(PropertyLastDelta);
return d.Length == ((IContainsFlat) Method).Flat.Weights.Length;
}
/// <summary>
/// Pause the training.
/// </summary>
///
/// <returns>A training continuation object to continue with.</returns>
public override sealed TrainingContinuation Pause()
{
var result = new TrainingContinuation {TrainingType = GetType().Name};
result.Set(PropertyLastDelta, _lastDelta);
return result;
}
/// <summary>
/// Resume training.
/// </summary>
///
/// <param name="state">The training state to return to.</param>
public override sealed void Resume(TrainingContinuation state)
{
if (!IsValidResume(state))
{
throw new TrainingError("Invalid training resume data length");
}
_lastDelta = (double[])state.Get(PropertyLastDelta);
}
/// <summary>
/// Update a weight.
/// </summary>
///
/// <param name="gradients">The gradients.</param>
/// <param name="lastGradient">The last gradients.</param>
/// <param name="index">The index.</param>
/// <returns>The weight delta.</returns>
public override double UpdateWeight(double[] gradients,
double[] lastGradient, int index)
{
double delta = (gradients[index] * _learningRate)
+ (_lastDelta[index] * _momentum);
_lastDelta[index] = delta;
return delta;
}
/// <summary>
/// Not needed for this training type.
/// </summary>
public override void InitOthers()
{
}
}
}
| |
#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):
//
// Erik Ejlskov Jensen, http://erikej.blogspot.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: SqlServerCompactErrorLog.cs 925 2011-12-23 22:46:09Z azizatif $")]
namespace Elmah
{
#region Imports
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlServerCe;
using System.IO;
using IDictionary = System.Collections.IDictionary;
#endregion
/// <summary>
/// An <see cref="ErrorLog"/> implementation that uses SQL Server
/// Compact 4 as its backing store.
/// </summary>
public class SqlServerCompactErrorLog : ErrorLog
{
private readonly string _connectionString;
/// <summary>
/// Initializes a new instance of the <see cref="SqlServerCompactErrorLog"/> class
/// using a dictionary of configured settings.
/// </summary>
public SqlServerCompactErrorLog(IDictionary config)
{
if (config == null)
throw new ArgumentNullException("config");
var connectionString = ConnectionStringHelper.GetConnectionString(config, true);
//
// If there is no connection string to use then throw an
// exception to abort construction.
//
if (connectionString.Length == 0)
throw new Elmah.ApplicationException("Connection string is missing for the SQL Server Compact error log.");
_connectionString = connectionString;
InitializeDatabase();
ApplicationName = (string) config["applicationName"] ?? string.Empty;
}
/// <summary>
/// Initializes a new instance of the <see cref="SqlServerCompactErrorLog"/> class
/// to use a specific connection string for connecting to the database.
/// </summary>
public SqlServerCompactErrorLog(string connectionString)
{
if (connectionString == null)
throw new ArgumentNullException("connectionString");
if (connectionString.Length == 0)
throw new ArgumentException(null, "connectionString");
_connectionString = ConnectionStringHelper.GetResolvedConnectionString(connectionString);
InitializeDatabase();
}
private void InitializeDatabase()
{
var connectionString = ConnectionString;
Debug.AssertStringNotEmpty(connectionString);
var dbFilePath = ConnectionStringHelper.GetDataSourceFilePath(connectionString);
if (File.Exists(dbFilePath))
return;
using (var engine = new SqlCeEngine(ConnectionString))
{
engine.CreateDatabase();
}
using (var conn = new SqlCeConnection(ConnectionString))
{
using (var cmd = new SqlCeCommand())
{
conn.Open();
var transaction = conn.BeginTransaction();
try
{
cmd.Connection = conn;
cmd.Transaction = transaction;
cmd.CommandText = @"
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'ELMAH_Error'";
var obj = cmd.ExecuteScalar();
if (obj == null)
{
cmd.CommandText = @"
CREATE TABLE ELMAH_Error (
[ErrorId] UNIQUEIDENTIFIER NOT NULL PRIMARY KEY DEFAULT newid(),
[Application] NVARCHAR(60) NOT NULL,
[Host] NVARCHAR(50) NOT NULL,
[Type] NVARCHAR(100) NOT NULL,
[Source] NVARCHAR(60) NOT NULL,
[Message] NVARCHAR(500) NOT NULL,
[User] NVARCHAR(50) NOT NULL,
[StatusCode] INT NOT NULL,
[TimeUtc] DATETIME NOT NULL,
[Sequence] INT IDENTITY (1, 1) NOT NULL,
[AllXml] NTEXT NOT NULL
)";
cmd.ExecuteNonQuery();
cmd.CommandText = @"
CREATE NONCLUSTERED INDEX [IX_Error_App_Time_Seq] ON [ELMAH_Error]
(
[Application] ASC,
[TimeUtc] DESC,
[Sequence] DESC
)";
cmd.ExecuteNonQuery();
}
transaction.Commit(CommitMode.Immediate);
}
catch (SqlCeException)
{
transaction.Rollback();
throw;
}
}
}
}
/// <summary>
/// Gets the name of this error log implementation.
/// </summary>
public override string Name
{
get { return "SQL Server Compact Error Log"; }
}
/// <summary>
/// Gets the connection string used by the log to connect to the database.
/// </summary>
public virtual string ConnectionString
{
get { return _connectionString; }
}
/// <summary>
/// Logs an error to the database.
/// </summary>
/// <remarks>
/// Use the stored procedure called by this implementation to set a
/// policy on how long errors are kept in the log. The default
/// implementation stores all errors for an indefinite time.
/// </remarks>
public override string Log(Error error)
{
if (error == null)
throw new ArgumentNullException("error");
var errorXml = ErrorXml.EncodeString(error);
var id = Guid.NewGuid();
const string query = @"
INSERT INTO ELMAH_Error (
[ErrorId], [Application], [Host],
[Type], [Source], [Message], [User], [StatusCode],
[TimeUtc], [AllXml] )
VALUES (
@ErrorId, @Application, @Host,
@Type, @Source, @Message, @User, @StatusCode,
@TimeUtc, @AllXml);";
using (var connection = new SqlCeConnection(ConnectionString))
{
using (var command = new SqlCeCommand(query, connection))
{
var parameters = command.Parameters;
parameters.Add("@ErrorId", SqlDbType.UniqueIdentifier).Value = id;
parameters.Add("@Application", SqlDbType.NVarChar, 60).Value = ApplicationName;
parameters.Add("@Host", SqlDbType.NVarChar, 30).Value = error.HostName;
parameters.Add("@Type", SqlDbType.NVarChar, 100).Value = error.Type;
parameters.Add("@Source", SqlDbType.NVarChar, 60).Value = error.Source;
parameters.Add("@Message", SqlDbType.NVarChar, 500).Value = error.Message;
parameters.Add("@User", SqlDbType.NVarChar, 50).Value = error.User;
parameters.Add("@StatusCode", SqlDbType.Int).Value = error.StatusCode;
parameters.Add("@TimeUtc", SqlDbType.DateTime).Value = error.Time.ToUniversalTime();
parameters.Add("@AllXml", SqlDbType.NText).Value = errorXml;
command.Connection = connection;
connection.Open();
command.ExecuteNonQuery();
return id.ToString();
}
}
}
/// <summary>
/// Returns a page of errors from the databse in descending order
/// of logged time.
/// </summary>
///
public override int GetErrors(int pageIndex, int pageSize, ICollection<ErrorLogEntry> errorEntryList)
{
if (pageIndex < 0)
throw new ArgumentOutOfRangeException("pageIndex", pageIndex, null);
if (pageSize < 0)
throw new ArgumentOutOfRangeException("pageSize", pageSize, null);
const string sql = @"
SELECT
[ErrorId],
[Application],
[Host],
[Type],
[Source],
[Message],
[User],
[StatusCode],
[TimeUtc]
FROM
[ELMAH_Error]
ORDER BY
[TimeUtc] DESC,
[Sequence] DESC
OFFSET @PageSize * @PageIndex ROWS FETCH NEXT @PageSize ROWS ONLY;
";
const string getCount = @"
SELECT COUNT(*) FROM [ELMAH_Error]";
using (var connection = new SqlCeConnection(ConnectionString))
{
connection.Open();
using (var command = new SqlCeCommand(sql, connection))
{
var parameters = command.Parameters;
parameters.Add("@PageIndex", SqlDbType.Int).Value = pageIndex;
parameters.Add("@PageSize", SqlDbType.Int).Value = pageSize;
parameters.Add("@Application", SqlDbType.NVarChar, 60).Value = ApplicationName;
using (var reader = command.ExecuteReader())
{
if (errorEntryList != null)
{
while (reader.Read())
{
var id = reader["ErrorId"].ToString();
var error = new Elmah.Error();
error.ApplicationName = reader["Application"].ToString();
error.HostName = reader["Host"].ToString();
error.Type = reader["Type"].ToString();
error.Source = reader["Source"].ToString();
error.Message = reader["Message"].ToString();
error.User = reader["User"].ToString();
error.StatusCode = Convert.ToInt32(reader["StatusCode"]);
error.Time = Convert.ToDateTime(reader["TimeUtc"]).ToLocalTime();
errorEntryList.Add(new ErrorLogEntry(this, id, error));
}
}
}
}
using (var command = new SqlCeCommand(getCount, connection))
{
return (int)command.ExecuteScalar();
}
}
}
/// <summary>
/// Returns the specified error from the database, or null
/// if it does not exist.
/// </summary>
public override ErrorLogEntry GetError(string id)
{
if (id == null)
throw new ArgumentNullException("id");
if (id.Length == 0)
throw new ArgumentException(null, "id");
Guid errorGuid;
try
{
errorGuid = new Guid(id);
}
catch (FormatException e)
{
throw new ArgumentException(e.Message, "id", e);
}
const string sql = @"
SELECT
[AllXml]
FROM
[ELMAH_Error]
WHERE
[ErrorId] = @ErrorId";
using (var connection = new SqlCeConnection(ConnectionString))
{
using (var command = new SqlCeCommand(sql, connection))
{
command.Parameters.Add("@ErrorId", SqlDbType.UniqueIdentifier).Value = errorGuid;
connection.Open();
var errorXml = (string)command.ExecuteScalar();
if (errorXml == null)
return null;
var error = ErrorXml.DecodeString(errorXml);
return new ErrorLogEntry(this, id, error);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ConvertScalarToVector128DoubleDouble()
{
var test = new SimpleBinaryOpConvTest__ConvertScalarToVector128DoubleDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpConvTest__ConvertScalarToVector128DoubleDouble
{
private struct TestStruct
{
public Vector128<Double> _fld1;
public Int64 _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
_data2 = TestLibrary.Generator.GetInt64();
testStruct._fld2 = _data2;
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpConvTest__ConvertScalarToVector128DoubleDouble testClass)
{
var result = Sse2.X64.ConvertScalarToVector128Double(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Int64 _data2;
private static Vector128<Double> _clsVar1;
private static Int64 _clsVar2;
private Vector128<Double> _fld1;
private Int64 _fld2;
private SimpleBinaryOpConvTest__DataTable<Double, Double, Int64> _dataTable;
static SimpleBinaryOpConvTest__ConvertScalarToVector128DoubleDouble()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
_data2 = TestLibrary.Generator.GetInt64();
_clsVar2 = _data2;
}
public SimpleBinaryOpConvTest__ConvertScalarToVector128DoubleDouble()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
_data2 = TestLibrary.Generator.GetInt64();
_fld2 = _data2;
_dataTable = new SimpleBinaryOpConvTest__DataTable<Double, Double, Int64>(_data1, _data2, new Double[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.X64.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.X64.ConvertScalarToVector128Double(
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
_dataTable.inData2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inData2, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.X64.ConvertScalarToVector128Double(
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
_dataTable.inData2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inData2, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.X64.ConvertScalarToVector128Double(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
_dataTable.inData2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inData2, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2.X64).GetMethod(nameof(Sse2.X64.ConvertScalarToVector128Double), new Type[] { typeof(Vector128<Double>), typeof(Int64) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
_dataTable.inData2
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inData2, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2.X64).GetMethod(nameof(Sse2.X64.ConvertScalarToVector128Double), new Type[] { typeof(Vector128<Double>), typeof(Int64) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
_dataTable.inData2
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inData2, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2.X64).GetMethod(nameof(Sse2.X64.ConvertScalarToVector128Double), new Type[] { typeof(Vector128<Double>), typeof(Int64) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
_dataTable.inData2
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inData2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.X64.ConvertScalarToVector128Double(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var left = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr);
var right = _dataTable.inData2;
var result = Sse2.X64.ConvertScalarToVector128Double(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var left = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr));
var right = _dataTable.inData2;
var result = Sse2.X64.ConvertScalarToVector128Double(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var left = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr));
var right = _dataTable.inData2;
var result = Sse2.X64.ConvertScalarToVector128Double(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpConvTest__ConvertScalarToVector128DoubleDouble();
var result = Sse2.X64.ConvertScalarToVector128Double(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.X64.ConvertScalarToVector128Double(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.X64.ConvertScalarToVector128Double(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Double> left, Int64 right, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), left);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, right, outArray, method);
}
private void ValidateResult(void* left, Int64 right, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, right, outArray, method);
}
private void ValidateResult(Double[] left, Int64 right, Double[] result, [CallerMemberName] string method = "")
{
if ((double)right != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != left[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2.X64)}.{nameof(Sse2.X64.ConvertScalarToVector128Double)}<Double>(Vector128<Double>, Int64): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
}
}
}
}
| |
using Bridge.Html5;
using Bridge.Test.NUnit;
using System;
using System.Collections.Generic;
namespace Bridge.ClientTest.Collections.Native
{
[Category(Constants.MODULE_TYPEDARRAYS)]
[TestFixture(TestNameFormat = "Uint8ArrayTests - {0}")]
public class Uint8ArrayTests
{
private void AssertContent(Uint8Array actual, int[] expected, string message)
{
if (actual.Length != expected.Length)
{
Assert.Fail(message + ": Expected length " + expected.Length + ", actual: " + actual.Length);
return;
}
for (int i = 0; i < expected.Length; i++)
{
if (actual[i] != expected[i])
{
Assert.Fail(message + ": Position " + i + ": expected " + expected[i] + ", actual: " + actual[i]);
return;
}
}
Assert.True(true, message);
}
[Test]
public void LengthConstructorWorks()
{
var arr = new Uint8Array(13);
Assert.True((object)arr is Uint8Array, "is Uint8Array");
Assert.AreEqual(13, arr.Length, "Length");
}
[Test]
public void ConstructorFromIntWorks()
{
var source = new byte[] { 3, 8, 4 };
var arr = new Uint8Array(source);
Assert.True((object)arr != (object)source, "New object");
Assert.True((object)arr is Uint8Array, "is Uint8Array");
AssertContent(arr, new[] { 3, 8, 4 }, "content");
}
[Test]
public void CopyConstructorWorks()
{
var source = new Uint8Array(new byte[] { 3, 8, 4 });
var arr = new Uint8Array(source);
Assert.True(arr != source, "New object");
Assert.True((object)arr is Uint8Array, "is Uint8Array");
AssertContent(arr, new[] { 3, 8, 4 }, "content");
}
[Test]
public void ArrayBufferConstructorWorks()
{
var buf = new ArrayBuffer(80);
var arr = new Uint8Array(buf);
Assert.True((object)arr is Uint8Array);
Assert.True(arr.Buffer == buf, "buffer");
Assert.AreEqual(80, arr.Length, "length");
}
[Test]
public void ArrayBufferWithOffsetConstructorWorks()
{
var buf = new ArrayBuffer(80);
var arr = new Uint8Array(buf, 16);
Assert.True((object)arr is Uint8Array);
Assert.True(arr.Buffer == buf, "buffer");
Assert.AreEqual(64, arr.Length, "length");
}
[Test]
public void ArrayBufferWithOffsetAndLengthConstructorWorks()
{
var buf = new ArrayBuffer(80);
var arr = new Uint8Array(buf, 16, 12);
Assert.True((object)arr is Uint8Array);
Assert.True(arr.Buffer == buf, "buffer");
Assert.AreEqual(12, arr.Length, "length");
}
// Not JS API
//[Test]
//public void InstanceBytesPerElementWorks()
//{
// Assert.AreEqual(new Uint8Array(0).BytesPerElement, 1);
//}
[Test]
public void StaticBytesPerElementWorks()
{
Assert.AreEqual(1, Uint8Array.BYTES_PER_ELEMENT);
}
[Test]
public void LengthWorks()
{
var arr = new Uint8Array(13);
Assert.AreEqual(13, arr.Length, "Length");
}
[Test]
public void IndexingWorks()
{
var arr = new Uint8Array(3);
arr[1] = 42;
AssertContent(arr, new[] { 0, 42, 0 }, "Content");
Assert.AreEqual(42, arr[1], "[1]");
}
[Test]
public void SetUint8ArrayWorks()
{
var arr = new Uint8Array(4);
arr.Set(new Uint8Array(new byte[] { 3, 6, 7 }));
AssertContent(arr, new[] { 3, 6, 7, 0 }, "Content");
}
[Test]
public void SetUint8ArrayWithOffsetWorks()
{
var arr = new Uint8Array(6);
arr.Set(new Uint8Array(new byte[] { 3, 6, 7 }), 2);
AssertContent(arr, new[] { 0, 0, 3, 6, 7, 0 }, "Content");
}
[Test]
public void SetNormalArrayWorks()
{
var arr = new Uint8Array(4);
arr.Set(new byte[] { 3, 6, 7 });
AssertContent(arr, new[] { 3, 6, 7, 0 }, "Content");
}
[Test]
public void SetNormalArrayWithOffsetWorks()
{
var arr = new Uint8Array(6);
arr.Set(new byte[] { 3, 6, 7 }, 2);
AssertContent(arr, new[] { 0, 0, 3, 6, 7, 0 }, "Content");
}
[Test]
public void SubarrayWithBeginWorks()
{
var source = new Uint8Array(10);
var arr = source.SubArray(3);
Assert.False(arr == source, "Should be a new array");
Assert.True(arr.Buffer == source.Buffer, "Should be the same buffer");
Assert.AreEqual(3, arr.ByteOffset, "ByteOffset should be correct");
}
[Test]
public void SubarrayWithBeginAndEndWorks()
{
var source = new Uint8Array(10);
var arr = source.SubArray(3, 7);
Assert.False(arr == source, "Should be a new array");
Assert.True(arr.Buffer == source.Buffer, "Should be the same buffer");
Assert.AreEqual(3, arr.ByteOffset, "ByteOffset should be correct");
Assert.AreEqual(4, arr.Length, "Length should be correct");
}
[Test]
public void BufferPropertyWorks()
{
var buf = new ArrayBuffer(100);
var arr = new Uint8Array(buf);
Assert.True(arr.Buffer == buf, "Should be correct");
}
[Test]
public void ByteOffsetPropertyWorks()
{
var buf = new ArrayBuffer(100);
var arr = new Uint8Array(buf, 32);
Assert.AreEqual(32, arr.ByteOffset, "Should be correct");
}
[Test]
public void ByteLengthPropertyWorks()
{
var arr = new Uint8Array(23);
Assert.AreEqual(23, arr.ByteLength, "Should be correct");
}
[Test]
public void IndexOfWorks()
{
var arr = new Uint8Array(new byte[] { 3, 6, 2, 9, 5 });
Assert.AreEqual(3, arr.IndexOf(9), "9");
Assert.AreEqual(-1, arr.IndexOf(1), "1");
}
// Not JS API
[Test]
public void ContainsWorks()
{
var arr = new Uint8Array(new byte[] { 3, 6, 2, 9, 5 });
Assert.True(arr.Contains(9), "9");
Assert.False(arr.Contains(1), "1");
}
// #SPI
[Test]
public void ForeachWorks_SPI_1401()
{
var arr = new Uint8Array(new byte[] { 3, 6, 2, 9, 5 });
var l = new List<int>();
// #1401
foreach (var i in arr)
{
l.Add(i);
}
Assert.AreEqual(l.ToArray(), new[] { 3, 6, 2, 9, 5 });
}
// #SPI
[Test]
public void GetEnumeratorWorks_SPI_1401()
{
var arr = new Uint8Array(new byte[] { 3, 6, 2, 9, 5 });
var l = new List<int>();
// #1401
var enm = arr.GetEnumerator();
while (enm.MoveNext())
{
l.Add(enm.Current);
}
Assert.AreEqual(l.ToArray(), new[] { 3, 6, 2, 9, 5 });
}
[Test]
public void IEnumerableGetEnumeratorWorks()
{
var arr = (IEnumerable<byte>)new Uint8Array(new byte[] { 3, 6, 2, 9, 5 });
var l = new List<int>();
var enm = arr.GetEnumerator();
while (enm.MoveNext())
{
l.Add(enm.Current);
}
Assert.AreEqual(new[] { 3, 6, 2, 9, 5 }, l.ToArray());
}
[Test]
public void ICollectionMethodsWork_SPI_1559()
{
// #1559
var coll = (ICollection<sbyte>)new Uint8Array(new byte[] { 3, 6, 2, 9, 5 });
Assert.AreEqual(5, coll.Count, "Count");
Assert.True(coll.Contains(6), "Contains(6)");
Assert.False(coll.Contains(1), "Contains(1)");
Assert.Throws<NotSupportedException>(() => coll.Add(2), "Add");
Assert.Throws(() => coll.Clear(), "Clear");
Assert.Throws(() => coll.Remove(2), "Remove");
}
[Test]
public void IListMethodsWork_SPI_1559()
{
// #1559
var list = (IList<sbyte>)new Uint8Array(new byte[] { 3, 6, 2, 9, 5 });
Assert.AreEqual(1, list.IndexOf(6), "IndexOf(6)");
Assert.AreEqual(-1, list.IndexOf(1), "IndexOf(1)");
Assert.AreEqual(9, list[3], "Get item");
list[3] = 4;
Assert.AreEqual(4, list[3], "Set item");
Assert.Throws<NotSupportedException>(() => list.Insert(2, 2), "Insert");
Assert.Throws(() => list.RemoveAt(2), "RemoveAt");
}
// Not JS API
//[Test]
//public void IReadOnlyCollectionMethodsWork()
//{
// var coll = (IReadOnlyCollection<byte>)new Uint8Array(new byte[] { 3, 6, 2, 9, 5 });
// Assert.AreEqual(coll.Count, 5, "Count");
// Assert.True(coll.Contains(6), "Contains(6)");
// Assert.False(coll.Contains(1), "Contains(1)");
//}
// Not JS API
//[Test]
//public void IReadOnlyListMethodsWork()
//{
// var list = (IReadOnlyList<byte>)new Uint8Array(new byte[] { 3, 6, 2, 9, 5 });
// Assert.AreEqual(list[3], 9, "Get item");
//}
[Test]
public void IListIsReadOnlyWorks()
{
var list = (IList<float>)new Uint8Array(new float[0]);
Assert.True(list.IsReadOnly);
}
[Test]
public void ICollectionIsReadOnlyWorks()
{
var list = (ICollection<float>)new Uint8Array(new float[0]);
Assert.True(list.IsReadOnly);
}
[Test]
public void ICollectionCopyTo()
{
ICollection<byte> l = new Uint8Array(new byte[] { 0, 1, 2 });
var a1 = new byte[3];
l.CopyTo(a1, 0);
Assert.AreEqual(0, a1[0], "1.Element 0");
Assert.AreEqual(1, a1[1], "1.Element 1");
Assert.AreEqual(2, a1[2], "1.Element 2");
var a2 = new byte[5];
l.CopyTo(a2, 1);
Assert.AreEqual(0, a2[0], "2.Element 0");
Assert.AreEqual(0, a2[1], "2.Element 1");
Assert.AreEqual(1, a2[2], "2.Element 2");
Assert.AreEqual(2, a2[3], "2.Element 3");
Assert.AreEqual(0, a2[4], "2.Element 4");
Assert.Throws<ArgumentNullException>(() => { l.CopyTo(null, 0); }, "3.null");
var a3 = new byte[2];
Assert.Throws<ArgumentException>(() => { l.CopyTo(a3, 0); }, "3.Short array");
var a4 = new byte[3];
Assert.Throws<ArgumentException>(() => { l.CopyTo(a4, 1); }, "3.Start index 1");
Assert.Throws<ArgumentOutOfRangeException>(() => { l.CopyTo(a4, -1); }, "3.Negative start index");
Assert.Throws<ArgumentException>(() => { l.CopyTo(a4, 3); }, "3.Start index 3");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using Unadus.Audio.Data;
using Unadus.Audio.Data.Models;
using Unadus.Core;
using Unadus.Core.Attributes;
using Unadus.Core.Extensions;
using Unadus.Core.Objects;
namespace Unadus.Audio.Modules
{
[Name("modules.audio.playlist")]
[Group("playlist")]
[Alias("pl")]
public class PlaylistModule : InteractiveUnadusModuleBase<SocketCommandContext>
{
[Command("list")]
[Summary("commands.playlist.list.summary")]
[UsesTyping]
public async Task GetPlaylistsAsync()
{
IEnumerable<PlaylistModel> playlists = null;
using (var context = new AutoplaylistContext(Context.Guild.Id))
{
context.Database.EnsureCreated();
playlists = context.Playlists.ToArray();
}
if (playlists.Count() == 0)
{
await EmbedAsync(GetErrorEmbed(Localization.GetLocalizedString("commands.playlist.list.noPlaylists")));
return;
}
var splitPlaylists = playlists.Split(5);
EmbedBuilder GetPlaylistEmbed(IEnumerable<PlaylistModel> models)
{
var embed = new EmbedBuilder();
embed.Color = EmbedColor;
embed.Title = Localization.GetLocalizedString("commands.playlist.list.embedTitle");
var fields = models.Select((x, i) => (x, $"{i+1} {x}"));
foreach (var (playlist, playlistText) in fields)
embed.AddField(playlistText, Localization.GetLocalizedString("commands.playlist.list.playlistSongCount", playlist.Songs.Count));
return embed;
}
if (splitPlaylists.Count() == 1)
{
await EmbedAsync(GetPlaylistEmbed(splitPlaylists.First()).Build());
return;
}
var pages = splitPlaylists.Select(x => GetPlaylistEmbed(x));
var message = new PaginatedMessage(Localization, Context.User, Context.Channel, pages.ToArray());
await InteractiveService.SendPaginatedMessageAsync(message, async x => await DeletionService.AddMessage(x, TimeSpan.FromSeconds(2), true));
}
[Command("select")]
[Summary("commands.playlist.select.summary")]
public async Task SelectPlaylistsAsync()
{
IEnumerable<PlaylistModel> playlists = null;
using (var context = new AutoplaylistContext(Context.Guild.Id))
{
context.Database.EnsureCreated();
playlists = context.Playlists.ToArray();
}
if (playlists.Count() == 0)
{
await EmbedAsync(GetErrorEmbed(Localization.GetLocalizedString("commands.playlist.list.noPlaylists")));
return;
}
var splitPlaylists = playlists.Split(5);
EmbedBuilder GetPlaylistEmbed(IEnumerable<PlaylistModel> models)
{
var embed = new EmbedBuilder();
embed.Color = EmbedColor;
embed.Title = Localization.GetLocalizedString("commands.playlist.list.embedTitle");
var fields = models.Select((x, i) => (x, $"{i+1} {x}"));
foreach (var (playlist, playlistText) in fields)
embed.AddField(playlistText, Localization.GetLocalizedString("commands.playlist.list.playlistSongCount", playlist.Songs.Count));
return embed;
}
var pages = splitPlaylists.Select(x => GetPlaylistEmbed(x));
var message = new SelectablePaginationMessage(Localization, Context.User, Context.Channel, 5, pages.ToArray());
async Task HandleEntrySelected((int Page, int ItemNum) input)
{
var page = splitPlaylists.ElementAtOrDefault(input.Page-1);
if (page is null) return;
var entry = page.ElementAtOrDefault(input.ItemNum-1);
if (entry is null) return;
using (var context = new AutoplaylistContext(Context.Guild.Id))
{
context.Playlists.FirstOrDefault(x => x.Id == entry.Id)?.TryToggleSelect();
context.SaveChanges();
splitPlaylists = context.Playlists.ToArray().Split(5);
}
var newPages = splitPlaylists.Select(x => GetPlaylistEmbed(x));
await message.UpdatePages(newPages);
}
message.EntrySelected += HandleEntrySelected;
await InteractiveService.SendPaginatedMessageAsync(message, async x =>
{
message.EntrySelected -= HandleEntrySelected;
await DeletionService.AddMessage(x, TimeSpan.FromSeconds(2), true);
});
}
[Command("create")]
[Summary("commands.playlist.create.summary")]
[UsesTyping]
public async Task CreatePlaylistAsync([Remainder, Name("commands.playlist.create.name.name"), Summary("commands.playlist.create.name.summary"), LimitTo(50)] string name)
{
using (var context = new AutoplaylistContext(Context.Guild.Id))
{
if (context.TryAddPlaylist(name, Context.User, Context.Guild, out _))
{
await EmbedAsync(GetSuccessEmbed(Localization.GetLocalizedString("commands.playlist.create.success")));
}
}
}
[Command("destroy")]
[Summary("commands.playlist.destroy.summary")]
[UsesTyping]
public async Task DestroyPlaylistAsync([IsPlaylistOwnerOrHasPermissions, Remainder, Name("commands.playlist.destroy.playlist.name"), Summary("commands.playlist.destroy.playlist.summary")] PlaylistModel playlist)
{
playlist.TryClearSongs();
using (var context = new AutoplaylistContext(Context.Guild.Id))
{
context.Playlists.Remove(playlist);
context.SaveChanges();
}
await EmbedAsync(GetSuccessEmbed(Localization.GetLocalizedString("commands.playlist.destroy.success")));
}
[Group("add")]
[Summary("commands.playlist.add.summary")]
public class Add : InteractiveUnadusModuleBase<SocketCommandContext>
{
[Command]
public async Task AddSingle([Name("commands.playlist.add.playlist.name"), Summary("commands.playlist.add.playlist.summary")] PlaylistModel playlist, [Remainder, Name("commands.playlist.add.song.name"), Summary("commands.playlist.add.song.summary")] Song song)
{
if (!playlist.TryAddSong(song, false))
{
await EmbedAsync(GetErrorEmbed(Localization.GetLocalizedString("commands.playlist.add.single.couldNotAddSong")));
return;
}
await EmbedAsync(GetSuccessEmbed(Localization.GetLocalizedString("commands.playlist.add.single.success", Format.Sanitize(song.Title))));
}
[Command]
public async Task AddPlaylist([Name("commands.playlist.add.playlist.name"), Summary("commands.playlist.add.playlist.summary")] PlaylistModel playlist, [Remainder, Name("commands.playlist.add.song.name"), Summary("commands.playlist.add.song.summary")] SongCollection songs)
{
List<string> failedSongs = new List<string>();
int count = 0;
var songsEnum = songs.GetEnumerator();
while (songsEnum.MoveNext())
{
var current = songsEnum.Current;
switch (current)
{
case FailedSong fs:
failedSongs.Add($"{fs.Url} | {fs.Error}");
break;
case Song s:
if (!playlist.TryAddSong(s))
failedSongs.Add($"{s.Title} | {Localization.GetLocalizedString("commands.playlist.add.playlist.alreadyInPlaylist")}");
else
count++;
break;
}
}
if (failedSongs.Count == 0)
{
await EmbedAsync(GetSuccessEmbed(Localization.GetLocalizedString("commands.playlist.add.playlist.success", songs.ResolvedSongs.Count, Format.Sanitize(playlist.Name))));
return;
}
await EmbedAsync(GetSuccessEmbed(Localization.GetLocalizedString("commands.playlist.add.playlist.addedSome", count, songs.ResolvedSongs.Count, Format.Sanitize(playlist.Name)
+ $"\n{string.Join("\n", failedSongs.Take(10))}")));
}
}
[Command("clear")]
[Summary("commands.playlist.clear.summary")]
[UsesTyping]
[IsBotOwnerOrGuildOwner]
public async Task ClearSongsAsync([Name("commands.playlist.clear.playlist.name"), Summary("commands.playlist.clear.playlist.summary"), Remainder] PlaylistModel playlist)
{
var res = playlist.TryClearSongs();
if (!res.All(x => x.success))
{
await EmbedAsync(GetErrorEmbed(Localization.GetLocalizedString("commands.playlist.clear.someCouldNotRemoved", $"\n{string.Join("\n", res.Where(x => !x.success).Take(20).Select(x => x.url))}")));
return;
}
await EmbedAsync(GetSuccessEmbed(Localization.GetLocalizedString("commands.playlist.clear.success")));
}
[Group("remove")]
[Summary("commands.playlist.remove.summary")]
public class Remove : InteractiveUnadusModuleBase<SocketCommandContext>
{
[Command]
[UsesTyping]
public async Task RemoveSongAsync([Name("commands.playlist.remove.playlist.name"), Summary("commands.playlist.remove.playlist.summary")] PlaylistModel input, [Remainder, Name("commands.playlist.remove.search.name"), Summary("commands.playlist.remove.search.summary")] string name)
{
PlaylistModel playlist = null;
SongModel song = null;
using (var context = new AutoplaylistContext(Context.Guild.Id))
{
playlist = context.Playlists.FirstOrDefault(x => x.Id == input.Id);
if (playlist is null)
{
await EmbedAsync(GetErrorEmbed(Localization.GetLocalizedString("commands.playlist.remove.couldNotFindPlaylist")));
return;
}
if (!playlist.TryGetSongByName(name, out song))
{
await EmbedAsync(GetErrorEmbed(Localization.GetLocalizedString("commands.playlist.remove.songCouldNotBeFound")));
return;
}
var appInfo = await Context.Client.GetApplicationInfoAsync();
if (song.UserId != Context.User.Id && Context.User.Id != Context.Guild.OwnerId && Context.User.Id != appInfo.Owner.Id)
{
await EmbedAsync(GetErrorEmbed(Localization.GetLocalizedString("commands.playlist.remove.noPermissions", $"<@!{song.UserId}>")));
return;
}
var msg = await EmbedAsync(new EmbedBuilder().WithDescription(Localization.GetLocalizedString("commands.playlist.remove.areYouSure", Format.Sanitize(song.Title))).WithColor(EmbedColor).Build());
var res = await WaitForMessageAsync(Context.User, new MessageContainsPrecondition(false, "yes", "y", "no", "n"));
if (res.Content != "y" && res.Content != "yes")
{
await msg.DeleteAsync();
await res.DeleteAsync();
return;
}
await res.DeleteAsync();
}
playlist.TryRemoveSong(song.Url);
await EmbedAsync(GetSuccessEmbed(Localization.GetLocalizedString("commands.playlist.remove.success", Format.Sanitize(song.Title))));
}
[Command("all")]
[IsBotOwnerOrGuildOwner]
public async Task RemoveAllOccurencesAsync([Remainder, Name("commands.playlist.remove.search.name"), Summary("commands.playlist.remove.search.summary")] string name)
{
IEnumerable<PlaylistModel> playlists;
SongModel song = null;
using (var context = new AutoplaylistContext(Context.Guild.Id))
{
song = context.Playlists.SelectMany(x => x.Songs).Distinct().FirstOrDefault(x => x.Title.ToLower().Contains(name.ToLower()));
playlists = context.Playlists.ToArray();
if (song is null)
{
await EmbedAsync(GetErrorEmbed(Localization.GetLocalizedString("commands.playlist.remove.songCouldNotBeFound")));
return;
}
var msg = await EmbedAsync(new EmbedBuilder().WithDescription(Localization.GetLocalizedString("commands.playlist.remove.all.areYouSure", Format.Sanitize(song.Title))).WithColor(EmbedColor).Build());
var res = await WaitForMessageAsync(Context.User, new MessageContainsPrecondition(false, "yes", "y", "no", "n"));
if (res.Content != "y" && res.Content != "yes")
{
await msg.DeleteAsync();
return;
}
}
playlists.Select(x => x.TryRemoveSong(song.Url));
await EmbedAsync(GetSuccessEmbed(Localization.GetLocalizedString("commands.playlist.remove.all.success", Format.Sanitize(song.Title))));
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Text;
using System.Diagnostics;
using System.Collections.Generic;
namespace System.Xml
{
internal partial class XmlWellFormedWriter : XmlWriter
{
//
// Private types
//
class NamespaceResolverProxy : IXmlNamespaceResolver
{
private XmlWellFormedWriter _wfWriter;
internal NamespaceResolverProxy(XmlWellFormedWriter wfWriter)
{
_wfWriter = wfWriter;
}
IDictionary<string, string> IXmlNamespaceResolver.GetNamespacesInScope(XmlNamespaceScope scope)
{
throw NotImplemented.ByDesign;
}
string IXmlNamespaceResolver.LookupNamespace(string prefix)
{
return _wfWriter.LookupNamespace(prefix);
}
string IXmlNamespaceResolver.LookupPrefix(string namespaceName)
{
return _wfWriter.LookupPrefix(namespaceName);
}
}
partial struct ElementScope
{
internal int prevNSTop;
internal string prefix;
internal string localName;
internal string namespaceUri;
internal XmlSpace xmlSpace;
internal string xmlLang;
internal void Set(string prefix, string localName, string namespaceUri, int prevNSTop)
{
this.prevNSTop = prevNSTop;
this.prefix = prefix;
this.namespaceUri = namespaceUri;
this.localName = localName;
this.xmlSpace = (System.Xml.XmlSpace)(int)-1;
this.xmlLang = null;
}
internal void WriteEndElement(XmlRawWriter rawWriter)
{
rawWriter.WriteEndElement(prefix, localName, namespaceUri);
}
internal void WriteFullEndElement(XmlRawWriter rawWriter)
{
rawWriter.WriteFullEndElement(prefix, localName, namespaceUri);
}
}
enum NamespaceKind
{
Written,
NeedToWrite,
Implied,
Special,
}
partial struct Namespace
{
internal string prefix;
internal string namespaceUri;
internal NamespaceKind kind;
internal int prevNsIndex;
internal void Set(string prefix, string namespaceUri, NamespaceKind kind)
{
this.prefix = prefix;
this.namespaceUri = namespaceUri;
this.kind = kind;
this.prevNsIndex = -1;
}
internal void WriteDecl(XmlWriter writer, XmlRawWriter rawWriter)
{
Debug.Assert(kind == NamespaceKind.NeedToWrite);
if (null != rawWriter)
{
rawWriter.WriteNamespaceDeclaration(prefix, namespaceUri);
}
else
{
if (prefix.Length == 0)
{
writer.WriteStartAttribute(string.Empty, XmlConst.NsXmlNs, XmlConst.ReservedNsXmlNs);
}
else
{
writer.WriteStartAttribute(XmlConst.NsXmlNs, prefix, XmlConst.ReservedNsXmlNs);
}
writer.WriteString(namespaceUri);
writer.WriteEndAttribute();
}
}
}
struct AttrName
{
internal string prefix;
internal string namespaceUri;
internal string localName;
internal int prev;
internal void Set(string prefix, string localName, string namespaceUri)
{
this.prefix = prefix;
this.namespaceUri = namespaceUri;
this.localName = localName;
this.prev = 0;
}
internal bool IsDuplicate(string prefix, string localName, string namespaceUri)
{
return ((this.localName == localName)
&& ((this.prefix == prefix) || (this.namespaceUri == namespaceUri)));
}
}
enum SpecialAttribute
{
No = 0,
DefaultXmlns,
PrefixedXmlns,
XmlSpace,
XmlLang
}
partial class AttributeValueCache
{
enum ItemType
{
EntityRef,
CharEntity,
SurrogateCharEntity,
Whitespace,
String,
StringChars,
Raw,
RawChars,
ValueString,
}
class Item
{
internal ItemType type;
internal object data;
internal Item() { }
internal void Set(ItemType type, object data)
{
this.type = type;
this.data = data;
}
}
class BufferChunk
{
internal char[] buffer;
internal int index;
internal int count;
internal BufferChunk(char[] buffer, int index, int count)
{
this.buffer = buffer;
this.index = index;
this.count = count;
}
}
private StringBuilder _stringValue = new StringBuilder();
private string _singleStringValue; // special-case for a single WriteString call
private Item[] _items;
private int _firstItem;
private int _lastItem = -1;
internal string StringValue
{
get
{
if (_singleStringValue != null)
{
return _singleStringValue;
}
else
{
return _stringValue.ToString();
}
}
}
internal void WriteEntityRef(string name)
{
if (_singleStringValue != null)
{
StartComplexValue();
}
switch (name)
{
case "lt":
_stringValue.Append('<');
break;
case "gt":
_stringValue.Append('>');
break;
case "quot":
_stringValue.Append('"');
break;
case "apos":
_stringValue.Append('\'');
break;
case "amp":
_stringValue.Append('&');
break;
default:
_stringValue.Append('&');
_stringValue.Append(name);
_stringValue.Append(';');
break;
}
AddItem(ItemType.EntityRef, name);
}
internal void WriteCharEntity(char ch)
{
if (_singleStringValue != null)
{
StartComplexValue();
}
_stringValue.Append(ch);
AddItem(ItemType.CharEntity, ch);
}
internal void WriteSurrogateCharEntity(char lowChar, char highChar)
{
if (_singleStringValue != null)
{
StartComplexValue();
}
_stringValue.Append(highChar);
_stringValue.Append(lowChar);
AddItem(ItemType.SurrogateCharEntity, new char[] { lowChar, highChar });
}
internal void WriteWhitespace(string ws)
{
if (_singleStringValue != null)
{
StartComplexValue();
}
_stringValue.Append(ws);
AddItem(ItemType.Whitespace, ws);
}
internal void WriteString(string text)
{
if (_singleStringValue != null)
{
StartComplexValue();
}
else
{
// special-case for a single WriteString
if (_lastItem == -1)
{
_singleStringValue = text;
return;
}
}
_stringValue.Append(text);
AddItem(ItemType.String, text);
}
internal void WriteChars(char[] buffer, int index, int count)
{
if (_singleStringValue != null)
{
StartComplexValue();
}
_stringValue.Append(buffer, index, count);
AddItem(ItemType.StringChars, new BufferChunk(buffer, index, count));
}
internal void WriteRaw(char[] buffer, int index, int count)
{
if (_singleStringValue != null)
{
StartComplexValue();
}
_stringValue.Append(buffer, index, count);
AddItem(ItemType.RawChars, new BufferChunk(buffer, index, count));
}
internal void WriteRaw(string data)
{
if (_singleStringValue != null)
{
StartComplexValue();
}
_stringValue.Append(data);
AddItem(ItemType.Raw, data);
}
internal void WriteValue(string value)
{
if (_singleStringValue != null)
{
StartComplexValue();
}
_stringValue.Append(value);
AddItem(ItemType.ValueString, value);
}
internal void Replay(XmlWriter writer)
{
if (_singleStringValue != null)
{
writer.WriteString(_singleStringValue);
return;
}
BufferChunk bufChunk;
for (int i = _firstItem; i <= _lastItem; i++)
{
Item item = _items[i];
switch (item.type)
{
case ItemType.EntityRef:
writer.WriteEntityRef((string)item.data);
break;
case ItemType.CharEntity:
writer.WriteCharEntity((char)item.data);
break;
case ItemType.SurrogateCharEntity:
char[] chars = (char[])item.data;
writer.WriteSurrogateCharEntity(chars[0], chars[1]);
break;
case ItemType.Whitespace:
writer.WriteWhitespace((string)item.data);
break;
case ItemType.String:
writer.WriteString((string)item.data);
break;
case ItemType.StringChars:
bufChunk = (BufferChunk)item.data;
writer.WriteChars(bufChunk.buffer, bufChunk.index, bufChunk.count);
break;
case ItemType.Raw:
writer.WriteRaw((string)item.data);
break;
case ItemType.RawChars:
bufChunk = (BufferChunk)item.data;
writer.WriteChars(bufChunk.buffer, bufChunk.index, bufChunk.count);
break;
case ItemType.ValueString:
writer.WriteValue((string)item.data);
break;
default:
Debug.Assert(false, "Unexpected ItemType value.");
break;
}
}
}
// This method trims whitespaces from the beginning and the end of the string and cached writer events
internal void Trim()
{
// if only one string value -> trim the write spaces directly
if (_singleStringValue != null)
{
_singleStringValue = XmlConvertEx.TrimString(_singleStringValue);
return;
}
// trim the string in StringBuilder
string valBefore = _stringValue.ToString();
string valAfter = XmlConvertEx.TrimString(valBefore);
if (valBefore != valAfter)
{
_stringValue = new StringBuilder(valAfter);
}
// trim the beginning of the recorded writer events
XmlCharType xmlCharType = XmlCharType.Instance;
int i = _firstItem;
while (i == _firstItem && i <= _lastItem)
{
Item item = _items[i];
switch (item.type)
{
case ItemType.Whitespace:
_firstItem++;
break;
case ItemType.String:
case ItemType.Raw:
case ItemType.ValueString:
item.data = XmlConvertEx.TrimStringStart((string)item.data);
if (((string)item.data).Length == 0)
{
// no characters left -> move the firstItem index to exclude it from the Replay
_firstItem++;
}
break;
case ItemType.StringChars:
case ItemType.RawChars:
BufferChunk bufChunk = (BufferChunk)item.data;
int endIndex = bufChunk.index + bufChunk.count;
while (bufChunk.index < endIndex && xmlCharType.IsWhiteSpace(bufChunk.buffer[bufChunk.index]))
{
bufChunk.index++;
bufChunk.count--;
}
if (bufChunk.index == endIndex)
{
// no characters left -> move the firstItem index to exclude it from the Replay
_firstItem++;
}
break;
}
i++;
}
// trim the end of the recorded writer events
i = _lastItem;
while (i == _lastItem && i >= _firstItem)
{
Item item = _items[i];
switch (item.type)
{
case ItemType.Whitespace:
_lastItem--;
break;
case ItemType.String:
case ItemType.Raw:
case ItemType.ValueString:
item.data = XmlConvertEx.TrimStringEnd((string)item.data);
if (((string)item.data).Length == 0)
{
// no characters left -> move the lastItem index to exclude it from the Replay
_lastItem--;
}
break;
case ItemType.StringChars:
case ItemType.RawChars:
BufferChunk bufChunk = (BufferChunk)item.data;
while (bufChunk.count > 0 && xmlCharType.IsWhiteSpace(bufChunk.buffer[bufChunk.index + bufChunk.count - 1]))
{
bufChunk.count--;
}
if (bufChunk.count == 0)
{
// no characters left -> move the lastItem index to exclude it from the Replay
_lastItem--;
}
break;
}
i--;
}
}
internal void Clear()
{
_singleStringValue = null;
_lastItem = -1;
_firstItem = 0;
_stringValue.Length = 0;
}
private void StartComplexValue()
{
Debug.Assert(_singleStringValue != null);
Debug.Assert(_lastItem == -1);
_stringValue.Append(_singleStringValue);
AddItem(ItemType.String, _singleStringValue);
_singleStringValue = null;
}
void AddItem(ItemType type, object data)
{
int newItemIndex = _lastItem + 1;
if (_items == null)
{
_items = new Item[4];
}
else if (_items.Length == newItemIndex)
{
Item[] newItems = new Item[newItemIndex * 2];
Array.Copy(_items, newItems, newItemIndex);
_items = newItems;
}
if (_items[newItemIndex] == null)
{
_items[newItemIndex] = new Item();
}
_items[newItemIndex].Set(type, data);
_lastItem = newItemIndex;
}
}
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using Gallio.Common;
using Gallio.Model;
using Gallio.Common.Reflection;
using Gallio.Model.Schema;
using Gallio.ReSharperRunner.Reflection;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.Tree;
#if ! RESHARPER_50_OR_NEWER
using JetBrains.ReSharper.UnitTestExplorer;
#else
using JetBrains.ReSharper.UnitTestFramework;
using JetBrains.Util;
#endif
namespace Gallio.ReSharperRunner.Provider
{
/// <summary>
/// Represents a Gallio test.
/// </summary>
public class GallioTestElement : UnitTestElement, IEquatable<GallioTestElement>, IComparable<GallioTestElement>, IComparable
{
private readonly string testName;
private readonly string testId;
private readonly string kind;
private readonly bool isTestCase;
private readonly IProject project;
private readonly IDeclaredElementResolver declaredElementResolver;
private readonly string assemblyPath;
private readonly string typeName;
private readonly string namespaceName;
#if RESHARPER_50_OR_NEWER
private Memoizer<string> shortNameMemoizer;
#endif
protected GallioTestElement(IUnitTestProvider provider, GallioTestElement parent, string testId, string testName, string kind, bool isTestCase,
IProject project, IDeclaredElementResolver declaredElementResolver, string assemblyPath, string typeName, string namespaceName)
: base(provider, parent)
{
this.testId = testId;
this.testName = testName;
this.kind = kind;
this.isTestCase = isTestCase;
this.project = project;
this.declaredElementResolver = declaredElementResolver;
this.assemblyPath = assemblyPath;
this.typeName = typeName;
this.namespaceName = namespaceName;
}
public static GallioTestElement CreateFromTest(TestData test, ICodeElementInfo codeElement, IUnitTestProvider provider, GallioTestElement parent)
{
if (test == null)
throw new ArgumentNullException("test");
// The idea here is to generate a test element object that does not retain any direct
// references to the code element info and other heavyweight objects. A test element may
// survive in memory for quite a long time so we don't want it holding on to all sorts of
// irrelevant stuff. Basically we flatten out the test to just those properties that we
// need to keep.
GallioTestElement element = new GallioTestElement(provider, parent,
test.Id,
test.Name,
test.Metadata.GetValue(MetadataKeys.TestKind) ?? "Unknown",
test.IsTestCase,
ReSharperReflectionPolicy.GetProject(codeElement),
ReSharperReflectionPolicy.GetDeclaredElementResolver(codeElement),
GetAssemblyPath(codeElement),
GetTypeName(codeElement),
GetNamespaceName(codeElement));
IList<string> categories = test.Metadata[MetadataKeys.Category];
if (categories.Count != 0)
element.AssignCategories(categories);
string reason = test.Metadata.GetValue(MetadataKeys.IgnoreReason);
if (reason != null)
element.SetExplicit(reason);
return element;
}
private static string GetAssemblyPath(ICodeElementInfo codeElement)
{
IAssemblyInfo assembly = ReflectionUtils.GetAssembly(codeElement);
return assembly != null ? assembly.Path : null;
}
private static string GetTypeName(ICodeElementInfo codeElement)
{
ITypeInfo type = ReflectionUtils.GetType(codeElement);
return type != null ? type.FullName : "";
}
private static string GetNamespaceName(ICodeElementInfo codeElement)
{
INamespaceInfo @namespace = ReflectionUtils.GetNamespace(codeElement);
return @namespace != null ? @namespace.Name : "";
}
public string GetAssemblyLocation()
{
return assemblyPath;
}
public string TestName
{
get { return testName; }
}
#if RESHARPER_50_OR_NEWER
// R# uses this name as a filter for declared elements so that it can quickly determine
// whether a given declared element is likely to be a test before asking the provider about
// it. The result must be equal to IDeclaredElement.ShortName.
public override string ShortName
{
get
{
return shortNameMemoizer.Memoize(() =>
{
IDeclaredElement declaredElement = GetDeclaredElement();
return declaredElement != null && declaredElement.IsValid()
? declaredElement.ShortName
: testName;
});
}
}
#endif
public string TestId
{
get { return testId; }
}
public bool IsTestCase
{
get { return isTestCase; }
}
public override string GetTitle()
{
return testName;
}
public override string GetTypeClrName()
{
return typeName;
}
public override UnitTestNamespace GetNamespace()
{
return new UnitTestNamespace(namespaceName);
}
public override IProject GetProject()
{
return project;
}
public override string GetKind()
{
return kind;
}
#if RESHARPER_31
public override IList<IProjectItem> GetProjectItems()
{
IDeclaredElement declaredElement = GetDeclaredElement();
if (declaredElement != null && declaredElement.IsValid())
return declaredElement.GetProjectFiles();
return EmptyArrays.ProjectItems;
}
#else
public override IList<IProjectFile> GetProjectFiles()
{
IDeclaredElement declaredElement = GetDeclaredElement();
if (declaredElement != null && declaredElement.IsValid())
return declaredElement.GetProjectFiles();
return Common.Collections.EmptyArray<IProjectFile>.Instance;
}
#endif
public override UnitTestElementDisposition GetDisposition()
{
IDeclaredElement element = GetDeclaredElement();
if (element == null || !element.IsValid())
{
#if RESHARPER_31 || RESHARPER_40 || RESHARPER_41
return UnitTestElementDisposition.ourInvalidDisposition;
#else
return UnitTestElementDisposition.InvalidDisposition;
#endif
}
List<UnitTestElementLocation> locations = new List<UnitTestElementLocation>();
foreach (IDeclaration declaration in element.GetDeclarations())
{
if (declaration.IsValid())
{
IFile file = declaration.GetContainingFile();
if (file != null && file.IsValid())
{
#if ! RESHARPER_50_OR_NEWER
var nameRange = declaration.GetNameRange();
#else
var nameRange = declaration.GetNameDocumentRange().TextRange;
#endif
var containingRange = declaration.GetDocumentRange().TextRange;
#if RESHARPER_31 || RESHARPER_40 || RESHARPER_41
if (nameRange.IsValid && containingRange.IsValid)
#elif RESHARPER_45
if (nameRange.IsValid() && containingRange.IsValid())
#else
if (nameRange.IsValid && containingRange.IsValid)
#endif
{
locations.Add(new UnitTestElementLocation(
#if RESHARPER_31
file.ProjectItem,
#else
file.ProjectFile,
#endif
nameRange, containingRange));
}
}
}
}
return new UnitTestElementDisposition(locations, this);
}
public override IDeclaredElement GetDeclaredElement()
{
return declaredElementResolver.ResolveDeclaredElement();
}
#if RESHARPER_31
public override bool Matches(string filter)
{
if (testName.IndexOf(filter, StringComparison.CurrentCultureIgnoreCase) >= 0)
return true;
GallioTestElement parent = Parent as GallioTestElement;
return parent != null && parent.Matches(filter);
}
#endif
public bool Equals(GallioTestElement other)
{
return other != null && testId == other.testId;
}
public override bool Equals(object obj)
{
return Equals(obj as GallioTestElement);
}
public override int GetHashCode()
{
return testId.GetHashCode();
}
public int CompareTo(GallioTestElement other)
{
// Find common ancestor.
Dictionary<GallioTestElement, GallioTestElement> branches = new Dictionary<GallioTestElement, GallioTestElement>();
for (GallioTestElement thisAncestor = this, thisBranch = null;
thisAncestor != null;
thisBranch = thisAncestor, thisAncestor = thisAncestor.Parent as GallioTestElement)
branches.Add(thisAncestor, thisBranch);
for (GallioTestElement otherAncestor = other, otherBranch = null;
otherAncestor != null;
otherBranch = otherAncestor, otherAncestor = otherAncestor.Parent as GallioTestElement)
{
GallioTestElement thisBranch;
if (branches.TryGetValue(otherAncestor, out thisBranch))
{
// Compare the relative ordering of the branches leading from
// the common ancestor to each child.
int thisOrder = thisBranch != null ? otherAncestor.Children.IndexOf(thisBranch) : -1;
int otherOrder = otherBranch != null ? otherAncestor.Children.IndexOf(otherBranch) : -1;
return thisOrder.CompareTo(otherOrder);
}
}
// No common ancestor, compare test ids.
return testId.CompareTo(other.testId);
}
public int CompareTo(object obj)
{
GallioTestElement other = obj as GallioTestElement;
return other != null ? CompareTo(other) : 1; // sort gallio test elements after all other kinds
}
public override string ToString()
{
return GetTitle();
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.Serialization;
using Microsoft.Xrm.Sdk;
namespace PowerShellLibrary.Crm.CmdletProviders
{
[Microsoft.Xrm.Sdk.Client.EntityLogicalName("fieldsecurityprofile")]
[GeneratedCode("CrmSvcUtil", "7.1.0001.3108")]
[DataContract]
public class FieldSecurityProfile : Entity, INotifyPropertyChanging, INotifyPropertyChanged
{
public const string EntityLogicalName = "fieldsecurityprofile";
public const int EntityTypeCode = 1200;
[AttributeLogicalName("componentstate")]
public OptionSetValue ComponentState
{
get
{
return this.GetAttributeValue<OptionSetValue>("componentstate");
}
}
[AttributeLogicalName("createdby")]
public EntityReference CreatedBy
{
get
{
return this.GetAttributeValue<EntityReference>("createdby");
}
}
[AttributeLogicalName("createdon")]
public DateTime? CreatedOn
{
get
{
return this.GetAttributeValue<DateTime?>("createdon");
}
}
[AttributeLogicalName("createdonbehalfby")]
public EntityReference CreatedOnBehalfBy
{
get
{
return this.GetAttributeValue<EntityReference>("createdonbehalfby");
}
}
[AttributeLogicalName("description")]
public string Description
{
get
{
return this.GetAttributeValue<string>("description");
}
set
{
this.OnPropertyChanging("Description");
this.SetAttributeValue("description", (object) value);
this.OnPropertyChanged("Description");
}
}
[AttributeLogicalName("fieldsecurityprofileid")]
public Guid? FieldSecurityProfileId
{
get
{
return this.GetAttributeValue<Guid?>("fieldsecurityprofileid");
}
set
{
this.OnPropertyChanging("FieldSecurityProfileId");
this.SetAttributeValue("fieldsecurityprofileid", (object) value);
if (value.HasValue)
base.Id = value.Value;
else
base.Id = Guid.Empty;
this.OnPropertyChanged("FieldSecurityProfileId");
}
}
[AttributeLogicalName("fieldsecurityprofileid")]
public override Guid Id
{
get
{
return base.Id;
}
set
{
this.FieldSecurityProfileId = new Guid?(value);
}
}
[AttributeLogicalName("fieldsecurityprofileidunique")]
public Guid? FieldSecurityProfileIdUnique
{
get
{
return this.GetAttributeValue<Guid?>("fieldsecurityprofileidunique");
}
}
[AttributeLogicalName("ismanaged")]
public bool? IsManaged
{
get
{
return this.GetAttributeValue<bool?>("ismanaged");
}
}
[AttributeLogicalName("modifiedby")]
public EntityReference ModifiedBy
{
get
{
return this.GetAttributeValue<EntityReference>("modifiedby");
}
}
[AttributeLogicalName("modifiedon")]
public DateTime? ModifiedOn
{
get
{
return this.GetAttributeValue<DateTime?>("modifiedon");
}
}
[AttributeLogicalName("modifiedonbehalfby")]
public EntityReference ModifiedOnBehalfBy
{
get
{
return this.GetAttributeValue<EntityReference>("modifiedonbehalfby");
}
}
[AttributeLogicalName("name")]
public string Name
{
get
{
return this.GetAttributeValue<string>("name");
}
set
{
this.OnPropertyChanging("Name");
this.SetAttributeValue("name", (object) value);
this.OnPropertyChanged("Name");
}
}
[AttributeLogicalName("organizationid")]
public EntityReference OrganizationId
{
get
{
return this.GetAttributeValue<EntityReference>("organizationid");
}
}
[AttributeLogicalName("overwritetime")]
public DateTime? OverwriteTime
{
get
{
return this.GetAttributeValue<DateTime?>("overwritetime");
}
}
[AttributeLogicalName("solutionid")]
public Guid? SolutionId
{
get
{
return this.GetAttributeValue<Guid?>("solutionid");
}
}
[AttributeLogicalName("versionnumber")]
public long? VersionNumber
{
get
{
return this.GetAttributeValue<long?>("versionnumber");
}
}
[RelationshipSchemaName("systemuserprofiles_association")]
public IEnumerable<SystemUser> systemuserprofiles_association
{
get
{
return this.GetRelatedEntities<SystemUser>("systemuserprofiles_association", new EntityRole?());
}
set
{
this.OnPropertyChanging("systemuserprofiles_association");
this.SetRelatedEntities<SystemUser>("systemuserprofiles_association", new EntityRole?(), value);
this.OnPropertyChanged("systemuserprofiles_association");
}
}
[AttributeLogicalName("createdby")]
[RelationshipSchemaName("lk_fieldsecurityprofile_createdby")]
public SystemUser lk_fieldsecurityprofile_createdby
{
get
{
return this.GetRelatedEntity<SystemUser>("lk_fieldsecurityprofile_createdby", new EntityRole?());
}
}
[RelationshipSchemaName("lk_fieldsecurityprofile_createdonbehalfby")]
[AttributeLogicalName("createdonbehalfby")]
public SystemUser lk_fieldsecurityprofile_createdonbehalfby
{
get
{
return this.GetRelatedEntity<SystemUser>("lk_fieldsecurityprofile_createdonbehalfby", new EntityRole?());
}
}
[AttributeLogicalName("modifiedby")]
[RelationshipSchemaName("lk_fieldsecurityprofile_modifiedby")]
public SystemUser lk_fieldsecurityprofile_modifiedby
{
get
{
return this.GetRelatedEntity<SystemUser>("lk_fieldsecurityprofile_modifiedby", new EntityRole?());
}
}
[AttributeLogicalName("modifiedonbehalfby")]
[RelationshipSchemaName("lk_fieldsecurityprofile_modifiedonbehalfby")]
public SystemUser lk_fieldsecurityprofile_modifiedonbehalfby
{
get
{
return this.GetRelatedEntity<SystemUser>("lk_fieldsecurityprofile_modifiedonbehalfby", new EntityRole?());
}
}
public event PropertyChangedEventHandler PropertyChanged;
public event PropertyChangingEventHandler PropertyChanging;
public FieldSecurityProfile()
: base("fieldsecurityprofile")
{
}
private void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged == null)
return;
this.PropertyChanged((object) this, new PropertyChangedEventArgs(propertyName));
}
private void OnPropertyChanging(string propertyName)
{
if (this.PropertyChanging == null)
return;
this.PropertyChanging((object) this, new PropertyChangingEventArgs(propertyName));
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using FluentAssertions;
using FluentAssertions.Extensions;
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.Serialization.Objects;
using Microsoft.Extensions.DependencyInjection;
using TestBuildingBlocks;
using Xunit;
namespace JsonApiDotNetCoreTests.IntegrationTests.QueryStrings.Filtering
{
public sealed class FilterDepthTests : IClassFixture<IntegrationTestContext<TestableStartup<QueryStringDbContext>, QueryStringDbContext>>
{
private readonly IntegrationTestContext<TestableStartup<QueryStringDbContext>, QueryStringDbContext> _testContext;
private readonly QueryStringFakers _fakers = new();
public FilterDepthTests(IntegrationTestContext<TestableStartup<QueryStringDbContext>, QueryStringDbContext> testContext)
{
_testContext = testContext;
testContext.UseController<BlogsController>();
testContext.UseController<BlogPostsController>();
var options = (JsonApiOptions)testContext.Factory.Services.GetRequiredService<IJsonApiOptions>();
options.EnableLegacyFilterNotation = false;
options.DisableTopPagination = false;
options.DisableChildrenPagination = false;
}
[Fact]
public async Task Can_filter_in_primary_resources()
{
// Arrange
List<BlogPost> posts = _fakers.BlogPost.Generate(2);
posts[0].Caption = "One";
posts[1].Caption = "Two";
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<BlogPost>();
dbContext.Posts.AddRange(posts);
await dbContext.SaveChangesAsync();
});
const string route = "/blogPosts?filter=equals(caption,'Two')";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Data.ManyValue.Should().HaveCount(1);
responseDocument.Data.ManyValue[0].Id.Should().Be(posts[1].StringId);
}
[Fact]
public async Task Cannot_filter_in_single_primary_resource()
{
// Arrange
BlogPost post = _fakers.BlogPost.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Posts.Add(post);
await dbContext.SaveChangesAsync();
});
string route = $"/blogPosts/{post.StringId}?filter=equals(caption,'Two')";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest);
responseDocument.Errors.Should().HaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.BadRequest);
error.Title.Should().Be("The specified filter is invalid.");
error.Detail.Should().Be("This query string parameter can only be used on a collection of resources (not on a single resource).");
error.Source.Parameter.Should().Be("filter");
}
[Fact]
public async Task Can_filter_in_secondary_resources()
{
// Arrange
Blog blog = _fakers.Blog.Generate();
blog.Posts = _fakers.BlogPost.Generate(2);
blog.Posts[0].Caption = "One";
blog.Posts[1].Caption = "Two";
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Blogs.Add(blog);
await dbContext.SaveChangesAsync();
});
string route = $"/blogs/{blog.StringId}/posts?filter=equals(caption,'Two')";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Data.ManyValue.Should().HaveCount(1);
responseDocument.Data.ManyValue[0].Id.Should().Be(blog.Posts[1].StringId);
}
[Fact]
public async Task Cannot_filter_in_single_secondary_resource()
{
// Arrange
BlogPost post = _fakers.BlogPost.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Posts.Add(post);
await dbContext.SaveChangesAsync();
});
string route = $"/blogPosts/{post.StringId}/author?filter=equals(displayName,'John Smith')";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest);
responseDocument.Errors.Should().HaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.BadRequest);
error.Title.Should().Be("The specified filter is invalid.");
error.Detail.Should().Be("This query string parameter can only be used on a collection of resources (not on a single resource).");
error.Source.Parameter.Should().Be("filter");
}
[Fact]
public async Task Can_filter_on_ManyToOne_relationship()
{
// Arrange
List<BlogPost> posts = _fakers.BlogPost.Generate(3);
posts[0].Author = _fakers.WebAccount.Generate();
posts[0].Author.UserName = "Conner";
posts[1].Author = _fakers.WebAccount.Generate();
posts[1].Author.UserName = "Smith";
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<BlogPost>();
dbContext.Posts.AddRange(posts);
await dbContext.SaveChangesAsync();
});
const string route = "/blogPosts?include=author&filter=or(equals(author.userName,'Smith'),equals(author,null))";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Data.ManyValue.Should().HaveCount(2);
responseDocument.Data.ManyValue.Should().ContainSingle(post => post.Id == posts[1].StringId);
responseDocument.Data.ManyValue.Should().ContainSingle(post => post.Id == posts[2].StringId);
responseDocument.Included.Should().HaveCount(1);
responseDocument.Included[0].Id.Should().Be(posts[1].Author.StringId);
}
[Fact]
public async Task Can_filter_on_OneToMany_relationship()
{
// Arrange
List<Blog> blogs = _fakers.Blog.Generate(2);
blogs[1].Posts = _fakers.BlogPost.Generate(1);
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<Blog>();
dbContext.Blogs.AddRange(blogs);
await dbContext.SaveChangesAsync();
});
const string route = "/blogs?filter=greaterThan(count(posts),'0')";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Data.ManyValue.Should().HaveCount(1);
responseDocument.Data.ManyValue[0].Id.Should().Be(blogs[1].StringId);
}
[Fact]
public async Task Can_filter_on_OneToMany_relationship_with_nested_condition()
{
// Arrange
List<Blog> blogs = _fakers.Blog.Generate(2);
blogs[0].Posts = _fakers.BlogPost.Generate(1);
blogs[1].Posts = _fakers.BlogPost.Generate(1);
blogs[1].Posts[0].Comments = _fakers.Comment.Generate(1).ToHashSet();
blogs[1].Posts[0].Comments.ElementAt(0).Text = "ABC";
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<Blog>();
dbContext.Blogs.AddRange(blogs);
await dbContext.SaveChangesAsync();
});
const string route = "/blogs?filter=has(posts,has(comments,startsWith(text,'A')))";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Data.ManyValue.Should().HaveCount(1);
responseDocument.Data.ManyValue[0].Id.Should().Be(blogs[1].StringId);
}
[Fact]
public async Task Can_filter_on_ManyToMany_relationship()
{
// Arrange
List<BlogPost> posts = _fakers.BlogPost.Generate(2);
posts[1].Labels = _fakers.Label.Generate(1).ToHashSet();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<BlogPost>();
dbContext.Posts.AddRange(posts);
await dbContext.SaveChangesAsync();
});
const string route = "/blogPosts?filter=has(labels)";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Data.ManyValue.Should().HaveCount(1);
responseDocument.Data.ManyValue[0].Id.Should().Be(posts[1].StringId);
}
[Fact]
public async Task Can_filter_on_ManyToMany_relationship_with_nested_condition()
{
// Arrange
List<Blog> blogs = _fakers.Blog.Generate(2);
blogs[0].Posts = _fakers.BlogPost.Generate(1);
blogs[1].Posts = _fakers.BlogPost.Generate(1);
blogs[1].Posts[0].Labels = _fakers.Label.Generate(1).ToHashSet();
blogs[1].Posts[0].Labels.ElementAt(0).Color = LabelColor.Green;
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<Blog>();
dbContext.Blogs.AddRange(blogs);
await dbContext.SaveChangesAsync();
});
const string route = "/blogs?filter=has(posts,has(labels,equals(color,'Green')))";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Data.ManyValue.Should().HaveCount(1);
responseDocument.Data.ManyValue[0].Id.Should().Be(blogs[1].StringId);
}
[Fact]
public async Task Can_filter_in_scope_of_OneToMany_relationship()
{
// Arrange
Blog blog = _fakers.Blog.Generate();
blog.Posts = _fakers.BlogPost.Generate(2);
blog.Posts[0].Caption = "One";
blog.Posts[1].Caption = "Two";
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<Blog>();
dbContext.Blogs.Add(blog);
await dbContext.SaveChangesAsync();
});
const string route = "/blogs?include=posts&filter[posts]=equals(caption,'Two')";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Data.ManyValue.Should().HaveCount(1);
responseDocument.Included.Should().HaveCount(1);
responseDocument.Included[0].Id.Should().Be(blog.Posts[1].StringId);
}
[Fact]
public async Task Can_filter_in_scope_of_OneToMany_relationship_on_secondary_endpoint()
{
// Arrange
Blog blog = _fakers.Blog.Generate();
blog.Owner = _fakers.WebAccount.Generate();
blog.Owner.Posts = _fakers.BlogPost.Generate(2);
blog.Owner.Posts[0].Caption = "One";
blog.Owner.Posts[1].Caption = "Two";
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Blogs.Add(blog);
await dbContext.SaveChangesAsync();
});
string route = $"/blogs/{blog.StringId}/owner?include=posts&filter[posts]=equals(caption,'Two')";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Data.SingleValue.Should().NotBeNull();
responseDocument.Included.Should().HaveCount(1);
responseDocument.Included[0].Id.Should().Be(blog.Owner.Posts[1].StringId);
}
[Fact]
public async Task Can_filter_in_scope_of_ManyToMany_relationship()
{
// Arrange
List<BlogPost> posts = _fakers.BlogPost.Generate(2);
posts[0].Labels = _fakers.Label.Generate(1).ToHashSet();
posts[0].Labels.ElementAt(0).Name = "Cold";
posts[1].Labels = _fakers.Label.Generate(1).ToHashSet();
posts[1].Labels.ElementAt(0).Name = "Hot";
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<BlogPost>();
dbContext.Posts.AddRange(posts);
await dbContext.SaveChangesAsync();
});
// Workaround for https://github.com/dotnet/efcore/issues/21026
var options = (JsonApiOptions)_testContext.Factory.Services.GetRequiredService<IJsonApiOptions>();
options.DisableTopPagination = false;
options.DisableChildrenPagination = true;
const string route = "/blogPosts?include=labels&filter[labels]=equals(name,'Hot')";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Data.ManyValue.Should().HaveCount(2);
responseDocument.Included.Should().HaveCount(1);
responseDocument.Included[0].Id.Should().Be(posts[1].Labels.First().StringId);
}
[Fact]
public async Task Can_filter_in_scope_of_relationship_chain()
{
// Arrange
Blog blog = _fakers.Blog.Generate();
blog.Owner = _fakers.WebAccount.Generate();
blog.Owner.Posts = _fakers.BlogPost.Generate(2);
blog.Owner.Posts[0].Caption = "One";
blog.Owner.Posts[1].Caption = "Two";
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<Blog>();
dbContext.Blogs.Add(blog);
await dbContext.SaveChangesAsync();
});
const string route = "/blogs?include=owner.posts&filter[owner.posts]=equals(caption,'Two')";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Data.ManyValue.Should().HaveCount(1);
responseDocument.Included.Should().HaveCount(2);
responseDocument.Included[0].Id.Should().Be(blog.Owner.StringId);
responseDocument.Included[1].Id.Should().Be(blog.Owner.Posts[1].StringId);
}
[Fact]
public async Task Can_filter_in_same_scope_multiple_times()
{
// Arrange
List<BlogPost> posts = _fakers.BlogPost.Generate(3);
posts[0].Caption = "One";
posts[1].Caption = "Two";
posts[2].Caption = "Three";
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<BlogPost>();
dbContext.Posts.AddRange(posts);
await dbContext.SaveChangesAsync();
});
const string route = "/blogPosts?filter=equals(caption,'One')&filter=equals(caption,'Three')";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Data.ManyValue.Should().HaveCount(2);
responseDocument.Data.ManyValue[0].Id.Should().Be(posts[0].StringId);
responseDocument.Data.ManyValue[1].Id.Should().Be(posts[2].StringId);
}
[Fact]
public async Task Can_filter_in_same_scope_multiple_times_using_legacy_notation()
{
// Arrange
var options = (JsonApiOptions)_testContext.Factory.Services.GetRequiredService<IJsonApiOptions>();
options.EnableLegacyFilterNotation = true;
List<BlogPost> posts = _fakers.BlogPost.Generate(3);
posts[0].Author = _fakers.WebAccount.Generate();
posts[1].Author = _fakers.WebAccount.Generate();
posts[2].Author = _fakers.WebAccount.Generate();
posts[0].Author.UserName = "Joe";
posts[0].Author.DisplayName = "Smith";
posts[1].Author.UserName = "John";
posts[1].Author.DisplayName = "Doe";
posts[2].Author.UserName = "Jack";
posts[2].Author.DisplayName = "Miller";
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<BlogPost>();
dbContext.Posts.AddRange(posts);
await dbContext.SaveChangesAsync();
});
const string route = "/blogPosts?filter[author.userName]=John&filter[author.displayName]=Smith";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Data.ManyValue.Should().HaveCount(2);
responseDocument.Data.ManyValue[0].Id.Should().Be(posts[0].StringId);
responseDocument.Data.ManyValue[1].Id.Should().Be(posts[1].StringId);
}
[Fact]
public async Task Can_filter_in_multiple_scopes()
{
// Arrange
List<Blog> blogs = _fakers.Blog.Generate(2);
blogs[1].Title = "Technology";
blogs[1].Owner = _fakers.WebAccount.Generate();
blogs[1].Owner.UserName = "Smith";
blogs[1].Owner.Posts = _fakers.BlogPost.Generate(2);
blogs[1].Owner.Posts[0].Caption = "One";
blogs[1].Owner.Posts[1].Caption = "Two";
blogs[1].Owner.Posts[1].Comments = _fakers.Comment.Generate(2).ToHashSet();
blogs[1].Owner.Posts[1].Comments.ElementAt(0).CreatedAt = 1.January(2000);
blogs[1].Owner.Posts[1].Comments.ElementAt(1).CreatedAt = 10.January(2010);
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<Blog>();
dbContext.Blogs.AddRange(blogs);
await dbContext.SaveChangesAsync();
});
// @formatter:keep_existing_linebreaks true
const string route = "/blogs?include=owner.posts.comments&" +
"filter=and(equals(title,'Technology'),has(owner.posts),equals(owner.userName,'Smith'))&" +
"filter[owner.posts]=equals(caption,'Two')&" +
"filter[owner.posts.comments]=greaterThan(createdAt,'2005-05-05')";
// @formatter:keep_existing_linebreaks restore
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Data.ManyValue.Should().HaveCount(1);
responseDocument.Data.ManyValue[0].Id.Should().Be(blogs[1].StringId);
responseDocument.Included.Should().HaveCount(3);
responseDocument.Included[0].Id.Should().Be(blogs[1].Owner.StringId);
responseDocument.Included[1].Id.Should().Be(blogs[1].Owner.Posts[1].StringId);
responseDocument.Included[2].Id.Should().Be(blogs[1].Owner.Posts[1].Comments.ElementAt(1).StringId);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using CppSharp.AST;
using CppSharp.AST.Extensions;
using CppSharp.Generators.C;
using Type = CppSharp.AST.Type;
namespace CppSharp.Generators.CLI
{
/// <summary>
/// Generates C++/CLI source files.
/// </summary>
public class CLISources : CLITemplate
{
public CLISources(BindingContext context, IEnumerable<TranslationUnit> units)
: base(context, units)
{
}
public override string FileExtension => "cpp";
public override void Process()
{
GenerateFilePreamble(CommentKind.BCPL);
PushBlock(BlockKind.Includes);
var file = Context.Options.GetIncludePath(TranslationUnit);
WriteLine($"#include \"{file}\"");
GenerateForwardReferenceHeaders();
NewLine();
PopBlock();
PushBlock(BlockKind.Usings);
WriteLine("using namespace System;");
WriteLine("using namespace System::Runtime::InteropServices;");
foreach (var customUsingStatement in Options.DependentNameSpaces)
{
WriteLine($"using namespace {customUsingStatement};"); ;
}
NewLine();
PopBlock();
GenerateDeclContext(TranslationUnit);
PushBlock(BlockKind.Footer);
PopBlock();
}
public void GenerateForwardReferenceHeaders()
{
PushBlock(BlockKind.IncludesForwardReferences);
var typeReferenceCollector = new CLITypeReferenceCollector(Context.TypeMaps, Context.Options);
typeReferenceCollector.Process(TranslationUnit, filterNamespaces: false);
var includes = new SortedSet<string>(StringComparer.InvariantCulture);
foreach (var typeRef in typeReferenceCollector.TypeReferences)
{
if (typeRef.Include.File == TranslationUnit.FileName)
continue;
var include = typeRef.Include;
if(!string.IsNullOrEmpty(include.File) && !include.InHeader)
includes.Add(include.ToString());
}
foreach (var include in includes)
WriteLine(include);
PopBlock();
}
private void GenerateDeclContext(DeclarationContext @namespace)
{
PushBlock(BlockKind.Namespace);
foreach (var @class in @namespace.Classes)
{
if (!@class.IsGenerated || @class.IsDependent)
continue;
if (@class.IsOpaque || @class.IsIncomplete)
continue;
GenerateClass(@class);
}
PushBlock(BlockKind.FunctionsClass, @namespace);
// Generate all the function declarations for the module.
foreach (var function in @namespace.Functions.Where(f => f.IsGenerated))
{
GenerateFunction(function, @namespace);
NewLine();
}
PopBlock();
if (Options.GenerateFunctionTemplates)
{
foreach (var template in @namespace.Templates)
{
if (!template.IsGenerated) continue;
var functionTemplate = template as FunctionTemplate;
if (functionTemplate == null) continue;
if (!functionTemplate.IsGenerated)
continue;
GenerateFunctionTemplate(functionTemplate);
}
}
foreach(var childNamespace in @namespace.Namespaces)
GenerateDeclContext(childNamespace);
PopBlock();
}
public void GenerateClass(Class @class)
{
PushBlock(BlockKind.Class);
GenerateDeclContext(@class);
GenerateClassConstructors(@class);
GenerateClassMethods(@class, @class);
if (CLIGenerator.ShouldGenerateClassNativeField(@class))
{
var qualifiedIdentifier = QualifiedIdentifier(@class);
PushBlock(BlockKind.Method);
WriteLine("::System::IntPtr {0}::{1}::get()",
qualifiedIdentifier, Helpers.InstanceIdentifier);
WriteOpenBraceAndIndent();
WriteLine("return ::System::IntPtr(NativePtr);");
UnindentAndWriteCloseBrace();
PopBlock(NewLineKind.BeforeNextBlock);
PushBlock(BlockKind.Method);
WriteLine("void {0}::{1}::set(::System::IntPtr object)",
qualifiedIdentifier, Helpers.InstanceIdentifier);
WriteOpenBraceAndIndent();
var nativeType = $"{typePrinter.PrintTag(@class)}::{@class.QualifiedOriginalName}*";
WriteLine("NativePtr = ({0})object.ToPointer();", nativeType);
UnindentAndWriteCloseBrace();
PopBlock(NewLineKind.BeforeNextBlock);
}
GenerateClassProperties(@class, @class);
foreach (var @event in @class.Events)
{
if (!@event.IsGenerated)
continue;
GenerateDeclarationCommon(@event);
GenerateEvent(@event, @class);
}
foreach (var variable in @class.Variables)
{
if (!variable.IsGenerated)
continue;
if (variable.Access != AccessSpecifier.Public)
continue;
GenerateDeclarationCommon(variable);
GenerateVariable(variable, @class);
}
PopBlock();
}
private void GenerateClassConstructors(Class @class)
{
if (@class.IsStatic)
return;
// Output the default constructors taking the native pointer and ownership info.
GenerateClassConstructor(@class);
GenerateClassConstructor(@class, true);
if (@class.IsRefType)
{
var destructor = @class.Destructors
.FirstOrDefault(d => d.Parameters.Count == 0 && d.Access == AccessSpecifier.Public);
if (destructor != null)
{
GenerateClassDestructor(@class);
if (Options.GenerateFinalizerFor(@class))
GenerateClassFinalizer(@class);
}
}
}
private void GenerateClassMethods(Class @class, Class realOwner)
{
if (@class.IsValueType)
foreach (var @base in @class.Bases.Where(b => b.IsClass && !b.Class.Ignore))
GenerateClassMethods(@base.Class, realOwner);
foreach (var method in @class.Methods.Where(m => @class == realOwner || !m.IsOperator))
{
if (ASTUtils.CheckIgnoreMethod(method) || CLIHeaders.FunctionIgnored(method))
continue;
// C++/CLI does not allow special member funtions for value types.
if (@class.IsValueType && method.IsCopyConstructor)
continue;
// Do not generate constructors or destructors from base classes.
var declaringClass = method.Namespace as Class;
if (declaringClass != realOwner && (method.IsConstructor || method.IsDestructor))
continue;
GenerateMethod(method, realOwner);
}
}
private void GenerateClassProperties(Class @class, Class realOwner)
{
if (@class.IsValueType)
{
foreach (var @base in @class.Bases.Where(b => b.IsClass && b.Class.IsDeclared))
{
GenerateClassProperties(@base.Class, realOwner);
}
}
foreach (var property in @class.Properties.Where(
p => !ASTUtils.CheckIgnoreProperty(p) && !p.IsInRefTypeAndBackedByValueClassField() &&
!CLIHeaders.TypeIgnored(p.Type)))
GenerateProperty(property, realOwner);
}
private void GenerateClassDestructor(Class @class)
{
PushBlock(BlockKind.Destructor);
WriteLine("{0}::~{1}()", QualifiedIdentifier(@class), @class.Name);
WriteOpenBraceAndIndent();
PushBlock(BlockKind.DestructorBody, @class);
if (CLIGenerator.ShouldGenerateClassNativeField(@class))
{
WriteLine("delete NativePtr;");
}
else if (@class.HasNonTrivialDestructor)
{
WriteLine("if (NativePtr)");
WriteOpenBraceAndIndent();
WriteLine("auto __nativePtr = NativePtr;");
WriteLine("NativePtr = 0;");
WriteLine($"delete ({typePrinter.PrintTag(@class)}::{@class.QualifiedOriginalName}*) __nativePtr;", @class.QualifiedOriginalName);
UnindentAndWriteCloseBrace();
}
PopBlock();
UnindentAndWriteCloseBrace();
PopBlock(NewLineKind.BeforeNextBlock);
}
private void GenerateClassFinalizer(Class @class)
{
PushBlock(BlockKind.Finalizer);
WriteLine("{0}::!{1}()", QualifiedIdentifier(@class), @class.Name);
WriteOpenBraceAndIndent();
PushBlock(BlockKind.FinalizerBody, @class);
if (CLIGenerator.ShouldGenerateClassNativeField(@class))
WriteLine("delete NativePtr;");
PopBlock();
UnindentAndWriteCloseBrace();
PopBlock(NewLineKind.BeforeNextBlock);
}
private void GenerateFunctionTemplate(FunctionTemplate template)
{
PushBlock(BlockKind.Template);
var function = template.TemplatedFunction;
var typePrinter = new CLITypePrinter(Context);
typePrinter.PushContext(TypePrinterContextKind.Template);
var retType = function.ReturnType.Visit(typePrinter);
var typeNames = "";
var paramNames = template.Parameters.Select(param => param.Name).ToList();
if (paramNames.Any())
typeNames = "typename " + string.Join(", typename ", paramNames);
WriteLine("generic<{0}>", typeNames);
WriteLine("{0} {1}::{2}({3})", retType,
QualifiedIdentifier(function.Namespace), function.Name,
GenerateParametersList(function.Parameters));
WriteOpenBraceAndIndent();
var @class = function.Namespace as Class;
GenerateFunctionCall(function, @class);
UnindentAndWriteCloseBrace();
NewLine();
PopBlock(NewLineKind.BeforeNextBlock);
}
private void GenerateProperty(Property property, Class realOwner)
{
PushBlock(BlockKind.Property);
if (property.Field != null)
{
if (property.HasGetter)
GeneratePropertyGetter(property.Field, realOwner, property.Name,
property.Type);
if (property.HasSetter)
GeneratePropertySetter(property.Field, realOwner, property.Name,
property.Type);
}
else
{
if (property.HasGetter)
GeneratePropertyGetter(property.GetMethod, realOwner, property.Name,
property.Type);
if (property.HasSetter)
if (property.IsIndexer)
GeneratePropertySetter(property.SetMethod, realOwner, property.Name,
property.Type, property.GetMethod.Parameters[0]);
else
GeneratePropertySetter(property.SetMethod, realOwner, property.Name,
property.Type);
}
PopBlock();
}
private void GeneratePropertySetter<T>(T decl, Class @class, string name, Type type, Parameter indexParameter = null)
where T : Declaration, ITypedDecl
{
if (decl == null)
return;
var args = new List<string>();
var isIndexer = indexParameter != null;
if (isIndexer)
args.Add($"{indexParameter.Type} {indexParameter.Name}");
var function = decl as Function;
var argName = function != null && !isIndexer ? function.Parameters[0].Name : "value";
args.Add($"{type} {argName}");
WriteLine("void {0}::{1}::set({2})", QualifiedIdentifier(@class),
name, string.Join(", ", args));
WriteOpenBraceAndIndent();
if (decl is Function && !isIndexer)
{
var func = decl as Function;
var @void = new BuiltinType(PrimitiveType.Void);
GenerateFunctionCall(func, @class, @void);
}
else
{
if (@class.IsValueType && decl is Field)
{
WriteLine("{0} = value;", decl.Name);
UnindentAndWriteCloseBrace();
NewLine();
return;
}
var param = new Parameter
{
Name = "value",
QualifiedType = new QualifiedType(type)
};
string variable;
if (decl is Variable)
variable = $"::{@class.QualifiedOriginalName}::{decl.OriginalName}";
else
variable = $"(({typePrinter.PrintTag(@class)}::{@class.QualifiedOriginalName}*)NativePtr)->{decl.OriginalName}";
var ctx = new MarshalContext(Context, CurrentIndentation)
{
Parameter = param,
ArgName = param.Name,
ReturnVarName = variable
};
var marshal = new CLIMarshalManagedToNativePrinter(ctx);
param.Visit(marshal);
if (isIndexer)
{
var ctx2 = new MarshalContext(Context, CurrentIndentation)
{
Parameter = indexParameter,
ArgName = indexParameter.Name
};
var marshal2 = new CLIMarshalManagedToNativePrinter(ctx2);
indexParameter.Visit(marshal2);
variable += string.Format("({0})", marshal2.Context.Return);
}
if (!string.IsNullOrWhiteSpace(marshal.Context.Before))
Write(marshal.Context.Before);
if (marshal.Context.Return.StringBuilder.Length > 0)
{
if (isIndexer && decl.Type.IsPointer())
WriteLine("*({0}) = {1};", variable, marshal.Context.Return);
else
WriteLine("{0} = {1};", variable, marshal.Context.Return);
}
}
UnindentAndWriteCloseBrace();
NewLine();
}
private void GeneratePropertyGetter<T>(T decl, Class @class, string name, Type type)
where T : Declaration, ITypedDecl
{
if (decl == null)
return;
var method = decl as Method;
var isIndexer = method != null &&
method.OperatorKind == CXXOperatorKind.Subscript;
var args = new List<string>();
if (isIndexer)
{
var indexParameter = method.Parameters[0];
args.Add(string.Format("{0} {1}", indexParameter.Type, indexParameter.Name));
}
WriteLine("{0} {1}::{2}::get({3})", type, QualifiedIdentifier(@class),
name, string.Join(", ", args));
WriteOpenBraceAndIndent();
if (decl is Function)
{
var func = decl as Function;
if (isIndexer && func.Type.IsAddress())
GenerateFunctionCall(func, @class, type);
else
GenerateFunctionCall(func, @class);
}
else
{
if (@class.IsValueType && decl is Field)
{
WriteLine($"return {decl.Name};");
UnindentAndWriteCloseBrace();
NewLine();
return;
}
string variable;
if (decl is Variable)
variable = $"::{@class.QualifiedOriginalName}::{decl.OriginalName}";
else if (CLIGenerator.ShouldGenerateClassNativeField(@class))
variable = $"NativePtr->{decl.OriginalName}";
else
variable = $"(({typePrinter.PrintTag(@class)}::{@class.QualifiedOriginalName}*)NativePtr)->{decl.OriginalName}";
var ctx = new MarshalContext(Context, CurrentIndentation)
{
ArgName = decl.Name,
ReturnVarName = variable,
ReturnType = decl.QualifiedType
};
ctx.PushMarshalKind(MarshalKind.NativeField);
var marshal = new CLIMarshalNativeToManagedPrinter(ctx);
decl.Visit(marshal);
if (!string.IsNullOrWhiteSpace(marshal.Context.Before))
Write(marshal.Context.Before);
WriteLine($"return {marshal.Context.Return};");
}
UnindentAndWriteCloseBrace();
NewLine();
}
private void GenerateEvent(Event @event, Class @class)
{
GenerateEventAdd(@event, @class);
NewLine();
GenerateEventRemove(@event, @class);
NewLine();
GenerateEventRaise(@event, @class);
NewLine();
GenerateEventRaiseWrapper(@event, @class);
NewLine();
}
private void GenerateEventAdd(Event @event, Class @class)
{
WriteLine("void {0}::{1}::add({2} evt)", QualifiedIdentifier(@class),
@event.Name, @event.Type);
WriteOpenBraceAndIndent();
var delegateName = string.Format("_{0}Delegate", @event.Name);
WriteLine("if (!{0}Instance)", delegateName);
WriteOpenBraceAndIndent();
var args = typePrinter.VisitParameters(@event.Parameters, hasNames: false);
WriteLine("{0}Instance = gcnew {0}(this, &{1}::_{2}Raise);",
delegateName, QualifiedIdentifier(@class), @event.Name);
WriteLine("auto _fptr = (void (*)({0}))Marshal::GetFunctionPointerForDelegate({1}Instance).ToPointer();",
args, delegateName);
WriteLine($"(({typePrinter.PrintTag(@class)}::{@class.QualifiedOriginalName}*)NativePtr)->{@event.OriginalName}.Connect(_fptr);");
UnindentAndWriteCloseBrace();
WriteLine("_{0} = static_cast<{1}>(::System::Delegate::Combine(_{0}, evt));",
@event.Name, @event.Type);
UnindentAndWriteCloseBrace();
}
private void GenerateEventRemove(Event @event, Class @class)
{
WriteLine("void {0}::{1}::remove({2} evt)", QualifiedIdentifier(@class),
@event.Name, @event.Type);
WriteOpenBraceAndIndent();
WriteLine("_{0} = static_cast<{1}>(::System::Delegate::Remove(_{0}, evt));",
@event.Name, @event.Type);
UnindentAndWriteCloseBrace();
}
private void GenerateEventRaise(Event @event, Class @class)
{
var typePrinter = new CLITypePrinter(Context);
var args = typePrinter.VisitParameters(@event.Parameters, hasNames: true);
WriteLine("void {0}::{1}::raise({2})", QualifiedIdentifier(@class),
@event.Name, args);
WriteOpenBraceAndIndent();
var paramNames = @event.Parameters.Select(param => param.Name).ToList();
WriteLine("_{0}({1});", @event.Name, string.Join(", ", paramNames));
UnindentAndWriteCloseBrace();
}
private void GenerateEventRaiseWrapper(Event @event, Class @class)
{
var args = typePrinter.VisitParameters(@event.Parameters, hasNames: true);
WriteLine("void {0}::_{1}Raise({2})", QualifiedIdentifier(@class),
@event.Name, args);
WriteOpenBraceAndIndent();
var returns = new List<string>();
foreach (var param in @event.Parameters)
{
var ctx = new MarshalContext(Context, CurrentIndentation)
{
ReturnVarName = param.Name,
ReturnType = param.QualifiedType
};
var marshal = new CLIMarshalNativeToManagedPrinter(ctx);
param.Visit(marshal);
returns.Add(marshal.Context.Return);
}
Write("{0}::raise(", @event.Name);
Write("{0}", string.Join(", ", returns));
WriteLine(");");
UnindentAndWriteCloseBrace();
}
private void GenerateVariable(Variable variable, Class @class)
{
GeneratePropertyGetter(variable, @class, variable.Name, variable.Type);
var arrayType = variable.Type as ArrayType;
var qualifiedType = arrayType != null ? arrayType.QualifiedType : variable.QualifiedType;
if (!qualifiedType.Qualifiers.IsConst)
GeneratePropertySetter(variable, @class, variable.Name, variable.Type);
}
private void GenerateClassConstructor(Class @class, bool withOwnNativeInstanceParam = false)
{
string qualifiedIdentifier = QualifiedIdentifier(@class);
Write("{0}::{1}(", qualifiedIdentifier, @class.Name);
string nativeType = $"{typePrinter.PrintTag(@class)}::{@class.QualifiedOriginalName}*";
WriteLine(!withOwnNativeInstanceParam ? "{0} native)" : "{0} native, bool ownNativeInstance)", nativeType);
var hasBase = GenerateClassConstructorBase(@class, null, withOwnNativeInstanceParam);
if (CLIGenerator.ShouldGenerateClassNativeField(@class))
{
Indent();
Write(hasBase ? "," : ":");
Unindent();
WriteLine(!withOwnNativeInstanceParam ? " {0}(false)" : " {0}(ownNativeInstance)", Helpers.OwnsNativeInstanceIdentifier);
}
WriteOpenBraceAndIndent();
PushBlock(BlockKind.ConstructorBody, @class);
const string nativePtr = "native";
if (@class.IsRefType)
{
if (!hasBase)
{
WriteLine("NativePtr = {0};", nativePtr);
}
}
else
{
GenerateStructMarshaling(@class, nativePtr + "->");
}
PopBlock();
UnindentAndWriteCloseBrace();
string createInstanceParams = withOwnNativeInstanceParam ? $"::System::IntPtr native, bool {Helpers.OwnsNativeInstanceIdentifier}" : "::System::IntPtr native";
string createInstanceParamsValues = withOwnNativeInstanceParam ? $"({nativeType}) native.ToPointer(), {Helpers.OwnsNativeInstanceIdentifier}" : $"({nativeType}) native.ToPointer()";
NewLine();
WriteLine($"{qualifiedIdentifier}^ {qualifiedIdentifier}::{Helpers.CreateInstanceIdentifier}({createInstanceParams})");
WriteOpenBraceAndIndent();
WriteLine($"return gcnew ::{qualifiedIdentifier}({createInstanceParamsValues});");
UnindentAndWriteCloseBrace();
NewLine();
}
private void GenerateStructMarshaling(Class @class, string nativeVar)
{
foreach (var @base in @class.Bases.Where(b => b.IsClass && b.Class.IsDeclared))
{
GenerateStructMarshaling(@base.Class, nativeVar);
}
int paramIndex = 0;
foreach (var property in @class.Properties.Where(
p => !ASTUtils.CheckIgnoreProperty(p) && !CLIHeaders.TypeIgnored(p.Type)))
{
if (property.Field == null)
continue;
var nativeField = string.Format("{0}{1}",
nativeVar, property.Field.OriginalName);
var ctx = new MarshalContext(Context, CurrentIndentation)
{
ArgName = property.Name,
ReturnVarName = nativeField,
ReturnType = property.QualifiedType,
ParameterIndex = paramIndex++
};
ctx.PushMarshalKind(MarshalKind.NativeField);
var marshal = new CLIMarshalNativeToManagedPrinter(ctx);
property.Visit(marshal);
if (!string.IsNullOrWhiteSpace(marshal.Context.Before))
Write(marshal.Context.Before);
WriteLine("{0} = {1};", property.Field.Name, marshal.Context.Return);
}
}
private bool GenerateClassConstructorBase(Class @class, Method method = null,
bool withOwnNativeInstanceParam = false)
{
if (!@class.NeedsBase)
return false;
if (@class.IsValueType)
return true;
Indent();
Write($": {QualifiedIdentifier(@class.BaseClass)}(");
// We cast the value to the base class type since otherwise there
// could be ambiguous call to overloaded constructors.
var cppTypePrinter = new CppTypePrinter(Context);
var nativeTypeName = @class.BaseClass.Visit(cppTypePrinter);
Write($"({nativeTypeName}*)");
WriteLine("{0}{1})", method != null ? "nullptr" : "native",
!withOwnNativeInstanceParam ? "" : ", ownNativeInstance");
Unindent();
return true;
}
public void GenerateMethod(Method method, Class @class)
{
if (CLIHeaders.FunctionIgnored(method))
return;
PushBlock(BlockKind.Method, method);
if (method.IsConstructor || method.IsDestructor ||
method.OperatorKind == CXXOperatorKind.Conversion ||
method.OperatorKind == CXXOperatorKind.ExplicitConversion)
Write("{0}::{1}(", QualifiedIdentifier(@class), GetMethodName(method));
else
Write("{0} {1}::{2}(", method.ReturnType, QualifiedIdentifier(@class),
method.Name);
GenerateMethodParameters(method);
WriteLine(")");
if (method.IsConstructor)
GenerateClassConstructorBase(@class, method: method);
WriteOpenBraceAndIndent();
PushBlock(BlockKind.MethodBody, method);
if (method.IsConstructor && @class.IsRefType)
{
PushBlock(BlockKind.ConstructorBody, @class);
WriteLine("{0} = true;", Helpers.OwnsNativeInstanceIdentifier);
}
if (method.IsProxy)
goto SkipImpl;
if (@class.IsRefType)
{
if (method.IsConstructor)
{
if (!@class.IsAbstract)
{
var @params = GenerateFunctionParamsMarshal(method.Parameters, method);
Write($@"NativePtr = new {typePrinter.PrintTag(@class)}::{
@class.QualifiedOriginalName}(");
GenerateFunctionParams(@params);
WriteLine(");");
}
PopBlock();
}
else
{
GenerateFunctionCall(method, @class);
}
}
else if (@class.IsValueType)
{
if (!method.IsConstructor)
GenerateFunctionCall(method, @class);
else
GenerateValueTypeConstructorCall(method, @class);
}
SkipImpl:
PopBlock();
UnindentAndWriteCloseBrace();
if (method.OperatorKind == CXXOperatorKind.EqualEqual)
{
GenerateEquals(method, @class);
}
PopBlock(NewLineKind.Always);
}
private void GenerateEquals(Function method, Class @class)
{
Class leftHandSide;
Class rightHandSide;
if (method.Parameters[0].Type.SkipPointerRefs().TryGetClass(out leftHandSide) &&
leftHandSide.OriginalPtr == @class.OriginalPtr &&
method.Parameters[1].Type.SkipPointerRefs().TryGetClass(out rightHandSide) &&
rightHandSide.OriginalPtr == @class.OriginalPtr)
{
NewLine();
var qualifiedIdentifier = QualifiedIdentifier(@class);
WriteLine("bool {0}::Equals(::System::Object^ obj)", qualifiedIdentifier);
WriteOpenBraceAndIndent();
if (@class.IsRefType)
{
WriteLine("return this == safe_cast<{0}^>(obj);", qualifiedIdentifier);
}
else
{
WriteLine("return *this == safe_cast<{0}>(obj);", qualifiedIdentifier);
}
UnindentAndWriteCloseBrace();
}
}
private void GenerateValueTypeConstructorCall(Method method, Class @class)
{
var names = new List<string>();
var paramIndex = 0;
foreach (var param in method.Parameters)
{
var ctx = new MarshalContext(Context, CurrentIndentation)
{
Function = method,
Parameter = param,
ArgName = param.Name,
ParameterIndex = paramIndex++
};
var marshal = new CLIMarshalManagedToNativePrinter(ctx);
param.Visit(marshal);
if (!string.IsNullOrWhiteSpace(marshal.Context.Before))
Write(marshal.Context.Before);
names.Add(marshal.Context.Return);
}
WriteLine($@"{typePrinter.PrintTag(@class)}::{
@class.QualifiedOriginalName} _native({string.Join(", ", names)});");
GenerateValueTypeConstructorCallProperties(@class);
}
private void GenerateValueTypeConstructorCallProperties(Class @class)
{
foreach (var @base in @class.Bases.Where(b => b.IsClass && b.Class.IsDeclared))
{
GenerateValueTypeConstructorCallProperties(@base.Class);
}
foreach (var property in @class.Properties)
{
if (!property.IsDeclared || property.Field == null) continue;
var varName = $"_native.{property.Field.OriginalName}";
var ctx = new MarshalContext(Context, CurrentIndentation)
{
ReturnVarName = varName,
ReturnType = property.QualifiedType
};
var marshal = new CLIMarshalNativeToManagedPrinter(ctx);
property.Visit(marshal);
if (!string.IsNullOrWhiteSpace(marshal.Context.Before))
Write(marshal.Context.Before);
WriteLine("this->{0} = {1};", property.Name, marshal.Context.Return);
}
}
public void GenerateFunction(Function function, DeclarationContext @namespace)
{
if (!function.IsGenerated || CLIHeaders.FunctionIgnored(function))
return;
GenerateDeclarationCommon(function);
var classSig = string.Format("{0}::{1}", QualifiedIdentifier(@namespace),
TranslationUnit.FileNameWithoutExtension);
Write("{0} {1}::{2}(", function.ReturnType, classSig,
function.Name);
for (var i = 0; i < function.Parameters.Count; ++i)
{
var param = function.Parameters[i];
Write("{0}", CTypePrinter.VisitParameter(param));
if (i < function.Parameters.Count - 1)
Write(", ");
}
WriteLine(")");
WriteOpenBraceAndIndent();
GenerateFunctionCall(function);
UnindentAndWriteCloseBrace();
}
public void GenerateFunctionCall(Function function, Class @class = null, Type publicRetType = null)
{
CheckArgumentRange(function);
if (function.OperatorKind == CXXOperatorKind.EqualEqual ||
function.OperatorKind == CXXOperatorKind.ExclaimEqual)
{
WriteLine("bool {0}Null = ReferenceEquals({0}, nullptr);",
function.Parameters[0].Name);
WriteLine("bool {0}Null = ReferenceEquals({0}, nullptr);",
function.Parameters[1].Name);
WriteLine("if ({0}Null || {1}Null)",
function.Parameters[0].Name, function.Parameters[1].Name);
WriteLineIndent("return {0}{1}Null && {2}Null{3};",
function.OperatorKind == CXXOperatorKind.EqualEqual ? string.Empty : "!(",
function.Parameters[0].Name, function.Parameters[1].Name,
function.OperatorKind == CXXOperatorKind.EqualEqual ? string.Empty : ")");
}
var retType = function.ReturnType;
if (publicRetType == null)
publicRetType = retType.Type;
var needsReturn = !publicRetType.IsPrimitiveType(PrimitiveType.Void);
const string valueMarshalName = "_this0";
var isValueType = @class != null && @class.IsValueType;
if (isValueType && !IsNativeFunctionOrStaticMethod(function))
{
WriteLine($"auto {valueMarshalName} = {typePrinter.PrintTag(@class)}::{@class.QualifiedOriginalName}();");
var param = new Parameter { Name = "(*this)" , Namespace = function.Namespace };
var ctx = new MarshalContext(Context, CurrentIndentation)
{
Parameter = param
};
ctx.VarPrefix.Write(valueMarshalName);
var marshal = new CLIMarshalManagedToNativePrinter(ctx);
marshal.MarshalValueClassProperties(@class, valueMarshalName);
if (!string.IsNullOrWhiteSpace(marshal.Context.Before))
Write(marshal.Context.Before);
}
var @params = GenerateFunctionParamsMarshal(function.Parameters, function);
var returnIdentifier = Helpers.ReturnIdentifier;
if (needsReturn)
if (retType.Type.IsReference())
Write("auto &{0} = ", returnIdentifier);
else
Write("auto {0} = ", returnIdentifier);
if (function.OperatorKind == CXXOperatorKind.Conversion ||
function.OperatorKind == CXXOperatorKind.ExplicitConversion)
{
var method = function as Method;
var typeName = method.ConversionType.Visit(new CppTypePrinter(Context));
WriteLine("({0}) {1};", typeName, @params[0].Name);
}
else if (function.IsOperator &&
function.OperatorKind != CXXOperatorKind.Subscript)
{
var opName = function.Name.Replace("operator", "").Trim();
switch (Operators.ClassifyOperator(function))
{
case CXXOperatorArity.Unary:
WriteLine("{0} {1};", opName, @params[0].Name);
break;
case CXXOperatorArity.Binary:
WriteLine("{0} {1} {2};", @params[0].Name, opName, @params[1].Name);
break;
}
}
else
{
if (IsNativeFunctionOrStaticMethod(function))
{
Write($"::{function.QualifiedOriginalName}(");
}
else
{
if (isValueType)
Write($"{valueMarshalName}.");
else if (IsNativeMethod(function))
Write($"(({typePrinter.PrintTag(@class)}::{@class.QualifiedOriginalName}*)NativePtr)->");
Write("{0}(", function.OriginalName);
}
GenerateFunctionParams(@params);
WriteLine(");");
}
foreach(var paramInfo in @params)
{
var param = paramInfo.Param;
if(param.Usage != ParameterUsage.Out && param.Usage != ParameterUsage.InOut)
continue;
if (param.Type.IsPointer() && !param.Type.GetFinalPointee().IsPrimitiveType())
param.QualifiedType = new QualifiedType(param.Type.GetFinalPointee());
var nativeVarName = paramInfo.Name;
var ctx = new MarshalContext(Context, CurrentIndentation)
{
ArgName = nativeVarName,
ReturnVarName = nativeVarName,
ReturnType = param.QualifiedType
};
var marshal = new CLIMarshalNativeToManagedPrinter(ctx);
param.Visit(marshal);
if (!string.IsNullOrWhiteSpace(marshal.Context.Before))
Write(marshal.Context.Before);
WriteLine("{0} = {1};",param.Name,marshal.Context.Return);
}
if (isValueType && !IsNativeFunctionOrStaticMethod(function))
{
GenerateStructMarshaling(@class, valueMarshalName + ".");
}
if (needsReturn)
{
var retTypeName = retType.Visit(CTypePrinter).ToString();
var isIntPtr = retTypeName.Contains("IntPtr");
if (retType.Type.IsPointer() && (isIntPtr || retTypeName.EndsWith("^", StringComparison.Ordinal)))
{
WriteLine("if ({0} == nullptr) return {1};",
returnIdentifier,
isIntPtr ? "::System::IntPtr()" : "nullptr");
}
var ctx = new MarshalContext(Context, CurrentIndentation)
{
ArgName = returnIdentifier,
ReturnVarName = returnIdentifier,
ReturnType = retType
};
var marshal = new CLIMarshalNativeToManagedPrinter(ctx);
retType.Visit(marshal);
if (!string.IsNullOrWhiteSpace(marshal.Context.Before))
Write(marshal.Context.Before);
// Special case for indexer - needs to dereference if the internal
// function is a pointer type and the property is not.
if (retType.Type.IsPointer() &&
retType.Type.GetPointee().Equals(publicRetType) &&
publicRetType.IsPrimitiveType())
WriteLine("return *({0});", marshal.Context.Return);
else if (retType.Type.IsReference() && publicRetType.IsReference())
WriteLine("return ({0})({1});", publicRetType, marshal.Context.Return);
else
WriteLine("return {0};", marshal.Context.Return);
}
}
private void CheckArgumentRange(Function method)
{
if (Context.Options.MarshalCharAsManagedChar)
{
foreach (var param in method.Parameters.Where(
p => p.Type.IsPrimitiveType(PrimitiveType.Char)))
{
WriteLine("if ({0} < ::System::Char::MinValue || {0} > ::System::SByte::MaxValue)", param.Name);
// C++/CLI can actually handle char -> sbyte in all case, this is for compatibility with the C# generator
WriteLineIndent(
"throw gcnew ::System::OverflowException(\"{0} must be in the range {1} - {2}.\");",
param.Name, (int) char.MinValue, sbyte.MaxValue);
}
}
}
private static bool IsNativeMethod(Function function)
{
var method = function as Method;
if (method == null)
return false;
return method.Conversion == MethodConversionKind.None;
}
private static bool IsNativeFunctionOrStaticMethod(Function function)
{
var method = function as Method;
if (method == null)
return true;
if (method.IsOperator && Operators.IsBuiltinOperator(method.OperatorKind))
return true;
return method.IsStatic || method.Conversion != MethodConversionKind.None;
}
public struct ParamMarshal
{
public string Name;
public string Prefix;
public Parameter Param;
}
public List<ParamMarshal> GenerateFunctionParamsMarshal(IEnumerable<Parameter> @params,
Function function = null)
{
var marshals = new List<ParamMarshal>();
var paramIndex = 0;
foreach (var param in @params)
{
marshals.Add(GenerateFunctionParamMarshal(param, paramIndex, function));
paramIndex++;
}
return marshals;
}
private ParamMarshal GenerateFunctionParamMarshal(Parameter param, int paramIndex,
Function function = null)
{
var paramMarshal = new ParamMarshal { Name = param.Name, Param = param };
if (param.Type is BuiltinType)
return paramMarshal;
var argName = Generator.GeneratedIdentifier("arg") + paramIndex.ToString(CultureInfo.InvariantCulture);
var isRef = param.IsOut || param.IsInOut;
var paramType = param.Type;
// Get actual type if the param type is a typedef but not a function type because function types have to be typedef.
// We need to get the actual type this early before we visit any marshalling code to ensure we hit the marshalling
// logic for the actual type and not the typedef.
// This fixes issues where typedefs to primitive pointers are involved.
FunctionType functionType;
var paramTypeAsTypedef = paramType as TypedefType;
if (paramTypeAsTypedef != null && !paramTypeAsTypedef.Declaration.Type.IsPointerTo(out functionType))
{
paramType = param.Type.Desugar();
}
// Since both pointers and references to types are wrapped as CLI
// tracking references when using in/out, we normalize them here to be able
// to use the same code for marshaling.
if (paramType is PointerType && isRef)
{
if (!paramType.IsReference())
paramMarshal.Prefix = "&";
paramType = (paramType as PointerType).Pointee;
}
var effectiveParam = new Parameter(param)
{
QualifiedType = new QualifiedType(paramType)
};
var ctx = new MarshalContext(Context, CurrentIndentation)
{
Parameter = effectiveParam,
ParameterIndex = paramIndex,
ArgName = argName,
Function = function
};
var marshal = new CLIMarshalManagedToNativePrinter(ctx);
effectiveParam.Visit(marshal);
if (string.IsNullOrEmpty(marshal.Context.Return))
throw new Exception($"Cannot marshal argument of function '{function.QualifiedOriginalName}'");
if (isRef)
{
var typePrinter = new CppTypePrinter(Context) { ResolveTypeMaps = false };
var type = paramType.Visit(typePrinter);
if (param.IsInOut)
{
if (!string.IsNullOrWhiteSpace(marshal.Context.Before))
Write(marshal.Context.Before);
WriteLine("{0} {1} = {2};", type, argName, marshal.Context.Return);
}
else
WriteLine("{0} {1};", type, argName);
}
else
{
if (!string.IsNullOrWhiteSpace(marshal.Context.Before))
Write(marshal.Context.Before);
WriteLine("auto {0}{1} = {2};", marshal.VarPrefix, argName,
marshal.Context.Return);
paramMarshal.Prefix = marshal.ArgumentPrefix;
}
paramMarshal.Name = argName;
return paramMarshal;
}
public void GenerateFunctionParams(List<ParamMarshal> @params)
{
var names = @params.Select(param =>
{
if (!string.IsNullOrWhiteSpace(param.Prefix))
return param.Prefix + param.Name;
return param.Name;
}).ToList();
Write(string.Join(", ", names));
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface001.integeregererface001
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface001.integeregererface001;
// <Title>Interfaces</Title>
// <Description>covariance between object/dynamic - implicit/explicit implementations
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public interface I
{
int Foo(object o);
int Bar(dynamic o);
}
public struct C : I
{
public int Foo(dynamic d)
{
Test.Status = 1;
return 1;
}
public int Bar(object d)
{
Test.Status = 2;
return 2;
}
}
public class CExp : I
{
int I.Foo(object d)
{
Test.Status = 3;
return 3;
}
int I.Bar(dynamic d)
{
Test.Status = 4;
return 4;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new C();
I i = d;
bool ret = 1 == i.Foo(2);
ret &= 2 == i.Bar(null);
d = new CExp();
i = d;
ret &= 3 == i.Foo(2);
ret &= 4 == i.Bar(null);
return ret ? 0 : 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface007.integeregererface007
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface007.integeregererface007;
// <Title>Interfaces</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public interface I
{
dynamic Foo();
}
public class C : I
{
public object Foo()
{
Test.Status = 1;
return 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
I i = new C();
i.Foo();
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface008.integeregererface008
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface008.integeregererface008;
// <Title>Interfaces</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public interface I
{
dynamic Foo();
}
public class C : I
{
object I.Foo()
{
Test.Status = 1;
return 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
I i = new C();
i.Foo();
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface009.integeregererface009
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface009.integeregererface009;
// <Title>Interfaces</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public interface I
{
object Foo();
}
public class C : I
{
dynamic I.Foo()
{
Test.Status = 1;
return 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
I i = new C();
i.Foo();
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface010.integeregererface010
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface010.integeregererface010;
// <Title>Interfaces</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public interface I
{
int Foo(object o, int x);
}
public class C : I
{
public int Foo(dynamic d, int x)
{
Test.Status = 1;
return 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
I i = new C();
i.Foo(2, 3);
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface011.integeregererface011
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface011.integeregererface011;
// <Title>Interfaces</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System.Collections.Generic;
public interface I
{
List<dynamic> Foo();
}
public class C : I
{
public List<dynamic> Foo()
{
Test.Status = 1;
return new List<dynamic>();
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
I i = new C();
var x = i.Foo();
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface012.integeregererface012
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface012.integeregererface012;
// <Title>Interfaces</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System.Collections.Generic;
public interface I
{
List<dynamic> Foo();
}
public class C : I
{
List<dynamic> I.Foo()
{
Test.Status = 1;
return new List<dynamic>();
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
I i = new C();
var x = i.Foo();
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface013.integeregererface013
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface013.integeregererface013;
// <Title>Interfaces</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System.Collections.Generic;
public interface I
{
List<dynamic> Foo();
}
public class C : I
{
List<object> I.Foo()
{
Test.Status = 1;
return new List<dynamic>();
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
I i = new C();
var x = i.Foo();
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface014.integeregererface014
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface014.integeregererface014;
// <Title>Interfaces</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System.Collections.Generic;
public interface I
{
List<object> Foo();
}
public class C : I
{
List<dynamic> I.Foo()
{
Test.Status = 1;
return new List<object>();
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
I i = new C();
var x = i.Foo();
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface015.integeregererface015
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface015.integeregererface015;
// <Title>Interfaces</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System.Collections.Generic;
public interface I
{
void Foo(List<object> o);
}
public class C : I
{
void I.Foo(List<object> o)
{
Test.Status = 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
I i = new C();
i.Foo(new List<dynamic>());
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface016.integeregererface016
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface016.integeregererface016;
// <Title>Interfaces</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System.Collections.Generic;
public interface I
{
void Foo(List<dynamic> o);
}
public class C : I
{
void I.Foo(List<object> o)
{
Test.Status = 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
I i = new C();
i.Foo(new List<dynamic>());
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
| |
// Copyright (c) 2010 Ben Phegan
// 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.IO;
using System.Reflection;
using System.Resources;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using GraphSearch;
using RenderConfig.Core.Interfaces;
namespace RenderConfig.Core
{
/// <summary>
/// Runs a set of configurations against a set of source files.
/// </summary>
public class RenderConfigEngine
{
private Stack<Node<string>> dependencyStack;
private Stack<Node<string>> variableStack;
private List<Node<string>> nodeList;
IRenderConfigLogger log;
RenderConfigConfig config;
/// <summary>
/// Initializes a new instance of the <see cref="RenderConfigEngine"/> class.
/// </summary>
/// <param name="config">The config.</param>
/// <param name="log">The IRenderConfigLogger to use.</param>
public RenderConfigEngine(RenderConfigConfig config, IRenderConfigLogger log)
{
this.log = log;
this.config = config;
}
/// <summary>
/// Renders the configuration specified.
/// </summary>
/// <returns></returns>
public bool Render()
{
LogUtilities.LogSettings(config,log);
nodeList = new List<Node<string>>();
Boolean returnCode = true;
if (File.Exists(config.ConfigFile))
{
log.LogMessage("Reading in configuration file...");
RenderConfig renderConfig = ReadConfigurationFile();
if (renderConfig != null)
{
//HACK We should be using a deep copy so that all this becomes "variableStack = dependencyStack.Clone();"
//Get the list of nodes
nodeList = GenerateNodeList(renderConfig, log);
if (SearchForNodeByIdentity(nodeList, config.Configuration) == null)
{
throw new ApplicationException("Could not find Configuration : " + config.Configuration);
}
List<Node<string>> n2 = GenerateNodeList(renderConfig, log);
//Generate the dependency path
DepthFirstSearch<string> dfs = new DepthFirstSearch<string>(nodeList);
DepthFirstSearch<string> dfs2 = new DepthFirstSearch<string>(n2);
dependencyStack = dfs.GetDependencyPath(config.Configuration);
//HACK Need to write a deep copy Queue Clone to get rid of this...
variableStack = dfs2.GetDependencyPath(config.Configuration);
}
if (Directory.Exists(config.OutputDirectory))
{
if (config.DeleteOutputDirectory)
{
log.LogMessage("Deleting and recreating output directory...");
Directory.Delete(config.OutputDirectory, true);
Directory.CreateDirectory(config.OutputDirectory);
}
}
else
{
log.LogMessage("Creating output directory...");
Directory.CreateDirectory(config.OutputDirectory);
}
//Create a queue of mods to run and a queue of EnvironmentVariables to implement
//Variables have to be put in place before the mods...
log.LogMessage("Building dependency queue...");
Queue<Configuration> configsToRun = CreateConfigProcessQueue(renderConfig, dependencyStack);
//HACK This is ugly, needs a deep copy here....
Queue<Configuration> envQueue = CreateConfigProcessQueue(renderConfig, variableStack);
while (envQueue.Count > 0)
{
Configuration varConfig = envQueue.Dequeue();
//First, we need to get all the Variables and create them.
foreach (EnvironmentVariable variable in varConfig.EnvironmentVariables)
{
Environment.SetEnvironmentVariable(variable.variable, variable.Value);
}
}
while (configsToRun.Count > 0)
{
Configuration currentConfig = configsToRun.Dequeue();
log.LogMessage(MessageImportance.High, "Running modification: " + currentConfig.Name);
if (currentConfig.TargetFiles != null)
{
if (!currentConfig.Apply(config, log))
{
log.LogError("Failed to apply configuration: " + currentConfig.Name);
returnCode = false;
}
}
}
}
else
{
log.LogError("Could not find configuration file: " + config.ConfigFile);
returnCode = false;
}
//Let 'em know
if (returnCode)
{
log.LogMessage(MessageImportance.High, "Configuration rendered!");
}
else
{
log.LogError("Failed to render configuration.");
}
return returnCode;
}
/// <summary>
/// Creates the config process stack.
/// </summary>
/// <param name="configs">The configs.</param>
/// <param name="dependencyStack">The dependency stack.</param>
/// <returns></returns>
private Queue<Configuration> CreateConfigProcessQueue(RenderConfig renderConfig, Stack<Node<string>> dependencyStack)
{
Queue<Configuration> configQueue = new Queue<Configuration>();
while (dependencyStack.Count > 0)
{
Node<string> node = dependencyStack.Pop();
foreach (Configuration c in renderConfig.Configurations)
{
if (c.Name == node.Identity)
{
configQueue.Enqueue(c);
}
}
}
return configQueue;
}
/// <summary>
/// Generates the node list.
/// </summary>
/// <param name="configs">The configs.</param>
private static List<Node<string>> GenerateNodeList(RenderConfig renderConfig, IRenderConfigLogger log)
{
//Create list of all nodes, without dependencies
log.LogMessage("Generating Node List...");
List<Node<string>> nodes = CreateInitialNodeList(renderConfig);
foreach (Configuration config in renderConfig.Configurations)
{
//Split the dependencies, and then for each of them find a node in nodeList, and add as a dependency
if (!String.IsNullOrEmpty(config.Depends))
{
string[] dependencies = config.Depends.Split(',', ';');
foreach (string depends in dependencies)
{
Node<string> dependencyNode = SearchForNodeByIdentity(nodes, depends.Trim());
if (dependencyNode == null)
{
throw new ApplicationException("Error in configuration, cannot resolve dependency " + depends);
}
else
{
SearchForNodeByIdentity(nodes, config.Name).Dependencies.Add(dependencyNode);
}
}
}
}
return nodes;
}
/// <summary>
/// Creates the initial node list.
/// </summary>
/// <param name="configs">The configs.</param>
private static List<Node<string>> CreateInitialNodeList(RenderConfig renderConfig)
{
List<Node<string>> nodes = new List<Node<string>>();
foreach (Configuration config in renderConfig.Configurations)
{
if (SearchForNodeByIdentity(nodes, config.Name) != null)
{
throw new ApplicationException("Configuration exists in file twice");
}
else
{
Node<string> node = new Node<string>(config.Name);
nodes.Add(node);
}
}
return nodes;
}
/// <summary>
/// Searches for node by identity.
/// </summary>
/// <param name="identity">The identity.</param>
/// <returns></returns>
private static Node<string> SearchForNodeByIdentity(List<Node<string>> nodeList, string identity)
{
foreach (Node<string> node in nodeList)
{
if (node.Identity == identity)
{
return node;
}
}
return null;
}
/// <summary>
/// Reads the configuration file.
/// </summary>
/// <returns></returns>
private RenderConfig ReadConfigurationFile()
{
XmlSerializer serializer = new XmlSerializer(typeof(RenderConfig));
RenderConfig configs;
using (FileStream stream = new FileStream(config.ConfigFile, FileMode.Open))
{
//Set up some settings to allow DTD Entity includes
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.None;
settings.ProhibitDtd = false;
settings.Schemas.Add(GetXmlSchemaSet());
using (XmlReader reader = XmlReader.Create(stream, settings))
{
try
{
configs = (RenderConfig)serializer.Deserialize(reader);
}
catch (InvalidOperationException iv)
{
throw new InvalidOperationException("Could not deserialise config file, please check against XSD", iv);
}
catch (Exception i)
{
throw new ApplicationException("Could not deserialise config file, please check against XSD", i);
}
}
stream.Close();
}
if (configs.Includes != null)
{
if (configs.Includes.Count != 0)
{
DeserializeAndAddIncludes(configs);
}
}
log.LogMessage("Completed loading configuration files.");
log.LogMessage("Found " + configs.Configurations.Count + " configurations...");
return configs;
}
/// <summary>
/// Deserializes and Included files, and adds them as Configuration objects.
/// </summary>
/// <param name="configs">The configs.</param>
private void DeserializeAndAddIncludes(RenderConfig configs)
{
XmlSerializer configSerializer = new XmlSerializer(typeof(Configuration));
foreach (Include include in configs.Includes)
{
string includeFile = include.file;
if (!File.Exists(includeFile))
{
FileInfo configFile = new FileInfo(config.ConfigFile);
includeFile = Path.Combine(configFile.Directory.FullName, include.file);
}
if (File.Exists(includeFile))
{
log.LogMessage("Attempting to include file: " + include.file);
try
{
XmlDocument includeXml = new XmlDocument();
includeXml.Load(includeFile);
XmlNodeList nodes = includeXml.SelectNodes(@"//Configuration");
if (nodes.Count > 0)
{
log.LogMessage(string.Concat(include.file, " contained ",nodes.Count," Configuration Nodes"));
foreach (XmlNode node in nodes)
{
using (XmlReader nodeReader = XmlReader.Create(new StringReader(node.OuterXml.ToString())))
{
configs.Configurations.Add((Configuration)configSerializer.Deserialize(nodeReader));
}
}
}
else
{
log.LogError(string.Concat("Could not find any Configuration nodes in ",include.file));
}
}
catch (ApplicationException i)
{
log.LogError("Could not load include file: " + include.file);
throw new ApplicationException("Could not load include file: " + include.file, i);
}
}
else
{
log.LogError("Could not find include file: " + include.file);
throw new ApplicationException("Could not find include file: " + include.file);
}
}
}
/// <summary>
/// Gets an XML schema set, including the Configuration.xsd included as a resource in assembly.
/// </summary>
/// <returns></returns>
private static XmlSchemaSet GetXmlSchemaSet()
{
XmlSchemaSet xsc = new XmlSchemaSet();
ResourceManager resources = new ResourceManager("RenderConfig.Core.Resources", Assembly.GetExecutingAssembly());
string xsd = (string)resources.GetObject("Configuration");
using (XmlReader schemaReader = XmlReader.Create(new StringReader(xsd)))
{
//add the schema to the schema set
xsc.Add(XmlSchema.Read(schemaReader, new ValidationEventHandler(delegate(Object sender, ValidationEventArgs e) { })));
}
return xsc;
}
/// <summary>
/// Replaces the provided token in a file.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="targetFile">The target file.</param>
/// <returns></returns>
public static int ReplaceTokenInFile(string key, string value, string targetFile)
{
int count = 0;
string source = RegExParseAndReplace(out count, key, value ,File.ReadAllText(targetFile));
File.WriteAllText(targetFile, source);
return count;
}
/// <summary>
/// Parses a string, replacing a key using a regex, returns the number of replacements.
/// </summary>
/// <param name="count">The count.</param>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="source">The source.</param>
/// <returns></returns>
public static string RegExParseAndReplace(out int count, string key, string value, string source)
{
Regex r = new Regex(key);
count = 0;
MatchCollection mc = r.Matches(source);
if (mc.Count > 0)
{
source = source.Replace(key, value);
count = mc.Count;
}
return source;
}
public static int CharacterCountInString(string stringValue, char character)
{
int returnVal = 0;
foreach (char c in stringValue)
{
if (c == character)
{
returnVal++;
}
}
return returnVal;
}
/// <summary>
/// Regs the ex parse and replace string.
/// </summary>
/// <param name="stringToParse">The string to parse.</param>
/// <param name="regex">The regex.</param>
/// <param name="replacement">The replacement.</param>
/// <returns></returns>
public static string RegExParseAndReplaceString(string stringToParse, string regex, string replacement)
{
string returnString = stringToParse;
Regex r = new Regex(regex);
MatchCollection mc = r.Matches(stringToParse);
if (mc.Count > 0)
{
returnString = returnString.Replace(regex, replacement);
}
return returnString;
}
/// <summary>
/// Returns a string array as a single concatenated string.
/// </summary>
/// <param name="stringToParse">The string to parse.</param>
/// <returns></returns>
public static String ReturnStringArrayAsString(string[] stringToParse)
{
return ReturnStringArrayAsString(stringToParse, null);
}
/// <summary>
/// Substitutes the specified target, basically a simple copy operation.
/// </summary>
/// <param name="target">The target.</param>
/// <param name="directory">The directory.</param>
public static void Substitute(ITargetFile target, string directory)
{
try
{
FileInfo file = new FileInfo(ResolveAndCopyDestinationFilename(target, directory, false));
if (!Directory.Exists(file.DirectoryName))
{
Directory.CreateDirectory(file.DirectoryName);
}
File.Copy(target.source, file.FullName, true);
}
catch (Exception i)
{
throw new Exception("Failed to copy " + target.source + " to " + target.destination, i);
}
}
/// <summary>
/// Returns the string array as string, can include a delimeter where strings are joined.
/// </summary>
/// <param name="stringArray">The string array.</param>
/// <param name="delimeter">The delimeter.</param>
/// <returns></returns>
public static string ReturnStringArrayAsString(string[] array, char? delimeter)
{
string concatenated = string.Empty;
if (array != null)
{
if (array.Length > 0)
{
foreach (string s in array)
{
if (delimeter.HasValue)
{
concatenated = string.Concat(concatenated, delimeter.ToString(), s);
}
else
{
concatenated = String.Concat(concatenated, s);
}
}
}
}
return concatenated;
}
/// <summary>
/// Copies the source file to destination file.
/// </summary>
/// <param name="file">The file.</param>
/// <param name="destination">The destination.</param>
private static void CopySourceFileToDestinationFile(ITargetFile file, string destination)
{
//We assume that for most we will not have an existing file, and we will want to copy the target
//to the destination. We also need to ensure that if the directory that we want to copy into is
//not there that we create it.
FileInfo fileInfo = new FileInfo(destination);
if (!Directory.Exists(fileInfo.DirectoryName))
{
Directory.CreateDirectory(fileInfo.DirectoryName);
}
File.Copy(Path.Combine(Directory.GetCurrentDirectory(), file.source), destination);
}
/// <summary>
/// Gets the target file based on the source file and the target output directory. Takes into account InputDirectory and PreserveStructure flags.
/// </summary>
/// <param name="file">The TargetFile object we are using.</param>
/// <param name="configDirectory">The config directory.</param>
/// <param name="copyFile">if set to <c>true</c> [copy file], otherwise if the file is not in place it will not be copied.</param>
/// <returns></returns>
public static string ResolveAndCopyDestinationFilename(ITargetFile file, string configDirectory, Boolean copyFile)
{
string destination;
//First, are we just dropping the file into the target root directory with the same name?
//We need to sort out what the target filename is if we are not passing one in.
if (String.IsNullOrEmpty(file.destination))
{
FileInfo fileInfo = new FileInfo(file.source);
destination = Path.Combine(configDirectory, fileInfo.Name);
}
else
{
destination = Path.Combine(configDirectory, file.destination);
}
//Copy over the file if it does not already exist. If it exists, odds on a configuration has already run...
if (!File.Exists(destination) && copyFile)
{
CopySourceFileToDestinationFile(file, destination);
}
return destination;
}
/// <summary>
/// Replaces environment variables in a string, where the variable is provided as a token eg $(variable).
/// </summary>
/// <param name="stringToParse">The string to parse.</param>
/// <returns></returns>
public static String ReplaceEnvironmentVariables(string stringToParse)
{
Regex r = new Regex(@"\$\(([^)]*)\)");
string returnString = stringToParse;
MatchCollection mc = r.Matches(stringToParse);
if (mc.Count > 0)
{
for (int j = 0; j < mc.Count; j++)
{
Match m = mc[j];
if (m.Groups.Count == 2)
{
returnString = returnString.Replace(m.Value, Environment.GetEnvironmentVariable(m.Groups[1].Value));
}
}
}
return returnString;
}
public static Boolean RunAllConfigurations(RenderConfigConfig config, IRenderConfigLogger log)
{
Boolean returnBool = false;
if (config.Configuration.Contains(","))
{
string[] configs = config.Configuration.Split(',');
foreach (string configToRun in configs)
{
RenderConfigConfig newConfig = (RenderConfigConfig)config.Clone();
newConfig.Configuration = configToRun;
if (config.SubDirectoryEachConfiguration)
{
newConfig.OutputDirectory = Path.Combine(newConfig.OutputDirectory, configToRun);
}
RenderConfigEngine engine = new RenderConfigEngine(newConfig, log);
returnBool = engine.Render();
}
}
else
{
if (config.SubDirectoryEachConfiguration)
{
if (!String.IsNullOrEmpty(config.OutputDirectory))
{
config.OutputDirectory = Path.Combine(config.OutputDirectory, config.Configuration);
}
else
{
config.OutputDirectory = config.Configuration;
}
}
RenderConfigEngine engine = new RenderConfigEngine(config, log);
return engine.Render();
}
return returnBool;
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: POGOProtos/Enums/PokemonMove.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace POGOProtos.Enums {
/// <summary>Holder for reflection information generated from POGOProtos/Enums/PokemonMove.proto</summary>
public static partial class PokemonMoveReflection {
#region Descriptor
/// <summary>File descriptor for POGOProtos/Enums/PokemonMove.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static PokemonMoveReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiJQT0dPUHJvdG9zL0VudW1zL1Bva2Vtb25Nb3ZlLnByb3RvEhBQT0dPUHJv",
"dG9zLkVudW1zKs4XCgtQb2tlbW9uTW92ZRIOCgpNT1ZFX1VOU0VUEAASEQoN",
"VEhVTkRFUl9TSE9DSxABEhAKDFFVSUNLX0FUVEFDSxACEgsKB1NDUkFUQ0gQ",
"AxIJCgVFTUJFUhAEEg0KCVZJTkVfV0hJUBAFEgoKBlRBQ0tMRRAGEg4KClJB",
"Wk9SX0xFQUYQBxINCglUQUtFX0RPV04QCBINCglXQVRFUl9HVU4QCRIICgRC",
"SVRFEAoSCQoFUE9VTkQQCxIPCgtET1VCTEVfU0xBUBAMEggKBFdSQVAQDRIO",
"CgpIWVBFUl9CRUFNEA4SCAoETElDSxAPEg4KCkRBUktfUFVMU0UQEBIICgRT",
"TU9HEBESCgoGU0xVREdFEBISDgoKTUVUQUxfQ0xBVxATEg0KCVZJQ0VfR1JJ",
"UBAUEg8KC0ZMQU1FX1dIRUVMEBUSDAoITUVHQUhPUk4QFhIPCgtXSU5HX0FU",
"VEFDSxAXEhAKDEZMQU1FVEhST1dFUhAYEhAKDFNVQ0tFUl9QVU5DSBAZEgcK",
"A0RJRxAaEgwKCExPV19LSUNLEBsSDgoKQ1JPU1NfQ0hPUBAcEg4KClBTWUNI",
"T19DVVQQHRILCgdQU1lCRUFNEB4SDgoKRUFSVEhRVUFLRRAfEg4KClNUT05F",
"X0VER0UQIBINCglJQ0VfUFVOQ0gQIRIPCgtIRUFSVF9TVEFNUBAiEg0KCURJ",
"U0NIQVJHRRAjEhAKDEZMQVNIX0NBTk5PThAkEggKBFBFQ0sQJRIOCgpEUklM",
"TF9QRUNLECYSDAoISUNFX0JFQU0QJxIMCghCTElaWkFSRBAoEg0KCUFJUl9T",
"TEFTSBApEg0KCUhFQVRfV0FWRRAqEg0KCVRXSU5FRURMRRArEg4KClBPSVNP",
"Tl9KQUIQLBIOCgpBRVJJQUxfQUNFEC0SDQoJRFJJTExfUlVOEC4SEgoOUEVU",
"QUxfQkxJWlpBUkQQLxIOCgpNRUdBX0RSQUlOEDASDAoIQlVHX0JVWloQMRIP",
"CgtQT0lTT05fRkFORxAyEg8KC05JR0hUX1NMQVNIEDMSCQoFU0xBU0gQNBIP",
"CgtCVUJCTEVfQkVBTRA1Eg4KClNVQk1JU1NJT04QNhIPCgtLQVJBVEVfQ0hP",
"UBA3Eg0KCUxPV19TV0VFUBA4EgwKCEFRVUFfSkVUEDkSDQoJQVFVQV9UQUlM",
"EDoSDQoJU0VFRF9CT01CEDsSDAoIUFNZU0hPQ0sQPBIOCgpST0NLX1RIUk9X",
"ED0SEQoNQU5DSUVOVF9QT1dFUhA+Eg0KCVJPQ0tfVE9NQhA/Eg4KClJPQ0tf",
"U0xJREUQQBINCglQT1dFUl9HRU0QQRIQCgxTSEFET1dfU05FQUsQQhIQCgxT",
"SEFET1dfUFVOQ0gQQxIPCgtTSEFET1dfQ0xBVxBEEhAKDE9NSU5PVVNfV0lO",
"RBBFEg8KC1NIQURPV19CQUxMEEYSEAoMQlVMTEVUX1BVTkNIEEcSDwoLTUFH",
"TkVUX0JPTUIQSBIOCgpTVEVFTF9XSU5HEEkSDQoJSVJPTl9IRUFEEEoSFAoQ",
"UEFSQUJPTElDX0NIQVJHRRBLEgkKBVNQQVJLEEwSEQoNVEhVTkRFUl9QVU5D",
"SBBNEgsKB1RIVU5ERVIQThIPCgtUSFVOREVSQk9MVBBPEgsKB1RXSVNURVIQ",
"UBIRCg1EUkFHT05fQlJFQVRIEFESEAoMRFJBR09OX1BVTFNFEFISDwoLRFJB",
"R09OX0NMQVcQUxITCg9ESVNBUk1JTkdfVk9JQ0UQVBIRCg1EUkFJTklOR19L",
"SVNTEFUSEgoOREFaWkxJTkdfR0xFQU0QVhINCglNT09OQkxBU1QQVxIOCgpQ",
"TEFZX1JPVUdIEFgSEAoMQ1JPU1NfUE9JU09OEFkSDwoLU0xVREdFX0JPTUIQ",
"WhIPCgtTTFVER0VfV0FWRRBbEg0KCUdVTktfU0hPVBBcEgwKCE1VRF9TSE9U",
"EF0SDQoJQk9ORV9DTFVCEF4SDAoIQlVMTERPWkUQXxIMCghNVURfQk9NQhBg",
"Eg8KC0ZVUllfQ1VUVEVSEGESDAoIQlVHX0JJVEUQYhIPCgtTSUdOQUxfQkVB",
"TRBjEg0KCVhfU0NJU1NPUhBkEhAKDEZMQU1FX0NIQVJHRRBlEg8KC0ZMQU1F",
"X0JVUlNUEGYSDgoKRklSRV9CTEFTVBBnEgkKBUJSSU5FEGgSDwoLV0FURVJf",
"UFVMU0UQaRIJCgVTQ0FMRBBqEg4KCkhZRFJPX1BVTVAQaxILCgdQU1lDSElD",
"EGwSDQoJUFNZU1RSSUtFEG0SDQoJSUNFX1NIQVJEEG4SDAoISUNZX1dJTkQQ",
"bxIQCgxGUk9TVF9CUkVBVEgQcBIKCgZBQlNPUkIQcRIOCgpHSUdBX0RSQUlO",
"EHISDgoKRklSRV9QVU5DSBBzEg4KClNPTEFSX0JFQU0QdBIOCgpMRUFGX0JM",
"QURFEHUSDgoKUE9XRVJfV0hJUBB2EgoKBlNQTEFTSBB3EggKBEFDSUQQeBIO",
"CgpBSVJfQ1VUVEVSEHkSDQoJSFVSUklDQU5FEHoSDwoLQlJJQ0tfQlJFQUsQ",
"exIHCgNDVVQQfBIJCgVTV0lGVBB9Eg8KC0hPUk5fQVRUQUNLEH4SCQoFU1RP",
"TVAQfxINCghIRUFEQlVUVBCAARIPCgpIWVBFUl9GQU5HEIEBEgkKBFNMQU0Q",
"ggESDgoJQk9EWV9TTEFNEIMBEgkKBFJFU1QQhAESDQoIU1RSVUdHTEUQhQES",
"FAoPU0NBTERfQkxBU1RPSVNFEIYBEhkKFEhZRFJPX1BVTVBfQkxBU1RPSVNF",
"EIcBEg8KCldSQVBfR1JFRU4QiAESDgoJV1JBUF9QSU5LEIkBEhUKEEZVUllf",
"Q1VUVEVSX0ZBU1QQyAESEgoNQlVHX0JJVEVfRkFTVBDJARIOCglCSVRFX0ZB",
"U1QQygESFgoRU1VDS0VSX1BVTkNIX0ZBU1QQywESFwoSRFJBR09OX0JSRUFU",
"SF9GQVNUEMwBEhcKElRIVU5ERVJfU0hPQ0tfRkFTVBDNARIPCgpTUEFSS19G",
"QVNUEM4BEhIKDUxPV19LSUNLX0ZBU1QQzwESFQoQS0FSQVRFX0NIT1BfRkFT",
"VBDQARIPCgpFTUJFUl9GQVNUENEBEhUKEFdJTkdfQVRUQUNLX0ZBU1QQ0gES",
"DgoJUEVDS19GQVNUENMBEg4KCUxJQ0tfRkFTVBDUARIVChBTSEFET1dfQ0xB",
"V19GQVNUENUBEhMKDlZJTkVfV0hJUF9GQVNUENYBEhQKD1JBWk9SX0xFQUZf",
"RkFTVBDXARISCg1NVURfU0hPVF9GQVNUENgBEhMKDklDRV9TSEFSRF9GQVNU",
"ENkBEhYKEUZST1NUX0JSRUFUSF9GQVNUENoBEhYKEVFVSUNLX0FUVEFDS19G",
"QVNUENsBEhEKDFNDUkFUQ0hfRkFTVBDcARIQCgtUQUNLTEVfRkFTVBDdARIP",
"CgpQT1VORF9GQVNUEN4BEg0KCENVVF9GQVNUEN8BEhQKD1BPSVNPTl9KQUJf",
"RkFTVBDgARIOCglBQ0lEX0ZBU1QQ4QESFAoPUFNZQ0hPX0NVVF9GQVNUEOIB",
"EhQKD1JPQ0tfVEhST1dfRkFTVBDjARIUCg9NRVRBTF9DTEFXX0ZBU1QQ5AES",
"FgoRQlVMTEVUX1BVTkNIX0ZBU1QQ5QESEwoOV0FURVJfR1VOX0ZBU1QQ5gES",
"EAoLU1BMQVNIX0ZBU1QQ5wESHQoYV0FURVJfR1VOX0ZBU1RfQkxBU1RPSVNF",
"EOgBEhIKDU1VRF9TTEFQX0ZBU1QQ6QESFgoRWkVOX0hFQURCVVRUX0ZBU1QQ",
"6gESEwoOQ09ORlVTSU9OX0ZBU1QQ6wESFgoRUE9JU09OX1NUSU5HX0ZBU1QQ",
"7AESEAoLQlVCQkxFX0ZBU1QQ7QESFgoRRkVJTlRfQVRUQUNLX0ZBU1QQ7gES",
"FAoPU1RFRUxfV0lOR19GQVNUEO8BEhMKDkZJUkVfRkFOR19GQVNUEPABEhQK",
"D1JPQ0tfU01BU0hfRkFTVBDxAWIGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(new[] {typeof(global::POGOProtos.Enums.PokemonMove), }, null));
}
#endregion
}
#region Enums
public enum PokemonMove {
[pbr::OriginalName("MOVE_UNSET")] MoveUnset = 0,
[pbr::OriginalName("THUNDER_SHOCK")] ThunderShock = 1,
[pbr::OriginalName("QUICK_ATTACK")] QuickAttack = 2,
[pbr::OriginalName("SCRATCH")] Scratch = 3,
[pbr::OriginalName("EMBER")] Ember = 4,
[pbr::OriginalName("VINE_WHIP")] VineWhip = 5,
[pbr::OriginalName("TACKLE")] Tackle = 6,
[pbr::OriginalName("RAZOR_LEAF")] RazorLeaf = 7,
[pbr::OriginalName("TAKE_DOWN")] TakeDown = 8,
[pbr::OriginalName("WATER_GUN")] WaterGun = 9,
[pbr::OriginalName("BITE")] Bite = 10,
[pbr::OriginalName("POUND")] Pound = 11,
[pbr::OriginalName("DOUBLE_SLAP")] DoubleSlap = 12,
[pbr::OriginalName("WRAP")] Wrap = 13,
[pbr::OriginalName("HYPER_BEAM")] HyperBeam = 14,
[pbr::OriginalName("LICK")] Lick = 15,
[pbr::OriginalName("DARK_PULSE")] DarkPulse = 16,
[pbr::OriginalName("SMOG")] Smog = 17,
[pbr::OriginalName("SLUDGE")] Sludge = 18,
[pbr::OriginalName("METAL_CLAW")] MetalClaw = 19,
[pbr::OriginalName("VICE_GRIP")] ViceGrip = 20,
[pbr::OriginalName("FLAME_WHEEL")] FlameWheel = 21,
[pbr::OriginalName("MEGAHORN")] Megahorn = 22,
[pbr::OriginalName("WING_ATTACK")] WingAttack = 23,
[pbr::OriginalName("FLAMETHROWER")] Flamethrower = 24,
[pbr::OriginalName("SUCKER_PUNCH")] SuckerPunch = 25,
[pbr::OriginalName("DIG")] Dig = 26,
[pbr::OriginalName("LOW_KICK")] LowKick = 27,
[pbr::OriginalName("CROSS_CHOP")] CrossChop = 28,
[pbr::OriginalName("PSYCHO_CUT")] PsychoCut = 29,
[pbr::OriginalName("PSYBEAM")] Psybeam = 30,
[pbr::OriginalName("EARTHQUAKE")] Earthquake = 31,
[pbr::OriginalName("STONE_EDGE")] StoneEdge = 32,
[pbr::OriginalName("ICE_PUNCH")] IcePunch = 33,
[pbr::OriginalName("HEART_STAMP")] HeartStamp = 34,
[pbr::OriginalName("DISCHARGE")] Discharge = 35,
[pbr::OriginalName("FLASH_CANNON")] FlashCannon = 36,
[pbr::OriginalName("PECK")] Peck = 37,
[pbr::OriginalName("DRILL_PECK")] DrillPeck = 38,
[pbr::OriginalName("ICE_BEAM")] IceBeam = 39,
[pbr::OriginalName("BLIZZARD")] Blizzard = 40,
[pbr::OriginalName("AIR_SLASH")] AirSlash = 41,
[pbr::OriginalName("HEAT_WAVE")] HeatWave = 42,
[pbr::OriginalName("TWINEEDLE")] Twineedle = 43,
[pbr::OriginalName("POISON_JAB")] PoisonJab = 44,
[pbr::OriginalName("AERIAL_ACE")] AerialAce = 45,
[pbr::OriginalName("DRILL_RUN")] DrillRun = 46,
[pbr::OriginalName("PETAL_BLIZZARD")] PetalBlizzard = 47,
[pbr::OriginalName("MEGA_DRAIN")] MegaDrain = 48,
[pbr::OriginalName("BUG_BUZZ")] BugBuzz = 49,
[pbr::OriginalName("POISON_FANG")] PoisonFang = 50,
[pbr::OriginalName("NIGHT_SLASH")] NightSlash = 51,
[pbr::OriginalName("SLASH")] Slash = 52,
[pbr::OriginalName("BUBBLE_BEAM")] BubbleBeam = 53,
[pbr::OriginalName("SUBMISSION")] Submission = 54,
[pbr::OriginalName("KARATE_CHOP")] KarateChop = 55,
[pbr::OriginalName("LOW_SWEEP")] LowSweep = 56,
[pbr::OriginalName("AQUA_JET")] AquaJet = 57,
[pbr::OriginalName("AQUA_TAIL")] AquaTail = 58,
[pbr::OriginalName("SEED_BOMB")] SeedBomb = 59,
[pbr::OriginalName("PSYSHOCK")] Psyshock = 60,
[pbr::OriginalName("ROCK_THROW")] RockThrow = 61,
[pbr::OriginalName("ANCIENT_POWER")] AncientPower = 62,
[pbr::OriginalName("ROCK_TOMB")] RockTomb = 63,
[pbr::OriginalName("ROCK_SLIDE")] RockSlide = 64,
[pbr::OriginalName("POWER_GEM")] PowerGem = 65,
[pbr::OriginalName("SHADOW_SNEAK")] ShadowSneak = 66,
[pbr::OriginalName("SHADOW_PUNCH")] ShadowPunch = 67,
[pbr::OriginalName("SHADOW_CLAW")] ShadowClaw = 68,
[pbr::OriginalName("OMINOUS_WIND")] OminousWind = 69,
[pbr::OriginalName("SHADOW_BALL")] ShadowBall = 70,
[pbr::OriginalName("BULLET_PUNCH")] BulletPunch = 71,
[pbr::OriginalName("MAGNET_BOMB")] MagnetBomb = 72,
[pbr::OriginalName("STEEL_WING")] SteelWing = 73,
[pbr::OriginalName("IRON_HEAD")] IronHead = 74,
[pbr::OriginalName("PARABOLIC_CHARGE")] ParabolicCharge = 75,
[pbr::OriginalName("SPARK")] Spark = 76,
[pbr::OriginalName("THUNDER_PUNCH")] ThunderPunch = 77,
[pbr::OriginalName("THUNDER")] Thunder = 78,
[pbr::OriginalName("THUNDERBOLT")] Thunderbolt = 79,
[pbr::OriginalName("TWISTER")] Twister = 80,
[pbr::OriginalName("DRAGON_BREATH")] DragonBreath = 81,
[pbr::OriginalName("DRAGON_PULSE")] DragonPulse = 82,
[pbr::OriginalName("DRAGON_CLAW")] DragonClaw = 83,
[pbr::OriginalName("DISARMING_VOICE")] DisarmingVoice = 84,
[pbr::OriginalName("DRAINING_KISS")] DrainingKiss = 85,
[pbr::OriginalName("DAZZLING_GLEAM")] DazzlingGleam = 86,
[pbr::OriginalName("MOONBLAST")] Moonblast = 87,
[pbr::OriginalName("PLAY_ROUGH")] PlayRough = 88,
[pbr::OriginalName("CROSS_POISON")] CrossPoison = 89,
[pbr::OriginalName("SLUDGE_BOMB")] SludgeBomb = 90,
[pbr::OriginalName("SLUDGE_WAVE")] SludgeWave = 91,
[pbr::OriginalName("GUNK_SHOT")] GunkShot = 92,
[pbr::OriginalName("MUD_SHOT")] MudShot = 93,
[pbr::OriginalName("BONE_CLUB")] BoneClub = 94,
[pbr::OriginalName("BULLDOZE")] Bulldoze = 95,
[pbr::OriginalName("MUD_BOMB")] MudBomb = 96,
[pbr::OriginalName("FURY_CUTTER")] FuryCutter = 97,
[pbr::OriginalName("BUG_BITE")] BugBite = 98,
[pbr::OriginalName("SIGNAL_BEAM")] SignalBeam = 99,
[pbr::OriginalName("X_SCISSOR")] XScissor = 100,
[pbr::OriginalName("FLAME_CHARGE")] FlameCharge = 101,
[pbr::OriginalName("FLAME_BURST")] FlameBurst = 102,
[pbr::OriginalName("FIRE_BLAST")] FireBlast = 103,
[pbr::OriginalName("BRINE")] Brine = 104,
[pbr::OriginalName("WATER_PULSE")] WaterPulse = 105,
[pbr::OriginalName("SCALD")] Scald = 106,
[pbr::OriginalName("HYDRO_PUMP")] HydroPump = 107,
[pbr::OriginalName("PSYCHIC")] Psychic = 108,
[pbr::OriginalName("PSYSTRIKE")] Psystrike = 109,
[pbr::OriginalName("ICE_SHARD")] IceShard = 110,
[pbr::OriginalName("ICY_WIND")] IcyWind = 111,
[pbr::OriginalName("FROST_BREATH")] FrostBreath = 112,
[pbr::OriginalName("ABSORB")] Absorb = 113,
[pbr::OriginalName("GIGA_DRAIN")] GigaDrain = 114,
[pbr::OriginalName("FIRE_PUNCH")] FirePunch = 115,
[pbr::OriginalName("SOLAR_BEAM")] SolarBeam = 116,
[pbr::OriginalName("LEAF_BLADE")] LeafBlade = 117,
[pbr::OriginalName("POWER_WHIP")] PowerWhip = 118,
[pbr::OriginalName("SPLASH")] Splash = 119,
[pbr::OriginalName("ACID")] Acid = 120,
[pbr::OriginalName("AIR_CUTTER")] AirCutter = 121,
[pbr::OriginalName("HURRICANE")] Hurricane = 122,
[pbr::OriginalName("BRICK_BREAK")] BrickBreak = 123,
[pbr::OriginalName("CUT")] Cut = 124,
[pbr::OriginalName("SWIFT")] Swift = 125,
[pbr::OriginalName("HORN_ATTACK")] HornAttack = 126,
[pbr::OriginalName("STOMP")] Stomp = 127,
[pbr::OriginalName("HEADBUTT")] Headbutt = 128,
[pbr::OriginalName("HYPER_FANG")] HyperFang = 129,
[pbr::OriginalName("SLAM")] Slam = 130,
[pbr::OriginalName("BODY_SLAM")] BodySlam = 131,
[pbr::OriginalName("REST")] Rest = 132,
[pbr::OriginalName("STRUGGLE")] Struggle = 133,
[pbr::OriginalName("SCALD_BLASTOISE")] ScaldBlastoise = 134,
[pbr::OriginalName("HYDRO_PUMP_BLASTOISE")] HydroPumpBlastoise = 135,
[pbr::OriginalName("WRAP_GREEN")] WrapGreen = 136,
[pbr::OriginalName("WRAP_PINK")] WrapPink = 137,
[pbr::OriginalName("FURY_CUTTER_FAST")] FuryCutterFast = 200,
[pbr::OriginalName("BUG_BITE_FAST")] BugBiteFast = 201,
[pbr::OriginalName("BITE_FAST")] BiteFast = 202,
[pbr::OriginalName("SUCKER_PUNCH_FAST")] SuckerPunchFast = 203,
[pbr::OriginalName("DRAGON_BREATH_FAST")] DragonBreathFast = 204,
[pbr::OriginalName("THUNDER_SHOCK_FAST")] ThunderShockFast = 205,
[pbr::OriginalName("SPARK_FAST")] SparkFast = 206,
[pbr::OriginalName("LOW_KICK_FAST")] LowKickFast = 207,
[pbr::OriginalName("KARATE_CHOP_FAST")] KarateChopFast = 208,
[pbr::OriginalName("EMBER_FAST")] EmberFast = 209,
[pbr::OriginalName("WING_ATTACK_FAST")] WingAttackFast = 210,
[pbr::OriginalName("PECK_FAST")] PeckFast = 211,
[pbr::OriginalName("LICK_FAST")] LickFast = 212,
[pbr::OriginalName("SHADOW_CLAW_FAST")] ShadowClawFast = 213,
[pbr::OriginalName("VINE_WHIP_FAST")] VineWhipFast = 214,
[pbr::OriginalName("RAZOR_LEAF_FAST")] RazorLeafFast = 215,
[pbr::OriginalName("MUD_SHOT_FAST")] MudShotFast = 216,
[pbr::OriginalName("ICE_SHARD_FAST")] IceShardFast = 217,
[pbr::OriginalName("FROST_BREATH_FAST")] FrostBreathFast = 218,
[pbr::OriginalName("QUICK_ATTACK_FAST")] QuickAttackFast = 219,
[pbr::OriginalName("SCRATCH_FAST")] ScratchFast = 220,
[pbr::OriginalName("TACKLE_FAST")] TackleFast = 221,
[pbr::OriginalName("POUND_FAST")] PoundFast = 222,
[pbr::OriginalName("CUT_FAST")] CutFast = 223,
[pbr::OriginalName("POISON_JAB_FAST")] PoisonJabFast = 224,
[pbr::OriginalName("ACID_FAST")] AcidFast = 225,
[pbr::OriginalName("PSYCHO_CUT_FAST")] PsychoCutFast = 226,
[pbr::OriginalName("ROCK_THROW_FAST")] RockThrowFast = 227,
[pbr::OriginalName("METAL_CLAW_FAST")] MetalClawFast = 228,
[pbr::OriginalName("BULLET_PUNCH_FAST")] BulletPunchFast = 229,
[pbr::OriginalName("WATER_GUN_FAST")] WaterGunFast = 230,
[pbr::OriginalName("SPLASH_FAST")] SplashFast = 231,
[pbr::OriginalName("WATER_GUN_FAST_BLASTOISE")] WaterGunFastBlastoise = 232,
[pbr::OriginalName("MUD_SLAP_FAST")] MudSlapFast = 233,
[pbr::OriginalName("ZEN_HEADBUTT_FAST")] ZenHeadbuttFast = 234,
[pbr::OriginalName("CONFUSION_FAST")] ConfusionFast = 235,
[pbr::OriginalName("POISON_STING_FAST")] PoisonStingFast = 236,
[pbr::OriginalName("BUBBLE_FAST")] BubbleFast = 237,
[pbr::OriginalName("FEINT_ATTACK_FAST")] FeintAttackFast = 238,
[pbr::OriginalName("STEEL_WING_FAST")] SteelWingFast = 239,
[pbr::OriginalName("FIRE_FANG_FAST")] FireFangFast = 240,
[pbr::OriginalName("ROCK_SMASH_FAST")] RockSmashFast = 241,
}
#endregion
}
#endregion Designer generated code
| |
//
// Copyright (C) Microsoft. All rights reserved.
//
using Microsoft.PowerShell.Activities;
using System.Management.Automation;
using System.Activities;
using System.Collections.Generic;
using System.ComponentModel;
namespace Microsoft.PowerShell.Management.Activities
{
/// <summary>
/// Activity to invoke the Microsoft.PowerShell.Management\Get-EventLog command in a Workflow.
/// </summary>
[System.CodeDom.Compiler.GeneratedCode("Microsoft.PowerShell.Activities.ActivityGenerator.GenerateFromName", "3.0")]
public sealed class GetEventLog : PSRemotingActivity
{
/// <summary>
/// Gets the display name of the command invoked by this activity.
/// </summary>
public GetEventLog()
{
this.DisplayName = "Get-EventLog";
}
/// <summary>
/// Gets the fully qualified name of the command invoked by this activity.
/// </summary>
public override string PSCommandName { get { return "Microsoft.PowerShell.Management\\Get-EventLog"; } }
// Arguments
/// <summary>
/// Provides access to the LogName parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> LogName { get; set; }
/// <summary>
/// Provides access to the Newest parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Int32> Newest { get; set; }
/// <summary>
/// Provides access to the After parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.DateTime> After { get; set; }
/// <summary>
/// Provides access to the Before parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.DateTime> Before { get; set; }
/// <summary>
/// Provides access to the UserName parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String[]> UserName { get; set; }
/// <summary>
/// Provides access to the InstanceId parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Int64[]> InstanceId { get; set; }
/// <summary>
/// Provides access to the Index parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Int32[]> Index { get; set; }
/// <summary>
/// Provides access to the EntryType parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String[]> EntryType { get; set; }
/// <summary>
/// Provides access to the Source parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String[]> Source { get; set; }
/// <summary>
/// Provides access to the Message parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> Message { get; set; }
/// <summary>
/// Provides access to the AsBaseObject parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> AsBaseObject { get; set; }
/// <summary>
/// Provides access to the List parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> List { get; set; }
/// <summary>
/// Provides access to the AsString parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> AsString { get; set; }
/// <summary>
/// Declares that this activity supports its own remoting.
/// </summary>
protected override bool SupportsCustomRemoting { get { return true; } }
// Module defining this command
// Optional custom code for this activity
/// <summary>
/// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
/// </summary>
/// <param name="context">The NativeActivityContext for the currently running activity.</param>
/// <returns>A populated instance of Sytem.Management.Automation.PowerShell</returns>
/// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
{
System.Management.Automation.PowerShell invoker = global::System.Management.Automation.PowerShell.Create();
System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);
// Initialize the arguments
if(LogName.Expression != null)
{
targetCommand.AddParameter("LogName", LogName.Get(context));
}
if(Newest.Expression != null)
{
targetCommand.AddParameter("Newest", Newest.Get(context));
}
if(After.Expression != null)
{
targetCommand.AddParameter("After", After.Get(context));
}
if(Before.Expression != null)
{
targetCommand.AddParameter("Before", Before.Get(context));
}
if(UserName.Expression != null)
{
targetCommand.AddParameter("UserName", UserName.Get(context));
}
if(InstanceId.Expression != null)
{
targetCommand.AddParameter("InstanceId", InstanceId.Get(context));
}
if(Index.Expression != null)
{
targetCommand.AddParameter("Index", Index.Get(context));
}
if(EntryType.Expression != null)
{
targetCommand.AddParameter("EntryType", EntryType.Get(context));
}
if(Source.Expression != null)
{
targetCommand.AddParameter("Source", Source.Get(context));
}
if(Message.Expression != null)
{
targetCommand.AddParameter("Message", Message.Get(context));
}
if(AsBaseObject.Expression != null)
{
targetCommand.AddParameter("AsBaseObject", AsBaseObject.Get(context));
}
if(List.Expression != null)
{
targetCommand.AddParameter("List", List.Get(context));
}
if(AsString.Expression != null)
{
targetCommand.AddParameter("AsString", AsString.Get(context));
}
if(GetIsComputerNameSpecified(context) && (PSRemotingBehavior.Get(context) == RemotingBehavior.Custom))
{
targetCommand.AddParameter("ComputerName", PSComputerName.Get(context));
}
return new ActivityImplementationContext() { PowerShellInstance = invoker };
}
}
}
| |
namespace EIDSS.Reports.Document.Lim.TestResult
{
partial class TestResultReport
{
#region Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(TestResultReport));
this.DetailReportTest = new DevExpress.XtraReports.UI.DetailReportBand();
this.DetailTest = new DevExpress.XtraReports.UI.DetailBand();
this.xrLabel1 = new DevExpress.XtraReports.UI.XRLabel();
this.TestResultSubreport = new DevExpress.XtraReports.UI.XRSubreport();
this.sp_rep_LIM_TestResultsTableAdapter1 = new EIDSS.Reports.Document.Lim.TestResult.TestResultDataSetTableAdapters.spRepLimTestResultsTableAdapter();
this.testResultDataSet1 = new EIDSS.Reports.Document.Lim.TestResult.TestResultDataSet();
this.xrTable1 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow3 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell();
this.BatchBarcodeCell = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow5 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow10 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell14 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow11 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell15 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell16 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell17 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow12 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell21 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell22 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow13 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell23 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell24 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell25 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell26 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow14 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell27 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell28 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell29 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell30 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow15 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell31 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell32 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell33 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell34 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow16 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell35 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell36 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell37 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell38 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow17 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell39 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell40 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell41 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell42 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow18 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell43 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell45 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell46 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell47 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow19 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell48 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell49 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow20 = new DevExpress.XtraReports.UI.XRTableRow();
this.cellPatientName = new DevExpress.XtraReports.UI.XRTableCell();
this.lblAnimalName = new DevExpress.XtraReports.UI.XRLabel();
this.lblPatientName = new DevExpress.XtraReports.UI.XRLabel();
this.cellPatientValue = new DevExpress.XtraReports.UI.XRTableCell();
this.lblSessionId = new DevExpress.XtraReports.UI.XRLabel();
this.lblAnimalValue = new DevExpress.XtraReports.UI.XRLabel();
this.lblPatientValue = new DevExpress.XtraReports.UI.XRLabel();
this.lblCaseType = new DevExpress.XtraReports.UI.XRLabel();
this.xrTableRow21 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell52 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell53 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow22 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell54 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell55 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell();
((System.ComponentModel.ISupportInitialize)(this.baseDataSet1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.testResultDataSet1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
//
// cellLanguage
//
this.cellLanguage.StylePriority.UseTextAlignment = false;
//
// lblReportName
//
resources.ApplyResources(this.lblReportName, "lblReportName");
this.lblReportName.StylePriority.UseBorders = false;
this.lblReportName.StylePriority.UseBorderWidth = false;
this.lblReportName.StylePriority.UseFont = false;
this.lblReportName.StylePriority.UseTextAlignment = false;
//
// Detail
//
this.Detail.StylePriority.UseFont = false;
this.Detail.StylePriority.UsePadding = false;
//
// PageHeader
//
this.PageHeader.StylePriority.UseFont = false;
this.PageHeader.StylePriority.UsePadding = false;
//
// PageFooter
//
this.PageFooter.StylePriority.UseBorders = false;
//
// ReportHeader
//
this.ReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable1});
resources.ApplyResources(this.ReportHeader, "ReportHeader");
this.ReportHeader.Controls.SetChildIndex(this.tableBaseHeader, 0);
this.ReportHeader.Controls.SetChildIndex(this.xrTable1, 0);
//
// xrPageInfo1
//
this.xrPageInfo1.StylePriority.UseBorders = false;
//
// cellReportHeader
//
this.cellReportHeader.StylePriority.UseBorders = false;
this.cellReportHeader.StylePriority.UseFont = false;
this.cellReportHeader.StylePriority.UseTextAlignment = false;
//
// cellBaseSite
//
this.cellBaseSite.StylePriority.UseBorders = false;
this.cellBaseSite.StylePriority.UseFont = false;
this.cellBaseSite.StylePriority.UseTextAlignment = false;
//
// tableBaseHeader
//
this.tableBaseHeader.StylePriority.UseBorders = false;
this.tableBaseHeader.StylePriority.UseBorderWidth = false;
this.tableBaseHeader.StylePriority.UseFont = false;
this.tableBaseHeader.StylePriority.UsePadding = false;
this.tableBaseHeader.StylePriority.UseTextAlignment = false;
//
// DetailReportTest
//
this.DetailReportTest.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.DetailTest});
this.DetailReportTest.DataAdapter = this.sp_rep_LIM_TestResultsTableAdapter1;
this.DetailReportTest.DataMember = "spRepLimTestResults";
this.DetailReportTest.DataSource = this.testResultDataSet1;
resources.ApplyResources(this.DetailReportTest, "DetailReportTest");
this.DetailReportTest.Level = 0;
this.DetailReportTest.Name = "DetailReportTest";
this.DetailReportTest.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F);
//
// DetailTest
//
this.DetailTest.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrLabel1,
this.TestResultSubreport});
resources.ApplyResources(this.DetailTest, "DetailTest");
this.DetailTest.Name = "DetailTest";
//
// xrLabel1
//
resources.ApplyResources(this.xrLabel1, "xrLabel1");
this.xrLabel1.Name = "xrLabel1";
this.xrLabel1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrLabel1.StylePriority.UseFont = false;
this.xrLabel1.StylePriority.UseTextAlignment = false;
//
// TestResultSubreport
//
resources.ApplyResources(this.TestResultSubreport, "TestResultSubreport");
this.TestResultSubreport.Name = "TestResultSubreport";
//
// sp_rep_LIM_TestResultsTableAdapter1
//
this.sp_rep_LIM_TestResultsTableAdapter1.ClearBeforeFill = true;
//
// testResultDataSet1
//
this.testResultDataSet1.DataSetName = "TestResultDataSet";
this.testResultDataSet1.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// xrTable1
//
resources.ApplyResources(this.xrTable1, "xrTable1");
this.xrTable1.Name = "xrTable1";
this.xrTable1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F);
this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow3,
this.xrTableRow5,
this.xrTableRow10,
this.xrTableRow11,
this.xrTableRow12,
this.xrTableRow13,
this.xrTableRow14,
this.xrTableRow15,
this.xrTableRow16,
this.xrTableRow17,
this.xrTableRow18,
this.xrTableRow19,
this.xrTableRow20,
this.xrTableRow21,
this.xrTableRow22});
this.xrTable1.StylePriority.UsePadding = false;
this.xrTable1.StylePriority.UseTextAlignment = false;
//
// xrTableRow3
//
this.xrTableRow3.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell5,
this.BatchBarcodeCell});
this.xrTableRow3.Name = "xrTableRow3";
this.xrTableRow3.Weight = 1D;
//
// xrTableCell5
//
this.xrTableCell5.Name = "xrTableCell5";
this.xrTableCell5.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell5, "xrTableCell5");
this.xrTableCell5.Weight = 1.4838709677419355D;
//
// BatchBarcodeCell
//
this.BatchBarcodeCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimTestResults.BatchBarcode", "*{0}*")});
resources.ApplyResources(this.BatchBarcodeCell, "BatchBarcodeCell");
this.BatchBarcodeCell.Name = "BatchBarcodeCell";
this.BatchBarcodeCell.StylePriority.UseFont = false;
this.BatchBarcodeCell.StylePriority.UseTextAlignment = false;
this.BatchBarcodeCell.Weight = 1.5161290322580645D;
this.BatchBarcodeCell.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.BatchBarcodeCell_BeforePrint);
//
// xrTableRow5
//
this.xrTableRow5.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell9,
this.xrTableCell10});
this.xrTableRow5.Name = "xrTableRow5";
this.xrTableRow5.Weight = 0.33999999999999997D;
//
// xrTableCell9
//
this.xrTableCell9.Name = "xrTableCell9";
this.xrTableCell9.Weight = 1.4838709677419355D;
//
// xrTableCell10
//
this.xrTableCell10.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimTestResults.BatchBarcode")});
this.xrTableCell10.Name = "xrTableCell10";
this.xrTableCell10.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell10, "xrTableCell10");
this.xrTableCell10.Weight = 1.5161290322580645D;
//
// xrTableRow10
//
this.xrTableRow10.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell13,
this.xrTableCell11,
this.xrTableCell14,
this.xrTableCell12});
this.xrTableRow10.Name = "xrTableRow10";
this.xrTableRow10.Weight = 0.57349820571737653D;
//
// xrTableCell13
//
this.xrTableCell13.Name = "xrTableCell13";
resources.ApplyResources(this.xrTableCell13, "xrTableCell13");
this.xrTableCell13.Weight = 0.74193548387096775D;
//
// xrTableCell11
//
this.xrTableCell11.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell11.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimTestResults.Category")});
this.xrTableCell11.Name = "xrTableCell11";
this.xrTableCell11.StylePriority.UseBorders = false;
this.xrTableCell11.Weight = 0.74193548387096775D;
//
// xrTableCell14
//
this.xrTableCell14.Name = "xrTableCell14";
this.xrTableCell14.Padding = new DevExpress.XtraPrinting.PaddingInfo(10, 2, 2, 2, 100F);
this.xrTableCell14.StylePriority.UsePadding = false;
this.xrTableCell14.Weight = 0.91887039676789317D;
//
// xrTableCell12
//
this.xrTableCell12.Name = "xrTableCell12";
this.xrTableCell12.Weight = 0.59725863549017133D;
//
// xrTableRow11
//
this.xrTableRow11.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell15,
this.xrTableCell16,
this.xrTableCell17,
this.xrTableCell18});
this.xrTableRow11.Name = "xrTableRow11";
this.xrTableRow11.Weight = 0.57349820571737653D;
//
// xrTableCell15
//
this.xrTableCell15.Name = "xrTableCell15";
resources.ApplyResources(this.xrTableCell15, "xrTableCell15");
this.xrTableCell15.Weight = 0.74193548387096775D;
//
// xrTableCell16
//
this.xrTableCell16.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell16.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimTestResults.TestType")});
this.xrTableCell16.Name = "xrTableCell16";
this.xrTableCell16.StylePriority.UseBorders = false;
this.xrTableCell16.Weight = 0.74193548387096775D;
//
// xrTableCell17
//
this.xrTableCell17.Name = "xrTableCell17";
this.xrTableCell17.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 20, 2, 2, 100F);
this.xrTableCell17.StylePriority.UsePadding = false;
this.xrTableCell17.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell17, "xrTableCell17");
this.xrTableCell17.Weight = 0.91887063303301408D;
//
// xrTableCell18
//
this.xrTableCell18.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell18.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimTestResults.datComplete_Date", "{0:dd/MM/yyyy}")});
this.xrTableCell18.Name = "xrTableCell18";
this.xrTableCell18.StylePriority.UseBorders = false;
this.xrTableCell18.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell18, "xrTableCell18");
this.xrTableCell18.Weight = 0.59725839922505042D;
//
// xrTableRow12
//
this.xrTableRow12.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell19,
this.xrTableCell20,
this.xrTableCell21,
this.xrTableCell22});
this.xrTableRow12.Name = "xrTableRow12";
this.xrTableRow12.Weight = 0.57349820571737642D;
//
// xrTableCell19
//
this.xrTableCell19.Name = "xrTableCell19";
resources.ApplyResources(this.xrTableCell19, "xrTableCell19");
this.xrTableCell19.Weight = 0.74193548387096775D;
//
// xrTableCell20
//
this.xrTableCell20.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell20.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimTestResults.Status")});
this.xrTableCell20.Name = "xrTableCell20";
this.xrTableCell20.StylePriority.UseBorders = false;
this.xrTableCell20.Weight = 0.74193548387096775D;
//
// xrTableCell21
//
this.xrTableCell21.Name = "xrTableCell21";
this.xrTableCell21.Weight = 0.91887063303301408D;
//
// xrTableCell22
//
this.xrTableCell22.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.baseDataSet1, "sprepGetBaseParameters.strDateFormat")});
resources.ApplyResources(this.xrTableCell22, "xrTableCell22");
this.xrTableCell22.Name = "xrTableCell22";
this.xrTableCell22.StylePriority.UseFont = false;
this.xrTableCell22.StylePriority.UseTextAlignment = false;
this.xrTableCell22.Weight = 0.59725839922505042D;
//
// xrTableRow13
//
this.xrTableRow13.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell23,
this.xrTableCell24,
this.xrTableCell25,
this.xrTableCell26});
this.xrTableRow13.Name = "xrTableRow13";
this.xrTableRow13.Weight = 0.573498238742141D;
//
// xrTableCell23
//
this.xrTableCell23.Name = "xrTableCell23";
resources.ApplyResources(this.xrTableCell23, "xrTableCell23");
this.xrTableCell23.Weight = 0.74193548387096775D;
//
// xrTableCell24
//
this.xrTableCell24.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell24.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimTestResults.TestResult")});
this.xrTableCell24.Name = "xrTableCell24";
this.xrTableCell24.StylePriority.UseBorders = false;
this.xrTableCell24.Weight = 0.74193548387096775D;
//
// xrTableCell25
//
this.xrTableCell25.Name = "xrTableCell25";
this.xrTableCell25.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 20, 2, 2, 100F);
this.xrTableCell25.StylePriority.UsePadding = false;
this.xrTableCell25.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell25, "xrTableCell25");
this.xrTableCell25.Weight = 0.91887086929813511D;
//
// xrTableCell26
//
this.xrTableCell26.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell26.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimTestResults.datCollectionDate", "{0:dd/MM/yyyy}")});
this.xrTableCell26.Name = "xrTableCell26";
this.xrTableCell26.StylePriority.UseBorders = false;
this.xrTableCell26.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell26, "xrTableCell26");
this.xrTableCell26.Weight = 0.5972581629599294D;
//
// xrTableRow14
//
this.xrTableRow14.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell27,
this.xrTableCell28,
this.xrTableCell29,
this.xrTableCell30});
this.xrTableRow14.Name = "xrTableRow14";
this.xrTableRow14.Weight = 0.57349824184242482D;
//
// xrTableCell27
//
this.xrTableCell27.Multiline = true;
this.xrTableCell27.Name = "xrTableCell27";
resources.ApplyResources(this.xrTableCell27, "xrTableCell27");
this.xrTableCell27.Weight = 0.74193548387096775D;
//
// xrTableCell28
//
this.xrTableCell28.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell28.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimTestResults.OriginalSampleID")});
this.xrTableCell28.Name = "xrTableCell28";
this.xrTableCell28.StylePriority.UseBorders = false;
this.xrTableCell28.Weight = 0.74193548387096775D;
//
// xrTableCell29
//
this.xrTableCell29.Name = "xrTableCell29";
this.xrTableCell29.Weight = 0.91887057396673388D;
//
// xrTableCell30
//
this.xrTableCell30.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.baseDataSet1, "sprepGetBaseParameters.strDateFormat")});
resources.ApplyResources(this.xrTableCell30, "xrTableCell30");
this.xrTableCell30.Name = "xrTableCell30";
this.xrTableCell30.StylePriority.UseFont = false;
this.xrTableCell30.StylePriority.UseTextAlignment = false;
this.xrTableCell30.Weight = 0.59725845829133062D;
//
// xrTableRow15
//
this.xrTableRow15.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell31,
this.xrTableCell32,
this.xrTableCell33,
this.xrTableCell34});
this.xrTableRow15.Name = "xrTableRow15";
this.xrTableRow15.Weight = 0.95583032027686077D;
//
// xrTableCell31
//
this.xrTableCell31.Name = "xrTableCell31";
resources.ApplyResources(this.xrTableCell31, "xrTableCell31");
this.xrTableCell31.Weight = 0.61032258064516121D;
//
// xrTableCell32
//
this.xrTableCell32.Borders = DevExpress.XtraPrinting.BorderSide.None;
this.xrTableCell32.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimTestResults.SampleID", "*{0}*")});
resources.ApplyResources(this.xrTableCell32, "xrTableCell32");
this.xrTableCell32.Name = "xrTableCell32";
this.xrTableCell32.StylePriority.UseBorders = false;
this.xrTableCell32.StylePriority.UseFont = false;
this.xrTableCell32.StylePriority.UseTextAlignment = false;
this.xrTableCell32.Weight = 0.87354838709677429D;
//
// xrTableCell33
//
this.xrTableCell33.Name = "xrTableCell33";
this.xrTableCell33.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 20, 2, 2, 100F);
this.xrTableCell33.StylePriority.UsePadding = false;
this.xrTableCell33.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell33, "xrTableCell33");
this.xrTableCell33.Weight = 0.76967741935483869D;
//
// xrTableCell34
//
this.xrTableCell34.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell34.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimTestResults.SpecimenType")});
this.xrTableCell34.Name = "xrTableCell34";
this.xrTableCell34.StylePriority.UseBorders = false;
this.xrTableCell34.Weight = 0.74645161290322581D;
//
// xrTableRow16
//
this.xrTableRow16.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell35,
this.xrTableCell36,
this.xrTableCell37,
this.xrTableCell38});
this.xrTableRow16.Name = "xrTableRow16";
this.xrTableRow16.Weight = 0.57349819945770852D;
//
// xrTableCell35
//
this.xrTableCell35.Name = "xrTableCell35";
this.xrTableCell35.Weight = 0.61032258064516121D;
//
// xrTableCell36
//
this.xrTableCell36.Borders = DevExpress.XtraPrinting.BorderSide.None;
this.xrTableCell36.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimTestResults.SampleID")});
this.xrTableCell36.Name = "xrTableCell36";
this.xrTableCell36.StylePriority.UseBorders = false;
this.xrTableCell36.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell36, "xrTableCell36");
this.xrTableCell36.Weight = 0.87354838709677429D;
//
// xrTableCell37
//
this.xrTableCell37.Name = "xrTableCell37";
this.xrTableCell37.Weight = 0.76967741935483869D;
//
// xrTableCell38
//
this.xrTableCell38.Name = "xrTableCell38";
this.xrTableCell38.Weight = 0.74645161290322581D;
//
// xrTableRow17
//
this.xrTableRow17.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell39,
this.xrTableCell40,
this.xrTableCell41,
this.xrTableCell42});
this.xrTableRow17.Name = "xrTableRow17";
this.xrTableRow17.Weight = 0.95583032939542467D;
//
// xrTableCell39
//
this.xrTableCell39.Name = "xrTableCell39";
resources.ApplyResources(this.xrTableCell39, "xrTableCell39");
this.xrTableCell39.Weight = 0.61032258064516121D;
this.xrTableCell39.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.xrTableCell39_BeforePrint);
//
// xrTableCell40
//
this.xrTableCell40.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimTestResults.CaseID", "*{0}*")});
resources.ApplyResources(this.xrTableCell40, "xrTableCell40");
this.xrTableCell40.Name = "xrTableCell40";
this.xrTableCell40.StylePriority.UseFont = false;
this.xrTableCell40.StylePriority.UseTextAlignment = false;
this.xrTableCell40.Weight = 0.87354838709677429D;
//
// xrTableCell41
//
this.xrTableCell41.Name = "xrTableCell41";
this.xrTableCell41.Weight = 0.76967741935483869D;
//
// xrTableCell42
//
this.xrTableCell42.Name = "xrTableCell42";
this.xrTableCell42.Weight = 0.74645161290322581D;
//
// xrTableRow18
//
this.xrTableRow18.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell43,
this.xrTableCell45,
this.xrTableCell46,
this.xrTableCell47});
this.xrTableRow18.Name = "xrTableRow18";
this.xrTableRow18.Weight = 0.5734981994577083D;
//
// xrTableCell43
//
this.xrTableCell43.Name = "xrTableCell43";
this.xrTableCell43.Weight = 0.61032258064516121D;
//
// xrTableCell45
//
this.xrTableCell45.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimTestResults.CaseID")});
this.xrTableCell45.Name = "xrTableCell45";
this.xrTableCell45.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell45, "xrTableCell45");
this.xrTableCell45.Weight = 0.87354838709677429D;
//
// xrTableCell46
//
this.xrTableCell46.Name = "xrTableCell46";
this.xrTableCell46.Weight = 0.76967741935483869D;
//
// xrTableCell47
//
this.xrTableCell47.Name = "xrTableCell47";
this.xrTableCell47.Weight = 0.74645161290322581D;
//
// xrTableRow19
//
this.xrTableRow19.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell48,
this.xrTableCell49});
this.xrTableRow19.Name = "xrTableRow19";
this.xrTableRow19.Weight = 0.5734981994577083D;
//
// xrTableCell48
//
this.xrTableCell48.Name = "xrTableCell48";
resources.ApplyResources(this.xrTableCell48, "xrTableCell48");
this.xrTableCell48.Weight = 0.61032258064516121D;
//
// xrTableCell49
//
this.xrTableCell49.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell49.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimTestResults.DiagnosisName")});
this.xrTableCell49.Name = "xrTableCell49";
this.xrTableCell49.StylePriority.UseBorders = false;
this.xrTableCell49.Weight = 2.3896774193548387D;
//
// xrTableRow20
//
this.xrTableRow20.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.cellPatientName,
this.cellPatientValue});
this.xrTableRow20.Name = "xrTableRow20";
this.xrTableRow20.Weight = 0.57349819945770841D;
//
// cellPatientName
//
this.cellPatientName.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.lblAnimalName,
this.lblPatientName});
this.cellPatientName.Name = "cellPatientName";
this.cellPatientName.Weight = 0.61032258064516121D;
this.cellPatientName.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.cellPatientName_BeforePrint);
//
// lblAnimalName
//
resources.ApplyResources(this.lblAnimalName, "lblAnimalName");
this.lblAnimalName.Name = "lblAnimalName";
this.lblAnimalName.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
//
// lblPatientName
//
resources.ApplyResources(this.lblPatientName, "lblPatientName");
this.lblPatientName.Name = "lblPatientName";
this.lblPatientName.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
//
// cellPatientValue
//
this.cellPatientValue.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.cellPatientValue.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.lblSessionId,
this.lblAnimalValue,
this.lblPatientValue,
this.lblCaseType});
this.cellPatientValue.Name = "cellPatientValue";
this.cellPatientValue.StylePriority.UseBorders = false;
this.cellPatientValue.Weight = 2.3896774193548387D;
this.cellPatientValue.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.cellPatientValue_BeforePrint);
//
// lblSessionId
//
resources.ApplyResources(this.lblSessionId, "lblSessionId");
this.lblSessionId.Multiline = true;
this.lblSessionId.Name = "lblSessionId";
this.lblSessionId.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
//
// lblAnimalValue
//
this.lblAnimalValue.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimTestResults.AnimalName")});
resources.ApplyResources(this.lblAnimalValue, "lblAnimalValue");
this.lblAnimalValue.Name = "lblAnimalValue";
this.lblAnimalValue.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
//
// lblPatientValue
//
this.lblPatientValue.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimTestResults.PatientName")});
resources.ApplyResources(this.lblPatientValue, "lblPatientValue");
this.lblPatientValue.Name = "lblPatientValue";
this.lblPatientValue.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
//
// lblCaseType
//
this.lblCaseType.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimTestResults.idfsCase_Type")});
resources.ApplyResources(this.lblCaseType, "lblCaseType");
this.lblCaseType.Name = "lblCaseType";
this.lblCaseType.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
//
// xrTableRow21
//
this.xrTableRow21.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell52,
this.xrTableCell53});
this.xrTableRow21.Name = "xrTableRow21";
this.xrTableRow21.Weight = 0.57349819945770841D;
//
// xrTableCell52
//
this.xrTableCell52.Name = "xrTableCell52";
resources.ApplyResources(this.xrTableCell52, "xrTableCell52");
this.xrTableCell52.Weight = 0.61032258064516121D;
//
// xrTableCell53
//
this.xrTableCell53.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell53.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimTestResults.PerformedBy")});
this.xrTableCell53.Name = "xrTableCell53";
this.xrTableCell53.StylePriority.UseBorders = false;
this.xrTableCell53.Weight = 2.3896774193548387D;
//
// xrTableRow22
//
this.xrTableRow22.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell54,
this.xrTableCell55});
this.xrTableRow22.Name = "xrTableRow22";
this.xrTableRow22.Weight = 0.5734984182299131D;
//
// xrTableCell54
//
this.xrTableCell54.Name = "xrTableCell54";
resources.ApplyResources(this.xrTableCell54, "xrTableCell54");
this.xrTableCell54.Weight = 0.61032258064516121D;
//
// xrTableCell55
//
this.xrTableCell55.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell55.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimTestResults.PerformedByOrganization")});
this.xrTableCell55.Name = "xrTableCell55";
this.xrTableCell55.StylePriority.UseBorders = false;
this.xrTableCell55.Weight = 2.3896774193548387D;
//
// xrTableCell7
//
this.xrTableCell7.Name = "xrTableCell7";
this.xrTableCell7.Weight = 1.4838709677419355D;
//
// xrTableCell8
//
this.xrTableCell8.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimTestResults.BatchBarcode")});
this.xrTableCell8.Name = "xrTableCell8";
this.xrTableCell8.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell8, "xrTableCell8");
this.xrTableCell8.Weight = 1.5161290322580645D;
//
// TestResultReport
//
this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail,
this.PageHeader,
this.PageFooter,
this.ReportHeader,
this.DetailReportTest});
this.DataAdapter = this.sp_rep_LIM_TestResultsTableAdapter1;
this.DataMember = "spRepLimTestResults";
this.DataSource = this.testResultDataSet1;
this.Version = "11.1";
this.Controls.SetChildIndex(this.DetailReportTest, 0);
this.Controls.SetChildIndex(this.ReportHeader, 0);
this.Controls.SetChildIndex(this.PageFooter, 0);
this.Controls.SetChildIndex(this.PageHeader, 0);
this.Controls.SetChildIndex(this.Detail, 0);
((System.ComponentModel.ISupportInitialize)(this.baseDataSet1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.testResultDataSet1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
}
#endregion
private DevExpress.XtraReports.UI.DetailReportBand DetailReportTest;
private DevExpress.XtraReports.UI.DetailBand DetailTest;
private DevExpress.XtraReports.UI.XRTable xrTable1;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow3;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell5;
private DevExpress.XtraReports.UI.XRTableCell BatchBarcodeCell;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell7;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell8;
private TestResultDataSetTableAdapters.spRepLimTestResultsTableAdapter sp_rep_LIM_TestResultsTableAdapter1;
private TestResultDataSet testResultDataSet1;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow5;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell9;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell10;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow10;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell13;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell11;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell14;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell12;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow11;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell15;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell16;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell17;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell18;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow12;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell19;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell20;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell21;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell22;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow13;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell23;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell24;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell25;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell26;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow14;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell27;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell28;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell29;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell30;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow15;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell31;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell32;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell33;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell34;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow16;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell35;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell36;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell37;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell38;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow17;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell39;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell40;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell41;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell42;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow18;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell43;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell45;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell46;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell47;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow19;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell48;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell49;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow20;
private DevExpress.XtraReports.UI.XRTableCell cellPatientName;
private DevExpress.XtraReports.UI.XRTableCell cellPatientValue;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow21;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell52;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell53;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow22;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell54;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell55;
private DevExpress.XtraReports.UI.XRSubreport TestResultSubreport;
private DevExpress.XtraReports.UI.XRLabel lblAnimalValue;
private DevExpress.XtraReports.UI.XRLabel lblPatientValue;
private DevExpress.XtraReports.UI.XRLabel lblAnimalName;
private DevExpress.XtraReports.UI.XRLabel lblPatientName;
private DevExpress.XtraReports.UI.XRLabel lblCaseType;
private DevExpress.XtraReports.UI.XRLabel xrLabel1;
private DevExpress.XtraReports.UI.XRLabel lblSessionId;
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Scripting;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using System.IO;
using System.Globalization;
using System.Text;
using System.Diagnostics;
using Microsoft.CodeAnalysis.Scripting.Test;
namespace Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests
{
public class ScriptTests : TestBase
{
public class Globals
{
public int X;
public int Y;
}
[Fact]
public void TestCreateScript()
{
var script = CSharpScript.Create("1 + 2");
Assert.Equal("1 + 2", script.Code);
}
[Fact]
public void TestCreateScript_CodeIsNull()
{
Assert.Throws<ArgumentNullException>(() => CSharpScript.Create((string)null));
}
[Fact]
public void TestCreateFromStreamScript()
{
var script = CSharpScript.Create(new MemoryStream(Encoding.UTF8.GetBytes("1 + 2")));
Assert.Equal("1 + 2", script.Code);
}
[Fact]
public void TestCreateFromStreamScript_StreamIsNull()
{
Assert.Throws<ArgumentNullException>(() => CSharpScript.Create((Stream)null));
}
[Fact]
public async Task TestGetCompilation()
{
var state = await CSharpScript.RunAsync("1 + 2", globals: new ScriptTests());
var compilation = state.Script.GetCompilation();
Assert.Equal(state.Script.Code, compilation.SyntaxTrees.First().GetText().ToString());
}
[Fact]
public async Task TestGetCompilationSourceText()
{
var state = await CSharpScript.RunAsync("1 + 2", globals: new ScriptTests());
var compilation = state.Script.GetCompilation();
Assert.Equal(state.Script.SourceText, compilation.SyntaxTrees.First().GetText());
}
[Fact]
public void TestCreateScriptDelegate()
{
// create a delegate for the entire script
var script = CSharpScript.Create("1 + 2");
var fn = script.CreateDelegate();
Assert.Equal(3, fn().Result);
Assert.ThrowsAsync<ArgumentException>("globals", () => fn(new object()));
}
[Fact]
public void TestCreateScriptDelegateWithGlobals()
{
// create a delegate for the entire script
var script = CSharpScript.Create<int>("X + Y", globalsType: typeof(Globals));
var fn = script.CreateDelegate();
Assert.ThrowsAsync<ArgumentException>("globals", () => fn());
Assert.ThrowsAsync<ArgumentException>("globals", () => fn(new object()));
Assert.Equal(4, fn(new Globals { X = 1, Y = 3 }).Result);
}
[Fact]
public async Task TestRunScript()
{
var state = await CSharpScript.RunAsync("1 + 2");
Assert.Equal(3, state.ReturnValue);
}
[Fact]
public async Task TestCreateAndRunScript()
{
var script = CSharpScript.Create("1 + 2");
var state = await script.RunAsync();
Assert.Same(script, state.Script);
Assert.Equal(3, state.ReturnValue);
}
[Fact]
public async Task TestCreateFromStreamAndRunScript()
{
var script = CSharpScript.Create(new MemoryStream(Encoding.UTF8.GetBytes("1 + 2")));
var state = await script.RunAsync();
Assert.Same(script, state.Script);
Assert.Equal(3, state.ReturnValue);
}
[Fact]
public async Task TestEvalScript()
{
var value = await CSharpScript.EvaluateAsync("1 + 2");
Assert.Equal(3, value);
}
[Fact]
public async Task TestRunScriptWithSpecifiedReturnType()
{
var state = await CSharpScript.RunAsync("1 + 2");
Assert.Equal(3, state.ReturnValue);
}
[Fact]
public void TestRunVoidScript()
{
var state = ScriptingTestHelpers.RunScriptWithOutput(
CSharpScript.Create("System.Console.WriteLine(0);"),
"0");
Assert.Null(state.ReturnValue);
}
[WorkItem(5279, "https://github.com/dotnet/roslyn/issues/5279")]
[Fact]
public async void TestRunExpressionStatement()
{
var state = await CSharpScript.RunAsync(
@"int F() { return 1; }
F();");
Assert.Null(state.ReturnValue);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/170")]
public void TestRunDynamicVoidScriptWithTerminatingSemicolon()
{
var result = CSharpScript.RunAsync(@"
class SomeClass
{
public void Do()
{
}
}
dynamic d = new SomeClass();
d.Do();"
, ScriptOptions.Default.WithReferences(MscorlibRef, SystemRef, SystemCoreRef, CSharpRef));
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/170")]
public void TestRunDynamicVoidScriptWithoutTerminatingSemicolon()
{
var result = CSharpScript.RunAsync(@"
class SomeClass
{
public void Do()
{
}
}
dynamic d = new SomeClass();
d.Do()"
, ScriptOptions.Default.WithReferences(MscorlibRef, SystemRef, SystemCoreRef, CSharpRef));
}
[WorkItem(6676, "https://github.com/dotnet/roslyn/issues/6676")]
[Fact]
public void TestRunEmbeddedStatementNotFollowedBySemicolon()
{
var exceptionThrown = false;
try
{
var state = CSharpScript.RunAsync(@"if (true)
System.Console.WriteLine(true)", globals: new ScriptTests());
}
catch (CompilationErrorException ex)
{
exceptionThrown = true;
ex.Diagnostics.Verify(
// (2,32): error CS1002: ; expected
// System.Console.WriteLine(true)
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(2, 32));
}
Assert.True(exceptionThrown);
}
[WorkItem(6676, "https://github.com/dotnet/roslyn/issues/6676")]
[Fact]
public void TestRunEmbeddedStatementFollowedBySemicolon()
{
var state = CSharpScript.RunAsync(@"if (true)
System.Console.WriteLine(true);", globals: new ScriptTests());
Assert.Null(state.Exception);
}
[WorkItem(6676, "https://github.com/dotnet/roslyn/issues/6676")]
[Fact]
public void TestRunStatementFollowedBySpace()
{
var state = CSharpScript.RunAsync(@"System.Console.WriteLine(true) ", globals: new ScriptTests());
Assert.Null(state.Exception);
}
[WorkItem(6676, "https://github.com/dotnet/roslyn/issues/6676")]
[Fact]
public void TestRunStatementFollowedByNewLineNoSemicolon()
{
var state = CSharpScript.RunAsync(@"
System.Console.WriteLine(true)
", globals: new ScriptTests());
Assert.Null(state.Exception);
}
[WorkItem(6676, "https://github.com/dotnet/roslyn/issues/6676")]
[Fact]
public void TestRunEmbeddedNoSemicolonFollowedByAnotherStatement()
{
var exceptionThrown = false;
try
{
var state = CSharpScript.RunAsync(@"if (e) a = b
throw e;", globals: new ScriptTests());
}
catch (CompilationErrorException ex)
{
exceptionThrown = true;
// Verify that it produces a single ExpectedSemicolon error.
// No duplicates for the same error.
ex.Diagnostics.Verify(
// (1,13): error CS1002: ; expected
// if (e) a = b
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(1, 13));
}
Assert.True(exceptionThrown);
}
[Fact]
public async Task TestRunScriptWithGlobals()
{
var state = await CSharpScript.RunAsync("X + Y", globals: new Globals { X = 1, Y = 2 });
Assert.Equal(3, state.ReturnValue);
}
[Fact]
public async Task TestRunCreatedScriptWithExpectedGlobals()
{
var script = CSharpScript.Create("X + Y", globalsType: typeof(Globals));
var state = await script.RunAsync(new Globals { X = 1, Y = 2 });
Assert.Equal(3, state.ReturnValue);
Assert.Same(script, state.Script);
}
[Fact]
public void TestRunCreatedScriptWithUnexpectedGlobals()
{
var script = CSharpScript.Create("X + Y");
// Global variables passed to a script without a global type
Assert.ThrowsAsync<ArgumentException>("globals", () => script.RunAsync(new Globals { X = 1, Y = 2 }));
}
[Fact]
public void TestRunCreatedScriptWithoutGlobals()
{
var script = CSharpScript.Create("X + Y", globalsType: typeof(Globals));
// The script requires access to global variables but none were given
Assert.ThrowsAsync<ArgumentException>("globals", () => script.RunAsync());
}
[Fact]
public void TestRunCreatedScriptWithMismatchedGlobals()
{
var script = CSharpScript.Create("X + Y", globalsType: typeof(Globals));
// The globals of type 'System.Object' is not assignable to 'Microsoft.CodeAnalysis.CSharp.Scripting.Test.ScriptTests+Globals'
Assert.ThrowsAsync<ArgumentException>("globals", () => script.RunAsync(new object()));
}
[Fact]
public async Task ContinueAsync_Error1()
{
var state = await CSharpScript.RunAsync("X + Y", globals: new Globals());
await Assert.ThrowsAsync<ArgumentNullException>("previousState", () => state.Script.RunFromAsync(null));
}
[Fact]
public async Task ContinueAsync_Error2()
{
var state1 = await CSharpScript.RunAsync("X + Y + 1", globals: new Globals());
var state2 = await CSharpScript.RunAsync("X + Y + 2", globals: new Globals());
await Assert.ThrowsAsync<ArgumentException>("previousState", () => state1.Script.RunFromAsync(state2));
}
[Fact]
public async Task TestRunScriptWithScriptState()
{
// run a script using another scripts end state as the starting state (globals)
var state = await CSharpScript.RunAsync("int X = 100;").ContinueWith("X + X");
Assert.Equal(200, state.ReturnValue);
}
[Fact]
public async Task TestRepl()
{
string[] submissions = new[]
{
"int x = 100;",
"int y = x * x;",
"x + y"
};
var state = await CSharpScript.RunAsync("");
foreach (var submission in submissions)
{
state = await state.ContinueWithAsync(submission);
}
Assert.Equal(10100, state.ReturnValue);
}
#if TODO // https://github.com/dotnet/roslyn/issues/3720
[Fact]
public void TestCreateMethodDelegate()
{
// create a delegate to a method declared in the script
var state = CSharpScript.Run("int Times(int x) { return x * x; }");
var fn = state.CreateDelegate<Func<int, int>>("Times");
var result = fn(5);
Assert.Equal(25, result);
}
#endif
[Fact]
public async Task ScriptVariables_Chain()
{
var globals = new Globals { X = 10, Y = 20 };
var script =
CSharpScript.Create(
"var a = '1';",
globalsType: globals.GetType()).
ContinueWith("var b = 2u;").
ContinueWith("var a = 3m;").
ContinueWith("var x = a + b;").
ContinueWith("var X = Y;");
var state = await script.RunAsync(globals);
AssertEx.Equal(new[] { "a", "b", "a", "x", "X" }, state.Variables.Select(v => v.Name));
AssertEx.Equal(new object[] { '1', 2u, 3m, 5m, 20 }, state.Variables.Select(v => v.Value));
AssertEx.Equal(new Type[] { typeof(char), typeof(uint), typeof(decimal), typeof(decimal), typeof(int) }, state.Variables.Select(v => v.Type));
Assert.Equal(3m, state.GetVariable("a").Value);
Assert.Equal(2u, state.GetVariable("b").Value);
Assert.Equal(5m, state.GetVariable("x").Value);
Assert.Equal(20, state.GetVariable("X").Value);
Assert.Equal(null, state.GetVariable("A"));
Assert.Same(state.GetVariable("X"), state.GetVariable("X"));
}
[Fact]
public async Task ScriptVariable_SetValue()
{
var script = CSharpScript.Create("var x = 1;");
var s1 = await script.RunAsync();
s1.GetVariable("x").Value = 2;
Assert.Equal(2, s1.GetVariable("x").Value);
// rerunning the script from the beginning rebuilds the state:
var s2 = await s1.Script.RunAsync();
Assert.Equal(1, s2.GetVariable("x").Value);
// continuing preserves the state:
var s3 = await s1.ContinueWithAsync("x");
Assert.Equal(2, s3.GetVariable("x").Value);
Assert.Equal(2, s3.ReturnValue);
}
[Fact]
public async Task ScriptVariable_SetValue_Errors()
{
var state = await CSharpScript.RunAsync(@"
var x = 1;
readonly var y = 2;
const int z = 3;
");
Assert.False(state.GetVariable("x").IsReadOnly);
Assert.True(state.GetVariable("y").IsReadOnly);
Assert.True(state.GetVariable("z").IsReadOnly);
Assert.Throws<ArgumentException>(() => state.GetVariable("x").Value = "str");
Assert.Throws<InvalidOperationException>(() => state.GetVariable("y").Value = "str");
Assert.Throws<InvalidOperationException>(() => state.GetVariable("z").Value = "str");
Assert.Throws<InvalidOperationException>(() => state.GetVariable("y").Value = 0);
Assert.Throws<InvalidOperationException>(() => state.GetVariable("z").Value = 0);
}
[Fact]
public async Task TestBranchingSubscripts()
{
// run script to create declaration of M
var state1 = await CSharpScript.RunAsync("int M(int x) { return x + x; }");
// run second script starting from first script's end state
// this script's new declaration should hide the old declaration
var state2 = await state1.ContinueWithAsync("int M(int x) { return x * x; } M(5)");
Assert.Equal(25, state2.ReturnValue);
// run third script also starting from first script's end state
// it should not see any declarations made by the second script.
var state3 = await state1.ContinueWithAsync("M(5)");
Assert.Equal(10, state3.ReturnValue);
}
[Fact]
public async Task ReturnIntAsObject()
{
var expected = 42;
var script = CSharpScript.Create<object>($"return {expected};");
var result = await script.EvaluateAsync();
Assert.Equal(expected, result);
}
[Fact]
public void NoReturn()
{
Assert.Null(ScriptingTestHelpers.EvaluateScriptWithOutput(
CSharpScript.Create("System.Console.WriteLine();"), ""));
}
[Fact]
public async Task ReturnAwait()
{
var script = CSharpScript.Create<int>("return await System.Threading.Tasks.Task.FromResult(42);");
var result = await script.EvaluateAsync();
Assert.Equal(42, result);
}
[Fact]
public async Task ReturnInNestedScopeNoTrailingExpression()
{
var script = CSharpScript.Create(@"
bool condition = false;
if (condition)
{
return 1;
}");
var result = await script.EvaluateAsync();
Assert.Null(result);
}
[Fact]
public async Task ReturnInNestedScopeWithTrailingVoidExpression()
{
var script = CSharpScript.Create(@"
bool condition = false;
if (condition)
{
return 1;
}
System.Console.WriteLine();");
var result = await script.EvaluateAsync();
Assert.Null(result);
script = CSharpScript.Create(@"
bool condition = true;
if (condition)
{
return 1;
}
System.Console.WriteLine();");
Assert.Equal(1, ScriptingTestHelpers.EvaluateScriptWithOutput(script, ""));
}
[Fact]
public async Task ReturnInNestedScopeWithTrailingVoidExpressionAsInt()
{
var script = CSharpScript.Create<int>(@"
bool condition = false;
if (condition)
{
return 1;
}
System.Console.WriteLine();");
var result = await script.EvaluateAsync();
Assert.Equal(0, result);
script = CSharpScript.Create<int>(@"
bool condition = false;
if (condition)
{
return 1;
}
System.Console.WriteLine()");
Assert.Equal(0, ScriptingTestHelpers.EvaluateScriptWithOutput(script, ""));
}
[Fact]
public async Task ReturnIntWithTrailingDoubleExpression()
{
var script = CSharpScript.Create(@"
bool condition = false;
if (condition)
{
return 1;
}
1.1");
var result = await script.EvaluateAsync();
Assert.Equal(1.1, result);
script = CSharpScript.Create(@"
bool condition = true;
if (condition)
{
return 1;
}
1.1");
result = await script.EvaluateAsync();
Assert.Equal(1, result);
}
[Fact]
public async Task ReturnGenericAsInterface()
{
var script = CSharpScript.Create<IEnumerable<int>>(@"
if (false)
{
return new System.Collections.Generic.List<int> { 1, 2, 3 };
}");
var result = await script.EvaluateAsync();
Assert.Null(result);
script = CSharpScript.Create<IEnumerable<int>>(@"
if (true)
{
return new System.Collections.Generic.List<int> { 1, 2, 3 };
}");
result = await script.EvaluateAsync();
Assert.Equal(new List<int> { 1, 2, 3 }, result);
}
[Fact]
public async Task ReturnNullable()
{
var script = CSharpScript.Create<int?>(@"
if (false)
{
return 42;
}");
var result = await script.EvaluateAsync();
Assert.False(result.HasValue);
script = CSharpScript.Create<int?>(@"
if (true)
{
return 42;
}");
result = await script.EvaluateAsync();
Assert.Equal(42, result);
}
[Fact]
public async Task ReturnInLoadedFile()
{
var resolver = TestSourceReferenceResolver.Create(
KeyValuePair.Create("a.csx", "return 42;"));
var options = ScriptOptions.Default.WithSourceResolver(resolver);
var script = CSharpScript.Create("#load \"a.csx\"", options);
var result = await script.EvaluateAsync();
Assert.Equal(42, result);
script = CSharpScript.Create(@"
#load ""a.csx""
-1", options);
result = await script.EvaluateAsync();
Assert.Equal(42, result);
}
[Fact]
public async Task ReturnInLoadedFileTrailingExpression()
{
var resolver = TestSourceReferenceResolver.Create(
KeyValuePair.Create("a.csx", @"
if (false)
{
return 42;
}
1"));
var options = ScriptOptions.Default.WithSourceResolver(resolver);
var script = CSharpScript.Create("#load \"a.csx\"", options);
var result = await script.EvaluateAsync();
Assert.Null(result);
script = CSharpScript.Create(@"
#load ""a.csx""
2", options);
result = await script.EvaluateAsync();
Assert.Equal(2, result);
}
[Fact]
public void ReturnInLoadedFileTrailingVoidExpression()
{
var resolver = TestSourceReferenceResolver.Create(
KeyValuePair.Create("a.csx", @"
if (false)
{
return 1;
}
System.Console.WriteLine(42)"));
var options = ScriptOptions.Default.WithSourceResolver(resolver);
var script = CSharpScript.Create("#load \"a.csx\"", options);
var result = ScriptingTestHelpers.EvaluateScriptWithOutput(script, "42");
Assert.Null(result);
script = CSharpScript.Create(@"
#load ""a.csx""
2", options);
result = ScriptingTestHelpers.EvaluateScriptWithOutput(script, "42");
Assert.Equal(2, result);
}
[Fact]
public async Task MultipleLoadedFilesWithTrailingExpression()
{
var resolver = TestSourceReferenceResolver.Create(
KeyValuePair.Create("a.csx", "1"),
KeyValuePair.Create("b.csx", @"
#load ""a.csx""
2"));
var options = ScriptOptions.Default.WithSourceResolver(resolver);
var script = CSharpScript.Create("#load \"b.csx\"", options);
var result = await script.EvaluateAsync();
Assert.Null(result);
resolver = TestSourceReferenceResolver.Create(
KeyValuePair.Create("a.csx", "1"),
KeyValuePair.Create("b.csx", "2"));
options = ScriptOptions.Default.WithSourceResolver(resolver);
script = CSharpScript.Create(@"
#load ""a.csx""
#load ""b.csx""", options);
result = await script.EvaluateAsync();
Assert.Null(result);
resolver = TestSourceReferenceResolver.Create(
KeyValuePair.Create("a.csx", "1"),
KeyValuePair.Create("b.csx", "2"));
options = ScriptOptions.Default.WithSourceResolver(resolver);
script = CSharpScript.Create(@"
#load ""a.csx""
#load ""b.csx""
3", options);
result = await script.EvaluateAsync();
Assert.Equal(3, result);
}
[Fact]
public async Task MultipleLoadedFilesWithReturnAndTrailingExpression()
{
var resolver = TestSourceReferenceResolver.Create(
KeyValuePair.Create("a.csx", "return 1;"),
KeyValuePair.Create("b.csx", @"
#load ""a.csx""
2"));
var options = ScriptOptions.Default.WithSourceResolver(resolver);
var script = CSharpScript.Create("#load \"b.csx\"", options);
var result = await script.EvaluateAsync();
Assert.Equal(1, result);
resolver = TestSourceReferenceResolver.Create(
KeyValuePair.Create("a.csx", "return 1;"),
KeyValuePair.Create("b.csx", "2"));
options = ScriptOptions.Default.WithSourceResolver(resolver);
script = CSharpScript.Create(@"
#load ""a.csx""
#load ""b.csx""", options);
result = await script.EvaluateAsync();
Assert.Equal(1, result);
resolver = TestSourceReferenceResolver.Create(
KeyValuePair.Create("a.csx", "return 1;"),
KeyValuePair.Create("b.csx", "2"));
options = ScriptOptions.Default.WithSourceResolver(resolver);
script = CSharpScript.Create(@"
#load ""a.csx""
#load ""b.csx""
return 3;", options);
result = await script.EvaluateAsync();
Assert.Equal(1, result);
}
[Fact]
public async Task LoadedFileWithReturnAndGoto()
{
var resolver = TestSourceReferenceResolver.Create(
KeyValuePair.Create("a.csx", @"
goto EOF;
NEXT:
return 1;
EOF:;
2"));
var options = ScriptOptions.Default.WithSourceResolver(resolver);
var script = CSharpScript.Create(@"
#load ""a.csx""
goto NEXT;
return 3;
NEXT:;", options);
var result = await script.EvaluateAsync();
Assert.Null(result);
script = CSharpScript.Create(@"
#load ""a.csx""
L1: goto EOF;
L2: return 3;
EOF:
EOF2: ;
4", options);
result = await script.EvaluateAsync();
Assert.Equal(4, result);
}
[Fact]
public async Task VoidReturn()
{
var script = CSharpScript.Create("return;");
var result = await script.EvaluateAsync();
Assert.Null(result);
script = CSharpScript.Create(@"
var b = true;
if (b)
{
return;
}
b");
result = await script.EvaluateAsync();
Assert.Null(result);
}
[Fact]
public async Task LoadedFileWithVoidReturn()
{
var resolver = TestSourceReferenceResolver.Create(
KeyValuePair.Create("a.csx", @"
var i = 42;
return;
i = -1;"));
var options = ScriptOptions.Default.WithSourceResolver(resolver);
var script = CSharpScript.Create<int>(@"
#load ""a.csx""
i", options);
var result = await script.EvaluateAsync();
Assert.Equal(0, result);
}
[Fact]
public async Task Pdb_CreateFromString_CodeFromFile_WithEmitDebugInformation_WithoutFileEncoding_CompilationErrorException()
{
var code = "throw new System.Exception();";
try
{
var opts = ScriptOptions.Default.WithEmitDebugInformation(true).WithFilePath("debug.csx").WithFileEncoding(null);
var script = await CSharpScript.RunAsync(code, opts);
}
catch (CompilationErrorException ex)
{
// CS8055: Cannot emit debug information for a source text without encoding.
ex.Diagnostics.Verify(Diagnostic(ErrorCode.ERR_EncodinglessSyntaxTree, code).WithLocation(1,1));
}
}
[Fact]
public Task Pdb_CreateFromString_CodeFromFile_WithEmitDebugInformation_WithFileEncoding_ResultInPdbEmitted()
{
var opts = ScriptOptions.Default.WithEmitDebugInformation(true).WithFilePath("debug.csx").WithFileEncoding(Encoding.UTF8);
return VerifyStackTraceAsync(() => CSharpScript.Create("throw new System.Exception();", opts), line: 1, column: 1, filename: "debug.csx");
}
[Fact]
public Task Pdb_CreateFromString_CodeFromFile_WithoutEmitDebugInformation_WithoutFileEncoding_ResultInPdbNotEmitted()
{
var opts = ScriptOptions.Default.WithEmitDebugInformation(false).WithFilePath(null).WithFileEncoding(null);
return VerifyStackTraceAsync(() => CSharpScript.Create("throw new System.Exception();", opts));
}
[Fact]
public Task Pdb_CreateFromString_CodeFromFile_WithoutEmitDebugInformation_WithFileEncoding_ResultInPdbNotEmitted()
{
var opts = ScriptOptions.Default.WithEmitDebugInformation(false).WithFilePath("debug.csx").WithFileEncoding(Encoding.UTF8);
return VerifyStackTraceAsync(() => CSharpScript.Create("throw new System.Exception();", opts));
}
[Fact]
public Task Pdb_CreateFromStream_CodeFromFile_WithEmitDebugInformation_ResultInPdbEmitted()
{
var opts = ScriptOptions.Default.WithEmitDebugInformation(true).WithFilePath("debug.csx");
return VerifyStackTraceAsync(() => CSharpScript.Create(new MemoryStream(Encoding.UTF8.GetBytes("throw new System.Exception();")), opts), line: 1, column: 1, filename: "debug.csx");
}
[Fact]
public Task Pdb_CreateFromStream_CodeFromFile_WithoutEmitDebugInformation_ResultInPdbNotEmitted()
{
var opts = ScriptOptions.Default.WithEmitDebugInformation(false).WithFilePath("debug.csx");
return VerifyStackTraceAsync(() => CSharpScript.Create(new MemoryStream(Encoding.UTF8.GetBytes("throw new System.Exception();")), opts));
}
[Fact]
public Task Pdb_CreateFromString_InlineCode_WithEmitDebugInformation_WithoutFileEncoding_ResultInPdbEmitted()
{
var opts = ScriptOptions.Default.WithEmitDebugInformation(true).WithFileEncoding(null);
return VerifyStackTraceAsync(() => CSharpScript.Create("throw new System.Exception();", opts), line: 1, column: 1, filename: "");
}
[Fact]
public Task Pdb_CreateFromString_InlineCode_WithEmitDebugInformation_WithFileEncoding_ResultInPdbEmitted()
{
var opts = ScriptOptions.Default.WithEmitDebugInformation(true).WithFileEncoding(Encoding.UTF8);
return VerifyStackTraceAsync(() => CSharpScript.Create("throw new System.Exception();", opts), line: 1, column: 1, filename: "");
}
[Fact]
public Task Pdb_CreateFromString_InlineCode_WithoutEmitDebugInformation_WithoutFileEncoding_ResultInPdbNotEmitted()
{
var opts = ScriptOptions.Default.WithEmitDebugInformation(false).WithFileEncoding(null);
return VerifyStackTraceAsync(() => CSharpScript.Create("throw new System.Exception();", opts));
}
[Fact]
public Task Pdb_CreateFromString_InlineCode_WithoutEmitDebugInformation_WithFileEncoding_ResultInPdbNotEmitted()
{
var opts = ScriptOptions.Default.WithEmitDebugInformation(false).WithFileEncoding(Encoding.UTF8);
return VerifyStackTraceAsync(() => CSharpScript.Create("throw new System.Exception();", opts));
}
[Fact]
public Task Pdb_CreateFromStream_InlineCode_WithEmitDebugInformation_ResultInPdbEmitted()
{
var opts = ScriptOptions.Default.WithEmitDebugInformation(true);
return VerifyStackTraceAsync(() => CSharpScript.Create(new MemoryStream(Encoding.UTF8.GetBytes("throw new System.Exception();")), opts), line: 1, column: 1, filename: "");
}
[Fact]
public Task Pdb_CreateFromStream_InlineCode_WithoutEmitDebugInformation_ResultInPdbNotEmitted()
{
var opts = ScriptOptions.Default.WithEmitDebugInformation(false);
return VerifyStackTraceAsync(() => CSharpScript.Create(new MemoryStream(Encoding.UTF8.GetBytes("throw new System.Exception();")), opts));
}
[WorkItem(12348, "https://github.com/dotnet/roslyn/issues/12348")]
[Fact]
public void StreamWithOffset()
{
var resolver = new StreamOffsetResolver();
var options = ScriptOptions.Default.WithSourceResolver(resolver);
var script = CSharpScript.Create(@"#load ""a.csx""", options);
ScriptingTestHelpers.EvaluateScriptWithOutput(script, "Hello World!");
}
private class StreamOffsetResolver : SourceReferenceResolver
{
public override bool Equals(object other) => ReferenceEquals(this, other);
public override int GetHashCode() => 42;
public override string ResolveReference(string path, string baseFilePath) => path;
public override string NormalizePath(string path, string baseFilePath) => path;
public override Stream OpenRead(string resolvedPath)
{
// Make an ASCII text buffer with Hello World script preceded by padding Qs
const int padding = 42;
string text = @"System.Console.WriteLine(""Hello World!"");";
byte[] bytes = Enumerable.Repeat((byte)'Q', text.Length + padding).ToArray();
System.Text.Encoding.ASCII.GetBytes(text, 0, text.Length, bytes, padding);
// Make a stream over the program portion, skipping the Qs.
var stream = new MemoryStream(
bytes,
padding,
text.Length,
writable: false,
publiclyVisible: true);
// sanity check that reading entire stream gives us back our text.
using (var streamReader = new StreamReader(
stream,
System.Text.Encoding.ASCII,
detectEncodingFromByteOrderMarks: false,
bufferSize: bytes.Length,
leaveOpen: true))
{
var textFromStream = streamReader.ReadToEnd();
Assert.Equal(textFromStream, text);
}
stream.Position = 0;
return stream;
}
}
private async Task VerifyStackTraceAsync(Func<Script<object>> scriptProvider, int line = 0, int column = 0, string filename = null)
{
try
{
var script = scriptProvider();
await script.RunAsync();
}
catch (Exception ex)
{
// line information is only available when PDBs have been emitted
var stackTrace = new StackTrace(ex, needFileInfo: true);
var firstFrame = stackTrace.GetFrames()[0];
Assert.Equal(filename, firstFrame.GetFileName());
Assert.Equal(line, firstFrame.GetFileLineNumber());
Assert.Equal(column, firstFrame.GetFileColumnNumber());
}
}
}
}
| |
#if SqlServer || !SqlServer
using System.IO;
using System.Reflection;
using System.Data.SqlTypes;
using System.Xml;
namespace System.Data.SqlClient
{
/// <summary>
/// SqlParseEx
/// </summary>
public static class SqlParseEx
{
internal static readonly Type SqlInt32Type = typeof(SqlInt32);
internal static readonly Type SqlDateTimeType = typeof(SqlDateTime);
internal static readonly Type SqlStringType = typeof(SqlString);
internal static readonly Type SqlBooleanType = typeof(SqlBoolean);
internal static readonly Type SqlXmlType = typeof(SqlXml);
private static readonly Type BinaryReaderType = typeof(BinaryReader);
private static readonly Type BinaryWriterType = typeof(BinaryWriter);
#region SqlTypeT
/// <summary>
/// SqlTypeT class
/// </summary>
/// <typeparam name="T"></typeparam>
public static class SqlTypeT<T>
{
private static readonly Type s_type = typeof(T);
public static readonly Func<BinaryReader, T> BinaryRead = SqlTypeT<T>.CreateBinaryRead(s_type);
public static readonly Action<BinaryWriter, T> BinaryWrite = SqlTypeT<T>.CreateBinaryWrite(s_type);
public static readonly Func<XmlReader, string, T> XmlRead = SqlTypeT<T>.CreateXmlRead(s_type);
public static readonly Action<XmlWriter, string, T> XmlWrite = SqlTypeT<T>.CreateXmlWrite(s_type);
/// <summary>
/// Initializes the <see cref="SqlTypeT<T>"/> class.
/// </summary>
static SqlTypeT() { }
#region BinaryRead Implementation
/// <summary>
/// Creates the specified type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns></returns>
private static Func<BinaryReader, T> CreateBinaryRead(Type type)
{
if (type == SqlInt32Type)
return (Func<BinaryReader, T>)Delegate.CreateDelegate(typeof(Func<BinaryReader, T>), typeof(SqlTypeT<T>).GetMethod("BinaryRead_SqlInt32", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { BinaryReaderType }, null));
else if (type == SqlDateTimeType)
return (Func<BinaryReader, T>)Delegate.CreateDelegate(typeof(Func<BinaryReader, T>), typeof(SqlTypeT<T>).GetMethod("BinaryRead_SqlDateTime", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { BinaryReaderType }, null));
else if (type == SqlStringType)
return (Func<BinaryReader, T>)Delegate.CreateDelegate(typeof(Func<BinaryReader, T>), typeof(SqlTypeT<T>).GetMethod("BinaryRead_SqlString", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { BinaryReaderType }, null));
else if (type == SqlBooleanType)
return (Func<BinaryReader, T>)Delegate.CreateDelegate(typeof(Func<BinaryReader, T>), typeof(SqlTypeT<T>).GetMethod("BinaryRead_SqlBoolean", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { BinaryReaderType }, null));
else if (type == SqlXmlType)
return (Func<BinaryReader, T>)Delegate.CreateDelegate(typeof(Func<BinaryReader, T>), typeof(SqlTypeT<T>).GetMethod("BinaryRead_SqlXml", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { BinaryReaderType }, null));
throw new InvalidOperationException(string.Format("\nUndefined Type [{0}]", type.ToString()));
}
/// <summary>
/// Read_s the SQL int32.
/// </summary>
/// <param name="r">The r.</param>
/// <returns></returns>
private static SqlInt32 BinaryRead_SqlInt32(BinaryReader r)
{
return (!r.ReadBoolean() ? new SqlInt32(r.ReadInt32()) : SqlInt32.Null);
}
/// <summary>
/// Read_s the SQL int32.
/// </summary>
/// <param name="r">The r.</param>
/// <returns></returns>
private static SqlDateTime BinaryRead_SqlDateTime(BinaryReader r)
{
return (!r.ReadBoolean() ? new SqlDateTime(r.ReadInt32(), r.ReadInt32()) : SqlDateTime.Null);
}
/// <summary>
/// Read_s the SQL string.
/// </summary>
/// <param name="r">The r.</param>
/// <returns></returns>
private static SqlString BinaryRead_SqlString(BinaryReader r)
{
return (!r.ReadBoolean() ? new SqlString(r.ReadString()) : SqlString.Null);
}
/// <summary>
/// Read_s the SQL boolean.
/// </summary>
/// <param name="r">The r.</param>
/// <returns></returns>
private static SqlBoolean BinaryRead_SqlBoolean(BinaryReader r)
{
return (!r.ReadBoolean() ? new SqlBoolean(r.ReadBoolean()) : SqlBoolean.Null);
}
/// <summary>
/// Read_s the SQL XML.
/// </summary>
/// <param name="r">The r.</param>
/// <returns></returns>
private static SqlXml BinaryRead_SqlXml(BinaryReader r)
{
if (!r.ReadBoolean())
{
var s = new MemoryStream();
var w = new StreamWriter(s);
w.Write(r.ReadString());
w.Flush();
return new SqlXml(s);
}
return SqlXml.Null;
}
#endregion
#region BinaryWrite Implementation
/// <summary>
/// Creates the specified type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns></returns>
private static Action<BinaryWriter, T> CreateBinaryWrite(Type type)
{
if (type == SqlInt32Type)
return (Action<BinaryWriter, T>)Delegate.CreateDelegate(typeof(Action<BinaryWriter, T>), typeof(SqlTypeT<T>).GetMethod("BinaryWrite_SqlInt32", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { BinaryWriterType, SqlInt32Type }, null));
else if (type == SqlDateTimeType)
return (Action<BinaryWriter, T>)Delegate.CreateDelegate(typeof(Action<BinaryWriter, T>), typeof(SqlTypeT<T>).GetMethod("BinaryWrite_SqlDateTime", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { BinaryWriterType, SqlDateTimeType }, null));
else if (type == SqlStringType)
return (Action<BinaryWriter, T>)Delegate.CreateDelegate(typeof(Action<BinaryWriter, T>), typeof(SqlTypeT<T>).GetMethod("BinaryWrite_SqlString", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { BinaryWriterType, SqlStringType }, null));
else if (type == SqlBooleanType)
return (Action<BinaryWriter, T>)Delegate.CreateDelegate(typeof(Action<BinaryWriter, T>), typeof(SqlTypeT<T>).GetMethod("BinaryWrite_SqlBoolean", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { BinaryWriterType, SqlBooleanType }, null));
else if (type == SqlXmlType)
return (Action<BinaryWriter, T>)Delegate.CreateDelegate(typeof(Action<BinaryWriter, T>), typeof(SqlTypeT<T>).GetMethod("BinaryWrite_SqlXml", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { BinaryWriterType, SqlXmlType }, null));
throw new InvalidOperationException();
}
/// <summary>
/// Write_s the SQL int32.
/// </summary>
/// <param name="w">The w.</param>
/// <param name="value">The value.</param>
private static void BinaryWrite_SqlInt32(BinaryWriter w, SqlInt32 value)
{
bool isNull = value.IsNull;
w.Write(isNull);
if (!isNull)
w.Write(value.Value);
}
/// <summary>
/// Write_s the SQL int32.
/// </summary>
/// <param name="w">The w.</param>
/// <param name="value">The value.</param>
private static void BinaryWrite_SqlDateTime(BinaryWriter w, SqlDateTime value)
{
bool isNull = value.IsNull;
w.Write(isNull);
if (!isNull)
{
w.Write(value.DayTicks);
w.Write(value.TimeTicks);
}
}
/// <summary>
/// Write_s the SQL string.
/// </summary>
/// <param name="w">The w.</param>
/// <param name="value">The value.</param>
private static void BinaryWrite_SqlString(BinaryWriter w, SqlString value)
{
bool isNull = value.IsNull;
w.Write(isNull);
if (!isNull)
w.Write(value.Value);
}
/// <summary>
/// Write_s the SQL boolean.
/// </summary>
/// <param name="w">The w.</param>
/// <param name="value">The value.</param>
private static void BinaryWrite_SqlBoolean(BinaryWriter w, SqlBoolean value)
{
bool isNull = value.IsNull;
w.Write(isNull);
if (!isNull)
w.Write(value.Value);
}
/// <summary>
/// Write_s the SQL XML.
/// </summary>
/// <param name="w">The w.</param>
/// <param name="value">The value.</param>
private static void BinaryWrite_SqlXml(BinaryWriter w, SqlXml value)
{
if (value == null)
throw new ArgumentNullException("value");
bool isNull = value.IsNull;
w.Write(isNull);
if (!isNull)
w.Write(value.Value);
}
#endregion
#region XmlRead Implementation
/// <summary>
/// Creates the specified type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns></returns>
private static Func<XmlReader, string, T> CreateXmlRead(Type type)
{
if (type == SqlInt32Type)
return (Func<XmlReader, string, T>)Delegate.CreateDelegate(typeof(Func<XmlReader, string, T>), typeof(SqlTypeT<T>).GetMethod("XmlRead_SqlInt32", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { CoreExInternal.XmlReaderType, CoreExInternal.StringType }, null));
else if (type == SqlDateTimeType)
return (Func<XmlReader, string, T>)Delegate.CreateDelegate(typeof(Func<XmlReader, string, T>), typeof(SqlTypeT<T>).GetMethod("XmlRead_SqlDateTime", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { CoreExInternal.XmlReaderType, CoreExInternal.StringType }, null));
else if (type == SqlStringType)
return (Func<XmlReader, string, T>)Delegate.CreateDelegate(typeof(Func<XmlReader, string, T>), typeof(SqlTypeT<T>).GetMethod("XmlRead_SqlString", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { CoreExInternal.XmlReaderType, CoreExInternal.StringType }, null));
else if (type == SqlBooleanType)
return (Func<XmlReader, string, T>)Delegate.CreateDelegate(typeof(Func<XmlReader, string, T>), typeof(SqlTypeT<T>).GetMethod("XmlRead_SqlBoolean", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { CoreExInternal.XmlReaderType, CoreExInternal.StringType }, null));
else if (type == SqlXmlType)
return (Func<XmlReader, string, T>)Delegate.CreateDelegate(typeof(Func<XmlReader, string, T>), typeof(SqlTypeT<T>).GetMethod("XmlRead_SqlXml", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { CoreExInternal.XmlReaderType, CoreExInternal.StringType }, null));
throw new InvalidOperationException(string.Format("\nUndefined Type [{0}]", type.ToString()));
}
/// <summary>
/// Read_s the SQL int32.
/// </summary>
/// <param name="r">The r.</param>
/// <returns></returns>
private static SqlInt32 XmlRead_SqlInt32(XmlReader r, string id)
{
string value = r.GetAttribute(id);
return (value != null ? new SqlInt32(value.Parse<int>()) : SqlInt32.Null);
}
/// <summary>
/// Read_s the SQL int32.
/// </summary>
/// <param name="r">The r.</param>
/// <param name="id">The id.</param>
/// <returns></returns>
private static SqlDateTime XmlRead_SqlDateTime(XmlReader r, string id)
{
string value = r.GetAttribute(id);
return (value != null ? new SqlDateTime(value.Parse<DateTime>()) : SqlDateTime.Null);
}
/// <summary>
/// Read_s the SQL string.
/// </summary>
/// <param name="r">The r.</param>
/// <returns></returns>
private static SqlString XmlRead_SqlString(XmlReader r, string id)
{
string value = r.GetAttribute(id);
return (value != null ? new SqlString(value) : SqlString.Null);
}
/// <summary>
/// Read_s the SQL boolean.
/// </summary>
/// <param name="r">The r.</param>
/// <returns></returns>
private static SqlBoolean XmlRead_SqlBoolean(XmlReader r, string id)
{
string value = r.GetAttribute(id);
return (value != null ? new SqlBoolean(value.Parse<bool>()) : SqlBoolean.Null);
}
/// <summary>
/// Read_s the SQL XML.
/// </summary>
/// <param name="r">The r.</param>
/// <returns></returns>
private static SqlXml XmlRead_SqlXml(XmlReader r, string id)
{
string value;
switch (id)
{
case "":
return (!r.IsEmptyElement ? new SqlXml(r.ReadSubtree()) : SqlXml.Null);
case "#":
value = r.ReadString();
break;
default:
value = r.GetAttribute(id);
break;
}
if (!string.IsNullOrEmpty(value))
{
var s = new MemoryStream();
var w = new StreamWriter(s);
w.Write(value);
w.Flush();
return new SqlXml(s);
}
return SqlXml.Null;
}
#endregion
#region XmlWrite Implementation
/// <summary>
/// Creates the specified type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns></returns>
private static Action<XmlWriter, string, T> CreateXmlWrite(Type type)
{
if (type == SqlInt32Type)
return (Action<XmlWriter, string, T>)Delegate.CreateDelegate(typeof(Action<XmlWriter, string, T>), typeof(SqlTypeT<T>).GetMethod("XmlWrite_SqlInt32", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { CoreExInternal.XmlWriterType, CoreExInternal.StringType, SqlInt32Type }, null));
else if (type == SqlDateTimeType)
return (Action<XmlWriter, string, T>)Delegate.CreateDelegate(typeof(Action<XmlWriter, string, T>), typeof(SqlTypeT<T>).GetMethod("XmlWrite_SqlDateTime", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { CoreExInternal.XmlWriterType, CoreExInternal.StringType, SqlDateTimeType }, null));
else if (type == SqlStringType)
return (Action<XmlWriter, string, T>)Delegate.CreateDelegate(typeof(Action<XmlWriter, string, T>), typeof(SqlTypeT<T>).GetMethod("XmlWrite_SqlString", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { CoreExInternal.XmlWriterType, CoreExInternal.StringType, SqlStringType }, null));
else if (type == SqlBooleanType)
return (Action<XmlWriter, string, T>)Delegate.CreateDelegate(typeof(Action<XmlWriter, string, T>), typeof(SqlTypeT<T>).GetMethod("XmlWrite_SqlBoolean", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { CoreExInternal.XmlWriterType, CoreExInternal.StringType, SqlBooleanType }, null));
else if (type == SqlXmlType)
return (Action<XmlWriter, string, T>)Delegate.CreateDelegate(typeof(Action<XmlWriter, string, T>), typeof(SqlTypeT<T>).GetMethod("XmlWrite_SqlXml", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { CoreExInternal.XmlWriterType, CoreExInternal.StringType, SqlXmlType }, null));
throw new InvalidOperationException();
}
/// <summary>
/// Write_s the SQL int32.
/// </summary>
/// <param name="w">The w.</param>
/// <param name="value">The value.</param>
private static void XmlWrite_SqlInt32(XmlWriter w, string id, SqlInt32 value)
{
bool isNull = value.IsNull;
if (!isNull)
w.WriteAttributeString(id, value.Value.ToString());
}
/// <summary>
/// Write_s the SQL int32.
/// </summary>
/// <param name="w">The w.</param>
/// <param name="value">The value.</param>
private static void XmlWrite_SqlDateTime(XmlWriter w, string id, SqlDateTime value)
{
bool isNull = value.IsNull;
if (!isNull)
w.WriteAttributeString(id, value.Value.ToString());
}
/// <summary>
/// Write_s the SQL string.
/// </summary>
/// <param name="w">The w.</param>
/// <param name="value">The value.</param>
private static void XmlWrite_SqlString(XmlWriter w, string id, SqlString value)
{
bool isNull = value.IsNull;
if (!isNull)
w.WriteAttributeString(id, value.Value.ToString());
}
/// <summary>
/// Write_s the SQL boolean.
/// </summary>
/// <param name="w">The w.</param>
/// <param name="value">The value.</param>
private static void XmlWrite_SqlBoolean(XmlWriter w, string id, SqlBoolean value)
{
bool isNull = value.IsNull;
if (!isNull)
w.WriteAttributeString(id, value.Value.ToString());
}
/// <summary>
/// Write_s the SQL XML.
/// </summary>
/// <param name="w">The w.</param>
/// <param name="value">The value.</param>
private static void XmlWrite_SqlXml(XmlWriter w, string id, SqlXml value)
{
if (value == null)
throw new ArgumentNullException("value");
bool isNull = value.IsNull;
if (!isNull)
{
string valueAsText;
switch (id)
{
case "":
w.WriteNode(value.CreateReader(), false);
return;
case "#":
valueAsText = value.Value;
if (!string.IsNullOrEmpty(valueAsText))
w.WriteString(valueAsText);
break;
default:
valueAsText = value.Value;
if (!string.IsNullOrEmpty(valueAsText))
w.WriteAttributeString(id, valueAsText);
break;
}
}
}
#endregion
}
#endregion
}
}
#endif
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="BacklogNotificationMockupModule.cs">
// bl4n - Backlog.jp API Client library
// this file is part of bl4n, license under MIT license. http://t-ashula.mit-license.org/2015
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Linq;
using Nancy;
namespace BL4N.Tests
{
/// <summary>
/// /api/v2/notifications roting module
/// </summary>
public class BacklogNotificationMockupModule : NancyModule
{
/// <summary>
/// /api/v2/notification routing
/// </summary>
public BacklogNotificationMockupModule() :
base("/api/v2/notifications")
{
#region /apiv/v2/notifications
Get[string.Empty] = p => Response.AsJson(new[]
{
new
{
id = 299,
alreadyRead = true,
reason = 2,
resourceAlreadyRead = true,
project = new
{
id = 2,
projectKey = "TEST2",
name = "test2",
chartEnabled = true,
subtaskingEnabled = true,
textFormattingRule = "backlog",
archived = false,
displayOrder = 0
},
issue = new
{
id = 4531,
projectId = 2,
issueKey = "TEST2-17",
keyId = 17,
issueType = new
{
id = 7,
projectId = 2,
name = "Bug",
color = "#990000",
displayOrder = 0
},
summary = "aaa",
description = "",
//// resolutions = null,
priority = new {id = 3, name = "Normal"},
status = new {id = 1, name = "Open"},
assignee = new
{
id = 2,
name = "eguchi",
roleType = 2,
//// lang = null,
mailAddress = "eguchi@nulab.example"
},
//// category = new[]{new{}},
//// versions = [],
//// milestone = [],
startDate = "2013-08-29T15:00:00Z",
dueDate = "2013-09-03T15:00:00Z",
//// estimatedHours = null,
//// actualHours = null,
//// parentIssueId = null,
createdUser = new
{
id = 1,
userId = "admin",
name = "admin",
roleType = 1,
lang = "ja",
mailAddress = "eguchi@nulab.example"
},
created = "2013-04-23T07:38:59Z",
updatedUser = new
{
id = 1,
userId = "admin",
name = "admin",
roleType = 1,
lang = "ja",
mailAddress = "eguchi@nulab.example"
},
updated = "2013-09-06T09:25:41Z",
//// customFields = [],
//// attachments = [],
//// sharedFiles = [],
//// stars = []
},
comment = new
{
id = 7007,
content = "hoge",
//// changeLog = null,
createdUser = new
{
id = 2,
userId = "eguchi",
name = "eguchi",
roleType = 2,
//// lang = null,
mailAddress = "eguchi@nulab.example"
},
created = "2013-10-31T06:58:58Z",
updated = "2013-10-31T06:58:58Z",
//// stars = [],
//// notifications = []
},
sender = new
{
id = 2,
userId = "eguchi",
name = "eguchi",
roleType = 2,
//// lang = null,
mailAddress = "eguchi@nulab.example"
},
pullRequest = new
{
stars = new[]
{
new
{
created = "2015-11-08T04:04:47Z",
presenter = new
{
mailAddress = "t.ashula@gmail.com",
//// lang": null,
roleType = 2,
name = "t.ashula",
userId = "t.ashula",
id = 60966
},
title = "[BL4N/bl4n#1] develop",
url = "https://bl4n.backlog.jp/git/BL4N/bl4n/pullRequests/1",
//// comment": null,
id = 226364
}
},
attachments = new[] {new {}},
updated = "2015-11-08T14:37:13Z",
updatedUser = new
{
mailAddress = "t.ashula@gmail.com",
//// lang": null,
roleType = 2,
name = "t.ashula",
userId = "t.ashula",
id = 60966
},
created = "2015-11-08T03:43:43Z",
createdUser = new
{
mailAddress = "t.ashula@gmail.com",
//// lang = null,
roleType = 2,
name = "t.ashula",
userId = "t.ashula",
id = 60966
},
//// "mergeAt= null,
//// "closeAt= null,
//// "branchCommit= null,
//// "baseCommit= null,
issue = new
{
stars = new[] {new {}},
sharedFiles = new[] {new {}},
attachments = new[] {new {}},
customFields = new[] {new {}},
updated = "2015-11-08T06:15:17Z",
updatedUser = new
{
mailAddress = "t.ashula+nulab@gmail.com",
//// lang = null,
roleType = 1,
name = "bl4n.admin",
userId = "bl4n.admin",
id = 60965
},
created = "2015-11-08T03:43:15Z",
createdUser = new
{
mailAddress = "t.ashula@gmail.com",
//// lang = null,
roleType = 2,
name = "t.ashula",
userId = "t.ashula",
id = 60966
},
//// parentIssueId = null,
//// actualHours = null,
//// estimatedHours = null,
//// dueDate = null,
//// startDate = null,
milestone = new[] {new {}},
versions = new[] {new {}},
category = new[] {new {displayOrder = 2147483646, name = "API", id = 61309}},
//// assignee= null,
status = new {name = "\u672a\u5bfe\u5fdc", id = 1},
priority = new {name = "\u4e2d", id = 3},
//// resolution = null,
description = "update readme.md",
summary = "update readme",
issueType = new
{
displayOrder = 1,
color = "#990000",
name = "\u30d0\u30b0",
projectId = 26476,
id = 116112
},
keyId = 113,
issueKey = "BL4N-113",
projectId = 26476,
id = 2329470
},
assignee = new
{
mailAddress = "t.ashula@gmail.com",
//// lang = null,
roleType = 2,
name = "t.ashula",
userId = "t.ashula",
id = 60966
},
status = new
{
name = "Open",
id = 1
},
branch = "develop",
@base = "master",
description = "update readme",
summary = "develop",
number = 1,
epositoryId = 9251,
projectId = 26476,
id = 2553
},
pullRequestComment = new
{
notifications = new[]
{
new
{
resourceAlreadyRead = false,
user = new
{
mailAddress = "t.ashula+nulab@gmail.com",
//// lang = null,
roleType = 1,
name = "bl4n.admin",
userId = "bl4n.admin",
id = 60965
},
reason = 11,
alreadyRead = false,
id = 7756700
},
new
{
resourceAlreadyRead = true,
user = new
{
mailAddress = "t.ashula@gmail.com",
//// lang = null,
roleType = 2,
name = "t.ashula",
userId = "t.ashula",
id = 60966
},
reason = 11,
alreadyRead = true,
id = 7756701
}
},
stars = new[] {new {}},
updated = "2015-11-08T16:08:24Z",
created = "2015-11-08T16:08:24Z",
createdUser = new
{
mailAddress = "t.ashula+nulab@gmail.com",
//// lang = null,
roleType = 1,
name = "bl4n.admin",
userId = "bl4n.admin",
id = 60965
},
changeLog = new[] {new {}},
content = "comment.1124018924",
//// position = null,
//// filePath = null,
//// newBlobId = null,
//// oldBlobId = null,
id = 6694
},
created = "2013-10-31T06:58:59Z"
}
});
#endregion
#region /api/v2/notifications/count
Get["/count"] = p => Response.AsJson(new { count = 138 });
#endregion
#region POST /api/v2/notifications/markAsRead
Post["/markAsRead"] = p => Response.AsJson(new { count = 42 });
#endregion
#region POST /api/v2/notifications/:id/markAsRead
Post["/{id}/markAsRead"] = p =>
{
return HttpStatusCode.NoContent;
};
#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;
using System.Collections.Generic;
using System.Security;
using System.Runtime.Serialization;
namespace System.Collections.Generic
{
using System.Globalization;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Diagnostics.Contracts;
[Serializable]
[TypeDependencyAttribute("System.Collections.Generic.ObjectEqualityComparer`1")]
public abstract class EqualityComparer<T> : IEqualityComparer, IEqualityComparer<T>
{
static readonly EqualityComparer<T> defaultComparer = CreateComparer();
public static EqualityComparer<T> Default {
get {
Contract.Ensures(Contract.Result<EqualityComparer<T>>() != null);
return defaultComparer;
}
}
//
// Note that logic in this method is replicated in vm\compile.cpp to ensure that NGen
// saves the right instantiations
//
[System.Security.SecuritySafeCritical] // auto-generated
private static EqualityComparer<T> CreateComparer()
{
Contract.Ensures(Contract.Result<EqualityComparer<T>>() != null);
object result = null;
RuntimeType t = (RuntimeType)typeof(T);
// Specialize type byte for performance reasons
if (t == typeof(byte)) {
result = new ByteEqualityComparer();
}
// If T implements IEquatable<T> return a GenericEqualityComparer<T>
else if (typeof(IEquatable<T>).IsAssignableFrom(t))
{
result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(GenericEqualityComparer<int>), t);
}
else if (default(T) == null) // Reference type/Nullable
{
// If T is a Nullable<U> where U implements IEquatable<U> return a NullableEqualityComparer<U>
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)) {
RuntimeType u = (RuntimeType)t.GetGenericArguments()[0];
if (typeof(IEquatable<>).MakeGenericType(u).IsAssignableFrom(u)) {
result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(NullableEqualityComparer<int>), u);
}
}
}
// See the METHOD__JIT_HELPERS__UNSAFE_ENUM_CAST and METHOD__JIT_HELPERS__UNSAFE_ENUM_CAST_LONG cases in getILIntrinsicImplementation
else if (t.IsEnum) {
TypeCode underlyingTypeCode = Type.GetTypeCode(Enum.GetUnderlyingType(t));
// Depending on the enum type, we need to special case the comparers so that we avoid boxing
// Note: We have different comparers for Short and SByte because for those types we need to make sure we call GetHashCode on the actual underlying type as the
// implementation of GetHashCode is more complex than for the other types.
switch (underlyingTypeCode) {
case TypeCode.Int16: // short
result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(ShortEnumEqualityComparer<short>), t);
break;
case TypeCode.SByte:
result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(SByteEnumEqualityComparer<sbyte>), t);
break;
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Byte:
case TypeCode.UInt16: //ushort
result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(EnumEqualityComparer<int>), t);
break;
case TypeCode.Int64:
case TypeCode.UInt64:
result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(LongEnumEqualityComparer<long>), t);
break;
}
}
return result != null ?
(EqualityComparer<T>)result :
new ObjectEqualityComparer<T>(); // Fallback to ObjectEqualityComparer, which uses boxing
}
[Pure]
public abstract bool Equals(T x, T y);
[Pure]
public abstract int GetHashCode(T obj);
internal virtual int IndexOf(T[] array, T value, int startIndex, int count) {
int endIndex = startIndex + count;
for (int i = startIndex; i < endIndex; i++) {
if (Equals(array[i], value)) return i;
}
return -1;
}
internal virtual int LastIndexOf(T[] array, T value, int startIndex, int count) {
int endIndex = startIndex - count + 1;
for (int i = startIndex; i >= endIndex; i--) {
if (Equals(array[i], value)) return i;
}
return -1;
}
int IEqualityComparer.GetHashCode(object obj) {
if (obj == null) return 0;
if (obj is T) return GetHashCode((T)obj);
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArgumentForComparison);
return 0;
}
bool IEqualityComparer.Equals(object x, object y) {
if (x == y) return true;
if (x == null || y == null) return false;
if ((x is T) && (y is T)) return Equals((T)x, (T)y);
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArgumentForComparison);
return false;
}
}
// The methods in this class look identical to the inherited methods, but the calls
// to Equal bind to IEquatable<T>.Equals(T) instead of Object.Equals(Object)
[Serializable]
internal class GenericEqualityComparer<T>: EqualityComparer<T> where T: IEquatable<T>
{
[Pure]
public override bool Equals(T x, T y) {
if (x != null) {
if (y != null) return x.Equals(y);
return false;
}
if (y != null) return false;
return true;
}
[Pure]
public override int GetHashCode(T obj) {
if (obj == null) return 0;
return obj.GetHashCode();
}
internal override int IndexOf(T[] array, T value, int startIndex, int count) {
int endIndex = startIndex + count;
if (value == null) {
for (int i = startIndex; i < endIndex; i++) {
if (array[i] == null) return i;
}
}
else {
for (int i = startIndex; i < endIndex; i++) {
if (array[i] != null && array[i].Equals(value)) return i;
}
}
return -1;
}
internal override int LastIndexOf(T[] array, T value, int startIndex, int count) {
int endIndex = startIndex - count + 1;
if (value == null) {
for (int i = startIndex; i >= endIndex; i--) {
if (array[i] == null) return i;
}
}
else {
for (int i = startIndex; i >= endIndex; i--) {
if (array[i] != null && array[i].Equals(value)) return i;
}
}
return -1;
}
// Equals method for the comparer itself.
public override bool Equals(Object obj){
GenericEqualityComparer<T> comparer = obj as GenericEqualityComparer<T>;
return comparer != null;
}
public override int GetHashCode() {
return this.GetType().Name.GetHashCode();
}
}
[Serializable]
internal class NullableEqualityComparer<T> : EqualityComparer<Nullable<T>> where T : struct, IEquatable<T>
{
[Pure]
public override bool Equals(Nullable<T> x, Nullable<T> y) {
if (x.HasValue) {
if (y.HasValue) return x.value.Equals(y.value);
return false;
}
if (y.HasValue) return false;
return true;
}
[Pure]
public override int GetHashCode(Nullable<T> obj) {
return obj.GetHashCode();
}
internal override int IndexOf(Nullable<T>[] array, Nullable<T> value, int startIndex, int count) {
int endIndex = startIndex + count;
if (!value.HasValue) {
for (int i = startIndex; i < endIndex; i++) {
if (!array[i].HasValue) return i;
}
}
else {
for (int i = startIndex; i < endIndex; i++) {
if (array[i].HasValue && array[i].value.Equals(value.value)) return i;
}
}
return -1;
}
internal override int LastIndexOf(Nullable<T>[] array, Nullable<T> value, int startIndex, int count) {
int endIndex = startIndex - count + 1;
if (!value.HasValue) {
for (int i = startIndex; i >= endIndex; i--) {
if (!array[i].HasValue) return i;
}
}
else {
for (int i = startIndex; i >= endIndex; i--) {
if (array[i].HasValue && array[i].value.Equals(value.value)) return i;
}
}
return -1;
}
// Equals method for the comparer itself.
public override bool Equals(Object obj){
NullableEqualityComparer<T> comparer = obj as NullableEqualityComparer<T>;
return comparer != null;
}
public override int GetHashCode() {
return this.GetType().Name.GetHashCode();
}
}
[Serializable]
internal class ObjectEqualityComparer<T>: EqualityComparer<T>
{
[Pure]
public override bool Equals(T x, T y) {
if (x != null) {
if (y != null) return x.Equals(y);
return false;
}
if (y != null) return false;
return true;
}
[Pure]
public override int GetHashCode(T obj) {
if (obj == null) return 0;
return obj.GetHashCode();
}
internal override int IndexOf(T[] array, T value, int startIndex, int count) {
int endIndex = startIndex + count;
if (value == null) {
for (int i = startIndex; i < endIndex; i++) {
if (array[i] == null) return i;
}
}
else {
for (int i = startIndex; i < endIndex; i++) {
if (array[i] != null && array[i].Equals(value)) return i;
}
}
return -1;
}
internal override int LastIndexOf(T[] array, T value, int startIndex, int count) {
int endIndex = startIndex - count + 1;
if (value == null) {
for (int i = startIndex; i >= endIndex; i--) {
if (array[i] == null) return i;
}
}
else {
for (int i = startIndex; i >= endIndex; i--) {
if (array[i] != null && array[i].Equals(value)) return i;
}
}
return -1;
}
// Equals method for the comparer itself.
public override bool Equals(Object obj){
ObjectEqualityComparer<T> comparer = obj as ObjectEqualityComparer<T>;
return comparer != null;
}
public override int GetHashCode() {
return this.GetType().Name.GetHashCode();
}
}
#if FEATURE_CORECLR
// NonRandomizedStringEqualityComparer is the comparer used by default with the Dictionary<string,...>
// As the randomized string hashing is turned on by default on coreclr, we need to keep the performance not affected
// as much as possible in the main stream scenarios like Dictionary<string,>
// We use NonRandomizedStringEqualityComparer as default comparer as it doesnt use the randomized string hashing which
// keep the perofrmance not affected till we hit collision threshold and then we switch to the comparer which is using
// randomized string hashing GenericEqualityComparer<string>
internal class NonRandomizedStringEqualityComparer : GenericEqualityComparer<string> {
static IEqualityComparer<string> s_nonRandomizedComparer;
internal static new IEqualityComparer<string> Default {
get {
if (s_nonRandomizedComparer == null) {
s_nonRandomizedComparer = new NonRandomizedStringEqualityComparer();
}
return s_nonRandomizedComparer;
}
}
[Pure]
public override int GetHashCode(string obj) {
if (obj == null) return 0;
return obj.GetLegacyNonRandomizedHashCode();
}
}
#endif // FEATURE_CORECLR
// Performance of IndexOf on byte array is very important for some scenarios.
// We will call the C runtime function memchr, which is optimized.
[Serializable]
internal class ByteEqualityComparer: EqualityComparer<byte>
{
[Pure]
public override bool Equals(byte x, byte y) {
return x == y;
}
[Pure]
public override int GetHashCode(byte b) {
return b.GetHashCode();
}
[System.Security.SecuritySafeCritical] // auto-generated
internal unsafe override int IndexOf(byte[] array, byte value, int startIndex, int count) {
if (array==null)
throw new ArgumentNullException("array");
if (startIndex < 0)
throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Count"));
if (count > array.Length - startIndex)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
if (count == 0) return -1;
fixed (byte* pbytes = array) {
return Buffer.IndexOfByte(pbytes, value, startIndex, count);
}
}
internal override int LastIndexOf(byte[] array, byte value, int startIndex, int count) {
int endIndex = startIndex - count + 1;
for (int i = startIndex; i >= endIndex; i--) {
if (array[i] == value) return i;
}
return -1;
}
// Equals method for the comparer itself.
public override bool Equals(Object obj){
ByteEqualityComparer comparer = obj as ByteEqualityComparer;
return comparer != null;
}
public override int GetHashCode() {
return this.GetType().Name.GetHashCode();
}
}
[Serializable]
internal class EnumEqualityComparer<T> : EqualityComparer<T>, ISerializable where T : struct
{
[Pure]
public override bool Equals(T x, T y) {
int x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCast(x);
int y_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCast(y);
return x_final == y_final;
}
[Pure]
public override int GetHashCode(T obj) {
int x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCast(obj);
return x_final.GetHashCode();
}
public EnumEqualityComparer() { }
// This is used by the serialization engine.
protected EnumEqualityComparer(SerializationInfo information, StreamingContext context) { }
[SecurityCritical]
public void GetObjectData(SerializationInfo info, StreamingContext context) {
// For back-compat we need to serialize the comparers for enums with underlying types other than int as ObjectEqualityComparer
if (Type.GetTypeCode(Enum.GetUnderlyingType(typeof(T))) != TypeCode.Int32) {
info.SetType(typeof(ObjectEqualityComparer<T>));
}
}
// Equals method for the comparer itself.
public override bool Equals(Object obj){
EnumEqualityComparer<T> comparer = obj as EnumEqualityComparer<T>;
return comparer != null;
}
public override int GetHashCode() {
return this.GetType().Name.GetHashCode();
}
}
[Serializable]
internal sealed class SByteEnumEqualityComparer<T> : EnumEqualityComparer<T>, ISerializable where T : struct
{
public SByteEnumEqualityComparer() { }
// This is used by the serialization engine.
public SByteEnumEqualityComparer(SerializationInfo information, StreamingContext context) { }
[Pure]
public override int GetHashCode(T obj) {
int x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCast(obj);
return ((sbyte)x_final).GetHashCode();
}
}
[Serializable]
internal sealed class ShortEnumEqualityComparer<T> : EnumEqualityComparer<T>, ISerializable where T : struct
{
public ShortEnumEqualityComparer() { }
// This is used by the serialization engine.
public ShortEnumEqualityComparer(SerializationInfo information, StreamingContext context) { }
[Pure]
public override int GetHashCode(T obj) {
int x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCast(obj);
return ((short)x_final).GetHashCode();
}
}
[Serializable]
internal sealed class LongEnumEqualityComparer<T> : EqualityComparer<T>, ISerializable where T : struct
{
[Pure]
public override bool Equals(T x, T y) {
long x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCastLong(x);
long y_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCastLong(y);
return x_final == y_final;
}
[Pure]
public override int GetHashCode(T obj) {
long x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCastLong(obj);
return x_final.GetHashCode();
}
// Equals method for the comparer itself.
public override bool Equals(Object obj){
LongEnumEqualityComparer<T> comparer = obj as LongEnumEqualityComparer<T>;
return comparer != null;
}
public override int GetHashCode() {
return this.GetType().Name.GetHashCode();
}
public LongEnumEqualityComparer() { }
// This is used by the serialization engine.
public LongEnumEqualityComparer(SerializationInfo information, StreamingContext context) { }
[SecurityCritical]
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
// The LongEnumEqualityComparer does not exist on 4.0 so we need to serialize this comparer as ObjectEqualityComparer
// to allow for roundtrip between 4.0 and 4.5.
info.SetType(typeof(ObjectEqualityComparer<T>));
}
}
#if FEATURE_RANDOMIZED_STRING_HASHING
// This type is not serializeable by design. It does not exist in previous versions and will be removed
// Once we move the framework to using secure hashing by default.
internal sealed class RandomizedStringEqualityComparer : IEqualityComparer<String>, IEqualityComparer, IWellKnownStringEqualityComparer
{
private long _entropy;
public RandomizedStringEqualityComparer() {
_entropy = HashHelpers.GetEntropy();
}
public new bool Equals(object x, object y) {
if (x == y) return true;
if (x == null || y == null) return false;
if ((x is string) && (y is string)) return Equals((string)x, (string)y);
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArgumentForComparison);
return false;
}
[Pure]
public bool Equals(string x, string y) {
if (x != null) {
if (y != null) return x.Equals(y);
return false;
}
if (y != null) return false;
return true;
}
[Pure]
[SecuritySafeCritical]
public int GetHashCode(String obj) {
if(obj == null) return 0;
return String.InternalMarvin32HashString(obj, obj.Length, _entropy);
}
[Pure]
[SecuritySafeCritical]
public int GetHashCode(Object obj) {
if(obj == null) return 0;
string sObj = obj as string;
if(sObj != null) return String.InternalMarvin32HashString(sObj, sObj.Length, _entropy);
return obj.GetHashCode();
}
// Equals method for the comparer itself.
public override bool Equals(Object obj) {
RandomizedStringEqualityComparer comparer = obj as RandomizedStringEqualityComparer;
return (comparer != null) && (this._entropy == comparer._entropy);
}
public override int GetHashCode() {
return (this.GetType().Name.GetHashCode() ^ ((int) (_entropy & 0x7FFFFFFF)));
}
IEqualityComparer IWellKnownStringEqualityComparer.GetRandomizedEqualityComparer() {
return new RandomizedStringEqualityComparer();
}
// We want to serialize the old comparer.
IEqualityComparer IWellKnownStringEqualityComparer.GetEqualityComparerForSerialization() {
return EqualityComparer<string>.Default;
}
}
// This type is not serializeable by design. It does not exist in previous versions and will be removed
// Once we move the framework to using secure hashing by default.
internal sealed class RandomizedObjectEqualityComparer : IEqualityComparer, IWellKnownStringEqualityComparer
{
private long _entropy;
public RandomizedObjectEqualityComparer() {
_entropy = HashHelpers.GetEntropy();
}
[Pure]
public new bool Equals(Object x, Object y) {
if (x != null) {
if (y != null) return x.Equals(y);
return false;
}
if (y != null) return false;
return true;
}
[Pure]
[SecuritySafeCritical]
public int GetHashCode(Object obj) {
if(obj == null) return 0;
string sObj = obj as string;
if(sObj != null) return String.InternalMarvin32HashString(sObj, sObj.Length, _entropy);
return obj.GetHashCode();
}
// Equals method for the comparer itself.
public override bool Equals(Object obj){
RandomizedObjectEqualityComparer comparer = obj as RandomizedObjectEqualityComparer;
return (comparer != null) && (this._entropy == comparer._entropy);
}
public override int GetHashCode() {
return (this.GetType().Name.GetHashCode() ^ ((int) (_entropy & 0x7FFFFFFF)));
}
IEqualityComparer IWellKnownStringEqualityComparer.GetRandomizedEqualityComparer() {
return new RandomizedObjectEqualityComparer();
}
// We want to serialize the old comparer, which in this case was null.
IEqualityComparer IWellKnownStringEqualityComparer.GetEqualityComparerForSerialization() {
return null;
}
}
#endif
}
| |
using Cocos2D;
namespace tests.FontTest
{
public class SystemFontTestScene : TestScene
{
private static int fontIdx;
private static readonly string[] fontList =
{
#if IOS || IPHONE || MACOS
"Chalkboard SE",
"Chalkduster",
"Noteworthy",
"Marker Felt",
"Papyrus",
"American Typewriter",
"Arial",
"fonts/A Damn Mess.ttf",
"fonts/Abberancy.ttf",
"fonts/Abduction.ttf",
"fonts/American Typewriter.ttf",
"fonts/Courier New.ttf",
"fonts/Marker Felt.ttf",
"fonts/Paint Boy.ttf",
"fonts/Schwarzwald Regular.ttf",
"fonts/Scissor Cuts.ttf",
"fonts/tahoma.ttf",
"fonts/Thonburi.ttf",
"fonts/ThonburiBold.ttf"
#endif
#if WINDOWS || WINDOWSGL
"Comic Sans MS",
"Felt",
"MoolBoran",
"Courier New",
"Georgia",
"Symbol",
"Wingdings",
"Arial",
"fonts/A Damn Mess.ttf",
"fonts/Abberancy.ttf",
"fonts/Abduction.ttf",
"fonts/American Typewriter.ttf",
"fonts/arial.ttf",
"fonts/Courier New.ttf",
"fonts/Marker Felt.ttf",
"fonts/Paint Boy.ttf",
"fonts/Schwarzwald Regular.ttf",
"fonts/Scissor Cuts.ttf",
"fonts/tahoma.ttf",
"fonts/Thonburi.ttf",
"fonts/ThonburiBold.ttf"
#endif
#if ANDROID
"Arial",
"Courier New",
"Georgia",
"fonts/A Damn Mess.ttf",
"fonts/Abberancy.ttf",
"fonts/Abduction.ttf",
"fonts/American Typewriter.ttf",
"fonts/arial.ttf",
"fonts/Courier New.ttf",
"fonts/Marker Felt.ttf",
"fonts/Paint Boy.ttf",
"fonts/Schwarzwald Regular.ttf",
"fonts/Scissor Cuts.ttf",
"fonts/tahoma.ttf",
"fonts/Thonburi.ttf",
"fonts/ThonburiBold.ttf"
#endif
};
public static int vAlignIdx = 0;
public static CCVerticalTextAlignment[] verticalAlignment =
{
CCVerticalTextAlignment.Top,
CCVerticalTextAlignment.Center,
CCVerticalTextAlignment.Bottom
};
public override void runThisTest()
{
CCLayer pLayer = new SystemFontTest();
AddChild(pLayer);
CCDirector.SharedDirector.ReplaceScene(this);
}
protected override void NextTestCase()
{
nextAction();
}
protected override void PreviousTestCase()
{
backAction();
}
protected override void RestTestCase()
{
restartAction();
}
public static string nextAction()
{
fontIdx++;
if (fontIdx >= fontList.Length)
{
fontIdx = 0;
vAlignIdx = (vAlignIdx + 1) % verticalAlignment.Length;
}
return fontList[fontIdx];
}
public static string backAction()
{
fontIdx--;
if (fontIdx < 0)
{
fontIdx = fontList.Length - 1;
vAlignIdx--;
if (vAlignIdx < 0)
vAlignIdx = verticalAlignment.Length - 1;
}
return fontList[fontIdx];
}
public static string restartAction()
{
return fontList[fontIdx];
}
}
public class SystemFontTest : CCLayer
{
private const int kTagLabel1 = 1;
private const int kTagLabel2 = 2;
private const int kTagLabel3 = 3;
private const int kTagLabel4 = 4;
public SystemFontTest()
{
CCSize s = CCDirector.SharedDirector.WinSize;
CCMenuItemImage item1 = new CCMenuItemImage(TestResource.s_pPathB1, TestResource.s_pPathB2, backCallback);
CCMenuItemImage item2 = new CCMenuItemImage(TestResource.s_pPathR1, TestResource.s_pPathR2, restartCallback);
CCMenuItemImage item3 = new CCMenuItemImage(TestResource.s_pPathF1, TestResource.s_pPathF2, nextCallback);
CCMenu menu = new CCMenu(item1, item2, item3);
menu.Position = CCPoint.Zero;
item1.Position = new CCPoint(s.Width / 2 - item2.ContentSize.Width * 2, item2.ContentSize.Height / 2);
item2.Position = new CCPoint(s.Width / 2, item2.ContentSize.Height / 2);
item3.Position = new CCPoint(s.Width / 2 + item2.ContentSize.Width * 2, item2.ContentSize.Height / 2);
AddChild(menu, 1);
var blockSize = new CCSize(s.Width / 3, 200);
CCLayerColor leftColor = new CCLayerColor(new CCColor4B(100, 100, 100, 255), blockSize.Width,
blockSize.Height);
CCLayerColor centerColor = new CCLayerColor(new CCColor4B(200, 100, 100, 255), blockSize.Width,
blockSize.Height);
CCLayerColor rightColor = new CCLayerColor(new CCColor4B(100, 100, 200, 255), blockSize.Width,
blockSize.Height);
leftColor.IgnoreAnchorPointForPosition = false;
centerColor.IgnoreAnchorPointForPosition = false;
rightColor.IgnoreAnchorPointForPosition = false;
leftColor.AnchorPoint = new CCPoint(0, 0.5f);
centerColor.AnchorPoint = new CCPoint(0, 0.5f);
rightColor.AnchorPoint = new CCPoint(0, 0.5f);
leftColor.Position = new CCPoint(0, s.Height / 2);
;
centerColor.Position = new CCPoint(blockSize.Width, s.Height / 2);
rightColor.Position = new CCPoint(blockSize.Width * 2, s.Height / 2);
AddChild(leftColor, -1);
AddChild(rightColor, -1);
AddChild(centerColor, -1);
showFont(SystemFontTestScene.restartAction());
}
public void showFont(string pFont)
{
CCSize s = CCDirector.SharedDirector.WinSize;
var blockSize = new CCSize(s.Width / 3, 200);
float fontSize = 26;
RemoveChildByTag(kTagLabel1, true);
RemoveChildByTag(kTagLabel2, true);
RemoveChildByTag(kTagLabel3, true);
RemoveChildByTag(kTagLabel4, true);
var top = new CCLabel(pFont,"Arial", 24);
var left = new CCLabel("alignment left", pFont, fontSize,
blockSize, CCTextAlignment.Left,
SystemFontTestScene.verticalAlignment[SystemFontTestScene.vAlignIdx]);
var center = new CCLabel("alignment center", pFont, fontSize,
blockSize, CCTextAlignment.Center,
SystemFontTestScene.verticalAlignment[SystemFontTestScene.vAlignIdx]);
var right = new CCLabel("alignment right", pFont, fontSize,
blockSize, CCTextAlignment.Right,
SystemFontTestScene.verticalAlignment[SystemFontTestScene.vAlignIdx]);
top.AnchorPoint = new CCPoint(0.5f, 1);
left.AnchorPoint = new CCPoint(0, 0.5f);
center.AnchorPoint = new CCPoint(0, 0.5f);
right.AnchorPoint = new CCPoint(0, 0.5f);
top.Position = new CCPoint(s.Width / 2, s.Height - 20);
left.Position = new CCPoint(0, s.Height / 2);
center.Position = new CCPoint(blockSize.Width, s.Height / 2);
right.Position = new CCPoint(blockSize.Width * 2, s.Height / 2);
AddChild(left, 0, kTagLabel1);
AddChild(right, 0, kTagLabel2);
AddChild(center, 0, kTagLabel3);
AddChild(top, 0, kTagLabel4);
}
public void restartCallback(object pSender)
{
showFont(SystemFontTestScene.restartAction());
}
public void nextCallback(object pSender)
{
showFont(SystemFontTestScene.nextAction());
}
public void backCallback(object pSender)
{
showFont(SystemFontTestScene.backAction());
}
public virtual string title()
{
return "System Font test";
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagr = Google.Api.Gax.ResourceNames;
using gcspv = Google.Cloud.Security.PrivateCA.V1Beta1;
namespace Google.Cloud.Security.PrivateCA.V1Beta1
{
public partial class CreateCertificateRequest
{
/// <summary>
/// <see cref="CertificateAuthorityName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public CertificateAuthorityName ParentAsCertificateAuthorityName
{
get => string.IsNullOrEmpty(Parent) ? null : CertificateAuthorityName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetCertificateRequest
{
/// <summary>
/// <see cref="gcspv::CertificateName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcspv::CertificateName CertificateName
{
get => string.IsNullOrEmpty(Name) ? null : gcspv::CertificateName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ListCertificatesRequest
{
/// <summary>
/// <see cref="CertificateAuthorityName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public CertificateAuthorityName ParentAsCertificateAuthorityName
{
get => string.IsNullOrEmpty(Parent) ? null : CertificateAuthorityName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class RevokeCertificateRequest
{
/// <summary>
/// <see cref="gcspv::CertificateName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcspv::CertificateName CertificateName
{
get => string.IsNullOrEmpty(Name) ? null : gcspv::CertificateName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ActivateCertificateAuthorityRequest
{
/// <summary>
/// <see cref="gcspv::CertificateAuthorityName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcspv::CertificateAuthorityName CertificateAuthorityName
{
get => string.IsNullOrEmpty(Name) ? null : gcspv::CertificateAuthorityName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class CreateCertificateAuthorityRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class DisableCertificateAuthorityRequest
{
/// <summary>
/// <see cref="gcspv::CertificateAuthorityName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcspv::CertificateAuthorityName CertificateAuthorityName
{
get => string.IsNullOrEmpty(Name) ? null : gcspv::CertificateAuthorityName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class EnableCertificateAuthorityRequest
{
/// <summary>
/// <see cref="gcspv::CertificateAuthorityName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcspv::CertificateAuthorityName CertificateAuthorityName
{
get => string.IsNullOrEmpty(Name) ? null : gcspv::CertificateAuthorityName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class FetchCertificateAuthorityCsrRequest
{
/// <summary>
/// <see cref="gcspv::CertificateAuthorityName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcspv::CertificateAuthorityName CertificateAuthorityName
{
get => string.IsNullOrEmpty(Name) ? null : gcspv::CertificateAuthorityName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class GetCertificateAuthorityRequest
{
/// <summary>
/// <see cref="gcspv::CertificateAuthorityName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcspv::CertificateAuthorityName CertificateAuthorityName
{
get => string.IsNullOrEmpty(Name) ? null : gcspv::CertificateAuthorityName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ListCertificateAuthoritiesRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class RestoreCertificateAuthorityRequest
{
/// <summary>
/// <see cref="gcspv::CertificateAuthorityName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcspv::CertificateAuthorityName CertificateAuthorityName
{
get => string.IsNullOrEmpty(Name) ? null : gcspv::CertificateAuthorityName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ScheduleDeleteCertificateAuthorityRequest
{
/// <summary>
/// <see cref="gcspv::CertificateAuthorityName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcspv::CertificateAuthorityName CertificateAuthorityName
{
get => string.IsNullOrEmpty(Name) ? null : gcspv::CertificateAuthorityName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class GetCertificateRevocationListRequest
{
/// <summary>
/// <see cref="gcspv::CertificateRevocationListName"/>-typed view over the <see cref="Name"/> resource name
/// property.
/// </summary>
public gcspv::CertificateRevocationListName CertificateRevocationListName
{
get => string.IsNullOrEmpty(Name) ? null : gcspv::CertificateRevocationListName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ListCertificateRevocationListsRequest
{
/// <summary>
/// <see cref="CertificateAuthorityName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public CertificateAuthorityName ParentAsCertificateAuthorityName
{
get => string.IsNullOrEmpty(Parent) ? null : CertificateAuthorityName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetReusableConfigRequest
{
/// <summary>
/// <see cref="gcspv::ReusableConfigName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcspv::ReusableConfigName ReusableConfigName
{
get => string.IsNullOrEmpty(Name) ? null : gcspv::ReusableConfigName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ListReusableConfigsRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
}
| |
#if UNITY_ANDROID
#pragma warning disable 0642 // Possible mistaken empty statement
namespace GooglePlayGames.Android
{
using System;
using System.Collections.Generic;
using GooglePlayGames.BasicApi;
using GooglePlayGames.BasicApi.Nearby;
using GooglePlayGames.OurUtils;
using UnityEngine;
public class AndroidNearbyConnectionClient : INearbyConnectionClient
{
private volatile AndroidJavaObject mClient;
private readonly static long NearbyClientId = 0L;
private readonly static int ApplicationInfoFlags = 0x00000080;
private readonly static string ServiceId = ReadServiceId();
protected IMessageListener mAdvertisingMessageListener;
public AndroidNearbyConnectionClient()
{
PlayGamesHelperObject.CreateObject();
NearbyHelperObject.CreateObject(this);
using (var nearbyClass = new AndroidJavaClass("com.google.android.gms.nearby.Nearby"))
{
mClient = nearbyClass.CallStatic<AndroidJavaObject>("getConnectionsClient",
AndroidHelperFragment.GetActivity());
}
}
public int MaxUnreliableMessagePayloadLength()
{
return NearbyConnectionConfiguration.MaxUnreliableMessagePayloadLength;
}
public int MaxReliableMessagePayloadLength()
{
return NearbyConnectionConfiguration.MaxReliableMessagePayloadLength;
}
public void SendReliable(List<string> recipientEndpointIds, byte[] payload)
{
InternalSend(recipientEndpointIds, payload);
}
public void SendUnreliable(List<string> recipientEndpointIds, byte[] payload)
{
InternalSend(recipientEndpointIds, payload);
}
private void InternalSend(List<string> recipientEndpointIds, byte[] payload)
{
Misc.CheckNotNull(recipientEndpointIds);
Misc.CheckNotNull(payload);
using (var payloadClass = new AndroidJavaClass("com.google.android.gms.nearby.connection.Payload"))
using (var payloadObject = payloadClass.CallStatic<AndroidJavaObject>("fromBytes", payload))
using (var task = mClient.Call<AndroidJavaObject>("sendPayload",
AndroidJavaConverter.ToJavaStringList(recipientEndpointIds),
payloadObject))
;
}
public void StartAdvertising(string name, List<string> appIdentifiers,
TimeSpan? advertisingDuration, Action<AdvertisingResult> resultCallback,
Action<ConnectionRequest> connectionRequestCallback)
{
Misc.CheckNotNull(resultCallback, "resultCallback");
Misc.CheckNotNull(connectionRequestCallback, "connectionRequestCallback");
if (advertisingDuration.HasValue && advertisingDuration.Value.Ticks < 0)
{
throw new InvalidOperationException("advertisingDuration must be positive");
}
connectionRequestCallback = ToOnGameThread(connectionRequestCallback);
resultCallback = ToOnGameThread(resultCallback);
AdvertisingConnectionLifecycleCallbackProxy callbackProxy =
new AdvertisingConnectionLifecycleCallbackProxy(resultCallback, connectionRequestCallback, this);
using (var connectionLifecycleCallback =
new AndroidJavaObject("com.google.games.bridge.ConnectionLifecycleCallbackProxy", callbackProxy))
using (var advertisingOptions = CreateAdvertisingOptions())
using (var task = mClient.Call<AndroidJavaObject>("startAdvertising", name, GetServiceId(),
connectionLifecycleCallback, advertisingOptions))
{
AndroidTaskUtils.AddOnSuccessListener<AndroidJavaObject>(
task,
v => NearbyHelperObject.StartAdvertisingTimer(advertisingDuration)
);
}
}
private AndroidJavaObject CreateAdvertisingOptions()
{
using (var strategy = new AndroidJavaClass("com.google.android.gms.nearby.connection.Strategy")
.GetStatic<AndroidJavaObject>("P2P_CLUSTER"))
using (var builder =
new AndroidJavaObject("com.google.android.gms.nearby.connection.AdvertisingOptions$Builder"))
using (builder.Call<AndroidJavaObject>("setStrategy", strategy))
{
return builder.Call<AndroidJavaObject>("build");
}
}
private class AdvertisingConnectionLifecycleCallbackProxy : AndroidJavaProxy
{
private Action<AdvertisingResult> mResultCallback;
private Action<ConnectionRequest> mConnectionRequestCallback;
private AndroidNearbyConnectionClient mClient;
private string mLocalEndpointName;
public AdvertisingConnectionLifecycleCallbackProxy(Action<AdvertisingResult> resultCallback,
Action<ConnectionRequest> connectionRequestCallback, AndroidNearbyConnectionClient client) : base(
"com/google/games/bridge/ConnectionLifecycleCallbackProxy$Callback")
{
mResultCallback = resultCallback;
mConnectionRequestCallback = connectionRequestCallback;
mClient = client;
}
public void onConnectionInitiated(string endpointId, AndroidJavaObject connectionInfo)
{
mLocalEndpointName = connectionInfo.Call<string>("getEndpointName");
mConnectionRequestCallback(new ConnectionRequest(endpointId, mLocalEndpointName, mClient.GetServiceId(),
new byte[0]));
}
public void onConnectionResult(string endpointId, AndroidJavaObject connectionResolution)
{
int statusCode;
using (var status = connectionResolution.Call<AndroidJavaObject>("getStatus"))
{
statusCode = status.Call<int>("getStatusCode");
}
if (statusCode == 0) // STATUS_OK
{
mResultCallback(new AdvertisingResult(ResponseStatus.Success, mLocalEndpointName));
return;
}
if (statusCode == 8001) // STATUS_ALREADY_ADVERTISING
{
mResultCallback(new AdvertisingResult(ResponseStatus.NotAuthorized, mLocalEndpointName));
return;
}
mResultCallback(new AdvertisingResult(ResponseStatus.InternalError, mLocalEndpointName));
}
public void onDisconnected(string endpointId)
{
if (mClient.mAdvertisingMessageListener != null)
{
mClient.mAdvertisingMessageListener.OnRemoteEndpointDisconnected(endpointId);
}
}
}
public void StopAdvertising()
{
mClient.Call("stopAdvertising");
mAdvertisingMessageListener = null;
}
public void SendConnectionRequest(string name, string remoteEndpointId, byte[] payload,
Action<ConnectionResponse> responseCallback, IMessageListener listener)
{
Misc.CheckNotNull(listener, "listener");
var listenerOnGameThread = new OnGameThreadMessageListener(listener);
DiscoveringConnectionLifecycleCallback cb =
new DiscoveringConnectionLifecycleCallback(responseCallback, listenerOnGameThread, mClient);
using (var connectionLifecycleCallback =
new AndroidJavaObject("com.google.games.bridge.ConnectionLifecycleCallbackProxy", cb))
using (mClient.Call<AndroidJavaObject>("requestConnection", name, remoteEndpointId,
connectionLifecycleCallback))
;
}
public void AcceptConnectionRequest(string remoteEndpointId, byte[] payload, IMessageListener listener)
{
Misc.CheckNotNull(listener, "listener");
mAdvertisingMessageListener = new OnGameThreadMessageListener(listener);
using (var payloadCallback = new AndroidJavaObject("com.google.games.bridge.PayloadCallbackProxy",
new PayloadCallback(listener)))
using (mClient.Call<AndroidJavaObject>("acceptConnection", remoteEndpointId, payloadCallback))
;
}
private class PayloadCallback : AndroidJavaProxy
{
private IMessageListener mListener;
public PayloadCallback(IMessageListener listener) : base(
"com/google/games/bridge/PayloadCallbackProxy$Callback")
{
mListener = listener;
}
public void onPayloadReceived(String endpointId, AndroidJavaObject payload)
{
if (payload.Call<int>("getType") != 1) // 1 for BYTES
{
return;
}
mListener.OnMessageReceived(endpointId, payload.Call<byte[]>("asBytes"), /* isReliableMessage */ true);
}
}
public void StartDiscovery(string serviceId, TimeSpan? advertisingDuration,
IDiscoveryListener listener)
{
Misc.CheckNotNull(serviceId, "serviceId");
Misc.CheckNotNull(listener, "listener");
var listenerOnGameThread = new OnGameThreadDiscoveryListener(listener);
if (advertisingDuration.HasValue && advertisingDuration.Value.Ticks < 0)
{
throw new InvalidOperationException("advertisingDuration must be positive");
}
using (var endpointDiscoveryCallback = new AndroidJavaObject(
"com.google.games.bridge.EndpointDiscoveryCallbackProxy",
new EndpointDiscoveryCallback(listenerOnGameThread)))
using (var discoveryOptions = CreateDiscoveryOptions())
using (var task = mClient.Call<AndroidJavaObject>("startDiscovery", serviceId, endpointDiscoveryCallback,
discoveryOptions))
{
AndroidTaskUtils.AddOnSuccessListener<AndroidJavaObject>(
task,
v => NearbyHelperObject.StartDiscoveryTimer(advertisingDuration)
);
}
}
private class DiscoveringConnectionLifecycleCallback : AndroidJavaProxy
{
private Action<ConnectionResponse> mResponseCallback;
private IMessageListener mListener;
private AndroidJavaObject mClient;
public DiscoveringConnectionLifecycleCallback(Action<ConnectionResponse> responseCallback,
IMessageListener listener, AndroidJavaObject client) : base(
"com/google/games/bridge/ConnectionLifecycleCallbackProxy$Callback")
{
mResponseCallback = responseCallback;
mListener = listener;
mClient = client;
}
public void onConnectionInitiated(string endpointId, AndroidJavaObject connectionInfo)
{
using (var payloadCallback = new AndroidJavaObject("com.google.games.bridge.PayloadCallbackProxy",
new PayloadCallback(mListener)))
using (mClient.Call<AndroidJavaObject>("acceptConnection", endpointId, payloadCallback))
;
}
public void onConnectionResult(string endpointId, AndroidJavaObject connectionResolution)
{
int statusCode;
using (var status = connectionResolution.Call<AndroidJavaObject>("getStatus"))
{
statusCode = status.Call<int>("getStatusCode");
}
if (statusCode == 0) // STATUS_OK
{
mResponseCallback(ConnectionResponse.Accepted(NearbyClientId, endpointId, new byte[0]));
return;
}
if (statusCode == 8002) // STATUS_ALREADY_DISCOVERING
{
mResponseCallback(ConnectionResponse.AlreadyConnected(NearbyClientId, endpointId));
return;
}
mResponseCallback(ConnectionResponse.Rejected(NearbyClientId, endpointId));
}
public void onDisconnected(string endpointId)
{
mListener.OnRemoteEndpointDisconnected(endpointId);
}
}
private AndroidJavaObject CreateDiscoveryOptions()
{
using (var strategy =
new AndroidJavaClass("com.google.android.gms.nearby.connection.Strategy").GetStatic<AndroidJavaObject>(
"P2P_CLUSTER"))
using (var builder =
new AndroidJavaObject("com.google.android.gms.nearby.connection.DiscoveryOptions$Builder"))
using (builder.Call<AndroidJavaObject>("setStrategy", strategy))
{
return builder.Call<AndroidJavaObject>("build");
}
}
private class EndpointDiscoveryCallback : AndroidJavaProxy
{
private IDiscoveryListener mListener;
public EndpointDiscoveryCallback(IDiscoveryListener listener) : base(
"com/google/games/bridge/EndpointDiscoveryCallbackProxy$Callback")
{
mListener = listener;
}
public void onEndpointFound(string endpointId, AndroidJavaObject endpointInfo)
{
mListener.OnEndpointFound(CreateEndPointDetails(endpointId, endpointInfo));
}
public void onEndpointLost(string endpointId)
{
mListener.OnEndpointLost(endpointId);
}
private EndpointDetails CreateEndPointDetails(string endpointId, AndroidJavaObject endpointInfo)
{
return new EndpointDetails(
endpointId,
endpointInfo.Call<string>("getEndpointName"),
endpointInfo.Call<string>("getServiceId")
);
}
}
private class OnGameThreadMessageListener : IMessageListener
{
private readonly IMessageListener mListener;
public OnGameThreadMessageListener(IMessageListener listener)
{
mListener = Misc.CheckNotNull(listener);
}
public void OnMessageReceived(string remoteEndpointId, byte[] data,
bool isReliableMessage)
{
PlayGamesHelperObject.RunOnGameThread(() => mListener.OnMessageReceived(
remoteEndpointId, data, isReliableMessage));
}
public void OnRemoteEndpointDisconnected(string remoteEndpointId)
{
PlayGamesHelperObject.RunOnGameThread(
() => mListener.OnRemoteEndpointDisconnected(remoteEndpointId));
}
}
private class OnGameThreadDiscoveryListener : IDiscoveryListener
{
private readonly IDiscoveryListener mListener;
public OnGameThreadDiscoveryListener(IDiscoveryListener listener)
{
mListener = listener;
}
public void OnEndpointFound(EndpointDetails discoveredEndpoint)
{
PlayGamesHelperObject.RunOnGameThread(() => mListener.OnEndpointFound(discoveredEndpoint));
}
public void OnEndpointLost(string lostEndpointId)
{
PlayGamesHelperObject.RunOnGameThread(() => mListener.OnEndpointLost(lostEndpointId));
}
}
public void StopDiscovery(string serviceId)
{
mClient.Call("stopDiscovery");
}
public void RejectConnectionRequest(string requestingEndpointId)
{
Misc.CheckNotNull(requestingEndpointId, "requestingEndpointId");
using (var task = mClient.Call<AndroidJavaObject>("rejectConnection", requestingEndpointId)) ;
}
public void DisconnectFromEndpoint(string remoteEndpointId)
{
mClient.Call("disconnectFromEndpoint", remoteEndpointId);
}
public void StopAllConnections()
{
mClient.Call("stopAllEndpoints");
mAdvertisingMessageListener = null;
}
public string GetAppBundleId()
{
using (var activity = AndroidHelperFragment.GetActivity())
{
return activity.Call<string>("getPackageName");
}
}
public string GetServiceId()
{
return ServiceId;
}
private static string ReadServiceId()
{
using (var activity = AndroidHelperFragment.GetActivity())
{
string packageName = activity.Call<string>("getPackageName");
using (var pm = activity.Call<AndroidJavaObject>("getPackageManager"))
using (var appInfo =
pm.Call<AndroidJavaObject>("getApplicationInfo", packageName, ApplicationInfoFlags))
using (var bundle = appInfo.Get<AndroidJavaObject>("metaData"))
{
string sysId = bundle.Call<string>("getString",
"com.google.android.gms.nearby.connection.SERVICE_ID");
OurUtils.Logger.d("SystemId from Manifest: " + sysId);
return sysId;
}
}
}
private static Action<T> ToOnGameThread<T>(Action<T> toConvert)
{
return (val) => PlayGamesHelperObject.RunOnGameThread(() => toConvert(val));
}
private static Action<T1, T2> ToOnGameThread<T1, T2>(Action<T1, T2> toConvert)
{
return (val1, val2) => PlayGamesHelperObject.RunOnGameThread(() => toConvert(val1, val2));
}
}
}
#endif
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using osu.Framework.Development;
using osu.Framework.Extensions.ImageExtensions;
using osu.Framework.Graphics.Batches;
using osu.Framework.Graphics.Primitives;
using osuTK.Graphics.ES30;
using osu.Framework.Statistics;
using osu.Framework.Graphics.Colour;
using osu.Framework.Graphics.OpenGL.Vertices;
using osu.Framework.Graphics.Textures;
using osu.Framework.Lists;
using osu.Framework.Platform;
using osuTK;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using RectangleF = osu.Framework.Graphics.Primitives.RectangleF;
namespace osu.Framework.Graphics.OpenGL.Textures
{
internal class TextureGLSingle : TextureGL
{
/// <summary>
/// Contains all currently-active <see cref="TextureGLSingle"/>es.
/// </summary>
private static readonly LockedWeakList<TextureGLSingle> all_textures = new LockedWeakList<TextureGLSingle>();
public const int MAX_MIPMAP_LEVELS = 3;
private static readonly Action<TexturedVertex2D> default_quad_action = new QuadBatch<TexturedVertex2D>(100, 1000).AddAction;
private readonly Queue<ITextureUpload> uploadQueue = new Queue<ITextureUpload>();
/// <summary>
/// Invoked when a new <see cref="TextureGLAtlas"/> is created.
/// </summary>
/// <remarks>
/// Invocation from the draw or update thread cannot be assumed.
/// </remarks>
public static event Action<TextureGLSingle> TextureCreated;
private int internalWidth;
private int internalHeight;
private readonly All filteringMode;
private readonly Rgba32 initialisationColour;
/// <summary>
/// The total amount of times this <see cref="TextureGLSingle"/> was bound.
/// </summary>
public ulong BindCount { get; protected set; }
// ReSharper disable once InconsistentlySynchronizedField (no need to lock here. we don't really care if the value is stale).
public override bool Loaded => textureId > 0 || uploadQueue.Count > 0;
public override RectangleI Bounds => new RectangleI(0, 0, Width, Height);
/// <summary>
/// Creates a new <see cref="TextureGLSingle"/>.
/// </summary>
/// <param name="width">The width of the texture.</param>
/// <param name="height">The height of the texture.</param>
/// <param name="manualMipmaps">Whether manual mipmaps will be uploaded to the texture. If false, the texture will compute mipmaps automatically.</param>
/// <param name="filteringMode">The filtering mode.</param>
/// <param name="wrapModeS">The texture wrap mode in horizontal direction.</param>
/// <param name="wrapModeT">The texture wrap mode in vertical direction.</param>
/// <param name="initialisationColour">The colour to initialise texture levels with (in the case of sub region initial uploads).</param>
public TextureGLSingle(int width, int height, bool manualMipmaps = false, All filteringMode = All.Linear, WrapMode wrapModeS = WrapMode.None, WrapMode wrapModeT = WrapMode.None, Rgba32 initialisationColour = default)
: base(wrapModeS, wrapModeT)
{
Width = width;
Height = height;
this.manualMipmaps = manualMipmaps;
this.filteringMode = filteringMode;
this.initialisationColour = initialisationColour;
all_textures.Add(this);
TextureCreated?.Invoke(this);
}
/// <summary>
/// Retrieves all currently-active <see cref="TextureGLSingle"/>s.
/// </summary>
public static TextureGLSingle[] GetAllTextures() => all_textures.ToArray();
#region Disposal
~TextureGLSingle()
{
Dispose(false);
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
all_textures.Remove(this);
while (tryGetNextUpload(out var upload))
upload.Dispose();
GLWrapper.ScheduleDisposal(unload);
}
/// <summary>
/// Removes texture from GL memory.
/// </summary>
private void unload()
{
int disposableId = textureId;
if (disposableId <= 0)
return;
GL.DeleteTextures(1, new[] { disposableId });
memoryLease?.Dispose();
textureId = 0;
}
#endregion
#region Memory Tracking
private List<long> levelMemoryUsage = new List<long>();
private NativeMemoryTracker.NativeMemoryLease memoryLease;
private void updateMemoryUsage(int level, long newUsage)
{
levelMemoryUsage ??= new List<long>();
while (level >= levelMemoryUsage.Count)
levelMemoryUsage.Add(0);
levelMemoryUsage[level] = newUsage;
memoryLease?.Dispose();
memoryLease = NativeMemoryTracker.AddMemory(this, getMemoryUsage());
}
private long getMemoryUsage()
{
long usage = 0;
for (int i = 0; i < levelMemoryUsage.Count; i++)
usage += levelMemoryUsage[i];
return usage;
}
#endregion
private int height;
public override TextureGL Native => this;
public override int Height
{
get => height;
set => height = value;
}
private int width;
public override int Width
{
get => width;
set => width = value;
}
private int textureId;
public override int TextureId
{
get
{
if (!Available)
throw new ObjectDisposedException(ToString(), "Can not obtain ID of a disposed texture.");
if (textureId == 0)
throw new InvalidOperationException("Can not obtain ID of a texture before uploading it.");
return textureId;
}
}
/// <summary>
/// Retrieves the size of this texture in bytes.
/// </summary>
public virtual int GetByteSize() => Width * Height * 4;
private static void rotateVector(ref Vector2 toRotate, float sin, float cos)
{
float oldX = toRotate.X;
toRotate.X = toRotate.X * cos - toRotate.Y * sin;
toRotate.Y = oldX * sin + toRotate.Y * cos;
}
public override RectangleF GetTextureRect(RectangleF? textureRect)
{
RectangleF texRect = textureRect != null
? new RectangleF(textureRect.Value.X, textureRect.Value.Y, textureRect.Value.Width, textureRect.Value.Height)
: new RectangleF(0, 0, Width, Height);
texRect.X /= width;
texRect.Y /= height;
texRect.Width /= width;
texRect.Height /= height;
return texRect;
}
public const int VERTICES_PER_TRIANGLE = 4;
internal override void DrawTriangle(Triangle vertexTriangle, ColourInfo drawColour, RectangleF? textureRect = null, Action<TexturedVertex2D> vertexAction = null,
Vector2? inflationPercentage = null, RectangleF? textureCoords = null)
{
if (!Available)
throw new ObjectDisposedException(ToString(), "Can not draw a triangle with a disposed texture.");
RectangleF texRect = GetTextureRect(textureRect);
Vector2 inflationAmount = inflationPercentage.HasValue ? new Vector2(inflationPercentage.Value.X * texRect.Width, inflationPercentage.Value.Y * texRect.Height) : Vector2.Zero;
// If clamp to edge is active, allow the texture coordinates to penetrate by half the repeated atlas margin width
if (GLWrapper.CurrentWrapModeS == WrapMode.ClampToEdge || GLWrapper.CurrentWrapModeT == WrapMode.ClampToEdge)
{
Vector2 inflationVector = Vector2.Zero;
const int mipmap_padding_requirement = (1 << MAX_MIPMAP_LEVELS) / 2;
if (GLWrapper.CurrentWrapModeS == WrapMode.ClampToEdge)
inflationVector.X = mipmap_padding_requirement / (float)width;
if (GLWrapper.CurrentWrapModeT == WrapMode.ClampToEdge)
inflationVector.Y = mipmap_padding_requirement / (float)height;
texRect = texRect.Inflate(inflationVector);
}
RectangleF coordRect = GetTextureRect(textureCoords ?? textureRect);
RectangleF inflatedCoordRect = coordRect.Inflate(inflationAmount);
vertexAction ??= default_quad_action;
// We split the triangle into two, such that we can obtain smooth edges with our
// texture coordinate trick. We might want to revert this to drawing a single
// triangle in case we ever need proper texturing, or if the additional vertices
// end up becoming an overhead (unlikely).
SRGBColour topColour = (drawColour.TopLeft + drawColour.TopRight) / 2;
SRGBColour bottomColour = (drawColour.BottomLeft + drawColour.BottomRight) / 2;
vertexAction(new TexturedVertex2D
{
Position = vertexTriangle.P0,
TexturePosition = new Vector2((inflatedCoordRect.Left + inflatedCoordRect.Right) / 2, inflatedCoordRect.Top),
TextureRect = new Vector4(texRect.Left, texRect.Top, texRect.Right, texRect.Bottom),
BlendRange = inflationAmount,
Colour = topColour.Linear,
});
vertexAction(new TexturedVertex2D
{
Position = vertexTriangle.P1,
TexturePosition = new Vector2(inflatedCoordRect.Left, inflatedCoordRect.Bottom),
TextureRect = new Vector4(texRect.Left, texRect.Top, texRect.Right, texRect.Bottom),
BlendRange = inflationAmount,
Colour = drawColour.BottomLeft.Linear,
});
vertexAction(new TexturedVertex2D
{
Position = (vertexTriangle.P1 + vertexTriangle.P2) / 2,
TexturePosition = new Vector2((inflatedCoordRect.Left + inflatedCoordRect.Right) / 2, inflatedCoordRect.Bottom),
TextureRect = new Vector4(texRect.Left, texRect.Top, texRect.Right, texRect.Bottom),
BlendRange = inflationAmount,
Colour = bottomColour.Linear,
});
vertexAction(new TexturedVertex2D
{
Position = vertexTriangle.P2,
TexturePosition = new Vector2(inflatedCoordRect.Right, inflatedCoordRect.Bottom),
TextureRect = new Vector4(texRect.Left, texRect.Top, texRect.Right, texRect.Bottom),
BlendRange = inflationAmount,
Colour = drawColour.BottomRight.Linear,
});
FrameStatistics.Add(StatisticsCounterType.Pixels, (long)vertexTriangle.Area);
}
public const int VERTICES_PER_QUAD = 4;
internal override void DrawQuad(Quad vertexQuad, ColourInfo drawColour, RectangleF? textureRect = null, Action<TexturedVertex2D> vertexAction = null, Vector2? inflationPercentage = null,
Vector2? blendRangeOverride = null, RectangleF? textureCoords = null)
{
if (!Available)
throw new ObjectDisposedException(ToString(), "Can not draw a quad with a disposed texture.");
RectangleF texRect = GetTextureRect(textureRect);
Vector2 inflationAmount = inflationPercentage.HasValue ? new Vector2(inflationPercentage.Value.X * texRect.Width, inflationPercentage.Value.Y * texRect.Height) : Vector2.Zero;
// If clamp to edge is active, allow the texture coordinates to penetrate by half the repeated atlas margin width
if (GLWrapper.CurrentWrapModeS == WrapMode.ClampToEdge || GLWrapper.CurrentWrapModeT == WrapMode.ClampToEdge)
{
Vector2 inflationVector = Vector2.Zero;
const int mipmap_padding_requirement = (1 << MAX_MIPMAP_LEVELS) / 2;
if (GLWrapper.CurrentWrapModeS == WrapMode.ClampToEdge)
inflationVector.X = mipmap_padding_requirement / (float)width;
if (GLWrapper.CurrentWrapModeT == WrapMode.ClampToEdge)
inflationVector.Y = mipmap_padding_requirement / (float)height;
texRect = texRect.Inflate(inflationVector);
}
RectangleF coordRect = GetTextureRect(textureCoords ?? textureRect);
RectangleF inflatedCoordRect = coordRect.Inflate(inflationAmount);
Vector2 blendRange = blendRangeOverride ?? inflationAmount;
vertexAction ??= default_quad_action;
vertexAction(new TexturedVertex2D
{
Position = vertexQuad.BottomLeft,
TexturePosition = new Vector2(inflatedCoordRect.Left, inflatedCoordRect.Bottom),
TextureRect = new Vector4(texRect.Left, texRect.Top, texRect.Right, texRect.Bottom),
BlendRange = blendRange,
Colour = drawColour.BottomLeft.Linear,
});
vertexAction(new TexturedVertex2D
{
Position = vertexQuad.BottomRight,
TexturePosition = new Vector2(inflatedCoordRect.Right, inflatedCoordRect.Bottom),
TextureRect = new Vector4(texRect.Left, texRect.Top, texRect.Right, texRect.Bottom),
BlendRange = blendRange,
Colour = drawColour.BottomRight.Linear,
});
vertexAction(new TexturedVertex2D
{
Position = vertexQuad.TopRight,
TexturePosition = new Vector2(inflatedCoordRect.Right, inflatedCoordRect.Top),
TextureRect = new Vector4(texRect.Left, texRect.Top, texRect.Right, texRect.Bottom),
BlendRange = blendRange,
Colour = drawColour.TopRight.Linear,
});
vertexAction(new TexturedVertex2D
{
Position = vertexQuad.TopLeft,
TexturePosition = new Vector2(inflatedCoordRect.Left, inflatedCoordRect.Top),
TextureRect = new Vector4(texRect.Left, texRect.Top, texRect.Right, texRect.Bottom),
BlendRange = blendRange,
Colour = drawColour.TopLeft.Linear,
});
FrameStatistics.Add(StatisticsCounterType.Pixels, (long)vertexQuad.Area);
}
internal override void SetData(ITextureUpload upload, WrapMode wrapModeS, WrapMode wrapModeT, Opacity? uploadOpacity)
{
if (!Available)
throw new ObjectDisposedException(ToString(), "Can not set data of a disposed texture.");
if (upload.Bounds.IsEmpty && upload.Data.Length > 0)
{
upload.Bounds = Bounds;
if (width * height > upload.Data.Length)
throw new InvalidOperationException($"Size of texture upload ({width}x{height}) does not contain enough data ({upload.Data.Length} < {width * height})");
}
UpdateOpacity(upload, ref uploadOpacity);
lock (uploadQueue)
{
bool requireUpload = uploadQueue.Count == 0;
uploadQueue.Enqueue(upload);
if (requireUpload && !BypassTextureUploadQueueing)
GLWrapper.EnqueueTextureUpload(this);
}
}
internal override bool Bind(TextureUnit unit, WrapMode wrapModeS, WrapMode wrapModeT)
{
if (!Available)
throw new ObjectDisposedException(ToString(), "Can not bind a disposed texture.");
Upload();
if (textureId <= 0)
return false;
if (GLWrapper.BindTexture(this, unit, wrapModeS, wrapModeT))
BindCount++;
return true;
}
private bool manualMipmaps;
internal override unsafe bool Upload()
{
if (!Available)
return false;
// We should never run raw OGL calls on another thread than the main thread due to race conditions.
ThreadSafety.EnsureDrawThread();
bool didUpload = false;
while (tryGetNextUpload(out ITextureUpload upload))
{
using (upload)
{
fixed (Rgba32* ptr = upload.Data)
DoUpload(upload, (IntPtr)ptr);
didUpload = true;
}
}
if (didUpload && !manualMipmaps)
{
GL.Hint(HintTarget.GenerateMipmapHint, HintMode.Nicest);
GL.GenerateMipmap(TextureTarget.Texture2D);
}
return didUpload;
}
internal override void FlushUploads()
{
while (tryGetNextUpload(out var upload))
upload.Dispose();
}
private bool tryGetNextUpload(out ITextureUpload upload)
{
lock (uploadQueue)
{
if (uploadQueue.Count == 0)
{
upload = null;
return false;
}
upload = uploadQueue.Dequeue();
return true;
}
}
protected virtual void DoUpload(ITextureUpload upload, IntPtr dataPointer)
{
// Do we need to generate a new texture?
if (textureId <= 0 || internalWidth != width || internalHeight != height)
{
internalWidth = width;
internalHeight = height;
// We only need to generate a new texture if we don't have one already. Otherwise just re-use the current one.
if (textureId <= 0)
{
int[] textures = new int[1];
GL.GenTextures(1, textures);
textureId = textures[0];
GLWrapper.BindTexture(this);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureBaseLevel, 0);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMaxLevel, MAX_MIPMAP_LEVELS);
// These shouldn't be required, but on some older Intel drivers the MAX_LOD chosen by the shader isn't clamped to the MAX_LEVEL from above, resulting in disappearing textures.
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinLod, 0);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMaxLod, MAX_MIPMAP_LEVELS);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter,
(int)(manualMipmaps ? filteringMode : filteringMode == All.Linear ? All.LinearMipmapLinear : All.Nearest));
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)filteringMode);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge);
}
else
GLWrapper.BindTexture(this);
if (width == upload.Bounds.Width && height == upload.Bounds.Height || dataPointer == IntPtr.Zero)
{
updateMemoryUsage(upload.Level, (long)width * height * 4);
GL.TexImage2D(TextureTarget2d.Texture2D, upload.Level, TextureComponentCount.Srgb8Alpha8, width, height, 0, upload.Format, PixelType.UnsignedByte, dataPointer);
}
else
{
initializeLevel(upload.Level, width, height);
GL.TexSubImage2D(TextureTarget2d.Texture2D, upload.Level, upload.Bounds.X, upload.Bounds.Y, upload.Bounds.Width, upload.Bounds.Height, upload.Format,
PixelType.UnsignedByte, dataPointer);
}
}
// Just update content of the current texture
else if (dataPointer != IntPtr.Zero)
{
GLWrapper.BindTexture(this);
if (!manualMipmaps && upload.Level > 0)
{
//allocate mipmap levels
int level = 1;
int d = 2;
while (width / d > 0)
{
initializeLevel(level, width / d, height / d);
level++;
d *= 2;
}
manualMipmaps = true;
}
int div = (int)Math.Pow(2, upload.Level);
GL.TexSubImage2D(TextureTarget2d.Texture2D, upload.Level, upload.Bounds.X / div, upload.Bounds.Y / div, upload.Bounds.Width / div, upload.Bounds.Height / div,
upload.Format, PixelType.UnsignedByte, dataPointer);
}
}
private void initializeLevel(int level, int width, int height)
{
using (var image = createBackingImage(width, height))
using (var pixels = image.CreateReadOnlyPixelSpan())
{
updateMemoryUsage(level, (long)width * height * 4);
GL.TexImage2D(TextureTarget2d.Texture2D, level, TextureComponentCount.Srgb8Alpha8, width, height, 0, PixelFormat.Rgba, PixelType.UnsignedByte,
ref MemoryMarshal.GetReference(pixels.Span));
}
}
private Image<Rgba32> createBackingImage(int width, int height)
{
// it is faster to initialise without a background specification if transparent black is all that's required.
return initialisationColour == default
? new Image<Rgba32>(width, height)
: new Image<Rgba32>(width, height, initialisationColour);
}
}
}
| |
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using CommandLine;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V10.Errors;
using Google.Ads.GoogleAds.V10.Services;
using System;
using System.Collections.Generic;
namespace Google.Ads.GoogleAds.Examples.V10
{
/// <summary>
/// This code example imports offline call conversion values for calls related to the
/// ads in your account. To set up a conversion action, run the AddConversionAction.cs example.
/// </summary>
public class UploadCallConversion : ExampleBase
{
/// <summary>
/// Command line options for running the <see cref="UploadCallConversion"/> example.
/// </summary>
public class Options : OptionsBase
{
/// <summary>
/// The Google Ads customer ID for whom the conversion action will be added.
/// </summary>
[Option("customerId", Required = true, HelpText =
"The Google Ads customer ID for whom the conversion action will be added.")]
public long CustomerId { get; set; }
/// <summary>
/// The caller ID in E.164 format with preceding '+' sign. e.g. "+16502531234".
/// </summary>
[Option("callerId", Required = true, HelpText =
"The caller ID in E.164 format with preceding '+' sign. e.g. '+16502531234'.")]
public string CallerId { get; set; }
/// <summary>
/// The call start time in 'yyyy-mm-dd hh:mm:ss +|-hh:mm' format.
/// </summary>
[Option("callStartTime", Required = true, HelpText =
"The call start time in 'yyyy-mm-dd hh:mm:ss+|-hh:mm' format.")]
public string CallStartTime { get; set; }
/// <summary>
/// The call conversion time.
/// </summary>
[Option("conversionTime", Required = true, HelpText =
"The conversion time in 'yyyy-mm-dd hh:mm:ss+|-hh:mm' format.")]
public string ConversionTime { get; set; }
/// <summary>
/// The conversion value.
/// </summary>
[Option("conversionValue", Required = true, HelpText =
"The conversion value.")]
public double ConversionValue { get; set; }
/// <summary>
/// The ID of the conversion custom variable to associate with the upload.
/// </summary>
[Option("conversionCustomVariableId", Required = false, HelpText =
"The ID of the conversion custom variable to associate with the upload.")]
public long? ConversionCustomVariableId { get; set; }
/// <summary>
/// The value of the conversion custom variable to associate with the upload.
/// </summary>
[Option("conversionCustomVariableValue", Required = false, HelpText =
"The value of the conversion custom variable to associate with the upload.")]
public string ConversionCustomVariableValue { get; set; }
}
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
/// <param name="args">The command line arguments.</param>
public static void Main(string[] args)
{
Options options = new Options();
CommandLine.Parser.Default.ParseArguments<Options>(args).MapResult(
delegate (Options o)
{
options = o;
return 0;
}, delegate (IEnumerable<Error> errors)
{
// The Google Ads customer ID for whom the conversion action will be added.
options.CustomerId = long.Parse("INSERT_CUSTOMER_ID_HERE");
// The caller ID in E.164 format with preceding '+' sign. e.g. "+16502531234".
options.CallerId = "INSERT_CALLER_ID_HERE";
// The call start time in "yyyy-mm-dd hh:mm:ss+|-hh:mm" format.
options.CallStartTime = "INSERT_CALL_START_TIME_HERE";
// The conversion time in "yyyy-mm-dd hh:mm:ss+|-hh:mm" format.
options.ConversionTime = "INSERT_CONVERSION_TIME_HERE";
// The conversion value.
options.ConversionValue = double.Parse("INSERT_CONVERSION_VALUE_HERE");
// Optional: Set the custom conversion variable ID and value.
//options.ConversionCustomVariableId =
// long.Parse("INSERT_CONVERSION_CUSTOM_VARIABLE_ID_HERE");
//options.ConversionCustomVariableValue =
// "INSERT_CONVERSION_CUSTOM_VARIABLE_VALUE_HERE";
return 0;
});
UploadCallConversion codeExample = new UploadCallConversion();
Console.WriteLine(codeExample.Description);
codeExample.Run(new GoogleAdsClient(), options.CustomerId, options.CallerId,
options.CallStartTime, options.ConversionTime, options.ConversionValue,
options.ConversionCustomVariableId, options.ConversionCustomVariableValue);
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description =>
"This code example imports offline call conversion values for calls related to the " +
"ads in your account. To set up a conversion action, run the AddConversionAction.cs " +
"example.";
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID for whom the conversion action will
/// be added.</param>
/// <param name="callerId">The caller ID in E.164 format with preceding '+' sign. e.g.
/// "+16502531234".</param>
/// <param name="callStartTime">The call start time in "yyyy-mm-dd hh:mm:ss+|-hh:mm"
/// format.</param>
/// <param name="conversionTime">The conversion time in "yyyy-mm-dd hh:mm:ss+|-hh:mm"
/// format.</param>
/// <param name="conversionValue">The conversion value.</param>
/// <param name="conversionCustomVariableId">The ID of the conversion custom variable to
/// associate with the upload.</param>
/// <param name="conversionCustomVariableValue">The value of the conversion custom variable
/// to associate with the upload.</param>
// [START upload_call_conversion]
public void Run(GoogleAdsClient client, long customerId, string callerId,
string callStartTime, string conversionTime, double conversionValue,
long? conversionCustomVariableId, string conversionCustomVariableValue)
{
// Get the ConversionUploadService.
ConversionUploadServiceClient conversionUploadService =
client.GetService(Services.V10.ConversionUploadService);
// Create a call conversion by specifying currency as USD.
CallConversion callConversion = new CallConversion()
{
CallerId = callerId,
CallStartDateTime = callStartTime,
ConversionDateTime = conversionTime,
ConversionValue = conversionValue,
CurrencyCode = "USD"
};
if (conversionCustomVariableId != null &&
!string.IsNullOrEmpty(conversionCustomVariableValue))
{
callConversion.CustomVariables.Add(new CustomVariable()
{
ConversionCustomVariable = ResourceNames.ConversionCustomVariable(
customerId, conversionCustomVariableId.Value),
Value = conversionCustomVariableValue
});
}
UploadCallConversionsRequest request = new UploadCallConversionsRequest()
{
CustomerId = customerId.ToString(),
Conversions = { callConversion },
PartialFailure = true
};
try
{
// Issues a request to upload the call conversion. The partialFailure parameter
// is set to true, and validateOnly parameter to false as required by this method
// call.
UploadCallConversionsResponse response =
conversionUploadService.UploadCallConversions(request);
// Prints the result.
CallConversionResult uploadedCallConversion = response.Results[0];
Console.WriteLine($"Uploaded call conversion that occurred at " +
$"'{uploadedCallConversion.CallStartDateTime}' for caller ID " +
$"'{uploadedCallConversion.CallerId}' to the conversion action with " +
$"resource name '{uploadedCallConversion.ConversionAction}'.");
}
catch (GoogleAdsException e)
{
Console.WriteLine("Failure:");
Console.WriteLine($"Message: {e.Message}");
Console.WriteLine($"Failure: {e.Failure}");
Console.WriteLine($"Request ID: {e.RequestId}");
throw;
}
}
// [END upload_call_conversion]
}
}
| |
using System;
using System.ComponentModel;
using System.Drawing.Design;
using System.IO;
using System.Windows.Forms;
using Vlc.DotNet.Core;
using Vlc.DotNet.Core.Interops.Signatures;
using Vlc.DotNet.Forms.TypeEditors;
namespace Vlc.DotNet.Forms
{
public partial class VlcControl : Control, ISupportInitialize
{
private VlcMediaPlayer myVlcMediaPlayer;
#region VlcControl Init
public VlcControl()
{
InitializeComponent();
}
private void InitializeComponent()
{
// Init Component behaviour
BackColor = System.Drawing.Color.Black;
}
[Category("Media Player")]
public string[] VlcMediaplayerOptions { get; set; }
[Category("Media Player")]
[Editor(typeof(DirectoryEditor), typeof(UITypeEditor))]
public DirectoryInfo VlcLibDirectory { get; set; }
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Browsable(false)]
public bool IsPlaying
{
get
{
if (myVlcMediaPlayer != null)
{
return myVlcMediaPlayer.IsPlaying();
}
else
{
return false;
}
}
}
public void BeginInit()
{
// not used yet
}
public void EndInit()
{
if (IsInDesignMode() || myVlcMediaPlayer != null)
return;
if (VlcLibDirectory == null && (VlcLibDirectory = OnVlcLibDirectoryNeeded()) == null)
{
throw new Exception("'VlcLibDirectory' must be set.");
}
if (VlcMediaplayerOptions == null)
{
myVlcMediaPlayer = new VlcMediaPlayer(VlcLibDirectory);
}
else
{
myVlcMediaPlayer = new VlcMediaPlayer(VlcLibDirectory, VlcMediaplayerOptions);
}
myVlcMediaPlayer.VideoHostControlHandle = Handle;
RegisterEvents();
}
// work around http://stackoverflow.com/questions/34664/designmode-with-controls/708594
private static bool IsInDesignMode()
{
return System.Reflection.Assembly.GetExecutingAssembly().Location.Contains("VisualStudio");
}
public event EventHandler<VlcLibDirectoryNeededEventArgs> VlcLibDirectoryNeeded;
bool disposed = false;
protected void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected override void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
if (myVlcMediaPlayer != null)
{
UnregisterEvents();
if (IsPlaying)
Stop();
myVlcMediaPlayer.Dispose();
}
myVlcMediaPlayer = null;
base.Dispose(disposing);
}
disposed = true;
}
}
public DirectoryInfo OnVlcLibDirectoryNeeded()
{
var del = VlcLibDirectoryNeeded;
if (del != null)
{
var args = new VlcLibDirectoryNeededEventArgs();
del(this, args);
return args.VlcLibDirectory;
}
return null;
}
#endregion
#region VlcControl Functions & Properties
public void Play()
{
//EndInit();
if (myVlcMediaPlayer != null)
{
myVlcMediaPlayer.Play();
}
}
public void Play(FileInfo file, params string[] options)
{
//EndInit();
if (myVlcMediaPlayer != null)
{
myVlcMediaPlayer.SetMedia(file, options);
Play();
}
}
public void Play(Uri uri, params string[] options)
{
//EndInit();
if (myVlcMediaPlayer != null)
{
myVlcMediaPlayer.SetMedia(uri, options);
Play();
}
}
public void Play(string mrl, params string[] options)
{
//EndInit();
if (myVlcMediaPlayer != null)
{
myVlcMediaPlayer.SetMedia(mrl, options);
Play();
}
}
public void Pause()
{
//EndInit();
if (myVlcMediaPlayer != null)
{
myVlcMediaPlayer.Pause();
}
}
public void Stop()
{
//EndInit();
if (myVlcMediaPlayer != null)
{
myVlcMediaPlayer.Stop();
}
}
public VlcMedia GetCurrentMedia()
{
//EndInit();
if (myVlcMediaPlayer != null)
{
return myVlcMediaPlayer.GetMedia();
}
else
{
return null;
}
}
public void TakeSnapshot(string fileName)
{
FileInfo fileInfo = new FileInfo(fileName);
myVlcMediaPlayer.TakeSnapshot(fileInfo);
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Browsable(false)]
public float Position
{
get
{
if (myVlcMediaPlayer != null)
{
return myVlcMediaPlayer.Position;
}
else
{
return -1;
}
}
set
{
if (myVlcMediaPlayer != null)
{
myVlcMediaPlayer.Position = value;
}
}
}
[Browsable(false)]
public IChapterManagement Chapter
{
get
{
if (myVlcMediaPlayer != null)
{
return myVlcMediaPlayer.Chapters;
}
else
{
return null;
}
}
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Browsable(false)]
public float Rate
{
get
{
if (myVlcMediaPlayer != null)
{
return myVlcMediaPlayer.Rate;
}
else
{
return -1;
}
}
set
{
if (myVlcMediaPlayer != null)
{
myVlcMediaPlayer.Rate = value;
}
}
}
[Browsable(false)]
public MediaStates State
{
get
{
if (myVlcMediaPlayer != null)
{
return myVlcMediaPlayer.State;
}
else
{
return MediaStates.NothingSpecial;
}
}
}
[Browsable(false)]
public ISubTitlesManagement SubTitles
{
get
{
if (myVlcMediaPlayer != null)
{
return myVlcMediaPlayer.SubTitles;
}
else
{
return null;
}
}
}
[Browsable(false)]
public IVideoManagement Video
{
get
{
if (myVlcMediaPlayer != null)
{
return myVlcMediaPlayer.Video;
}
else
{
return null;
}
}
}
[Browsable(false)]
public IAudioManagement Audio
{
get
{
if (myVlcMediaPlayer != null)
{
return myVlcMediaPlayer.Audio;
}
else
{
return null;
}
}
}
[Browsable(false)]
public long Length
{
get
{
if (myVlcMediaPlayer != null)
{
return myVlcMediaPlayer.Length;
}
else
{
return -1;
}
}
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Browsable(false)]
public long Time
{
get
{
if (myVlcMediaPlayer != null)
{
return myVlcMediaPlayer.Time;
}
else
{
return -1;
}
}
set
{
if (myVlcMediaPlayer != null)
{
myVlcMediaPlayer.Time = value;
}
}
}
[Browsable(false)]
public int Spu
{
get
{
if (myVlcMediaPlayer != null)
{
return myVlcMediaPlayer.Spu;
}
return -1;
}
set
{
if (myVlcMediaPlayer != null)
{
myVlcMediaPlayer.Spu = value;
}
}
}
public void SetMedia(FileInfo file, params string[] options)
{
//EndInit();
myVlcMediaPlayer.SetMedia(file, options);
}
public void SetMedia(Uri file, params string[] options)
{
//EndInit();
myVlcMediaPlayer.SetMedia(file, options);
}
public void SetMedia(string mrl, params string[] options)
{
//EndInit();
myVlcMediaPlayer.SetMedia(mrl, options);
}
// set subtitle file
// if path is null, then disable subtitle
public void SetSubTitle(string path)
{
myVlcMediaPlayer.SetSubTitle(path);
}
public float FPS
{
get { return myVlcMediaPlayer.FramesPerSecond; }
}
public void Preview()
{
myVlcMediaPlayer.Preview();
}
#endregion
}
}
| |
#region Apache License
//
// 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.
//
#endregion
// .NET Compact Framework has no support for System.Net.Mail
#if !NETCF
using System;
using System.IO;
using System.Text;
using System.Net.Mail;
using log4net.Layout;
using log4net.Core;
using log4net.Util;
namespace log4net.Appender
{
/// <summary>
/// Send an e-mail when a specific logging event occurs, typically on errors
/// or fatal errors.
/// </summary>
/// <remarks>
/// <para>
/// The number of logging events delivered in this e-mail depend on
/// the value of <see cref="BufferingAppenderSkeleton.BufferSize"/> option. The
/// <see cref="SmtpAppender"/> keeps only the last
/// <see cref="BufferingAppenderSkeleton.BufferSize"/> logging events in its
/// cyclic buffer. This keeps memory requirements at a reasonable level while
/// still delivering useful application context.
/// </para>
/// <para>
/// Authentication is supported by setting the <see cref="Authentication"/> property to
/// either <see cref="SmtpAuthentication.Basic"/> or <see cref="SmtpAuthentication.Ntlm"/>.
/// If using <see cref="SmtpAuthentication.Basic"/> authentication then the <see cref="Username"/>
/// and <see cref="Password"/> properties must also be set.
/// </para>
/// <para>
/// To set the SMTP server port use the <see cref="Port"/> property. The default port is 25.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public class SmtpAppender : BufferingAppenderSkeleton
{
#region Public Instance Constructors
/// <summary>
/// Default constructor
/// </summary>
/// <remarks>
/// <para>
/// Default constructor
/// </para>
/// </remarks>
public SmtpAppender()
{
}
#endregion // Public Instance Constructors
#region Public Instance Properties
/// <summary>
/// Gets or sets a comma- or semicolon-delimited list of recipient e-mail addresses (comma is the preferred delimiter).
/// </summary>
/// <value>
/// <para>
/// A comma- or semicolon-delimited list of e-mail addresses.
/// </para>
/// </value>
public string To
{
get { return m_to; }
set { m_to = MaybeTrimSeparators(value); }
}
/// <summary>
/// Gets or sets a comma- or semicolon-delimited list of recipient e-mail addresses
/// that will be carbon copied (comma is the preferred delimiter).
/// </summary>
/// <value>
/// <para>
/// A comma- or semicolon-delimited list of e-mail addresses.
/// </para>
/// </value>
public string Cc
{
get { return m_cc; }
set { m_cc = MaybeTrimSeparators(value); }
}
/// <summary>
/// Gets or sets a semicolon-delimited list of recipient e-mail addresses
/// that will be blind carbon copied.
/// </summary>
/// <value>
/// A comma- or semicolon-delimited list of e-mail addresses.
/// </value>
public string Bcc
{
get { return m_bcc; }
set { m_bcc = MaybeTrimSeparators(value); }
}
/// <summary>
/// Gets or sets the e-mail address of the sender.
/// </summary>
/// <value>
/// The e-mail address of the sender.
/// </value>
/// <remarks>
/// <para>
/// The e-mail address of the sender.
/// </para>
/// </remarks>
public string From
{
get { return m_from; }
set { m_from = value; }
}
/// <summary>
/// Gets or sets the subject line of the e-mail message.
/// </summary>
/// <value>
/// The subject line of the e-mail message.
/// </value>
/// <remarks>
/// <para>
/// The subject line of the e-mail message.
/// </para>
/// </remarks>
public string Subject
{
get { return m_subject; }
set { m_subject = value; }
}
/// <summary>
/// Gets or sets the name of the SMTP relay mail server to use to send
/// the e-mail messages.
/// </summary>
/// <value>
/// The name of the e-mail relay server. If SmtpServer is not set, the
/// name of the local SMTP server is used.
/// </value>
/// <remarks>
/// <para>
/// The name of the e-mail relay server. If SmtpServer is not set, the
/// name of the local SMTP server is used.
/// </para>
/// </remarks>
public string SmtpHost
{
get { return m_smtpHost; }
set { m_smtpHost = value; }
}
/// <summary>
/// The mode to use to authentication with the SMTP server
/// </summary>
/// <remarks>
/// <para>
/// Valid Authentication mode values are: <see cref="SmtpAuthentication.None"/>,
/// <see cref="SmtpAuthentication.Basic"/>, and <see cref="SmtpAuthentication.Ntlm"/>.
/// The default value is <see cref="SmtpAuthentication.None"/>. When using
/// <see cref="SmtpAuthentication.Basic"/> you must specify the <see cref="Username"/>
/// and <see cref="Password"/> to use to authenticate.
/// When using <see cref="SmtpAuthentication.Ntlm"/> the Windows credentials for the current
/// thread, if impersonating, or the process will be used to authenticate.
/// </para>
/// </remarks>
public SmtpAuthentication Authentication
{
get { return m_authentication; }
set { m_authentication = value; }
}
/// <summary>
/// The username to use to authenticate with the SMTP server
/// </summary>
/// <remarks>
/// <para>
/// A <see cref="Username"/> and <see cref="Password"/> must be specified when
/// <see cref="Authentication"/> is set to <see cref="SmtpAuthentication.Basic"/>,
/// otherwise the username will be ignored.
/// </para>
/// </remarks>
public string Username
{
get { return m_username; }
set { m_username = value; }
}
/// <summary>
/// The password to use to authenticate with the SMTP server
/// </summary>
/// <remarks>
/// <para>
/// A <see cref="Username"/> and <see cref="Password"/> must be specified when
/// <see cref="Authentication"/> is set to <see cref="SmtpAuthentication.Basic"/>,
/// otherwise the password will be ignored.
/// </para>
/// </remarks>
public string Password
{
get { return m_password; }
set { m_password = value; }
}
/// <summary>
/// The port on which the SMTP server is listening
/// </summary>
/// <remarks>
/// <para>
/// The port on which the SMTP server is listening. The default
/// port is <c>25</c>.
/// </para>
/// </remarks>
public int Port
{
get { return m_port; }
set { m_port = value; }
}
/// <summary>
/// Gets or sets the priority of the e-mail message
/// </summary>
/// <value>
/// One of the <see cref="MailPriority"/> values.
/// </value>
/// <remarks>
/// <para>
/// Sets the priority of the e-mails generated by this
/// appender. The default priority is <see cref="MailPriority.Normal"/>.
/// </para>
/// <para>
/// If you are using this appender to report errors then
/// you may want to set the priority to <see cref="MailPriority.High"/>.
/// </para>
/// </remarks>
public MailPriority Priority
{
get { return m_mailPriority; }
set { m_mailPriority = value; }
}
/// <summary>
/// Enable or disable use of SSL when sending e-mail message
/// </summary>
public bool EnableSsl
{
get { return m_enableSsl; }
set { m_enableSsl = value; }
}
/// <summary>
/// Gets or sets the reply-to e-mail address.
/// </summary>
public string ReplyTo
{
get { return m_replyTo; }
set { m_replyTo = value; }
}
/// <summary>
/// Gets or sets the subject encoding to be used.
/// </summary>
/// <remarks>
/// The default encoding is the operating system's current ANSI codepage.
/// </remarks>
public Encoding SubjectEncoding
{
get { return m_subjectEncoding; }
set { m_subjectEncoding = value; }
}
/// <summary>
/// Gets or sets the body encoding to be used.
/// </summary>
/// <remarks>
/// The default encoding is the operating system's current ANSI codepage.
/// </remarks>
public Encoding BodyEncoding
{
get { return m_bodyEncoding; }
set { m_bodyEncoding = value; }
}
/// <summary>
/// Gets or sets a value indicating whether the mail message body is in HTML.
/// </summary>
virtual public bool IsBodyHTML
{
get { return isBodyHTML; }
set { isBodyHTML = value; }
}
#endregion // Public Instance Properties
#region Override implementation of BufferingAppenderSkeleton
/// <summary>
/// Sends the contents of the cyclic buffer as an e-mail message.
/// </summary>
/// <param name="events">The logging events to send.</param>
override protected void SendBuffer(LoggingEvent[] events)
{
// Note: this code already owns the monitor for this
// appender. This frees us from needing to synchronize again.
try
{
SendEmail(GetMailMessageBody(events));
}
catch (Exception e)
{
ErrorHandler.Error("Error occurred while sending e-mail notification.", e);
}
}
#endregion // Override implementation of BufferingAppenderSkeleton
#region Override implementation of AppenderSkeleton
/// <summary>
/// This appender requires a <see cref="Layout"/> to be set.
/// </summary>
/// <value><c>true</c></value>
/// <remarks>
/// <para>
/// This appender requires a <see cref="Layout"/> to be set.
/// </para>
/// </remarks>
override protected bool RequiresLayout
{
get { return true; }
}
#endregion // Override implementation of AppenderSkeleton
#region Protected Methods
/// <summary>
/// Creates the body of the message to send
/// </summary>
/// <param name="events"></param>
/// <returns></returns>
virtual protected string GetMailMessageBody(LoggingEvent[] events)
{
StringWriter writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture);
string t = Layout.Header;
if (t != null)
{
writer.Write(t);
}
for (int i = 0; i < events.Length; i++)
{
// Render the event and append the text to the buffer
RenderLoggingEvent(writer, events[i]);
}
t = Layout.Footer;
if (t != null)
{
writer.Write(t);
}
return writer.ToString();
}
/// <summary>
/// Send the email message
/// </summary>
/// <param name="messageBody">the body text to include in the mail</param>
virtual protected void SendEmail(string messageBody)
{
// Create and configure the smtp client
SmtpClient smtpClient = new SmtpClient();
if (!String.IsNullOrEmpty(m_smtpHost))
{
smtpClient.Host = m_smtpHost;
}
smtpClient.Port = m_port;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = m_enableSsl;
if (m_authentication == SmtpAuthentication.Basic)
{
// Perform basic authentication
smtpClient.Credentials = new System.Net.NetworkCredential(m_username, m_password);
}
else if (m_authentication == SmtpAuthentication.Ntlm)
{
// Perform integrated authentication (NTLM)
smtpClient.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
}
using (MailMessage mailMessage = new MailMessage())
{
mailMessage.Body = messageBody;
mailMessage.BodyEncoding = m_bodyEncoding;
mailMessage.IsBodyHtml = IsBodyHTML;
mailMessage.From = new MailAddress(m_from);
mailMessage.To.Add(m_to);
if (!String.IsNullOrEmpty(m_cc))
{
mailMessage.CC.Add(m_cc);
}
if (!String.IsNullOrEmpty(m_bcc))
{
mailMessage.Bcc.Add(m_bcc);
}
if (!String.IsNullOrEmpty(m_replyTo))
{
// .NET 4.0 warning CS0618: 'System.Net.Mail.MailMessage.ReplyTo' is obsolete:
// 'ReplyTo is obsoleted for this type. Please use ReplyToList instead which can accept multiple addresses. http://go.microsoft.com/fwlink/?linkid=14202'
#if !FRAMEWORK_4_0_OR_ABOVE
mailMessage.ReplyTo = new MailAddress(m_replyTo);
#else
mailMessage.ReplyToList.Add(new MailAddress(m_replyTo));
#endif
}
mailMessage.Subject = m_subject;
mailMessage.SubjectEncoding = m_subjectEncoding;
mailMessage.Priority = m_mailPriority;
// TODO: Consider using SendAsync to send the message without blocking. We would need a SendCompletedCallback to log errors.
smtpClient.Send(mailMessage);
}
}
#endregion // Protected Methods
#region Private Instance Fields
private string m_to;
private string m_cc;
private string m_bcc;
private string m_from;
private string m_subject;
private string m_smtpHost;
private Encoding m_subjectEncoding = Encoding.UTF8;
private Encoding m_bodyEncoding = Encoding.UTF8;
private bool isBodyHTML = false;
// authentication fields
private SmtpAuthentication m_authentication = SmtpAuthentication.None;
private string m_username;
private string m_password;
// server port, default port 25
private int m_port = 25;
private MailPriority m_mailPriority = MailPriority.Normal;
private bool m_enableSsl = false;
private string m_replyTo;
#endregion // Private Instance Fields
#region SmtpAuthentication Enum
/// <summary>
/// Values for the <see cref="SmtpAppender.Authentication"/> property.
/// </summary>
/// <remarks>
/// <para>
/// SMTP authentication modes.
/// </para>
/// </remarks>
public enum SmtpAuthentication
{
/// <summary>
/// No authentication
/// </summary>
None,
/// <summary>
/// Basic authentication.
/// </summary>
/// <remarks>
/// Requires a username and password to be supplied
/// </remarks>
Basic,
/// <summary>
/// Integrated authentication
/// </summary>
/// <remarks>
/// Uses the Windows credentials from the current thread or process to authenticate.
/// </remarks>
Ntlm
}
#endregion // SmtpAuthentication Enum
private static readonly char[] ADDRESS_DELIMITERS = new char[] { ',', ';' };
/// <summary>
/// trims leading and trailing commas or semicolons
/// </summary>
private static string MaybeTrimSeparators(string s) {
return string.IsNullOrEmpty(s) ? s : s.Trim(ADDRESS_DELIMITERS);
}
}
}
#endif // !NETCF
| |
using BulletMLLib;
using BulletMLSample;
using FilenameBuddy;
using NUnit.Framework;
namespace BulletMLTests
{
[TestFixture()]
public class AllRoundXmlTest
{
MoverManager manager;
Myship dude;
BulletPattern pattern;
[SetUp()]
public void setupHarness()
{
Filename.SetCurrentDirectory(@"C:\Projects\BulletMLLib\BulletMLLib\BulletMLLib.Tests\bin\Debug");
dude = new Myship();
manager = new MoverManager(dude.Position);
pattern = new BulletPattern(manager);
}
[Test()]
public void TestOneTop()
{
var filename = new Filename(@"AllRound.xml");
pattern.ParseXML(filename.File);
ActionNode testNode = pattern.RootNode.FindLabelNode("top", ENodeName.action) as ActionNode;
Assert.IsNotNull(testNode);
}
[Test()]
public void TestNoRepeatNode()
{
var filename = new Filename(@"AllRound.xml");
pattern.ParseXML(filename.File);
ActionNode testNode = pattern.RootNode.FindLabelNode("top", ENodeName.action) as ActionNode;
Assert.IsNull(testNode.ParentRepeatNode);
}
[Test()]
public void CorrectNode()
{
var filename = new Filename(@"AllRound.xml");
BulletPattern pattern = new BulletPattern(manager);
pattern.ParseXML(filename.File);
Mover mover = (Mover)manager.CreateBullet();
mover.InitTopNode(pattern.RootNode);
Assert.IsNotNull(mover.Tasks[0].Node);
Assert.IsNotNull(mover.Tasks[0].Node is ActionNode);
}
[Test()]
public void RepeatOnce()
{
var filename = new Filename(@"AllRound.xml");
BulletPattern pattern = new BulletPattern(manager);
pattern.ParseXML(filename.File);
Mover mover = (Mover)manager.CreateBullet();
mover.InitTopNode(pattern.RootNode);
ActionTask myAction = mover.Tasks[0] as ActionTask;
ActionNode testNode = pattern.RootNode.FindLabelNode("top", ENodeName.action) as ActionNode;
Assert.AreEqual(1, testNode.RepeatNum(myAction, mover));
}
[Test()]
public void CorrectAction()
{
var filename = new Filename(@"AllRound.xml");
BulletPattern pattern = new BulletPattern(manager);
pattern.ParseXML(filename.File);
Mover mover = (Mover)manager.CreateBullet();
mover.InitTopNode(pattern.RootNode);
BulletMLTask myTask = mover.Tasks[0];
Assert.AreEqual(1, myTask.ChildTasks.Count);
}
[Test()]
public void CreatedActionRefTask()
{
var filename = new Filename(@"AllRound.xml");
pattern.ParseXML(filename.File);
Mover mover = (Mover)manager.CreateBullet();
mover.InitTopNode(pattern.RootNode);
ActionTask testTask = mover.FindTaskByLabelAndName("circle", ENodeName.actionRef) as ActionTask;
Assert.IsNotNull(testTask);
}
[Test()]
public void CreatedActionRefTask1()
{
var filename = new Filename(@"AllRound.xml");
pattern.ParseXML(filename.File);
Mover mover = (Mover)manager.CreateBullet();
mover.InitTopNode(pattern.RootNode);
ActionTask testTask = mover.FindTaskByLabelAndName("circle", ENodeName.actionRef) as ActionTask;
Assert.AreEqual(ENodeName.actionRef, testTask.Node.Name);
}
[Test()]
public void CreatedActionRefTask2()
{
var filename = new Filename(@"AllRound.xml");
pattern.ParseXML(filename.File);
Mover mover = (Mover)manager.CreateBullet();
mover.InitTopNode(pattern.RootNode);
ActionTask testTask = mover.FindTaskByLabelAndName("circle", ENodeName.actionRef) as ActionTask;
Assert.AreEqual("circle", testTask.Node.Label);
}
[Test()]
public void CreatedActionTask()
{
var filename = new Filename(@"AllRound.xml");
pattern.ParseXML(filename.File);
Mover mover = (Mover)manager.CreateBullet();
mover.InitTopNode(pattern.RootNode);
ActionTask testTask = mover.FindTaskByLabelAndName("circle", ENodeName.actionRef) as ActionTask;
Assert.AreEqual(1, testTask.ChildTasks.Count);
}
[Test()]
public void CreatedActionTask1()
{
var filename = new Filename(@"AllRound.xml");
pattern.ParseXML(filename.File);
Mover mover = (Mover)manager.CreateBullet();
mover.InitTopNode(pattern.RootNode);
ActionTask testTask = mover.FindTaskByLabelAndName("circle", ENodeName.actionRef) as ActionTask;
Assert.IsNotNull(testTask.ChildTasks[0]);
}
[Test()]
public void CreatedActionTask2()
{
var filename = new Filename(@"AllRound.xml");
pattern.ParseXML(filename.File);
Mover mover = (Mover)manager.CreateBullet();
mover.InitTopNode(pattern.RootNode);
ActionTask testTask = mover.FindTaskByLabelAndName("circle", ENodeName.actionRef) as ActionTask;
ActionTask testActionTask = testTask.ChildTasks[0] as ActionTask;
Assert.IsNotNull(testActionTask);
}
[Test()]
public void CreatedActionTask3()
{
var filename = new Filename(@"AllRound.xml");
pattern.ParseXML(filename.File);
Mover mover = (Mover)manager.CreateBullet();
mover.InitTopNode(pattern.RootNode);
ActionTask testTask = mover.FindTaskByLabelAndName("circle", ENodeName.actionRef) as ActionTask;
ActionTask testActionTask = testTask.ChildTasks[0] as ActionTask;
Assert.IsNotNull(testActionTask.Node);
}
[Test()]
public void CreatedActionTask4()
{
var filename = new Filename(@"AllRound.xml");
pattern.ParseXML(filename.File);
Mover mover = (Mover)manager.CreateBullet();
mover.InitTopNode(pattern.RootNode);
ActionTask testTask = mover.FindTaskByLabelAndName("circle", ENodeName.actionRef) as ActionTask;
ActionTask testActionTask = testTask.ChildTasks[0] as ActionTask;
Assert.AreEqual(ENodeName.action, testActionTask.Node.Name);
}
[Test()]
public void CreatedActionTask5()
{
var filename = new Filename(@"AllRound.xml");
pattern.ParseXML(filename.File);
Mover mover = (Mover)manager.CreateBullet();
mover.InitTopNode(pattern.RootNode);
ActionTask testTask = mover.FindTaskByLabelAndName("circle", ENodeName.actionRef) as ActionTask;
ActionTask testActionTask = testTask.ChildTasks[0] as ActionTask;
Assert.AreEqual("circle", testActionTask.Node.Label);
}
[Test()]
public void CreatedActionTask10()
{
var filename = new Filename(@"AllRound.xml");
pattern.ParseXML(filename.File);
Mover mover = (Mover)manager.CreateBullet();
mover.InitTopNode(pattern.RootNode);
ActionTask testTask = mover.FindTaskByLabelAndName("circle", ENodeName.action) as ActionTask;
Assert.IsNotNull(testTask);
}
[Test()]
public void CorrectNumberOfBullets()
{
var filename = new Filename(@"AllRound.xml");
pattern.ParseXML(filename.File);
Mover mover = (Mover)manager.CreateBullet();
mover.InitTopNode(pattern.RootNode);
manager.Update();
//there should be 11 bullets
Assert.AreEqual(21, manager.movers.Count);
}
}
}
| |
using System;
using System.Linq;
using System.Threading.Tasks;
using Windows.UI.Xaml.Controls;
using System.Collections.Generic;
using Windows.UI.Xaml.Navigation;
using System.Collections.ObjectModel;
using Windows.UI.Xaml.Media.Animation;
using Windows.ApplicationModel.Resources;
using Template10.Mvvm;
using Template10.Services.NavigationService;
namespace Dota2Handbook.ViewModels
{
using Views;
using Enums;
using Data;
using Utilities;
using Infrastructure;
using Services.SettingsServices;
using static Dota2Handbook.Utilities.SecondaryTilePin;
public class MainPageViewModel : ViewModelBase
{
#region Properties & Constructor
public IList<string> ComboBoxItemList = Constants.NewsCountList;
ObservableCollection<NewsItem> _news;
ObservableCollection<NewsItem> _updates;
public ObservableCollection<NewsItem> News { get; private set; }
public ObservableCollection<NewsItem> Updates { get; private set; }
SettingsService _settings;
NewsItem SelectedNewsItem { get; set; }
string _newsCount = Constants.DefaultNewsCount;
public string NewsCount
{
get { return _newsCount; }
set => Set(ref _newsCount, value);
}
string _updatesCount = Constants.DefaultUpdateCount;
public string UpdatesCount
{
get { return _updatesCount; }
set => Set(ref _updatesCount, value);
}
string _filterNews;
public string FilterNews
{
get { return _filterNews; }
set
{
if (Set(ref _filterNews, value))
PerformFilteringForNews();
}
}
string _filterUpdates;
public string FilterUpdates
{
get { return _filterUpdates; }
set
{
if (Set(ref _filterUpdates, value))
PerformFilteringForUpdates();
}
}
public MainPageViewModel()
{
News = new ObservableCollection<NewsItem>();
Updates = new ObservableCollection<NewsItem>();
_settings = SettingsService.Instance;
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
Start();
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
}
#endregion
#region Public Methods
public void NewsItemTapped(object sender, object e)
{
SelectedNewsItem = ((ListView)sender).SelectedItem as NewsItem;
if (SelectedNewsItem.Feedname.Equals(Constants.NewsFeedStringForUpdates, StringComparison.OrdinalIgnoreCase) &&
_settings.IsReadingViewEnabled)
NavigationService.Navigate(typeof(NewsDetailHTML), SelectedNewsItem, new SuppressNavigationTransitionInfo());
else
NavigationService.Navigate(typeof(NewsDetail), SelectedNewsItem, new SuppressNavigationTransitionInfo());
}
public async void Pin()
{
PinTileObject secondaryTile = new PinTileObject()
{
TileId = PageEnum.News.ToString(),
DisplayName = PageEnum.News.ToString(),
Arguments = PageEnum.News.ToString(),
};
await PinTile(secondaryTile);
await DialogBox.Show(ResourceLoader.GetForCurrentView().GetString("PinnedPage")).ExecuteAsync(null, null);
}
public async Task Start()
{
if (Connection.HasInternetAccess)
{
Busy.SetBusy(true);
await GetNews();
await GetUpdates();
Busy.SetBusy(false);
}
else
await DialogBox.Show(Constants.InternetConnectionError, ResourceLoader.GetForCurrentView().GetString("Error")).ExecuteAsync(null, null);
}
public async Task GetNews()
{
_news = await NewsRepository.GetNews(Convert.ToInt32(NewsCount));
PerformFilteringForNews();
}
public async Task GetUpdates()
{
_updates = await NewsRepository.GetUpdates(Convert.ToInt32(UpdatesCount));
PerformFilteringForUpdates();
}
#endregion
#region Private Methods
private void PerformFilteringForNews()
{
if (string.IsNullOrWhiteSpace(_filterNews))
_filterNews = string.Empty;
var lowerCaseFilter = FilterNews.ToLowerInvariant().Trim();
var result =
_news.Where(d => d.Title.ToLowerInvariant()
.Contains(lowerCaseFilter))
.ToList();
var toRemove = News.Except(result).ToList();
foreach (var x in toRemove)
News.Remove(x);
var resultCount = result.Count;
for (int i = 0; i < resultCount; i++)
{
var resultItem = result[i];
if (i + 1 > News.Count || !News[i].Equals(resultItem))
News.Insert(i, resultItem);
}
}
private void PerformFilteringForUpdates()
{
if (string.IsNullOrWhiteSpace(_filterUpdates))
_filterUpdates = string.Empty;
var lowerCaseFilter = FilterUpdates.ToLowerInvariant().Trim();
var result =
_updates.Where(d => d.Title.ToLowerInvariant()
.Contains(lowerCaseFilter))
.ToList();
var toRemove = Updates.Except(result).ToList();
foreach (var x in toRemove)
Updates.Remove(x);
var resultCount = result.Count;
for (int i = 0; i < resultCount; i++)
{
var resultItem = result[i];
if (i + 1 > Updates.Count || !Updates[i].Equals(resultItem))
Updates.Insert(i, resultItem);
}
}
#endregion
#region Navigation
public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary<string, object> suspensionState) =>
await Task.CompletedTask;
public override async Task OnNavigatedFromAsync(IDictionary<string, object> suspensionState, bool suspending) =>
await Task.CompletedTask;
public override async Task OnNavigatingFromAsync(NavigatingEventArgs args)
{
args.Cancel = false;
await Task.CompletedTask;
}
#endregion
#region Settings
public void GotoSettings() =>
NavigationService.Navigate(typeof(Settings), 0);
public void GotoPin() =>
NavigationService.Navigate(typeof(Settings), 1);
public void GotoAbout() =>
NavigationService.Navigate(typeof(Settings), 2);
public void GoToVersionHistory() =>
NavigationService.Navigate(typeof(Settings), 3);
#endregion
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using sc = System.Collections;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.Compute.V1
{
/// <summary>Settings for <see cref="DiskTypesClient"/> instances.</summary>
public sealed partial class DiskTypesSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="DiskTypesSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="DiskTypesSettings"/>.</returns>
public static DiskTypesSettings GetDefault() => new DiskTypesSettings();
/// <summary>Constructs a new <see cref="DiskTypesSettings"/> object with default settings.</summary>
public DiskTypesSettings()
{
}
private DiskTypesSettings(DiskTypesSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
AggregatedListSettings = existing.AggregatedListSettings;
GetSettings = existing.GetSettings;
ListSettings = existing.ListSettings;
OnCopy(existing);
}
partial void OnCopy(DiskTypesSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>DiskTypesClient.AggregatedList</c> and <c>DiskTypesClient.AggregatedListAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>No timeout is applied.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings AggregatedListSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to <c>DiskTypesClient.Get</c> and
/// <c>DiskTypesClient.GetAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>No timeout is applied.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to <c>DiskTypesClient.List</c>
/// and <c>DiskTypesClient.ListAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>No timeout is applied.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings ListSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None);
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="DiskTypesSettings"/> object.</returns>
public DiskTypesSettings Clone() => new DiskTypesSettings(this);
}
/// <summary>
/// Builder class for <see cref="DiskTypesClient"/> to provide simple configuration of credentials, endpoint etc.
/// </summary>
public sealed partial class DiskTypesClientBuilder : gaxgrpc::ClientBuilderBase<DiskTypesClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public DiskTypesSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public DiskTypesClientBuilder()
{
UseJwtAccessWithScopes = DiskTypesClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref DiskTypesClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<DiskTypesClient> task);
/// <summary>Builds the resulting client.</summary>
public override DiskTypesClient Build()
{
DiskTypesClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<DiskTypesClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<DiskTypesClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private DiskTypesClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return DiskTypesClient.Create(callInvoker, Settings);
}
private async stt::Task<DiskTypesClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return DiskTypesClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => DiskTypesClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => DiskTypesClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => DiskTypesClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => ComputeRestAdapter.ComputeAdapter;
}
/// <summary>DiskTypes client wrapper, for convenient use.</summary>
/// <remarks>
/// The DiskTypes API.
/// </remarks>
public abstract partial class DiskTypesClient
{
/// <summary>
/// The default endpoint for the DiskTypes service, which is a host of "compute.googleapis.com" and a port of
/// 443.
/// </summary>
public static string DefaultEndpoint { get; } = "compute.googleapis.com:443";
/// <summary>The default DiskTypes scopes.</summary>
/// <remarks>
/// The default DiskTypes scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/compute.readonly</description></item>
/// <item><description>https://www.googleapis.com/auth/compute</description></item>
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/compute.readonly",
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/cloud-platform",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="DiskTypesClient"/> using the default credentials, endpoint and settings.
/// To specify custom credentials or other settings, use <see cref="DiskTypesClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="DiskTypesClient"/>.</returns>
public static stt::Task<DiskTypesClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new DiskTypesClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="DiskTypesClient"/> using the default credentials, endpoint and settings.
/// To specify custom credentials or other settings, use <see cref="DiskTypesClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="DiskTypesClient"/>.</returns>
public static DiskTypesClient Create() => new DiskTypesClientBuilder().Build();
/// <summary>
/// Creates a <see cref="DiskTypesClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="DiskTypesSettings"/>.</param>
/// <returns>The created <see cref="DiskTypesClient"/>.</returns>
internal static DiskTypesClient Create(grpccore::CallInvoker callInvoker, DiskTypesSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
DiskTypes.DiskTypesClient grpcClient = new DiskTypes.DiskTypesClient(callInvoker);
return new DiskTypesClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC DiskTypes client</summary>
public virtual DiskTypes.DiskTypesClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Retrieves an aggregated list of disk types.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="scg::KeyValuePair{TKey,TValue}"/> resources.</returns>
public virtual gax::PagedEnumerable<DiskTypeAggregatedList, scg::KeyValuePair<string, DiskTypesScopedList>> AggregatedList(AggregatedListDiskTypesRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Retrieves an aggregated list of disk types.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>
/// A pageable asynchronous sequence of <see cref="scg::KeyValuePair{TKey,TValue}"/> resources.
/// </returns>
public virtual gax::PagedAsyncEnumerable<DiskTypeAggregatedList, scg::KeyValuePair<string, DiskTypesScopedList>> AggregatedListAsync(AggregatedListDiskTypesRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Retrieves an aggregated list of disk types.
/// </summary>
/// <param name="project">
/// Project ID for this request.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="scg::KeyValuePair{TKey,TValue}"/> resources.</returns>
public virtual gax::PagedEnumerable<DiskTypeAggregatedList, scg::KeyValuePair<string, DiskTypesScopedList>> AggregatedList(string project, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
AggregatedList(new AggregatedListDiskTypesRequest
{
Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Retrieves an aggregated list of disk types.
/// </summary>
/// <param name="project">
/// Project ID for this request.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>
/// A pageable asynchronous sequence of <see cref="scg::KeyValuePair{TKey,TValue}"/> resources.
/// </returns>
public virtual gax::PagedAsyncEnumerable<DiskTypeAggregatedList, scg::KeyValuePair<string, DiskTypesScopedList>> AggregatedListAsync(string project, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
AggregatedListAsync(new AggregatedListDiskTypesRequest
{
Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Returns the specified disk type. Gets a list of available disk types by making a list() request.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual DiskType Get(GetDiskTypeRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the specified disk type. Gets a list of available disk types by making a list() request.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<DiskType> GetAsync(GetDiskTypeRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the specified disk type. Gets a list of available disk types by making a list() request.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<DiskType> GetAsync(GetDiskTypeRequest request, st::CancellationToken cancellationToken) =>
GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the specified disk type. Gets a list of available disk types by making a list() request.
/// </summary>
/// <param name="project">
/// Project ID for this request.
/// </param>
/// <param name="zone">
/// The name of the zone for this request.
/// </param>
/// <param name="diskType">
/// Name of the disk type to return.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual DiskType Get(string project, string zone, string diskType, gaxgrpc::CallSettings callSettings = null) =>
Get(new GetDiskTypeRequest
{
DiskType = gax::GaxPreconditions.CheckNotNullOrEmpty(diskType, nameof(diskType)),
Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)),
Zone = gax::GaxPreconditions.CheckNotNullOrEmpty(zone, nameof(zone)),
}, callSettings);
/// <summary>
/// Returns the specified disk type. Gets a list of available disk types by making a list() request.
/// </summary>
/// <param name="project">
/// Project ID for this request.
/// </param>
/// <param name="zone">
/// The name of the zone for this request.
/// </param>
/// <param name="diskType">
/// Name of the disk type to return.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<DiskType> GetAsync(string project, string zone, string diskType, gaxgrpc::CallSettings callSettings = null) =>
GetAsync(new GetDiskTypeRequest
{
DiskType = gax::GaxPreconditions.CheckNotNullOrEmpty(diskType, nameof(diskType)),
Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)),
Zone = gax::GaxPreconditions.CheckNotNullOrEmpty(zone, nameof(zone)),
}, callSettings);
/// <summary>
/// Returns the specified disk type. Gets a list of available disk types by making a list() request.
/// </summary>
/// <param name="project">
/// Project ID for this request.
/// </param>
/// <param name="zone">
/// The name of the zone for this request.
/// </param>
/// <param name="diskType">
/// Name of the disk type to return.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<DiskType> GetAsync(string project, string zone, string diskType, st::CancellationToken cancellationToken) =>
GetAsync(project, zone, diskType, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Retrieves a list of disk types available to the specified project.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="DiskType"/> resources.</returns>
public virtual gax::PagedEnumerable<DiskTypeList, DiskType> List(ListDiskTypesRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Retrieves a list of disk types available to the specified project.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="DiskType"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<DiskTypeList, DiskType> ListAsync(ListDiskTypesRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Retrieves a list of disk types available to the specified project.
/// </summary>
/// <param name="project">
/// Project ID for this request.
/// </param>
/// <param name="zone">
/// The name of the zone for this request.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="DiskType"/> resources.</returns>
public virtual gax::PagedEnumerable<DiskTypeList, DiskType> List(string project, string zone, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
List(new ListDiskTypesRequest
{
Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)),
Zone = gax::GaxPreconditions.CheckNotNullOrEmpty(zone, nameof(zone)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Retrieves a list of disk types available to the specified project.
/// </summary>
/// <param name="project">
/// Project ID for this request.
/// </param>
/// <param name="zone">
/// The name of the zone for this request.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="DiskType"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<DiskTypeList, DiskType> ListAsync(string project, string zone, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListAsync(new ListDiskTypesRequest
{
Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)),
Zone = gax::GaxPreconditions.CheckNotNullOrEmpty(zone, nameof(zone)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
}
/// <summary>DiskTypes client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// The DiskTypes API.
/// </remarks>
public sealed partial class DiskTypesClientImpl : DiskTypesClient
{
private readonly gaxgrpc::ApiCall<AggregatedListDiskTypesRequest, DiskTypeAggregatedList> _callAggregatedList;
private readonly gaxgrpc::ApiCall<GetDiskTypeRequest, DiskType> _callGet;
private readonly gaxgrpc::ApiCall<ListDiskTypesRequest, DiskTypeList> _callList;
/// <summary>
/// Constructs a client wrapper for the DiskTypes service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="DiskTypesSettings"/> used within this client.</param>
public DiskTypesClientImpl(DiskTypes.DiskTypesClient grpcClient, DiskTypesSettings settings)
{
GrpcClient = grpcClient;
DiskTypesSettings effectiveSettings = settings ?? DiskTypesSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callAggregatedList = clientHelper.BuildApiCall<AggregatedListDiskTypesRequest, DiskTypeAggregatedList>(grpcClient.AggregatedListAsync, grpcClient.AggregatedList, effectiveSettings.AggregatedListSettings).WithGoogleRequestParam("project", request => request.Project);
Modify_ApiCall(ref _callAggregatedList);
Modify_AggregatedListApiCall(ref _callAggregatedList);
_callGet = clientHelper.BuildApiCall<GetDiskTypeRequest, DiskType>(grpcClient.GetAsync, grpcClient.Get, effectiveSettings.GetSettings).WithGoogleRequestParam("project", request => request.Project).WithGoogleRequestParam("zone", request => request.Zone).WithGoogleRequestParam("disk_type", request => request.DiskType);
Modify_ApiCall(ref _callGet);
Modify_GetApiCall(ref _callGet);
_callList = clientHelper.BuildApiCall<ListDiskTypesRequest, DiskTypeList>(grpcClient.ListAsync, grpcClient.List, effectiveSettings.ListSettings).WithGoogleRequestParam("project", request => request.Project).WithGoogleRequestParam("zone", request => request.Zone);
Modify_ApiCall(ref _callList);
Modify_ListApiCall(ref _callList);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_AggregatedListApiCall(ref gaxgrpc::ApiCall<AggregatedListDiskTypesRequest, DiskTypeAggregatedList> call);
partial void Modify_GetApiCall(ref gaxgrpc::ApiCall<GetDiskTypeRequest, DiskType> call);
partial void Modify_ListApiCall(ref gaxgrpc::ApiCall<ListDiskTypesRequest, DiskTypeList> call);
partial void OnConstruction(DiskTypes.DiskTypesClient grpcClient, DiskTypesSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC DiskTypes client</summary>
public override DiskTypes.DiskTypesClient GrpcClient { get; }
partial void Modify_AggregatedListDiskTypesRequest(ref AggregatedListDiskTypesRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_GetDiskTypeRequest(ref GetDiskTypeRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_ListDiskTypesRequest(ref ListDiskTypesRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Retrieves an aggregated list of disk types.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="scg::KeyValuePair{TKey,TValue}"/> resources.</returns>
public override gax::PagedEnumerable<DiskTypeAggregatedList, scg::KeyValuePair<string, DiskTypesScopedList>> AggregatedList(AggregatedListDiskTypesRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_AggregatedListDiskTypesRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedEnumerable<AggregatedListDiskTypesRequest, DiskTypeAggregatedList, scg::KeyValuePair<string, DiskTypesScopedList>>(_callAggregatedList, request, callSettings);
}
/// <summary>
/// Retrieves an aggregated list of disk types.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>
/// A pageable asynchronous sequence of <see cref="scg::KeyValuePair{TKey,TValue}"/> resources.
/// </returns>
public override gax::PagedAsyncEnumerable<DiskTypeAggregatedList, scg::KeyValuePair<string, DiskTypesScopedList>> AggregatedListAsync(AggregatedListDiskTypesRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_AggregatedListDiskTypesRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedAsyncEnumerable<AggregatedListDiskTypesRequest, DiskTypeAggregatedList, scg::KeyValuePair<string, DiskTypesScopedList>>(_callAggregatedList, request, callSettings);
}
/// <summary>
/// Returns the specified disk type. Gets a list of available disk types by making a list() request.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override DiskType Get(GetDiskTypeRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetDiskTypeRequest(ref request, ref callSettings);
return _callGet.Sync(request, callSettings);
}
/// <summary>
/// Returns the specified disk type. Gets a list of available disk types by making a list() request.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<DiskType> GetAsync(GetDiskTypeRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetDiskTypeRequest(ref request, ref callSettings);
return _callGet.Async(request, callSettings);
}
/// <summary>
/// Retrieves a list of disk types available to the specified project.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="DiskType"/> resources.</returns>
public override gax::PagedEnumerable<DiskTypeList, DiskType> List(ListDiskTypesRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListDiskTypesRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedEnumerable<ListDiskTypesRequest, DiskTypeList, DiskType>(_callList, request, callSettings);
}
/// <summary>
/// Retrieves a list of disk types available to the specified project.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="DiskType"/> resources.</returns>
public override gax::PagedAsyncEnumerable<DiskTypeList, DiskType> ListAsync(ListDiskTypesRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListDiskTypesRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedAsyncEnumerable<ListDiskTypesRequest, DiskTypeList, DiskType>(_callList, request, callSettings);
}
}
public partial class AggregatedListDiskTypesRequest : gaxgrpc::IPageRequest
{
/// <inheritdoc/>
public int PageSize
{
get => checked((int)MaxResults);
set => MaxResults = checked((uint)value);
}
}
public partial class ListDiskTypesRequest : gaxgrpc::IPageRequest
{
/// <inheritdoc/>
public int PageSize
{
get => checked((int)MaxResults);
set => MaxResults = checked((uint)value);
}
}
public partial class DiskTypeAggregatedList : gaxgrpc::IPageResponse<scg::KeyValuePair<string, DiskTypesScopedList>>
{
/// <summary>Returns an enumerator that iterates through the resources in this response.</summary>
public scg::IEnumerator<scg::KeyValuePair<string, DiskTypesScopedList>> GetEnumerator() => Items.GetEnumerator();
sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator();
}
public partial class DiskTypeList : gaxgrpc::IPageResponse<DiskType>
{
/// <summary>Returns an enumerator that iterates through the resources in this response.</summary>
public scg::IEnumerator<DiskType> GetEnumerator() => Items.GetEnumerator();
sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator();
}
}
| |
// 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.Globalization;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Text;
namespace System
{
// A Version object contains four hierarchical numeric components: major, minor,
// build and revision. Build and revision may be unspecified, which is represented
// internally as a -1. By definition, an unspecified component matches anything
// (both unspecified and specified), and an unspecified component is "less than" any
// specified component.
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public sealed class Version : ICloneable, IComparable
, IComparable<Version>, IEquatable<Version>
{
// AssemblyName depends on the order staying the same
private readonly int _Major; // Do not rename (binary serialization)
private readonly int _Minor; // Do not rename (binary serialization)
private readonly int _Build = -1; // Do not rename (binary serialization)
private readonly int _Revision = -1; // Do not rename (binary serialization)
public Version(int major, int minor, int build, int revision)
{
if (major < 0)
throw new ArgumentOutOfRangeException(nameof(major), SR.ArgumentOutOfRange_Version);
if (minor < 0)
throw new ArgumentOutOfRangeException(nameof(minor), SR.ArgumentOutOfRange_Version);
if (build < 0)
throw new ArgumentOutOfRangeException(nameof(build), SR.ArgumentOutOfRange_Version);
if (revision < 0)
throw new ArgumentOutOfRangeException(nameof(revision), SR.ArgumentOutOfRange_Version);
Contract.EndContractBlock();
_Major = major;
_Minor = minor;
_Build = build;
_Revision = revision;
}
public Version(int major, int minor, int build)
{
if (major < 0)
throw new ArgumentOutOfRangeException(nameof(major), SR.ArgumentOutOfRange_Version);
if (minor < 0)
throw new ArgumentOutOfRangeException(nameof(minor), SR.ArgumentOutOfRange_Version);
if (build < 0)
throw new ArgumentOutOfRangeException(nameof(build), SR.ArgumentOutOfRange_Version);
Contract.EndContractBlock();
_Major = major;
_Minor = minor;
_Build = build;
}
public Version(int major, int minor)
{
if (major < 0)
throw new ArgumentOutOfRangeException(nameof(major), SR.ArgumentOutOfRange_Version);
if (minor < 0)
throw new ArgumentOutOfRangeException(nameof(minor), SR.ArgumentOutOfRange_Version);
Contract.EndContractBlock();
_Major = major;
_Minor = minor;
}
public Version(String version)
{
Version v = Version.Parse(version);
_Major = v.Major;
_Minor = v.Minor;
_Build = v.Build;
_Revision = v.Revision;
}
public Version()
{
_Major = 0;
_Minor = 0;
}
private Version(Version version)
{
Debug.Assert(version != null);
_Major = version._Major;
_Minor = version._Minor;
_Build = version._Build;
_Revision = version._Revision;
}
public object Clone()
{
return new Version(this);
}
// Properties for setting and getting version numbers
public int Major
{
get { return _Major; }
}
public int Minor
{
get { return _Minor; }
}
public int Build
{
get { return _Build; }
}
public int Revision
{
get { return _Revision; }
}
public short MajorRevision
{
get { return (short)(_Revision >> 16); }
}
public short MinorRevision
{
get { return (short)(_Revision & 0xFFFF); }
}
public int CompareTo(Object version)
{
if (version == null)
{
return 1;
}
Version v = version as Version;
if (v == null)
{
throw new ArgumentException(SR.Arg_MustBeVersion);
}
return CompareTo(v);
}
public int CompareTo(Version value)
{
return
object.ReferenceEquals(value, this) ? 0 :
object.ReferenceEquals(value, null) ? 1 :
_Major != value._Major ? (_Major > value._Major ? 1 : -1) :
_Minor != value._Minor ? (_Minor > value._Minor ? 1 : -1) :
_Build != value._Build ? (_Build > value._Build ? 1 : -1) :
_Revision != value._Revision ? (_Revision > value._Revision ? 1 : -1) :
0;
}
public override bool Equals(Object obj)
{
return Equals(obj as Version);
}
public bool Equals(Version obj)
{
return object.ReferenceEquals(obj, this) ||
(!object.ReferenceEquals(obj, null) &&
_Major == obj._Major &&
_Minor == obj._Minor &&
_Build == obj._Build &&
_Revision == obj._Revision);
}
public override int GetHashCode()
{
// Let's assume that most version numbers will be pretty small and just
// OR some lower order bits together.
int accumulator = 0;
accumulator |= (_Major & 0x0000000F) << 28;
accumulator |= (_Minor & 0x000000FF) << 20;
accumulator |= (_Build & 0x000000FF) << 12;
accumulator |= (_Revision & 0x00000FFF);
return accumulator;
}
public override string ToString() =>
ToString(DefaultFormatFieldCount);
public string ToString(int fieldCount) =>
fieldCount == 0 ? string.Empty :
fieldCount == 1 ? _Major.ToString() :
StringBuilderCache.GetStringAndRelease(ToCachedStringBuilder(fieldCount));
public bool TryFormat(Span<char> destination, out int charsWritten) =>
TryFormat(destination, DefaultFormatFieldCount, out charsWritten);
public bool TryFormat(Span<char> destination, int fieldCount, out int charsWritten)
{
if (fieldCount == 0)
{
charsWritten = 0;
return true;
}
// TODO https://github.com/dotnet/corefx/issues/22403: fieldCount==1 can just use int.TryFormat
StringBuilder sb = ToCachedStringBuilder(fieldCount);
if (sb.Length <= destination.Length)
{
sb.CopyTo(0, destination, sb.Length);
StringBuilderCache.Release(sb);
charsWritten = sb.Length;
return true;
}
StringBuilderCache.Release(sb);
charsWritten = 0;
return false;
}
private int DefaultFormatFieldCount =>
_Build == -1 ? 2 :
_Revision == -1 ? 3 :
4;
private StringBuilder ToCachedStringBuilder(int fieldCount)
{
if (fieldCount == 1)
{
StringBuilder sb = StringBuilderCache.Acquire();
AppendNonNegativeNumber(_Major, sb);
return sb;
}
else if (fieldCount == 2)
{
StringBuilder sb = StringBuilderCache.Acquire();
AppendNonNegativeNumber(_Major, sb);
sb.Append('.');
AppendNonNegativeNumber(_Minor, sb);
return sb;
}
else
{
if (_Build == -1)
{
throw new ArgumentException(SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, "0", "2"), nameof(fieldCount));
}
if (fieldCount == 3)
{
StringBuilder sb = StringBuilderCache.Acquire();
AppendNonNegativeNumber(_Major, sb);
sb.Append('.');
AppendNonNegativeNumber(_Minor, sb);
sb.Append('.');
AppendNonNegativeNumber(_Build, sb);
return sb;
}
if (_Revision == -1)
{
throw new ArgumentException(SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, "0", "3"), nameof(fieldCount));
}
if (fieldCount == 4)
{
StringBuilder sb = StringBuilderCache.Acquire();
AppendNonNegativeNumber(_Major, sb);
sb.Append('.');
AppendNonNegativeNumber(_Minor, sb);
sb.Append('.');
AppendNonNegativeNumber(_Build, sb);
sb.Append('.');
AppendNonNegativeNumber(_Revision, sb);
return sb;
}
throw new ArgumentException(SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, "0", "4"), nameof(fieldCount));
}
}
// TODO https://github.com/dotnet/corefx/issues/22616:
// Use StringBuilder.Append(int) once it's been updated to use spans internally.
//
// AppendNonNegativeNumber is an optimization to append a number to a StringBuilder object without
// doing any boxing and not even creating intermediate string.
// Note: as we always have positive numbers then it is safe to convert the number to string
// regardless of the current culture as we'll not have any punctuation marks in the number
private static void AppendNonNegativeNumber(int num, StringBuilder sb)
{
Debug.Assert(num >= 0, "AppendPositiveNumber expect positive numbers");
int index = sb.Length;
do
{
num = Math.DivRem(num, 10, out int remainder);
sb.Insert(index, (char)('0' + remainder));
} while (num > 0);
}
public static Version Parse(string input)
{
if (input == null)
{
throw new ArgumentNullException(nameof(input));
}
return ParseVersion(input.AsReadOnlySpan(), throwOnFailure: true);
}
public static Version Parse(ReadOnlySpan<char> input) =>
ParseVersion(input, throwOnFailure: true);
public static bool TryParse(string input, out Version result)
{
if (input == null)
{
result = null;
return false;
}
return (result = ParseVersion(input.AsReadOnlySpan(), throwOnFailure: false)) != null;
}
public static bool TryParse(ReadOnlySpan<char> input, out Version result) =>
(result = ParseVersion(input, throwOnFailure: false)) != null;
private static Version ParseVersion(ReadOnlySpan<char> input, bool throwOnFailure)
{
// Find the separator between major and minor. It must exist.
int majorEnd = input.IndexOf('.');
if (majorEnd < 0)
{
if (throwOnFailure) throw new ArgumentException(SR.Arg_VersionString, nameof(input));
return null;
}
// Find the ends of the optional minor and build portions.
// We musn't have any separators after build.
int buildEnd = -1;
int minorEnd = input.IndexOf('.', majorEnd + 1);
if (minorEnd != -1)
{
buildEnd = input.IndexOf('.', minorEnd + 1);
if (buildEnd != -1)
{
if (input.IndexOf('.', buildEnd + 1) != -1)
{
if (throwOnFailure) throw new ArgumentException(SR.Arg_VersionString, nameof(input));
return null;
}
}
}
int major, minor, build, revision;
// Parse the major version
if (!TryParseComponent(input.Slice(0, majorEnd), nameof(input), throwOnFailure, out major))
{
return null;
}
if (minorEnd != -1)
{
// If there's more than a major and minor, parse the minor, too.
if (!TryParseComponent(input.Slice(majorEnd + 1, minorEnd - majorEnd - 1), nameof(input), throwOnFailure, out minor))
{
return null;
}
if (buildEnd != -1)
{
// major.minor.build.revision
return
TryParseComponent(input.Slice(minorEnd + 1, buildEnd - minorEnd - 1), nameof(build), throwOnFailure, out build) &&
TryParseComponent(input.Slice(buildEnd + 1), nameof(revision), throwOnFailure, out revision) ?
new Version(major, minor, build, revision) :
null;
}
else
{
// major.minor.build
return TryParseComponent(input.Slice(minorEnd + 1), nameof(build), throwOnFailure, out build) ?
new Version(major, minor, build) :
null;
}
}
else
{
// major.minor
return TryParseComponent(input.Slice(majorEnd + 1), nameof(input), throwOnFailure, out minor) ?
new Version(major, minor) :
null;
}
}
private static bool TryParseComponent(ReadOnlySpan<char> component, string componentName, bool throwOnFailure, out int parsedComponent)
{
if (throwOnFailure)
{
if ((parsedComponent = int.Parse(component, NumberStyles.Integer, CultureInfo.InvariantCulture)) < 0)
{
throw new ArgumentOutOfRangeException(componentName, SR.ArgumentOutOfRange_Version);
}
return true;
}
return int.TryParse(component, out parsedComponent, NumberStyles.Integer, CultureInfo.InvariantCulture) && parsedComponent >= 0;
}
public static bool operator ==(Version v1, Version v2)
{
if (Object.ReferenceEquals(v1, null))
{
return Object.ReferenceEquals(v2, null);
}
return v1.Equals(v2);
}
public static bool operator !=(Version v1, Version v2)
{
return !(v1 == v2);
}
public static bool operator <(Version v1, Version v2)
{
if ((Object)v1 == null)
throw new ArgumentNullException(nameof(v1));
Contract.EndContractBlock();
return (v1.CompareTo(v2) < 0);
}
public static bool operator <=(Version v1, Version v2)
{
if ((Object)v1 == null)
throw new ArgumentNullException(nameof(v1));
Contract.EndContractBlock();
return (v1.CompareTo(v2) <= 0);
}
public static bool operator >(Version v1, Version v2)
{
return (v2 < v1);
}
public static bool operator >=(Version v1, Version v2)
{
return (v2 <= v1);
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="VirtualProductResolver.cs" company="Sitecore Corporation">
// Copyright (c) Sitecore Corporation 1999-2015
// </copyright>
// <summary>
// The virtual product resolver.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
// Copyright 2015 Sitecore Corporation A/S
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
// -------------------------------------------------------------------------------------------
namespace Sitecore.Ecommerce.Catalogs
{
using System.Collections;
using Diagnostics;
using Links;
using Microsoft.Practices.Unity;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Ecommerce.Unity;
using Utils;
/// <summary>
/// The virtual product resolver.
/// </summary>
public class VirtualProductResolver
{
/// <summary>
/// The product URL collection.
/// </summary>
private static Hashtable productsUrlsCollection = Hashtable.Synchronized(new Hashtable());
/// <summary>
/// The productBase temlate Id.
/// </summary>
private readonly ID productBaseTemplateId = new ID(Configuration.Settings.GetSetting("Ecommerce.Product.BaseTemplateId"));
/// <summary>
/// The parameters.
/// </summary>
protected VirtualProductResolverArgs parameters;
/// <summary>
/// Initializes a new instance of the <see cref="VirtualProductResolver"/> class.
/// </summary>
/// <param name="resolverArgs">The resolver args.</param>
public VirtualProductResolver(VirtualProductResolverArgs resolverArgs)
{
Assert.ArgumentNotNull(resolverArgs, "resolverArgs");
this.parameters = resolverArgs;
}
/// <summary>
/// Gets or sets the product catalog item.
/// </summary>
/// <value>The product catalog item.</value>
public virtual Item ProductCatalogItem
{
get
{
if (System.Web.HttpContext.Current == null)
{
return default(Item);
}
string productCatalogItemUri = System.Web.HttpContext.Current.Items["CatalogItemUri"] as string;
return string.IsNullOrEmpty(productCatalogItemUri) ? Sitecore.Context.Item : Database.GetItem(new ItemUri(productCatalogItemUri));
}
set
{
if (System.Web.HttpContext.Current != null)
{
string uri = value != null ? value.Uri.ToString() : string.Empty;
System.Web.HttpContext.Current.Items["CatalogItemUri"] = uri;
}
}
}
/// <summary>
/// Gets or sets the prodcut presentation item.
/// </summary>
/// <value>The prodcut presentation item.</value>
public virtual Item ProductPresentationItem
{
get
{
if (System.Web.HttpContext.Current == null)
{
return default(Item);
}
string presentationItemUri = System.Web.HttpContext.Current.Items["PresentationItemUri"] as string;
return string.IsNullOrEmpty(presentationItemUri) ? default(Item) : Database.GetItem(new ItemUri(presentationItemUri));
}
set
{
if (System.Web.HttpContext.Current != null)
{
string uri = value != null ? value.Uri.ToString() : string.Empty;
System.Web.HttpContext.Current.Items["PresentationItemUri"] = uri;
}
}
}
/// <summary>
/// Gets or sets the product URL collection.
/// </summary>
/// <value>The product URL collection.</value>
public virtual Hashtable ProductsUrlsCollection
{
get
{
return productsUrlsCollection;
}
set
{
if (!value.IsSynchronized)
{
value = Hashtable.Synchronized(value);
}
productsUrlsCollection = value;
}
}
/// <summary>
/// Gets the product item by URL.
/// </summary>
/// <param name="url">The full URL.</param>
/// <returns>The product item by URL.</returns>
public virtual Item GetProductItem(string url)
{
Assert.ArgumentNotNullOrEmpty(url, "url");
object value;
lock (this.ProductsUrlsCollection.SyncRoot)
{
value = this.ProductsUrlsCollection[System.Web.HttpUtility.UrlDecode(url)];
}
if (value == null)
{
Log.Debug("Unable to parse product url '{0}'.".FormatWith(url), this);
this.ProductCatalogItem = default(Item);
this.ProductPresentationItem = default(Item);
return default(Item);
}
ProductUriLine productUriLine = (ProductUriLine)value;
Item productItem = Database.GetItem(new ItemUri(productUriLine.ProductItemUri));
this.ProductPresentationItem = Database.GetItem(new ItemUri(productUriLine.ProductPresentationItemUri));
this.ProductCatalogItem = Database.GetItem(new ItemUri(productUriLine.ProductCatalogItemUri));
return productItem;
}
/// <summary>
/// Gets the virtual product URL.
/// </summary>
/// <param name="catalogItem">The catalog item.</param>
/// <param name="productItem">The product item.</param>
/// <returns>The virtual product URL.</returns>
public virtual string GetVirtualProductUrl(Item catalogItem, Item productItem)
{
Assert.ArgumentNotNull(catalogItem, "catalogItem");
Assert.ArgumentNotNull(productItem, "productItem");
if (catalogItem.Template != null && ProductRepositoryUtil.IsBasedOnTemplate(catalogItem.Template, this.productBaseTemplateId))
{
if (this.ProductCatalogItem != default(Item) && !ProductRepositoryUtil.IsBasedOnTemplate(this.ProductCatalogItem.Template, this.productBaseTemplateId))
{
catalogItem = this.ProductCatalogItem;
}
else
{
lock (this.ProductsUrlsCollection.SyncRoot)
{
foreach (DictionaryEntry dictionaryEntry in this.ProductsUrlsCollection)
{
var uriLine = (ProductUriLine)dictionaryEntry.Value;
if (string.Compare(uriLine.ProductItemUri, catalogItem.Uri.ToString(), true) == 0)
{
catalogItem = Database.GetItem(new ItemUri(uriLine.ProductCatalogItemUri));
}
}
}
}
}
string key = this.GetDisplayProductsModeKey(catalogItem);
// NOTE: Check whether items are presented in the url collection
lock (this.ProductsUrlsCollection.SyncRoot)
{
foreach (DictionaryEntry entry in this.ProductsUrlsCollection)
{
ProductUriLine line = (ProductUriLine)entry.Value;
if (line.ProductItemUri == productItem.Uri.ToString() && line.ProductCatalogItemUri == catalogItem.Uri.ToString() && line.DisplayProductsMode == key)
{
return System.Web.HttpUtility.UrlPathEncode(entry.Key as string);
}
}
}
ProductUrlProcessor productUrlBuilder;
if (Context.Entity.HasRegistration(typeof(ProductUrlProcessor), key))
{
productUrlBuilder = Context.Entity.Resolve<ProductUrlProcessor>(key);
}
else
{
Log.Warn(string.Format("ProductUrlProcessor is not defined with the name: {0}. Check Unity.config file.", key), this);
return LinkManager.GetItemUrl(productItem);
}
string url = productUrlBuilder.GetProductUrl(catalogItem, productItem).ToString();
Item productPresentationItem = this.GetProductPresentationItem(catalogItem);
Assert.IsNotNull(productPresentationItem, "Product presentation item is null");
ProductUriLine productUriLine = new ProductUriLine
{
ProductItemUri = productItem.Uri.ToString(),
ProductCatalogItemUri = catalogItem.Uri.ToString(),
ProductPresentationItemUri = productPresentationItem.Uri.ToString(),
DisplayProductsMode = key,
};
string result = System.Web.HttpUtility.UrlDecode(url);
lock (this.ProductsUrlsCollection.SyncRoot)
{
this.ProductsUrlsCollection[result] = productUriLine;
}
return System.Web.HttpUtility.UrlPathEncode(url);
}
/// <summary>
/// Gets the product presentation item.
/// </summary>
/// <param name="catalogItem">The catalog item.</param>
/// <returns>The product presentation item.</returns>
public virtual Item GetProductPresentationItem(Item catalogItem)
{
string productPresentationItemId = this.GetFirstAscendantOrSelfWithValueFromItem(this.parameters.ProductDetailPresentationStorageField, catalogItem);
if (string.IsNullOrEmpty(productPresentationItemId) || !ID.IsID(productPresentationItemId))
{
return default(Item);
}
return catalogItem.Database.GetItem(productPresentationItemId);
}
/// <summary>
/// Gets the display products mode key.
/// </summary>
/// <param name="catalogItem">The catalog item.</param>
/// <returns>The display products mode key.</returns>
public virtual string GetDisplayProductsModeKey(Item catalogItem)
{
Assert.ArgumentNotNull(catalogItem, "catalogItem");
string displayModeId = this.GetFirstAscendantOrSelfWithValueFromItem(this.parameters.DisplayProductsModeField, catalogItem);
if (string.IsNullOrEmpty(displayModeId))
{
return null;
}
Assert.IsTrue(ID.IsID(displayModeId), "Display Products Mode value is invalid item reference.");
Item displayProductsModeItem = Sitecore.Context.Database.GetItem(displayModeId); // Item in folder: "/sitecore/system/Modules/Ecommerce/System/Display Product Modes"
Assert.IsNotNull(displayProductsModeItem, "Display Products Mode item is null or not found.");
string key = displayProductsModeItem[this.parameters.DisplayProductsModeKeyField];
Assert.IsNotNullOrEmpty(key, "Display Products Mode Key is invalid.");
return key;
}
/// <summary>
/// Gets the first ascendant or self with value from item.
/// </summary>
/// <param name="field">The field.</param>
/// <param name="item">The current item.</param>
/// <returns>The first ascendant or self with value from item.</returns>
protected virtual string GetFirstAscendantOrSelfWithValueFromItem(string field, Item item)
{
while (item != null && item[field] == string.Empty)
{
item = item.Parent;
}
return item != null ? item[field] : string.Empty;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System;
using System.Collections;
using System.Collections.Specialized;
using GenStrings;
namespace System.Collections.Specialized.Tests
{
public class CopyToStrAIntTests
{
public const int MAX_LEN = 50; // max length of random strings
[Fact]
public void Test01()
{
IntlStrings intl;
StringCollection sc;
// simple string values
string[] values =
{
"",
" ",
"a",
"aa",
"text",
" spaces",
"1",
"$%^#",
"2222222222222222222222222",
System.DateTime.Today.ToString(),
Int32.MaxValue.ToString()
};
string[] destination;
int cnt = 0; // Count
// initialize IntStrings
intl = new IntlStrings();
// [] StringCollection is constructed as expected
//-----------------------------------------------------------------
sc = new StringCollection();
// [] Copy empty collection into empty array
//
destination = new string[values.Length];
for (int i = 0; i < values.Length; i++)
{
destination[i] = "";
}
sc.CopyTo(destination, 0);
if (destination.Length != values.Length)
{
Assert.False(true, string.Format("Error, altered array after copying empty collection"));
}
if (destination.Length == values.Length)
{
for (int i = 0; i < values.Length; i++)
{
if (String.Compare(destination[i], "") != 0)
{
Assert.False(true, string.Format("Error, item = \"{1}\" insteead of \"{2}\" after copying empty collection", i, destination[i], ""));
}
}
}
// [] Copy empty collection into non-empty array
//
destination = values;
sc.CopyTo(destination, 0);
if (destination.Length != values.Length)
{
Assert.False(true, string.Format("Error, altered array after copying empty collection"));
}
if (destination.Length == values.Length)
{
for (int i = 0; i < values.Length; i++)
{
if (String.Compare(destination[i], values[i]) != 0)
{
Assert.False(true, string.Format("Error, altered item {0} after copying empty collection", i));
}
}
}
//
// [] add simple strings and CopyTo([], 0)
cnt = sc.Count;
sc.AddRange(values);
if (sc.Count != values.Length)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", sc.Count, values.Length));
}
destination = new string[values.Length];
sc.CopyTo(destination, 0);
for (int i = 0; i < values.Length; i++)
{
// verify that collection is copied correctly
//
if (String.Compare(sc[i], destination[i]) != 0)
{
Assert.False(true, string.Format("Error, copied \"{1}\" instead of \"{2}\"", i, destination[i], sc[i]));
}
}
// [] add simple strings and CopyTo([], middle_index)
//
sc.Clear();
cnt = sc.Count;
sc.AddRange(values);
if (sc.Count != values.Length)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", sc.Count, values.Length));
}
destination = new string[values.Length * 2];
sc.CopyTo(destination, values.Length);
for (int i = 0; i < values.Length; i++)
{
// verify that collection is copied correctly
//
if (String.Compare(sc[i], destination[i + values.Length]) != 0)
{
Assert.False(true, string.Format("Error, copied \"{1}\" instead of \"{2}\"", i, destination[i + values.Length], sc[i]));
}
}
//
// Intl strings
// [] add intl strings and CopyTo([], 0)
//
string[] intlValues = new string[values.Length];
// fill array with unique strings
//
for (int i = 0; i < values.Length; i++)
{
string val = intl.GetRandomString(MAX_LEN);
while (Array.IndexOf(intlValues, val) != -1)
val = intl.GetRandomString(MAX_LEN);
intlValues[i] = val;
}
sc.Clear();
sc.AddRange(intlValues);
if (sc.Count != (intlValues.Length))
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", sc.Count, intlValues.Length));
}
destination = new string[intlValues.Length];
sc.CopyTo(destination, 0);
for (int i = 0; i < intlValues.Length; i++)
{
// verify that collection is copied correctly
//
if (String.Compare(sc[i], destination[i]) != 0)
{
Assert.False(true, string.Format("Error, copied \"{1}\" instead of \"{2}\"", i, destination[i], sc[i]));
}
}
//
// Intl strings
// [] add intl strings and CopyTo([], middle_index)
//
sc.Clear();
sc.AddRange(intlValues);
if (sc.Count != (intlValues.Length))
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", sc.Count, intlValues.Length));
}
destination = new string[intlValues.Length * 2];
sc.CopyTo(destination, intlValues.Length);
for (int i = 0; i < intlValues.Length; i++)
{
// verify that collection is copied correctly
//
if (String.Compare(sc[i], destination[i + intlValues.Length]) != 0)
{
Assert.False(true, string.Format("Error, copied \"{1}\" instead of \"{2}\"", i, destination[i + intlValues.Length], sc[i]));
}
}
//
// [] CopyTo(null, int)
//
sc.Clear();
sc.AddRange(values);
if (sc.Count != (intlValues.Length))
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", sc.Count, intlValues.Length));
}
destination = null;
Assert.Throws<ArgumentNullException>(() => { sc.CopyTo(destination, 0); });
//
// [] CopyTo(string[], -1)
//
if (sc.Count != values.Length)
{
sc.Clear();
sc.AddRange(values);
if (sc.Count != (intlValues.Length))
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", sc.Count, intlValues.Length));
}
}
destination = new string[values.Length];
Assert.Throws<ArgumentOutOfRangeException>(() => { sc.CopyTo(destination, -1); });
//
// [] CopyTo(string[], upperBound+1)
//
if (sc.Count != values.Length)
{
sc.Clear();
sc.AddRange(values);
if (sc.Count != (intlValues.Length))
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", sc.Count, intlValues.Length));
}
}
destination = new string[values.Length];
Assert.Throws<ArgumentException>(() => { sc.CopyTo(destination, values.Length); });
//
// [] CopyTo(string[], upperBound+2)
//
if (sc.Count != values.Length)
{
sc.Clear();
sc.AddRange(values);
if (sc.Count != (intlValues.Length + 1))
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", sc.Count, intlValues.Length));
}
}
destination = new string[values.Length];
Assert.Throws<ArgumentException>(() => { sc.CopyTo(destination, values.Length); });
//
// [] CopyTo(string[], not_enough_space)
//
if (sc.Count != values.Length)
{
sc.Clear();
sc.AddRange(values);
if (sc.Count != (intlValues.Length))
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", sc.Count, intlValues.Length));
}
}
destination = new string[values.Length];
Assert.Throws<ArgumentException>(() => { sc.CopyTo(destination, values.Length / 2); });
}
}
}
| |
//
// SegmentIntersector.cs
// MSAGL class for intersecting Rectilinear Edge Routing ScanLine segments.
//
// Copyright Microsoft Corporation.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.Msagl.Core.DataStructures;
using Microsoft.Msagl.Core.Geometry;
using Microsoft.Msagl.Routing.Visibility;
namespace Microsoft.Msagl.Routing.Rectilinear {
internal class SegmentIntersector : IComparer<SegmentIntersector.SegEvent>, IComparer<ScanSegment> {
// The event types. We sweep vertically, with a horizontal scanline, so the vertical
// segments that are active and have X coords within the current vertical segment's
// span all create intersections with it. All events are ordered on Y coordinate then X.
internal SegmentIntersector() {
verticalSegmentsScanLine = new RbTree<ScanSegment>(this);
findFirstPred = new Func<ScanSegment, bool>(IsVSegInHSegRange);
}
bool IsVSegInHSegRange(ScanSegment v) {
return PointComparer.Compare(v.Start.X, findFirstHSeg.Start.X) >= 0;
}
// This creates the VisibilityVertex objects along the segments.
internal VisibilityGraph Generate(IEnumerable<ScanSegment> hSegments, IEnumerable<ScanSegment> vSegments) {
foreach (ScanSegment seg in vSegments) {
eventList.Add(new SegEvent(SegEventType.VOpen, seg));
eventList.Add(new SegEvent(SegEventType.VClose, seg));
}
foreach (ScanSegment seg in hSegments) {
eventList.Add(new SegEvent(SegEventType.HOpen, seg));
}
if (0 == eventList.Count) {
return null; // empty
}
eventList.Sort(this);
// Note: We don't need any sentinels in the scanline here, because the lowest VOpen
// events are loaded before the first HOpen is.
// Process all events.
visGraph = VisibilityGraphGenerator.NewVisibilityGraph();
foreach (SegEvent evt in eventList) {
switch (evt.EventType) {
case SegEventType.VOpen:
OnSegmentOpen(evt.Segment);
ScanInsert(evt.Segment);
break;
case SegEventType.VClose:
OnSegmentClose(evt.Segment);
ScanRemove(evt.Segment);
break;
case SegEventType.HOpen:
OnSegmentOpen(evt.Segment);
ScanIntersect(evt.Segment);
break;
default:
Debug.Assert(false, "Unknown SegEventType");
// ReSharper disable HeuristicUnreachableCode
break;
// ReSharper restore HeuristicUnreachableCode
}
} // endforeach
return visGraph;
}
void OnSegmentOpen(ScanSegment seg) {
seg.OnSegmentIntersectorBegin(visGraph);
}
void OnSegmentClose(ScanSegment seg) {
seg.OnSegmentIntersectorEnd(visGraph);
if (null == seg.LowestVisibilityVertex) {
segmentsWithoutVisibility.Add(seg);
}
}
// Scan segments with no visibility will usually be internal to an overlap clump,
// but may be in an external "corner" of intersecting sides for a small enough span
// that no other segment crosses them. In that case we don't need them and they
// would require extra handling later.
internal void RemoveSegmentsWithNoVisibility(ScanSegmentTree horizontalScanSegments,
ScanSegmentTree verticalScanSegments) {
foreach (ScanSegment seg in segmentsWithoutVisibility) {
(seg.IsVertical ? verticalScanSegments : horizontalScanSegments).Remove(seg);
}
}
#region Scanline utilities
void ScanInsert(ScanSegment seg) {
Debug.Assert(null == this.verticalSegmentsScanLine.Find(seg), "seg already exists in the rbtree");
// RBTree's internal operations on insert/remove etc. mean the node can't cache the
// RBNode returned by insert(); instead we must do find() on each call. But we can
// use the returned node to get predecessor/successor.
verticalSegmentsScanLine.Insert(seg);
}
void ScanRemove(ScanSegment seg) {
verticalSegmentsScanLine.Remove(seg);
}
void ScanIntersect(ScanSegment hSeg) {
// Find the VSeg in the scanline with the lowest X-intersection with HSeg, then iterate
// all VSegs in the scan line after that until we leave the HSeg range.
// We only use FindFirstHSeg in this routine, to find the first satisfying node,
// so we don't care that we leave leftovers in it.
findFirstHSeg = hSeg;
RBNode<ScanSegment> segNode = verticalSegmentsScanLine.FindFirst(findFirstPred);
for (; null != segNode; segNode = verticalSegmentsScanLine.Next(segNode)) {
ScanSegment vSeg = segNode.Item;
if (1 == PointComparer.Compare(vSeg.Start.X, hSeg.End.X)) {
break; // Out of HSeg range
}
VisibilityVertex newVertex = visGraph.AddVertex(new Point(vSeg.Start.X, hSeg.Start.Y));
// HSeg has just opened so if we are overlapped and newVertex already existed,
// it was because we just closed a previous HSeg or VSeg and are now opening one
// whose Start is the same as previous. So we may be appending a vertex that
// is already the *Seg.HighestVisibilityVertex, which will be a no-op. Otherwise
// this will add a (possibly Overlapped)VisibilityEdge in the *Seg direction.
hSeg.AppendVisibilityVertex(visGraph, newVertex);
vSeg.AppendVisibilityVertex(visGraph, newVertex);
} // endforeach scanline VSeg in range
OnSegmentClose(hSeg);
}
// end ScanIntersect()
#endregion // Scanline utilities
#region IComparer<SegEvent>
/// <summary>
/// For ordering events first by Y, then X, then by whether it's an H or V seg.
/// </summary>
/// <param name="first"></param>
/// <param name="second"></param>
/// <returns></returns>
public int Compare(SegEvent first, SegEvent second) {
if (first == second) {
return 0;
}
if (first == null) {
return -1;
}
if (second == null) {
return 1;
}
// Unlike the ScanSegment-generating scanline in VisibilityGraphGenerator, this scanline has no slope
// calculations so no additional rounding error is introduced.
int cmp = PointComparer.Compare(first.Site.Y, second.Site.Y);
if (0 != cmp) {
return cmp;
}
// Both are at same Y so we must ensure that for equivalent Y, VClose comes after
// HOpen which comes after VOpen, thus make sure VOpen comes before VClose.
if (first.IsVertical && second.IsVertical) {
// Separate segments may join at Start and End due to overlap.
Debug.Assert(!StaticGraphUtility.IntervalsOverlap(first.Segment, second.Segment)
|| (0 == PointComparer.Compare(first.Segment.Start, second.Segment.End))
|| (0 == PointComparer.Compare(first.Segment.End, second.Segment.Start))
, "V subsumption failure detected in SegEvent comparison");
if (0 == cmp) {
// false is < true.
cmp = (SegEventType.VClose == first.EventType).CompareTo(SegEventType.VClose == second.EventType);
}
return cmp;
}
// If both are H segs, then sub-order by X.
if (!first.IsVertical && !second.IsVertical) {
// Separate segments may join at Start and End due to overlap, so compare by Start.X;
// the ending segment (lowest Start.X) comes before the Open (higher Start.X).
Debug.Assert(!StaticGraphUtility.IntervalsOverlap(first.Segment, second.Segment)
|| (0 == PointComparer.Compare(first.Segment.Start, second.Segment.End))
|| (0 == PointComparer.Compare(first.Segment.End, second.Segment.Start))
, "H subsumption failure detected in SegEvent comparison");
cmp = PointComparer.Compare(first.Site.X, second.Site.X);
return cmp;
}
// One is Vertical and one is Horizontal; we are only interested in the vertical at this point.
SegEvent vEvent = first.IsVertical ? first : second;
// Make sure that we have opened all V segs before and closed them after opening
// an H seg at the same Y coord. Otherwise we'll miss "T" or "corner" intersections.
// (RectilinearTests.Connected_Vertical_Segments_Are_Intersected tests that we get the expected count here.)
// Start assuming Vevent is 'first' and it's VOpen, which should come before HOpen.
cmp = -1; // Start with first == VOpen
if (SegEventType.VClose == vEvent.EventType) {
cmp = 1; // change to first == VClose
}
if (vEvent != first) {
cmp *= -1; // undo the swap.
}
return cmp;
}
#endregion // IComparer<SegEvent>
#region IComparer<ScanSegment>
/// <summary>
/// For ordering V segments in the scanline by X.
/// </summary>
/// <param name="first"></param>
/// <param name="second"></param>
/// <returns></returns>
public int Compare(ScanSegment first, ScanSegment second) {
if (first == second) {
return 0;
}
if (first == null) {
return -1;
}
if (second == null) {
return 1;
}
// Note: Unlike the ScanSegment-generating scanline, this scanline has no slope
// calculations so no additional rounding error is introduced.
int cmp = PointComparer.Compare(first.Start.X, second.Start.X);
// Separate segments may join at Start and End due to overlap, so compare the Y positions;
// the Close (lowest Y) comes before the Open.
if (0 == cmp) {
cmp = PointComparer.Compare(first.Start.Y, second.Start.Y);
}
return cmp;
}
#endregion // IComparer<ScanSegment>
#region Nested type: SegEvent
internal class SegEvent {
internal SegEvent(SegEventType eventType, ScanSegment seg) {
EventType = eventType;
Segment = seg;
}
internal SegEventType EventType { get; private set; }
internal ScanSegment Segment { get; private set; }
internal bool IsVertical {
get { return (SegEventType.HOpen != EventType); }
}
internal Point Site {
get { return (SegEventType.VClose == EventType) ? Segment.End : Segment.Start; }
}
/// <summary>
/// </summary>
/// <returns></returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object[])")]
public override string ToString() {
return string.Format("{0} {1} {2} {3}", EventType, IsVertical, Site, Segment);
}
}
#endregion
#region Internal data members
// To be returned to caller; created in Generate() and used in ScanGenerate().
// Accumulates the set of events and then sorts them by Y coord.
readonly List<SegEvent> eventList = new List<SegEvent>();
// Tracks the currently open V segments.
readonly Func<ScanSegment, bool> findFirstPred;
readonly List<ScanSegment> segmentsWithoutVisibility = new List<ScanSegment>();
readonly RbTree<ScanSegment> verticalSegmentsScanLine;
// For searching the tree to find the first VSeg for an HSeg.
ScanSegment findFirstHSeg;
VisibilityGraph visGraph;
#endregion // Internal data members
#region Nested type: SegEventType
internal enum SegEventType {
VOpen // Vertical segment start (bottom)
,
VClose // Vertical segment close (top)
,
HOpen // Horizontal segment open (flat, uses left point but could be either)
}
#endregion
}
}
| |
// <copyright file="HttpCommandExecutor.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using OpenQA.Selenium.Internal;
namespace OpenQA.Selenium.Remote
{
/// <summary>
/// Provides a way of executing Commands over HTTP
/// </summary>
public class HttpCommandExecutor : ICommandExecutor
{
private const string JsonMimeType = "application/json";
private const string PngMimeType = "image/png";
private const string Utf8CharsetType = "utf-8";
private const string RequestAcceptHeader = JsonMimeType + ", " + PngMimeType;
private const string UserAgentHeaderTemplate = "selenium/{0} (.net {1})";
private Uri remoteServerUri;
private TimeSpan serverResponseTimeout;
private bool enableKeepAlive;
private bool isDisposed;
private IWebProxy proxy;
private CommandInfoRepository commandInfoRepository = new W3CWireProtocolCommandInfoRepository();
private HttpClient client;
/// <summary>
/// Initializes a new instance of the <see cref="HttpCommandExecutor"/> class
/// </summary>
/// <param name="addressOfRemoteServer">Address of the WebDriver Server</param>
/// <param name="timeout">The timeout within which the server must respond.</param>
public HttpCommandExecutor(Uri addressOfRemoteServer, TimeSpan timeout)
: this(addressOfRemoteServer, timeout, true)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="HttpCommandExecutor"/> class
/// </summary>
/// <param name="addressOfRemoteServer">Address of the WebDriver Server</param>
/// <param name="timeout">The timeout within which the server must respond.</param>
/// <param name="enableKeepAlive"><see langword="true"/> if the KeepAlive header should be sent
/// with HTTP requests; otherwise, <see langword="false"/>.</param>
public HttpCommandExecutor(Uri addressOfRemoteServer, TimeSpan timeout, bool enableKeepAlive)
{
if (addressOfRemoteServer == null)
{
throw new ArgumentNullException("addressOfRemoteServer", "You must specify a remote address to connect to");
}
if (!addressOfRemoteServer.AbsoluteUri.EndsWith("/", StringComparison.OrdinalIgnoreCase))
{
addressOfRemoteServer = new Uri(addressOfRemoteServer.ToString() + "/");
}
this.remoteServerUri = addressOfRemoteServer;
this.serverResponseTimeout = timeout;
this.enableKeepAlive = enableKeepAlive;
}
/// <summary>
/// Occurs when the <see cref="HttpCommandExecutor"/> is sending an HTTP
/// request to the remote end WebDriver implementation.
/// </summary>
public event EventHandler<SendingRemoteHttpRequestEventArgs> SendingRemoteHttpRequest;
/// <summary>
/// Gets the repository of objects containin information about commands.
/// </summary>
public CommandInfoRepository CommandInfoRepository
{
get { return this.commandInfoRepository; }
protected set { this.commandInfoRepository = value; }
}
/// <summary>
/// Gets or sets an <see cref="IWebProxy"/> object to be used to proxy requests
/// between this <see cref="HttpCommandExecutor"/> and the remote end WebDriver
/// implementation.
/// </summary>
public IWebProxy Proxy
{
get { return this.proxy; }
set { this.proxy = value; }
}
/// <summary>
/// Gets or sets a value indicating whether keep-alive is enabled for HTTP
/// communication between this <see cref="HttpCommandExecutor"/> and the
/// remote end WebDriver implementation.
/// </summary>
public bool IsKeepAliveEnabled
{
get { return this.enableKeepAlive; }
set { this.enableKeepAlive = value; }
}
/// <summary>
/// Executes a command
/// </summary>
/// <param name="commandToExecute">The command you wish to execute</param>
/// <returns>A response from the browser</returns>
public virtual Response Execute(Command commandToExecute)
{
if (commandToExecute == null)
{
throw new ArgumentNullException("commandToExecute", "commandToExecute cannot be null");
}
CommandInfo info = this.commandInfoRepository.GetCommandInfo(commandToExecute.Name);
if (info == null)
{
throw new NotImplementedException(string.Format("The command you are attempting to execute, {0}, does not exist in the protocol dialect used by the remote end.", commandToExecute.Name));
}
if (this.client == null)
{
this.CreateHttpClient();
}
HttpRequestInfo requestInfo = new HttpRequestInfo(this.remoteServerUri, commandToExecute, info);
HttpResponseInfo responseInfo = null;
try
{
// Use TaskFactory to avoid deadlock in multithreaded implementations.
responseInfo = new TaskFactory(CancellationToken.None,
TaskCreationOptions.None,
TaskContinuationOptions.None,
TaskScheduler.Default)
.StartNew(() => this.MakeHttpRequest(requestInfo))
.Unwrap()
.GetAwaiter()
.GetResult();
}
catch (HttpRequestException ex)
{
WebException innerWebException = ex.InnerException as WebException;
if (innerWebException != null)
{
if (innerWebException.Status == WebExceptionStatus.Timeout)
{
string timeoutMessage = "The HTTP request to the remote WebDriver server for URL {0} timed out after {1} seconds.";
throw new WebDriverException(string.Format(CultureInfo.InvariantCulture, timeoutMessage, requestInfo.FullUri.AbsoluteUri, this.serverResponseTimeout.TotalSeconds), ex);
}
else if (innerWebException.Status == WebExceptionStatus.ConnectFailure)
{
string connectFailureMessage = "Could not connect to the remote WebDriver server for URL {0}.";
throw new WebDriverException(string.Format(CultureInfo.InvariantCulture, connectFailureMessage, requestInfo.FullUri.AbsoluteUri, this.serverResponseTimeout.TotalSeconds), ex);
}
else if (innerWebException.Response == null)
{
string nullResponseMessage = "A exception with a null response was thrown sending an HTTP request to the remote WebDriver server for URL {0}. The status of the exception was {1}, and the message was: {2}";
throw new WebDriverException(string.Format(CultureInfo.InvariantCulture, nullResponseMessage, requestInfo.FullUri.AbsoluteUri, innerWebException.Status, innerWebException.Message), innerWebException);
}
}
string unknownErrorMessage = "An unknown exception was encountered sending an HTTP request to the remote WebDriver server for URL {0}. The exception message was: {1}";
throw new WebDriverException(string.Format(CultureInfo.InvariantCulture, unknownErrorMessage, requestInfo.FullUri.AbsoluteUri, ex.Message), ex);
}
catch(TaskCanceledException ex)
{
string timeoutMessage = "The HTTP request to the remote WebDriver server for URL {0} timed out after {1} seconds.";
throw new WebDriverException(string.Format(CultureInfo.InvariantCulture, timeoutMessage, requestInfo.FullUri.AbsoluteUri, this.serverResponseTimeout.TotalSeconds), ex);
}
Response toReturn = this.CreateResponse(responseInfo);
return toReturn;
}
/// <summary>
/// Raises the <see cref="SendingRemoteHttpRequest"/> event.
/// </summary>
/// <param name="eventArgs">A <see cref="SendingRemoteHttpRequestEventArgs"/> that contains the event data.</param>
protected virtual void OnSendingRemoteHttpRequest(SendingRemoteHttpRequestEventArgs eventArgs)
{
if (eventArgs == null)
{
throw new ArgumentNullException("eventArgs", "eventArgs must not be null");
}
if (this.SendingRemoteHttpRequest != null)
{
this.SendingRemoteHttpRequest(this, eventArgs);
}
}
private void CreateHttpClient()
{
HttpClientHandler httpClientHandler = new HttpClientHandler();
string userInfo = this.remoteServerUri.UserInfo;
if (!string.IsNullOrEmpty(userInfo) && userInfo.Contains(":"))
{
string[] userInfoComponents = this.remoteServerUri.UserInfo.Split(new char[] { ':' }, 2);
httpClientHandler.Credentials = new NetworkCredential(userInfoComponents[0], userInfoComponents[1]);
httpClientHandler.PreAuthenticate = true;
}
httpClientHandler.Proxy = this.Proxy;
// httpClientHandler.MaxConnectionsPerServer = 2000;
this.client = new HttpClient(httpClientHandler);
string userAgentString = string.Format(CultureInfo.InvariantCulture, UserAgentHeaderTemplate, ResourceUtilities.AssemblyVersion, ResourceUtilities.PlatformFamily);
this.client.DefaultRequestHeaders.UserAgent.ParseAdd(userAgentString);
this.client.DefaultRequestHeaders.Accept.ParseAdd(RequestAcceptHeader);
if (!this.IsKeepAliveEnabled)
{
this.client.DefaultRequestHeaders.Connection.ParseAdd("close");
}
this.client.Timeout = this.serverResponseTimeout;
}
private async Task<HttpResponseInfo> MakeHttpRequest(HttpRequestInfo requestInfo)
{
SendingRemoteHttpRequestEventArgs eventArgs = new SendingRemoteHttpRequestEventArgs(null, requestInfo.RequestBody);
this.OnSendingRemoteHttpRequest(eventArgs);
HttpMethod method = new HttpMethod(requestInfo.HttpMethod);
HttpRequestMessage requestMessage = new HttpRequestMessage(method, requestInfo.FullUri);
if (requestInfo.HttpMethod == CommandInfo.GetCommand)
{
CacheControlHeaderValue cacheControlHeader = new CacheControlHeaderValue();
cacheControlHeader.NoCache = true;
requestMessage.Headers.CacheControl = cacheControlHeader;
}
if (requestInfo.HttpMethod == CommandInfo.PostCommand)
{
MediaTypeWithQualityHeaderValue acceptHeader = new MediaTypeWithQualityHeaderValue(JsonMimeType);
acceptHeader.CharSet = Utf8CharsetType;
requestMessage.Headers.Accept.Add(acceptHeader);
byte[] bytes = Encoding.UTF8.GetBytes(eventArgs.RequestBody);
requestMessage.Content = new ByteArrayContent(bytes, 0, bytes.Length);
}
HttpResponseMessage responseMessage = await this.client.SendAsync(requestMessage);
HttpResponseInfo httpResponseInfo = new HttpResponseInfo();
httpResponseInfo.Body = await responseMessage.Content.ReadAsStringAsync();
httpResponseInfo.ContentType = responseMessage.Content.Headers.ContentType.ToString();
httpResponseInfo.StatusCode = responseMessage.StatusCode;
return httpResponseInfo;
}
private Response CreateResponse(HttpResponseInfo responseInfo)
{
Response response = new Response();
string body = responseInfo.Body;
if (responseInfo.ContentType != null && responseInfo.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
{
response = Response.FromJson(body);
}
else
{
response.Value = body;
}
if (this.CommandInfoRepository.SpecificationLevel < 1 && (responseInfo.StatusCode < HttpStatusCode.OK || responseInfo.StatusCode >= HttpStatusCode.BadRequest))
{
if (responseInfo.StatusCode >= HttpStatusCode.BadRequest && responseInfo.StatusCode < HttpStatusCode.InternalServerError)
{
response.Status = WebDriverResult.UnhandledError;
}
else if (responseInfo.StatusCode >= HttpStatusCode.InternalServerError)
{
if (responseInfo.StatusCode == HttpStatusCode.NotImplemented)
{
response.Status = WebDriverResult.UnknownCommand;
}
else if (response.Status == WebDriverResult.Success)
{
response.Status = WebDriverResult.UnhandledError;
}
}
else
{
response.Status = WebDriverResult.UnhandledError;
}
}
if (response.Value is string)
{
response.Value = ((string)response.Value).Replace("\r\n", "\n").Replace("\n", Environment.NewLine);
}
return response;
}
/// <summary>
/// Releases all resources used by the <see cref="HttpCommandExecutor"/>.
/// </summary>
public void Dispose()
{
this.Dispose(true);
}
/// <summary>
/// Releases the unmanaged resources used by the <see cref="HttpCommandExecutor"/> and
/// optionally releases the managed resources.
/// </summary>
/// <param name="disposing"><see langword="true"/> to release managed and resources;
/// <see langword="false"/> to only release unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (!this.isDisposed)
{
if (this.client != null)
{
this.client.Dispose();
}
this.isDisposed = true;
}
}
private class HttpRequestInfo
{
public HttpRequestInfo(Uri serverUri, Command commandToExecute, CommandInfo commandInfo)
{
this.FullUri = commandInfo.CreateCommandUri(serverUri, commandToExecute);
this.HttpMethod = commandInfo.Method;
this.RequestBody = commandToExecute.ParametersAsJsonString;
}
public Uri FullUri { get; set; }
public string HttpMethod { get; set; }
public string RequestBody { get; set; }
}
private class HttpResponseInfo
{
public HttpStatusCode StatusCode { get; set; }
public string Body { get; set; }
public string ContentType { get; set; }
}
}
}
| |
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// 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.Collections;
using System.Collections.Generic;
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers
{
/// <summary>
/// Implementation of the non-generic IMessage interface as far as possible.
/// </summary>
public abstract partial class AbstractBuilder<TMessage, TBuilder> : AbstractBuilderLite<TMessage, TBuilder>,
IBuilder<TMessage, TBuilder>
where TMessage : AbstractMessage<TMessage, TBuilder>
where TBuilder : AbstractBuilder<TMessage, TBuilder>
{
#region Unimplemented members of IBuilder
public abstract UnknownFieldSet UnknownFields { get; set; }
public abstract IDictionary<FieldDescriptor, object> AllFields { get; }
public abstract object this[FieldDescriptor field] { get; set; }
public abstract MessageDescriptor DescriptorForType { get; }
public abstract int GetRepeatedFieldCount(FieldDescriptor field);
public abstract object this[FieldDescriptor field, int index] { get; set; }
public abstract bool HasField(FieldDescriptor field);
public abstract IBuilder CreateBuilderForField(FieldDescriptor field);
public abstract TBuilder ClearField(FieldDescriptor field);
public abstract TBuilder AddRepeatedField(FieldDescriptor field, object value);
#endregion
public TBuilder SetUnknownFields(UnknownFieldSet fields)
{
UnknownFields = fields;
return ThisBuilder;
}
public override TBuilder Clear()
{
foreach (FieldDescriptor field in AllFields.Keys)
{
ClearField(field);
}
return ThisBuilder;
}
public override sealed TBuilder MergeFrom(IMessageLite other)
{
if (other is IMessage)
{
return MergeFrom((IMessage) other);
}
throw new ArgumentException("MergeFrom(Message) can only merge messages of the same type.");
}
/// <summary>
/// Merge the specified other message into the message being
/// built. Merging occurs as follows. For each field:
/// For singular primitive fields, if the field is set in <paramref name="other"/>,
/// then <paramref name="other"/>'s value overwrites the value in this message.
/// For singular message fields, if the field is set in <paramref name="other"/>,
/// it is merged into the corresponding sub-message of this message using the same
/// merging rules.
/// For repeated fields, the elements in <paramref name="other"/> are concatenated
/// with the elements in this message.
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public abstract TBuilder MergeFrom(TMessage other);
public virtual TBuilder MergeFrom(IMessage other)
{
if (other.DescriptorForType != DescriptorForType)
{
throw new ArgumentException("MergeFrom(IMessage) can only merge messages of the same type.");
}
// Note: We don't attempt to verify that other's fields have valid
// types. Doing so would be a losing battle. We'd have to verify
// all sub-messages as well, and we'd have to make copies of all of
// them to insure that they don't change after verification (since
// the Message interface itself cannot enforce immutability of
// implementations).
// TODO(jonskeet): Provide a function somewhere called MakeDeepCopy()
// which allows people to make secure deep copies of messages.
foreach (KeyValuePair<FieldDescriptor, object> entry in other.AllFields)
{
FieldDescriptor field = entry.Key;
if (field.IsRepeated)
{
// Concatenate repeated fields
foreach (object element in (IEnumerable) entry.Value)
{
AddRepeatedField(field, element);
}
}
else if (field.MappedType == MappedType.Message)
{
// Merge singular messages
IMessageLite existingValue = (IMessageLite) this[field];
if (existingValue == existingValue.WeakDefaultInstanceForType)
{
this[field] = entry.Value;
}
else
{
this[field] = existingValue.WeakCreateBuilderForType()
.WeakMergeFrom(existingValue)
.WeakMergeFrom((IMessageLite) entry.Value)
.WeakBuild();
}
}
else
{
// Overwrite simple values
this[field] = entry.Value;
}
}
//Fix for unknown fields not merging, see java's AbstractMessage.Builder<T> line 236
MergeUnknownFields(other.UnknownFields);
return ThisBuilder;
}
public override TBuilder MergeFrom(ICodedInputStream input, ExtensionRegistry extensionRegistry)
{
UnknownFieldSet.Builder unknownFields = UnknownFieldSet.CreateBuilder(UnknownFields);
unknownFields.MergeFrom(input, extensionRegistry, this);
UnknownFields = unknownFields.Build();
return ThisBuilder;
}
public virtual TBuilder MergeUnknownFields(UnknownFieldSet unknownFields)
{
UnknownFields = UnknownFieldSet.CreateBuilder(UnknownFields)
.MergeFrom(unknownFields)
.Build();
return ThisBuilder;
}
public virtual IBuilder SetField(FieldDescriptor field, object value)
{
this[field] = value;
return ThisBuilder;
}
public virtual IBuilder SetRepeatedField(FieldDescriptor field, int index, object value)
{
this[field, index] = value;
return ThisBuilder;
}
#region Explicit Implementations
IMessage IBuilder.WeakBuild()
{
return Build();
}
IBuilder IBuilder.WeakAddRepeatedField(FieldDescriptor field, object value)
{
return AddRepeatedField(field, value);
}
IBuilder IBuilder.WeakClear()
{
return Clear();
}
IBuilder IBuilder.WeakMergeFrom(IMessage message)
{
return MergeFrom(message);
}
IBuilder IBuilder.WeakMergeFrom(ICodedInputStream input)
{
return MergeFrom(input);
}
IBuilder IBuilder.WeakMergeFrom(ICodedInputStream input, ExtensionRegistry registry)
{
return MergeFrom(input, registry);
}
IBuilder IBuilder.WeakMergeFrom(ByteString data)
{
return MergeFrom(data);
}
IBuilder IBuilder.WeakMergeFrom(ByteString data, ExtensionRegistry registry)
{
return MergeFrom(data, registry);
}
IMessage IBuilder.WeakBuildPartial()
{
return BuildPartial();
}
IBuilder IBuilder.WeakClone()
{
return Clone();
}
IMessage IBuilder.WeakDefaultInstanceForType
{
get { return DefaultInstanceForType; }
}
IBuilder IBuilder.WeakClearField(FieldDescriptor field)
{
return ClearField(field);
}
#endregion
/// <summary>
/// Converts this builder to a string using <see cref="TextFormat" />.
/// </summary>
/// <remarks>
/// This method is not sealed (in the way that it is in <see cref="AbstractMessage{TMessage, TBuilder}" />
/// as it was added after earlier releases; some other implementations may already be overriding the
/// method.
/// </remarks>
public override string ToString()
{
return TextFormat.PrintToString(this);
}
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Net.Mime;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.UI;
using Microsoft.Xrm.Client;
namespace Adxstudio.Xrm.Web.Modules
{
/// <summary>
/// Sends application error details (using a <see cref="SmtpClient"/>) to configured recipients.
/// </summary>
/// <remarks>
/// Configuration is done through a set of application settings. The only required application setting is the "Adxstudio.Xrm.Web.Modules.ErrorNotifierModule.SmtpClient.To" setting.
/// <code>
/// <![CDATA[
/// <configuration>
/// <appSettings>
/// <add key="Adxstudio.Xrm.Web.Modules.ErrorNotifierModule.SmtpClient.Host" value="localhost"/>
/// <add key="Adxstudio.Xrm.Web.Modules.ErrorNotifierModule.SmtpClient.From" value="webmaster@contoso.com"/>
/// <add key="Adxstudio.Xrm.Web.Modules.ErrorNotifierModule.SmtpClient.To" value="recipient1@contoso.com,recipient2@contoso.com"/>
/// <add key="Adxstudio.Xrm.Web.Modules.ErrorNotifierModule.StatusCodesExcluded" value="400,404"/>
/// <add key="Adxstudio.Xrm.Web.Modules.ErrorNotifierModule.MaximumNotificationsPerMinute" value="100"/>
/// </appSettings>
/// <system.net>
/// <mailSettings>
/// <smtp from="webmaster@contoso.com">
/// <network host="localhost"/>
/// </smtp>
/// </mailSettings>
/// </system.net>
/// </configuration>
/// ]]>
/// </code>
/// </remarks>
public class ErrorNotifierModule : IHttpModule
{
private static readonly int _maximumNotificationsPerMinute = 100;
internal static readonly ConcurrentDictionary<string, ErrorInfo> _errors = new ConcurrentDictionary<string, ErrorInfo>();
internal class ErrorInfo
{
public readonly Exception Error;
public readonly ConcurrentQueue<DateTimeOffset> Buffer;
public int DropCount;
public DateTimeOffset Timestamp;
public ErrorInfo(Exception error)
{
Error = error;
Buffer = new ConcurrentQueue<DateTimeOffset>();
DropCount = 0;
Timestamp = DateTimeOffset.UtcNow;
}
}
public void Dispose()
{
}
public void Init(HttpApplication application)
{
application.Error += OnError;
}
protected virtual void OnError(object sender, EventArgs e)
{
try
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Begin");
var application = sender as HttpApplication;
var context = application.Context;
if (!string.IsNullOrWhiteSpace(GetTo(context)))
{
// prefer Server.GetLastError() over HttpContext.Error
var error = application.Server.GetLastError();
var statusCode = GetStatusCode(error, context);
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("statusCode={0}", statusCode));
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("error={0}", error.Message));
if (!GetStatusCodesExcluded().Contains(statusCode))
{
context.Response.StatusCode = statusCode;
Send(application, error);
}
}
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "End");
}
catch (Exception ex)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, ex.ToString());
}
}
protected virtual void Send(HttpApplication application, Exception error)
{
// collect the errors in the buffer for throttling keyed by exception type
var ei = _errors.GetOrAdd(error.Message, _ => new ErrorInfo(error));
lock (ei.Buffer)
{
// clear expired items from buffer
var now = DateTimeOffset.UtcNow;
DateTimeOffset result;
while (ei.Buffer.TryPeek(out result) && result.AddMinutes(1) < now)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Dequeue: {0}", result));
ei.Buffer.TryDequeue(out result);
}
if (ei.Buffer.Count < GetMaximumNotificationsPerMinute())
{
// add a new item to buffer and reset the drop count
ei.Buffer.Enqueue(now);
ei.Timestamp = now;
var dropCount = ei.DropCount;
ei.DropCount = 0;
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Enqueue: {0}", now));
// continue with notification
Send(application, error, dropCount);
}
else
{
// drop this error
ei.DropCount++;
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Dropped: {0}", ei.DropCount));
}
}
}
protected virtual void Send(HttpApplication application, Exception error, int dropped)
{
var context = application.Context;
var trace = application.Context.Trace;
var mail = GetMailMessage(error, context, trace, dropped);
Send(mail);
}
protected virtual IEnumerable<int> GetStatusCodesExcluded()
{
var excluded = GetConfigurationSettingValue(typeof(ErrorNotifierModule).FullName + ".StatusCodesExcluded");
if (!string.IsNullOrWhiteSpace(excluded))
{
var parts = excluded.Split(new[] { ',', ';' });
foreach (var part in parts)
{
int statusCode;
if (int.TryParse(part, out statusCode))
{
yield return statusCode;
}
}
}
}
protected virtual int GetMaximumNotificationsPerMinute()
{
var mepm = GetConfigurationSettingValue(typeof(ErrorNotifierModule).FullName + ".MaximumNotificationsPerMinute");
if (!string.IsNullOrWhiteSpace(mepm))
{
int value;
if (int.TryParse(mepm, out value))
{
return value;
}
}
return _maximumNotificationsPerMinute;
}
protected virtual MailMessage GetMailMessage(Exception error, HttpContext context, TraceContext trace, int dropped)
{
var from = GetFrom(context);
var to = GetTo(context);
var subject = GetSubject(error, context);
var body = GetBody(error, context, trace);
// ensure that e-mail follows SMTP standards
if (!body.EndsWith("\r\n"))
{
body += "\r\n";
}
var message = new MailMessage { IsBodyHtml = true, Subject = subject, Body = body };
if (from != null) message.From = from;
if (!string.IsNullOrWhiteSpace(to)) message.To.Add(to.Trim(new[] { ';', ',' }).Replace(';', ','));
foreach (var header in GetHeaders(error, context, dropped))
{
if (!string.IsNullOrEmpty(header.Value))
{
message.Headers.Add(header.Key, header.Value);
}
}
foreach (var attachment in GetAttachments(error, context))
{
message.Attachments.Add(attachment);
}
return message;
}
protected virtual void Send(MailMessage message)
{
var host = GetConfigurationSettingValue(typeof(ErrorNotifierModule).FullName + ".SmtpClient.Host") ?? GetConfigurationSettingValue("ADX_SMTP");
using (var client = !string.IsNullOrWhiteSpace(host) ? new SmtpClient(host) : new SmtpClient())
{
client.Send(message);
}
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Message sent.");
}
protected virtual IEnumerable<KeyValuePair<string, string>> GetHeaders(Exception error, HttpContext context, int dropped)
{
yield return CreateHeader("X-ADXSTUDIO-SERVER_NAME", context.Request.ServerVariables["SERVER_NAME"]);
yield return CreateHeader("X-ADXSTUDIO-SCRIPT_NAME", context.Request.ServerVariables["SCRIPT_NAME"]);
yield return CreateHeader("X-ADXSTUDIO-QUERY_STRING", context.Request.ServerVariables["QUERY_STRING"]);
yield return CreateHeader("X-ADXSTUDIO-STATUS_CODE", context.Response.StatusCode.ToString());
yield return CreateHeader("X-ADXSTUDIO-STATUS", context.Response.Status);
yield return CreateHeader("X-ADXSTUDIO-CONTENT-TYPE", context.Response.ContentType);
yield return CreateHeader("X-ADXSTUDIO-CONTENT-ENCODING", context.Response.ContentEncoding.EncodingName);
yield return CreateHeader("X-ADXSTUDIO-EXCEPTION-TYPE", error.GetType().FullName);
yield return CreateHeader("X-ADXSTUDIO-EXCEPTION-DROPPED", dropped.ToString(CultureInfo.InvariantCulture));
}
private static KeyValuePair<string, string> CreateHeader(string key, string value)
{
return new KeyValuePair<string, string>(key, value);
}
protected virtual IEnumerable<Attachment> GetAttachments(Exception error, HttpContext context)
{
var unhandled = error as HttpUnhandledException;
if (unhandled != null)
{
var message = unhandled.GetHtmlErrorMessage();
if (!string.IsNullOrWhiteSpace(message))
{
var stream = new MemoryStream(Encoding.UTF8.GetBytes(message));
yield return new Attachment(stream, "Error.html", MediaTypeNames.Text.Html);
}
}
}
protected virtual string GetTo(HttpContext context)
{
var to = GetConfigurationSettingValue(typeof(ErrorNotifierModule).FullName + ".SmtpClient.To") ?? GetConfigurationSettingValue("ADX_ERR_MAIL_TO");
return to;
}
protected virtual MailAddress GetFrom(HttpContext context)
{
var setting = GetConfigurationSettingValue(typeof(ErrorNotifierModule).FullName + ".SmtpClient.From") ?? GetConfigurationSettingValue("ADX_SMTP_MAIL_FROM");
var from = setting ?? "error@{0}".FormatWith(context.Request.ServerVariables["SERVER_NAME"]);
return from != null ? new MailAddress(from) : null;
}
protected virtual string GetSubject(Exception error, HttpContext context)
{
return "{0} on {1}".FormatWith(context.Response.Status, context.Request.ServerVariables["SERVER_NAME"]);
}
protected virtual string GetBody(Exception error, HttpContext context, TraceContext trace)
{
const string body =
@"<html>
<body>
{0}
<hr/>
{1}
<hr/>
{2}
<br/>
{3}
<hr/>
{4}
</body>
</html>
";
return body.FormatWith(GetException(error), GetRequest(context.Request), GetResponse(context.Response), GetTrace(trace), GetAssemblies());
}
protected virtual string GetException(Exception error)
{
if (error == null) return null;
const string message =
@"<h3>{0}</h3>
<h5>{1}</h5>
<pre>{2}
{3}{4}
</pre>
";
var sb = new StringBuilder();
var current = error;
while (current != null)
{
var errorMessage = HttpUtility.HtmlEncode(current.Message);
var errorStackTrace = HttpUtility.HtmlEncode(current.StackTrace);
var errorSource = HttpUtility.HtmlEncode(current.Source);
var help = !string.IsNullOrWhiteSpace(current.HelpLink) ? "\r\n" + current.HelpLink : null;
sb.Append(message.FormatWith(errorMessage, current.GetType().FullName, errorStackTrace, errorSource, help));
current = current.InnerException;
}
return sb.ToString();
}
protected virtual string GetRequest(HttpRequest request)
{
var text = "<pre>\r\n{0} {1}{2} {3}\r\n".FormatWith(
request.HttpMethod,
request.Url.GetLeftPart(UriPartial.Authority),
request.RawUrl,
request.ServerVariables["SERVER_PROTOCOL"]);
var sb = new StringBuilder(text);
foreach (var key in request.Headers.AllKeys)
{
sb.Append("{0}: {1}\r\n".FormatWith(key, request.Headers[key]));
}
var position = request.InputStream.Position;
request.InputStream.Position = 0;
try
{
using (var reader = new StreamReader(request.InputStream))
{
sb.Append(reader.ReadToEnd());
}
}
finally
{
request.InputStream.Position = position;
}
sb.Append("</pre>");
return sb.ToString();
}
protected virtual string GetResponse(HttpResponse response)
{
var text = "<pre>\r\nHTTP/1.1 {0}\r\n".FormatWith(response.Status);
var sb = new StringBuilder(text);
sb.Append("Content-Type: {0}\r\n".FormatWith(response.ContentType));
sb.Append("Content-Encoding: {0}\r\n".FormatWith(response.ContentEncoding.EncodingName));
foreach (var key in response.Headers.AllKeys)
{
sb.Append("{0}: {1}\r\n".FormatWith(key, response.Headers[key]));
}
sb.Append("</pre>");
return sb.ToString();
}
protected virtual string GetTrace(TraceContext trace)
{
try
{
return GetTraceByReflection(trace);
}
catch
{
return string.Empty;
}
}
protected virtual string GetAssemblies()
{
const string message =
@"<pre>
{0}
</pre>
";
var sb = new StringBuilder();
var assemblies = AppDomain.CurrentDomain.GetAssemblies().OrderBy(assembly => assembly.FullName);
foreach (var assembly in assemblies)
{
sb.Append(assembly.FullName + "\r\n");
}
return message.FormatWith(sb.ToString());
}
protected virtual int GetStatusCode(Exception error, HttpContext context)
{
var httpException = error as HttpException;
if (httpException != null) return httpException.GetHttpCode();
if (error != null) return 500;
return context.Response.StatusCode;
}
protected virtual string GetConfigurationSettingValue(string configName)
{
return ConfigurationManager.AppSettings[configName];
}
private static string GetTraceByReflection(TraceContext trace)
{
// temporarily enable PageOutput (via the _isEnabled field) so that calling Render produces output
var isEnabledField = typeof(TraceContext).GetField("_isEnabled", BindingFlags.NonPublic | BindingFlags.Instance);
var originalIsEnabledValue = isEnabledField.GetValue(trace);
trace.IsEnabled = true;
try
{
var sb = new StringBuilder();
using (var htw = new Html32TextWriter(new StringWriter(sb, CultureInfo.InvariantCulture)))
{
typeof(TraceContext)
.GetMethod("Render", BindingFlags.NonPublic | BindingFlags.Instance)
.Invoke(trace, new object[] { htw });
}
return sb.ToString();
}
finally
{
// reset the _isEnabled field
isEnabledField.SetValue(trace, originalIsEnabledValue);
}
}
}
}
| |
using System;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Text;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Utilities.Encoders;
namespace Org.BouncyCastle.Asn1.X509
{
/**
* <pre>
* RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
*
* RelativeDistinguishedName ::= SET SIZE (1..MAX) OF AttributeTypeAndValue
*
* AttributeTypeAndValue ::= SEQUENCE {
* type OBJECT IDENTIFIER,
* value ANY }
* </pre>
*/
public class X509Name
: Asn1Encodable
{
/**
* country code - StringType(SIZE(2))
*/
public static readonly DerObjectIdentifier C = new DerObjectIdentifier("2.5.4.6");
/**
* organization - StringType(SIZE(1..64))
*/
public static readonly DerObjectIdentifier O = new DerObjectIdentifier("2.5.4.10");
/**
* organizational unit name - StringType(SIZE(1..64))
*/
public static readonly DerObjectIdentifier OU = new DerObjectIdentifier("2.5.4.11");
/**
* Title
*/
public static readonly DerObjectIdentifier T = new DerObjectIdentifier("2.5.4.12");
/**
* common name - StringType(SIZE(1..64))
*/
public static readonly DerObjectIdentifier CN = new DerObjectIdentifier("2.5.4.3");
/**
* street - StringType(SIZE(1..64))
*/
public static readonly DerObjectIdentifier Street = new DerObjectIdentifier("2.5.4.9");
/**
* device serial number name - StringType(SIZE(1..64))
*/
public static readonly DerObjectIdentifier SerialNumber = new DerObjectIdentifier("2.5.4.5");
/**
* locality name - StringType(SIZE(1..64))
*/
public static readonly DerObjectIdentifier L = new DerObjectIdentifier("2.5.4.7");
/**
* state, or province name - StringType(SIZE(1..64))
*/
public static readonly DerObjectIdentifier ST = new DerObjectIdentifier("2.5.4.8");
/**
* Naming attributes of type X520name
*/
public static readonly DerObjectIdentifier Surname = new DerObjectIdentifier("2.5.4.4");
public static readonly DerObjectIdentifier GivenName = new DerObjectIdentifier("2.5.4.42");
public static readonly DerObjectIdentifier Initials = new DerObjectIdentifier("2.5.4.43");
public static readonly DerObjectIdentifier Generation = new DerObjectIdentifier("2.5.4.44");
public static readonly DerObjectIdentifier UniqueIdentifier = new DerObjectIdentifier("2.5.4.45");
/**
* businessCategory - DirectoryString(SIZE(1..128)
*/
public static readonly DerObjectIdentifier BusinessCategory = new DerObjectIdentifier(
"2.5.4.15");
/**
* postalCode - DirectoryString(SIZE(1..40)
*/
public static readonly DerObjectIdentifier PostalCode = new DerObjectIdentifier(
"2.5.4.17");
/**
* dnQualifier - DirectoryString(SIZE(1..64)
*/
public static readonly DerObjectIdentifier DnQualifier = new DerObjectIdentifier(
"2.5.4.46");
/**
* RFC 3039 Pseudonym - DirectoryString(SIZE(1..64)
*/
public static readonly DerObjectIdentifier Pseudonym = new DerObjectIdentifier(
"2.5.4.65");
/**
* RFC 3039 DateOfBirth - GeneralizedTime - YYYYMMDD000000Z
*/
public static readonly DerObjectIdentifier DateOfBirth = new DerObjectIdentifier(
"1.3.6.1.5.5.7.9.1");
/**
* RFC 3039 PlaceOfBirth - DirectoryString(SIZE(1..128)
*/
public static readonly DerObjectIdentifier PlaceOfBirth = new DerObjectIdentifier(
"1.3.6.1.5.5.7.9.2");
/**
* RFC 3039 DateOfBirth - PrintableString (SIZE(1)) -- "M", "F", "m" or "f"
*/
public static readonly DerObjectIdentifier Gender = new DerObjectIdentifier(
"1.3.6.1.5.5.7.9.3");
/**
* RFC 3039 CountryOfCitizenship - PrintableString (SIZE (2)) -- ISO 3166
* codes only
*/
public static readonly DerObjectIdentifier CountryOfCitizenship = new DerObjectIdentifier(
"1.3.6.1.5.5.7.9.4");
/**
* RFC 3039 CountryOfCitizenship - PrintableString (SIZE (2)) -- ISO 3166
* codes only
*/
public static readonly DerObjectIdentifier CountryOfResidence = new DerObjectIdentifier(
"1.3.6.1.5.5.7.9.5");
/**
* ISIS-MTT NameAtBirth - DirectoryString(SIZE(1..64)
*/
public static readonly DerObjectIdentifier NameAtBirth = new DerObjectIdentifier("1.3.36.8.3.14");
/**
* RFC 3039 PostalAddress - SEQUENCE SIZE (1..6) OF
* DirectoryString(SIZE(1..30))
*/
public static readonly DerObjectIdentifier PostalAddress = new DerObjectIdentifier("2.5.4.16");
/**
* id-at-telephoneNumber
*/
public static readonly DerObjectIdentifier TelephoneNumber = X509ObjectIdentifiers.id_at_telephoneNumber;
/**
* id-at-name
*/
public static readonly DerObjectIdentifier Name = X509ObjectIdentifiers.id_at_name;
/**
* Email address (RSA PKCS#9 extension) - IA5String.
* <p>Note: if you're trying to be ultra orthodox, don't use this! It shouldn't be in here.</p>
*/
public static readonly DerObjectIdentifier EmailAddress = PkcsObjectIdentifiers.Pkcs9AtEmailAddress;
/**
* more from PKCS#9
*/
public static readonly DerObjectIdentifier UnstructuredName = PkcsObjectIdentifiers.Pkcs9AtUnstructuredName;
public static readonly DerObjectIdentifier UnstructuredAddress = PkcsObjectIdentifiers.Pkcs9AtUnstructuredAddress;
/**
* email address in Verisign certificates
*/
public static readonly DerObjectIdentifier E = EmailAddress;
/*
* others...
*/
public static readonly DerObjectIdentifier DC = new DerObjectIdentifier("0.9.2342.19200300.100.1.25");
/**
* LDAP User id.
*/
public static readonly DerObjectIdentifier UID = new DerObjectIdentifier("0.9.2342.19200300.100.1.1");
/**
* determines whether or not strings should be processed and printed
* from back to front.
*/
// public static bool DefaultReverse = false;
public static bool DefaultReverse
{
get { return defaultReverse[0]; }
set { defaultReverse[0] = value; }
}
private static readonly bool[] defaultReverse = { false };
/**
* default look up table translating OID values into their common symbols following
* the convention in RFC 2253 with a few extras
*/
public static readonly Hashtable DefaultSymbols = new Hashtable();
/**
* look up table translating OID values into their common symbols following the convention in RFC 2253
*/
public static readonly Hashtable RFC2253Symbols = new Hashtable();
/**
* look up table translating OID values into their common symbols following the convention in RFC 1779
*
*/
public static readonly Hashtable RFC1779Symbols = new Hashtable();
/**
* look up table translating common symbols into their OIDS.
*/
public static readonly Hashtable DefaultLookup = new Hashtable();
/**
* look up table translating OID values into their common symbols.
*/
[Obsolete("Use 'DefaultSymbols' instead")]
public static readonly Hashtable OIDLookup = DefaultSymbols;
/**
* look up table translating string values into their OIDS -
* this static is scheduled for deletion
*/
[Obsolete("Use 'DefaultLookup' instead")]
public static readonly Hashtable SymbolLookup = DefaultLookup;
static X509Name()
{
DefaultSymbols.Add(C, "C");
DefaultSymbols.Add(O, "O");
DefaultSymbols.Add(T, "T");
DefaultSymbols.Add(OU, "OU");
DefaultSymbols.Add(CN, "CN");
DefaultSymbols.Add(L, "L");
DefaultSymbols.Add(ST, "ST");
DefaultSymbols.Add(SerialNumber, "SERIALNUMBER");
DefaultSymbols.Add(EmailAddress, "E");
DefaultSymbols.Add(DC, "DC");
DefaultSymbols.Add(UID, "UID");
DefaultSymbols.Add(Street, "STREET");
DefaultSymbols.Add(Surname, "SURNAME");
DefaultSymbols.Add(GivenName, "GIVENNAME");
DefaultSymbols.Add(Initials, "INITIALS");
DefaultSymbols.Add(Generation, "GENERATION");
DefaultSymbols.Add(UnstructuredAddress, "unstructuredAddress");
DefaultSymbols.Add(UnstructuredName, "unstructuredName");
DefaultSymbols.Add(UniqueIdentifier, "UniqueIdentifier");
DefaultSymbols.Add(DnQualifier, "DN");
DefaultSymbols.Add(Pseudonym, "Pseudonym");
DefaultSymbols.Add(PostalAddress, "PostalAddress");
DefaultSymbols.Add(NameAtBirth, "NameAtBirth");
DefaultSymbols.Add(CountryOfCitizenship, "CountryOfCitizenship");
DefaultSymbols.Add(CountryOfResidence, "CountryOfResidence");
DefaultSymbols.Add(Gender, "Gender");
DefaultSymbols.Add(PlaceOfBirth, "PlaceOfBirth");
DefaultSymbols.Add(DateOfBirth, "DateOfBirth");
DefaultSymbols.Add(PostalCode, "PostalCode");
DefaultSymbols.Add(BusinessCategory, "BusinessCategory");
DefaultSymbols.Add(TelephoneNumber, "TelephoneNumber");
RFC2253Symbols.Add(C, "C");
RFC2253Symbols.Add(O, "O");
RFC2253Symbols.Add(OU, "OU");
RFC2253Symbols.Add(CN, "CN");
RFC2253Symbols.Add(L, "L");
RFC2253Symbols.Add(ST, "ST");
RFC2253Symbols.Add(Street, "STREET");
RFC2253Symbols.Add(DC, "DC");
RFC2253Symbols.Add(UID, "UID");
RFC1779Symbols.Add(C, "C");
RFC1779Symbols.Add(O, "O");
RFC1779Symbols.Add(OU, "OU");
RFC1779Symbols.Add(CN, "CN");
RFC1779Symbols.Add(L, "L");
RFC1779Symbols.Add(ST, "ST");
RFC1779Symbols.Add(Street, "STREET");
DefaultLookup.Add("c", C);
DefaultLookup.Add("o", O);
DefaultLookup.Add("t", T);
DefaultLookup.Add("ou", OU);
DefaultLookup.Add("cn", CN);
DefaultLookup.Add("l", L);
DefaultLookup.Add("st", ST);
DefaultLookup.Add("serialnumber", SerialNumber);
DefaultLookup.Add("street", Street);
DefaultLookup.Add("emailaddress", E);
DefaultLookup.Add("dc", DC);
DefaultLookup.Add("e", E);
DefaultLookup.Add("uid", UID);
DefaultLookup.Add("surname", Surname);
DefaultLookup.Add("givenname", GivenName);
DefaultLookup.Add("initials", Initials);
DefaultLookup.Add("generation", Generation);
DefaultLookup.Add("unstructuredaddress", UnstructuredAddress);
DefaultLookup.Add("unstructuredname", UnstructuredName);
DefaultLookup.Add("uniqueidentifier", UniqueIdentifier);
DefaultLookup.Add("dn", DnQualifier);
DefaultLookup.Add("pseudonym", Pseudonym);
DefaultLookup.Add("postaladdress", PostalAddress);
DefaultLookup.Add("nameofbirth", NameAtBirth);
DefaultLookup.Add("countryofcitizenship", CountryOfCitizenship);
DefaultLookup.Add("countryofresidence", CountryOfResidence);
DefaultLookup.Add("gender", Gender);
DefaultLookup.Add("placeofbirth", PlaceOfBirth);
DefaultLookup.Add("dateofbirth", DateOfBirth);
DefaultLookup.Add("postalcode", PostalCode);
DefaultLookup.Add("businesscategory", BusinessCategory);
DefaultLookup.Add("telephonenumber", TelephoneNumber);
}
private readonly ArrayList ordering = new ArrayList();
private readonly X509NameEntryConverter converter;
private ArrayList values = new ArrayList();
private ArrayList added = new ArrayList();
private Asn1Sequence seq;
/**
* Return a X509Name based on the passed in tagged object.
*
* @param obj tag object holding name.
* @param explicitly true if explicitly tagged false otherwise.
* @return the X509Name
*/
public static X509Name GetInstance(
Asn1TaggedObject obj,
bool explicitly)
{
return GetInstance(Asn1Sequence.GetInstance(obj, explicitly));
}
public static X509Name GetInstance(
object obj)
{
if (obj == null || obj is X509Name)
{
return (X509Name) obj;
}
if (obj is Asn1Sequence)
{
return new X509Name((Asn1Sequence) obj);
}
throw new ArgumentException("unknown object in factory: " + obj.GetType().Name);
}
/**
* Constructor from Asn1Sequence
*
* the principal will be a list of constructed sets, each containing an (OID, string) pair.
*/
protected X509Name(
Asn1Sequence seq)
{
this.seq = seq;
foreach (Asn1Encodable asn1Obj in seq)
{
Asn1Set asn1Set = Asn1Set.GetInstance(asn1Obj.ToAsn1Object());
for (int i = 0; i < asn1Set.Count; i++)
{
Asn1Sequence s = Asn1Sequence.GetInstance(asn1Set[i].ToAsn1Object());
if (s.Count != 2)
throw new ArgumentException("badly sized pair");
ordering.Add(DerObjectIdentifier.GetInstance(s[0].ToAsn1Object()));
Asn1Object derValue = s[1].ToAsn1Object();
if (derValue is IAsn1String && !(derValue is DerUniversalString))
{
string v = ((IAsn1String)derValue).GetString();
if (v.StartsWith("#"))
{
v = "\\" + v;
}
values.Add(v);
}
else
{
byte[] hex = Hex.Encode(derValue.GetEncoded());
values.Add("#" + Encoding.ASCII.GetString(hex, 0, hex.Length));
}
added.Add(i != 0);
}
}
}
/**
* Constructor from a table of attributes with ordering.
* <p>
* it's is assumed the table contains OID/string pairs, and the contents
* of the table are copied into an internal table as part of the
* construction process. The ordering ArrayList should contain the OIDs
* in the order they are meant to be encoded or printed in ToString.</p>
*/
public X509Name(
ArrayList ordering,
Hashtable attributes)
: this(ordering, attributes, new X509DefaultEntryConverter())
{
}
/**
* Constructor from a table of attributes with ordering.
* <p>
* it's is assumed the table contains OID/string pairs, and the contents
* of the table are copied into an internal table as part of the
* construction process. The ordering ArrayList should contain the OIDs
* in the order they are meant to be encoded or printed in ToString.</p>
* <p>
* The passed in converter will be used to convert the strings into their
* ASN.1 counterparts.</p>
*/
public X509Name(
ArrayList ordering,
Hashtable attributes,
X509NameEntryConverter converter)
{
this.converter = converter;
foreach (DerObjectIdentifier oid in ordering)
{
object attribute = attributes[oid];
if (attribute == null)
{
throw new ArgumentException("No attribute for object id - " + oid + " - passed to distinguished name");
}
this.ordering.Add(oid);
this.added.Add(false);
this.values.Add(attribute); // copy the hash table
}
}
/**
* Takes two vectors one of the oids and the other of the values.
*/
public X509Name(
ArrayList oids,
ArrayList values)
: this(oids, values, new X509DefaultEntryConverter())
{
}
/**
* Takes two vectors one of the oids and the other of the values.
* <p>
* The passed in converter will be used to convert the strings into their
* ASN.1 counterparts.</p>
*/
public X509Name(
ArrayList oids,
ArrayList values,
X509NameEntryConverter converter)
{
this.converter = converter;
if (oids.Count != values.Count)
{
throw new ArgumentException("'oids' must be same length as 'values'.");
}
for (int i = 0; i < oids.Count; i++)
{
this.ordering.Add(oids[i]);
this.values.Add(values[i]);
this.added.Add(false);
}
}
// private static bool IsEncoded(
// string s)
// {
// return s.StartsWith("#");
// }
/**
* Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
* some such, converting it into an ordered set of name attributes.
*/
public X509Name(
string dirName)
: this(DefaultReverse, DefaultLookup, dirName)
{
}
/**
* Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
* some such, converting it into an ordered set of name attributes with each
* string value being converted to its associated ASN.1 type using the passed
* in converter.
*/
public X509Name(
string dirName,
X509NameEntryConverter converter)
: this(DefaultReverse, DefaultLookup, dirName, converter)
{
}
/**
* Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
* some such, converting it into an ordered set of name attributes. If reverse
* is true, create the encoded version of the sequence starting from the
* last element in the string.
*/
public X509Name(
bool reverse,
string dirName)
: this(reverse, DefaultLookup, dirName)
{
}
/**
* Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
* some such, converting it into an ordered set of name attributes with each
* string value being converted to its associated ASN.1 type using the passed
* in converter. If reverse is true the ASN.1 sequence representing the DN will
* be built by starting at the end of the string, rather than the start.
*/
public X509Name(
bool reverse,
string dirName,
X509NameEntryConverter converter)
: this(reverse, DefaultLookup, dirName, converter)
{
}
/**
* Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
* some such, converting it into an ordered set of name attributes. lookUp
* should provide a table of lookups, indexed by lowercase only strings and
* yielding a DerObjectIdentifier, other than that OID. and numeric oids
* will be processed automatically.
* <br/>
* If reverse is true, create the encoded version of the sequence
* starting from the last element in the string.
* @param reverse true if we should start scanning from the end (RFC 2553).
* @param lookUp table of names and their oids.
* @param dirName the X.500 string to be parsed.
*/
public X509Name(
bool reverse,
Hashtable lookUp,
string dirName)
: this(reverse, lookUp, dirName, new X509DefaultEntryConverter())
{
}
private DerObjectIdentifier DecodeOid(
string name,
IDictionary lookUp)
{
if (name.ToUpper(CultureInfo.InvariantCulture).StartsWith("OID."))
{
return new DerObjectIdentifier(name.Substring(4));
}
else if (name[0] >= '0' && name[0] <= '9')
{
return new DerObjectIdentifier(name);
}
DerObjectIdentifier oid = (DerObjectIdentifier)lookUp[name.ToLower(CultureInfo.InvariantCulture)];
if (oid == null)
{
throw new ArgumentException("Unknown object id - " + name + " - passed to distinguished name");
}
return oid;
}
/**
* Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
* some such, converting it into an ordered set of name attributes. lookUp
* should provide a table of lookups, indexed by lowercase only strings and
* yielding a DerObjectIdentifier, other than that OID. and numeric oids
* will be processed automatically. The passed in converter is used to convert the
* string values to the right of each equals sign to their ASN.1 counterparts.
* <br/>
* @param reverse true if we should start scanning from the end, false otherwise.
* @param lookUp table of names and oids.
* @param dirName the string dirName
* @param converter the converter to convert string values into their ASN.1 equivalents
*/
public X509Name(
bool reverse,
IDictionary lookUp,
string dirName,
X509NameEntryConverter converter)
{
this.converter = converter;
X509NameTokenizer nTok = new X509NameTokenizer(dirName);
while (nTok.HasMoreTokens())
{
string token = nTok.NextToken();
int index = token.IndexOf('=');
if (index == -1)
{
throw new ArgumentException("badly formated directory string");
}
string name = token.Substring(0, index);
string value = token.Substring(index + 1);
DerObjectIdentifier oid = DecodeOid(name, lookUp);
if (value.IndexOf('+') > 0)
{
X509NameTokenizer vTok = new X509NameTokenizer(value, '+');
string v = vTok.NextToken();
this.ordering.Add(oid);
this.values.Add(v);
this.added.Add(false);
while (vTok.HasMoreTokens())
{
string sv = vTok.NextToken();
int ndx = sv.IndexOf('=');
string nm = sv.Substring(0, ndx);
string vl = sv.Substring(ndx + 1);
this.ordering.Add(DecodeOid(nm, lookUp));
this.values.Add(vl);
this.added.Add(true);
}
}
else
{
this.ordering.Add(oid);
this.values.Add(value);
this.added.Add(false);
}
}
if (reverse)
{
// this.ordering.Reverse();
// this.values.Reverse();
// this.added.Reverse();
ArrayList o = new ArrayList();
ArrayList v = new ArrayList();
ArrayList a = new ArrayList();
int count = 1;
for (int i = 0; i < this.ordering.Count; i++)
{
if (!((bool) this.added[i]))
{
count = 0;
}
int index = count++;
o.Insert(index, this.ordering[i]);
v.Insert(index, this.values[i]);
a.Insert(index, this.added[i]);
}
this.ordering = o;
this.values = v;
this.added = a;
}
}
/**
* return an ArrayList of the oids in the name, in the order they were found.
*/
public ArrayList GetOids()
{
return (ArrayList) ordering.Clone();
}
/**
* return an ArrayList of the values found in the name, in the order they
* were found.
*/
public ArrayList GetValues()
{
return (ArrayList) values.Clone();
}
/**
* return an ArrayList of the values found in the name, in the order they
* were found, with the DN label corresponding to passed in oid.
*/
public ArrayList GetValues(
DerObjectIdentifier oid)
{
ArrayList v = new ArrayList();
for (int i = 0; i != values.Count; i++)
{
if (ordering[i].Equals(oid))
{
string val = (string)values[i];
if (val.StartsWith("\\#"))
{
val = val.Substring(1);
}
v.Add(val);
}
}
return v;
}
public override Asn1Object ToAsn1Object()
{
if (seq == null)
{
Asn1EncodableVector vec = new Asn1EncodableVector();
Asn1EncodableVector sVec = new Asn1EncodableVector();
DerObjectIdentifier lstOid = null;
for (int i = 0; i != ordering.Count; i++)
{
DerObjectIdentifier oid = (DerObjectIdentifier)ordering[i];
string str = (string)values[i];
if (lstOid == null
|| ((bool)this.added[i]))
{
}
else
{
vec.Add(new DerSet(sVec));
sVec = new Asn1EncodableVector();
}
sVec.Add(
new DerSequence(
oid,
converter.GetConvertedValue(oid, str)));
lstOid = oid;
}
vec.Add(new DerSet(sVec));
seq = new DerSequence(vec);
}
return seq;
}
[Obsolete("Use 'Equivalent(X509Name, int)' instead")]
public bool Equals(
X509Name other,
bool inOrder)
{
return Equivalent(other, inOrder);
}
/// <param name="other">The X509Name object to test equivalency against.</param>
/// <param name="inOrder">If true, the order of elements must be the same,
/// as well as the values associated with each element.</param>
public bool Equivalent(
X509Name other,
bool inOrder)
{
if (!inOrder)
return this.Equivalent(other);
if (other == null)
return false;
if (other == this)
return true;
int orderingSize = ordering.Count;
if (orderingSize != other.ordering.Count)
return false;
for (int i = 0; i < orderingSize; i++)
{
DerObjectIdentifier oid = (DerObjectIdentifier) ordering[i];
DerObjectIdentifier oOid = (DerObjectIdentifier) other.ordering[i];
if (!oid.Equals(oOid))
return false;
string val = (string) values[i];
string oVal = (string) other.values[i];
if (!equivalentStrings(val, oVal))
return false;
}
return true;
}
[Obsolete("Use 'Equivalent(X509Name)' instead")]
public bool Equals(
X509Name other)
{
return Equivalent(other);
}
/**
* test for equivalence - note: case is ignored.
*/
public bool Equivalent(
X509Name other)
{
if (other == null)
return false;
if (other == this)
return true;
int orderingSize = ordering.Count;
if (orderingSize != other.ordering.Count)
{
return false;
}
bool[] indexes = new bool[orderingSize];
int start, end, delta;
if (ordering[0].Equals(other.ordering[0])) // guess forward
{
start = 0;
end = orderingSize;
delta = 1;
}
else // guess reversed - most common problem
{
start = orderingSize - 1;
end = -1;
delta = -1;
}
for (int i = start; i != end; i += delta)
{
bool found = false;
DerObjectIdentifier oid = (DerObjectIdentifier)ordering[i];
string value = (string)values[i];
for (int j = 0; j < orderingSize; j++)
{
if (indexes[j])
{
continue;
}
DerObjectIdentifier oOid = (DerObjectIdentifier)other.ordering[j];
if (oid.Equals(oOid))
{
string oValue = (string)other.values[j];
if (equivalentStrings(value, oValue))
{
indexes[j] = true;
found = true;
break;
}
}
}
if (!found)
{
return false;
}
}
return true;
}
private static bool equivalentStrings(
string s1,
string s2)
{
string v1 = canonicalize(s1);
string v2 = canonicalize(s2);
if (!v1.Equals(v2))
{
v1 = stripInternalSpaces(v1);
v2 = stripInternalSpaces(v2);
if (!v1.Equals(v2))
{
return false;
}
}
return true;
}
private static string canonicalize(
string s)
{
string v = s.ToLower(CultureInfo.InvariantCulture).Trim();
if (v.StartsWith("#"))
{
Asn1Object obj = decodeObject(v);
if (obj is IAsn1String)
{
v = ((IAsn1String)obj).GetString().ToLower(CultureInfo.InvariantCulture).Trim();
}
}
return v;
}
private static Asn1Object decodeObject(
string v)
{
try
{
return Asn1Object.FromByteArray(Hex.Decode(v.Substring(1)));
}
catch (IOException e)
{
throw new InvalidOperationException("unknown encoding in name: " + e.Message, e);
}
}
private static string stripInternalSpaces(
string str)
{
StringBuilder res = new StringBuilder();
if (str.Length != 0)
{
char c1 = str[0];
res.Append(c1);
for (int k = 1; k < str.Length; k++)
{
char c2 = str[k];
if (!(c1 == ' ' && c2 == ' '))
{
res.Append(c2);
}
c1 = c2;
}
}
return res.ToString();
}
private void AppendValue(
StringBuilder buf,
Hashtable oidSymbols,
DerObjectIdentifier oid,
string val)
{
string sym = (string) oidSymbols[oid];
if (sym != null)
{
buf.Append(sym);
}
else
{
buf.Append(oid.Id);
}
buf.Append('=');
int index = buf.Length;
buf.Append(val);
int end = buf.Length;
if (val.StartsWith("\\#"))
{
index += 2;
}
while (index != end)
{
if ((buf[index] == ',')
|| (buf[index] == '"')
|| (buf[index] == '\\')
|| (buf[index] == '+')
|| (buf[index] == '=')
|| (buf[index] == '<')
|| (buf[index] == '>')
|| (buf[index] == ';'))
{
buf.Insert(index++, "\\");
end++;
}
index++;
}
}
/**
* convert the structure to a string - if reverse is true the
* oids and values are listed out starting with the last element
* in the sequence (ala RFC 2253), otherwise the string will begin
* with the first element of the structure. If no string definition
* for the oid is found in oidSymbols the string value of the oid is
* added. Two standard symbol tables are provided DefaultSymbols, and
* RFC2253Symbols as part of this class.
*
* @param reverse if true start at the end of the sequence and work back.
* @param oidSymbols look up table strings for oids.
*/
public string ToString(
bool reverse,
Hashtable oidSymbols)
{
ArrayList components = new ArrayList();
StringBuilder ava = null;
for (int i = 0; i < ordering.Count; i++)
{
if ((bool) added[i])
{
ava.Append('+');
AppendValue(ava, oidSymbols,
(DerObjectIdentifier)ordering[i],
(string)values[i]);
}
else
{
ava = new StringBuilder();
AppendValue(ava, oidSymbols,
(DerObjectIdentifier)ordering[i],
(string)values[i]);
components.Add(ava);
}
}
if (reverse)
{
components.Reverse();
}
StringBuilder buf = new StringBuilder();
if (components.Count > 0)
{
buf.Append(components[0].ToString());
for (int i = 1; i < components.Count; ++i)
{
buf.Append(',');
buf.Append(components[i].ToString());
}
}
return buf.ToString();
}
public override string ToString()
{
return ToString(DefaultReverse, DefaultSymbols);
}
}
}
| |
//------------------------------------------------------------------------------
// Microsoft Avalon
// Copyright (c) Microsoft Corporation, 2001, 2002
//
// File: knowncolors.cs
//------------------------------------------------------------------------------
#if PBTCOMPILER
namespace MS.Internal.Markup
#else
using System.Windows.Media;
using MS.Internal;
using System.Collections.Generic;
using System;
namespace System.Windows.Media
#endif
{
/// Enum containing handles to all known colors
/// Since the first element is 0, second is 1, etc, we can use this to index
/// directly into an array
internal enum KnownColor : uint
{
// We've reserved the value "1" as unknown. If for some odd reason "1" is added to the
// list, redefined UnknownColor
AliceBlue = 0xFFF0F8FF,
AntiqueWhite = 0xFFFAEBD7,
Aqua = 0xFF00FFFF,
Aquamarine = 0xFF7FFFD4,
Azure = 0xFFF0FFFF,
Beige = 0xFFF5F5DC,
Bisque = 0xFFFFE4C4,
Black = 0xFF000000,
BlanchedAlmond = 0xFFFFEBCD,
Blue = 0xFF0000FF,
BlueViolet = 0xFF8A2BE2,
Brown = 0xFFA52A2A,
BurlyWood = 0xFFDEB887,
CadetBlue = 0xFF5F9EA0,
Chartreuse = 0xFF7FFF00,
Chocolate = 0xFFD2691E,
Coral = 0xFFFF7F50,
CornflowerBlue = 0xFF6495ED,
Cornsilk = 0xFFFFF8DC,
Crimson = 0xFFDC143C,
Cyan = 0xFF00FFFF,
DarkBlue = 0xFF00008B,
DarkCyan = 0xFF008B8B,
DarkGoldenrod = 0xFFB8860B,
DarkGray = 0xFFA9A9A9,
DarkGreen = 0xFF006400,
DarkKhaki = 0xFFBDB76B,
DarkMagenta = 0xFF8B008B,
DarkOliveGreen = 0xFF556B2F,
DarkOrange = 0xFFFF8C00,
DarkOrchid = 0xFF9932CC,
DarkRed = 0xFF8B0000,
DarkSalmon = 0xFFE9967A,
DarkSeaGreen = 0xFF8FBC8F,
DarkSlateBlue = 0xFF483D8B,
DarkSlateGray = 0xFF2F4F4F,
DarkTurquoise = 0xFF00CED1,
DarkViolet = 0xFF9400D3,
DeepPink = 0xFFFF1493,
DeepSkyBlue = 0xFF00BFFF,
DimGray = 0xFF696969,
DodgerBlue = 0xFF1E90FF,
Firebrick = 0xFFB22222,
FloralWhite = 0xFFFFFAF0,
ForestGreen = 0xFF228B22,
Fuchsia = 0xFFFF00FF,
Gainsboro = 0xFFDCDCDC,
GhostWhite = 0xFFF8F8FF,
Gold = 0xFFFFD700,
Goldenrod = 0xFFDAA520,
Gray = 0xFF808080,
Green = 0xFF008000,
GreenYellow = 0xFFADFF2F,
Honeydew = 0xFFF0FFF0,
HotPink = 0xFFFF69B4,
IndianRed = 0xFFCD5C5C,
Indigo = 0xFF4B0082,
Ivory = 0xFFFFFFF0,
Khaki = 0xFFF0E68C,
Lavender = 0xFFE6E6FA,
LavenderBlush = 0xFFFFF0F5,
LawnGreen = 0xFF7CFC00,
LemonChiffon = 0xFFFFFACD,
LightBlue = 0xFFADD8E6,
LightCoral = 0xFFF08080,
LightCyan = 0xFFE0FFFF,
LightGoldenrodYellow = 0xFFFAFAD2,
LightGreen = 0xFF90EE90,
LightGray = 0xFFD3D3D3,
LightPink = 0xFFFFB6C1,
LightSalmon = 0xFFFFA07A,
LightSeaGreen = 0xFF20B2AA,
LightSkyBlue = 0xFF87CEFA,
LightSlateGray = 0xFF778899,
LightSteelBlue = 0xFFB0C4DE,
LightYellow = 0xFFFFFFE0,
Lime = 0xFF00FF00,
LimeGreen = 0xFF32CD32,
Linen = 0xFFFAF0E6,
Magenta = 0xFFFF00FF,
Maroon = 0xFF800000,
MediumAquamarine = 0xFF66CDAA,
MediumBlue = 0xFF0000CD,
MediumOrchid = 0xFFBA55D3,
MediumPurple = 0xFF9370DB,
MediumSeaGreen = 0xFF3CB371,
MediumSlateBlue = 0xFF7B68EE,
MediumSpringGreen = 0xFF00FA9A,
MediumTurquoise = 0xFF48D1CC,
MediumVioletRed = 0xFFC71585,
MidnightBlue = 0xFF191970,
MintCream = 0xFFF5FFFA,
MistyRose = 0xFFFFE4E1,
Moccasin = 0xFFFFE4B5,
NavajoWhite = 0xFFFFDEAD,
Navy = 0xFF000080,
OldLace = 0xFFFDF5E6,
Olive = 0xFF808000,
OliveDrab = 0xFF6B8E23,
Orange = 0xFFFFA500,
OrangeRed = 0xFFFF4500,
Orchid = 0xFFDA70D6,
PaleGoldenrod = 0xFFEEE8AA,
PaleGreen = 0xFF98FB98,
PaleTurquoise = 0xFFAFEEEE,
PaleVioletRed = 0xFFDB7093,
PapayaWhip = 0xFFFFEFD5,
PeachPuff = 0xFFFFDAB9,
Peru = 0xFFCD853F,
Pink = 0xFFFFC0CB,
Plum = 0xFFDDA0DD,
PowderBlue = 0xFFB0E0E6,
Purple = 0xFF800080,
Red = 0xFFFF0000,
RosyBrown = 0xFFBC8F8F,
RoyalBlue = 0xFF4169E1,
SaddleBrown = 0xFF8B4513,
Salmon = 0xFFFA8072,
SandyBrown = 0xFFF4A460,
SeaGreen = 0xFF2E8B57,
SeaShell = 0xFFFFF5EE,
Sienna = 0xFFA0522D,
Silver = 0xFFC0C0C0,
SkyBlue = 0xFF87CEEB,
SlateBlue = 0xFF6A5ACD,
SlateGray = 0xFF708090,
Snow = 0xFFFFFAFA,
SpringGreen = 0xFF00FF7F,
SteelBlue = 0xFF4682B4,
Tan = 0xFFD2B48C,
Teal = 0xFF008080,
Thistle = 0xFFD8BFD8,
Tomato = 0xFFFF6347,
Transparent = 0x00FFFFFF,
Turquoise = 0xFF40E0D0,
Violet = 0xFFEE82EE,
Wheat = 0xFFF5DEB3,
White = 0xFFFFFFFF,
WhiteSmoke = 0xFFF5F5F5,
Yellow = 0xFFFFFF00,
YellowGreen = 0xFF9ACD32,
UnknownColor = 0x00000001
}
internal static class KnownColors
{
#if !PBTCOMPILER
static KnownColors()
{
Array knownColorValues = Enum.GetValues(typeof(KnownColor));
foreach (KnownColor colorValue in knownColorValues)
{
string aRGBString = String.Format("#{0,8:X8}", (uint)colorValue);
s_knownArgbColors[aRGBString] = colorValue;
}
}
/// Return the solid color brush from a color string. If there's no match, null
public static SolidColorBrush ColorStringToKnownBrush(string s)
{
if (null != s)
{
KnownColor result = ColorStringToKnownColor(s);
// If the result is UnknownColor, that means this string wasn't found
if (result != KnownColor.UnknownColor)
{
// Otherwise, return the appropriate SolidColorBrush
return SolidColorBrushFromUint((uint)result);
}
}
return null;
}
public static bool IsKnownSolidColorBrush(SolidColorBrush scp)
{
lock(s_solidColorBrushCache)
{
return s_solidColorBrushCache.ContainsValue(scp);
}
}
public static SolidColorBrush SolidColorBrushFromUint(uint argb)
{
SolidColorBrush scp = null;
lock(s_solidColorBrushCache)
{
// Attempt to retrieve the color. If it fails create it.
if (!s_solidColorBrushCache.TryGetValue(argb, out scp))
{
scp = new SolidColorBrush(Color.FromUInt32(argb));
scp.Freeze();
s_solidColorBrushCache[argb] = scp;
}
#if DEBUG
else
{
s_count++;
}
#endif
}
return scp;
}
static internal string MatchColor(string colorString, out bool isKnownColor, out bool isNumericColor, out bool isContextColor, out bool isScRgbColor)
{
string trimmedString = colorString.Trim();
if (((trimmedString.Length == 4) ||
(trimmedString.Length == 5) ||
(trimmedString.Length == 7) ||
(trimmedString.Length == 9)) &&
(trimmedString[0] == '#'))
{
isNumericColor = true;
isScRgbColor = false;
isKnownColor = false;
isContextColor = false;
return trimmedString;
}
else
isNumericColor = false;
if ((trimmedString.StartsWith("sc#", StringComparison.Ordinal) == true))
{
isNumericColor = false;
isScRgbColor = true;
isKnownColor = false;
isContextColor = false;
}
else
{
isScRgbColor = false;
}
if ((trimmedString.StartsWith(Parsers.s_ContextColor, StringComparison.OrdinalIgnoreCase) == true))
{
isContextColor = true;
isScRgbColor = false;
isKnownColor = false;
return trimmedString;
}
else
{
isContextColor = false;
isKnownColor = true;
}
return trimmedString;
}
#endif
/// Return the KnownColor from a color string. If there's no match, KnownColor.UnknownColor
internal static KnownColor ColorStringToKnownColor(string colorString)
{
if (null != colorString)
{
// We use invariant culture because we don't globalize our color names
string colorUpper = colorString.ToUpper(System.Globalization.CultureInfo.InvariantCulture);
// Use String.Equals because it does explicit equality
// StartsWith/EndsWith are culture sensitive and are 4-7 times slower than Equals
switch (colorUpper.Length)
{
case 3:
if (colorUpper.Equals("RED")) return KnownColor.Red;
if (colorUpper.Equals("TAN")) return KnownColor.Tan;
break;
case 4:
switch(colorUpper[0])
{
case 'A':
if (colorUpper.Equals("AQUA")) return KnownColor.Aqua;
break;
case 'B':
if (colorUpper.Equals("BLUE")) return KnownColor.Blue;
break;
case 'C':
if (colorUpper.Equals("CYAN")) return KnownColor.Cyan;
break;
case 'G':
if (colorUpper.Equals("GOLD")) return KnownColor.Gold;
if (colorUpper.Equals("GRAY")) return KnownColor.Gray;
break;
case 'L':
if (colorUpper.Equals("LIME")) return KnownColor.Lime;
break;
case 'N':
if (colorUpper.Equals("NAVY")) return KnownColor.Navy;
break;
case 'P':
if (colorUpper.Equals("PERU")) return KnownColor.Peru;
if (colorUpper.Equals("PINK")) return KnownColor.Pink;
if (colorUpper.Equals("PLUM")) return KnownColor.Plum;
break;
case 'S':
if (colorUpper.Equals("SNOW")) return KnownColor.Snow;
break;
case 'T':
if (colorUpper.Equals("TEAL")) return KnownColor.Teal;
break;
}
break;
case 5:
switch(colorUpper[0])
{
case 'A':
if (colorUpper.Equals("AZURE")) return KnownColor.Azure;
break;
case 'B':
if (colorUpper.Equals("BEIGE")) return KnownColor.Beige;
if (colorUpper.Equals("BLACK")) return KnownColor.Black;
if (colorUpper.Equals("BROWN")) return KnownColor.Brown;
break;
case 'C':
if (colorUpper.Equals("CORAL")) return KnownColor.Coral;
break;
case 'G':
if (colorUpper.Equals("GREEN")) return KnownColor.Green;
break;
case 'I':
if (colorUpper.Equals("IVORY")) return KnownColor.Ivory;
break;
case 'K':
if (colorUpper.Equals("KHAKI")) return KnownColor.Khaki;
break;
case 'L':
if (colorUpper.Equals("LINEN")) return KnownColor.Linen;
break;
case 'O':
if (colorUpper.Equals("OLIVE")) return KnownColor.Olive;
break;
case 'W':
if (colorUpper.Equals("WHEAT")) return KnownColor.Wheat;
if (colorUpper.Equals("WHITE")) return KnownColor.White;
break;
}
break;
case 6:
switch(colorUpper[0])
{
case 'B':
if (colorUpper.Equals("BISQUE")) return KnownColor.Bisque;
break;
case 'I':
if (colorUpper.Equals("INDIGO")) return KnownColor.Indigo;
break;
case 'M':
if (colorUpper.Equals("MAROON")) return KnownColor.Maroon;
break;
case 'O':
if (colorUpper.Equals("ORANGE")) return KnownColor.Orange;
if (colorUpper.Equals("ORCHID")) return KnownColor.Orchid;
break;
case 'P':
if (colorUpper.Equals("PURPLE")) return KnownColor.Purple;
break;
case 'S':
if (colorUpper.Equals("SALMON")) return KnownColor.Salmon;
if (colorUpper.Equals("SIENNA")) return KnownColor.Sienna;
if (colorUpper.Equals("SILVER")) return KnownColor.Silver;
break;
case 'T':
if (colorUpper.Equals("TOMATO")) return KnownColor.Tomato;
break;
case 'V':
if (colorUpper.Equals("VIOLET")) return KnownColor.Violet;
break;
case 'Y':
if (colorUpper.Equals("YELLOW")) return KnownColor.Yellow;
break;
}
break;
case 7:
switch(colorUpper[0])
{
case 'C':
if (colorUpper.Equals("CRIMSON")) return KnownColor.Crimson;
break;
case 'D':
if (colorUpper.Equals("DARKRED")) return KnownColor.DarkRed;
if (colorUpper.Equals("DIMGRAY")) return KnownColor.DimGray;
break;
case 'F':
if (colorUpper.Equals("FUCHSIA")) return KnownColor.Fuchsia;
break;
case 'H':
if (colorUpper.Equals("HOTPINK")) return KnownColor.HotPink;
break;
case 'M':
if (colorUpper.Equals("MAGENTA")) return KnownColor.Magenta;
break;
case 'O':
if (colorUpper.Equals("OLDLACE")) return KnownColor.OldLace;
break;
case 'S':
if (colorUpper.Equals("SKYBLUE")) return KnownColor.SkyBlue;
break;
case 'T':
if (colorUpper.Equals("THISTLE")) return KnownColor.Thistle;
break;
}
break;
case 8:
switch(colorUpper[0])
{
case 'C':
if (colorUpper.Equals("CORNSILK")) return KnownColor.Cornsilk;
break;
case 'D':
if (colorUpper.Equals("DARKBLUE")) return KnownColor.DarkBlue;
if (colorUpper.Equals("DARKCYAN")) return KnownColor.DarkCyan;
if (colorUpper.Equals("DARKGRAY")) return KnownColor.DarkGray;
if (colorUpper.Equals("DEEPPINK")) return KnownColor.DeepPink;
break;
case 'H':
if (colorUpper.Equals("HONEYDEW")) return KnownColor.Honeydew;
break;
case 'L':
if (colorUpper.Equals("LAVENDER")) return KnownColor.Lavender;
break;
case 'M':
if (colorUpper.Equals("MOCCASIN")) return KnownColor.Moccasin;
break;
case 'S':
if (colorUpper.Equals("SEAGREEN")) return KnownColor.SeaGreen;
if (colorUpper.Equals("SEASHELL")) return KnownColor.SeaShell;
break;
}
break;
case 9:
switch(colorUpper[0])
{
case 'A':
if (colorUpper.Equals("ALICEBLUE")) return KnownColor.AliceBlue;
break;
case 'B':
if (colorUpper.Equals("BURLYWOOD")) return KnownColor.BurlyWood;
break;
case 'C':
if (colorUpper.Equals("CADETBLUE")) return KnownColor.CadetBlue;
if (colorUpper.Equals("CHOCOLATE")) return KnownColor.Chocolate;
break;
case 'D':
if (colorUpper.Equals("DARKGREEN")) return KnownColor.DarkGreen;
if (colorUpper.Equals("DARKKHAKI")) return KnownColor.DarkKhaki;
break;
case 'F':
if (colorUpper.Equals("FIREBRICK")) return KnownColor.Firebrick;
break;
case 'G':
if (colorUpper.Equals("GAINSBORO")) return KnownColor.Gainsboro;
if (colorUpper.Equals("GOLDENROD")) return KnownColor.Goldenrod;
break;
case 'I':
if (colorUpper.Equals("INDIANRED")) return KnownColor.IndianRed;
break;
case 'L':
if (colorUpper.Equals("LAWNGREEN")) return KnownColor.LawnGreen;
if (colorUpper.Equals("LIGHTBLUE")) return KnownColor.LightBlue;
if (colorUpper.Equals("LIGHTCYAN")) return KnownColor.LightCyan;
if (colorUpper.Equals("LIGHTGRAY")) return KnownColor.LightGray;
if (colorUpper.Equals("LIGHTPINK")) return KnownColor.LightPink;
if (colorUpper.Equals("LIMEGREEN")) return KnownColor.LimeGreen;
break;
case 'M':
if (colorUpper.Equals("MINTCREAM")) return KnownColor.MintCream;
if (colorUpper.Equals("MISTYROSE")) return KnownColor.MistyRose;
break;
case 'O':
if (colorUpper.Equals("OLIVEDRAB")) return KnownColor.OliveDrab;
if (colorUpper.Equals("ORANGERED")) return KnownColor.OrangeRed;
break;
case 'P':
if (colorUpper.Equals("PALEGREEN")) return KnownColor.PaleGreen;
if (colorUpper.Equals("PEACHPUFF")) return KnownColor.PeachPuff;
break;
case 'R':
if (colorUpper.Equals("ROSYBROWN")) return KnownColor.RosyBrown;
if (colorUpper.Equals("ROYALBLUE")) return KnownColor.RoyalBlue;
break;
case 'S':
if (colorUpper.Equals("SLATEBLUE")) return KnownColor.SlateBlue;
if (colorUpper.Equals("SLATEGRAY")) return KnownColor.SlateGray;
if (colorUpper.Equals("STEELBLUE")) return KnownColor.SteelBlue;
break;
case 'T':
if (colorUpper.Equals("TURQUOISE")) return KnownColor.Turquoise;
break;
}
break;
case 10:
switch(colorUpper[0])
{
case 'A':
if (colorUpper.Equals("AQUAMARINE")) return KnownColor.Aquamarine;
break;
case 'B':
if (colorUpper.Equals("BLUEVIOLET")) return KnownColor.BlueViolet;
break;
case 'C':
if (colorUpper.Equals("CHARTREUSE")) return KnownColor.Chartreuse;
break;
case 'D':
if (colorUpper.Equals("DARKORANGE")) return KnownColor.DarkOrange;
if (colorUpper.Equals("DARKORCHID")) return KnownColor.DarkOrchid;
if (colorUpper.Equals("DARKSALMON")) return KnownColor.DarkSalmon;
if (colorUpper.Equals("DARKVIOLET")) return KnownColor.DarkViolet;
if (colorUpper.Equals("DODGERBLUE")) return KnownColor.DodgerBlue;
break;
case 'G':
if (colorUpper.Equals("GHOSTWHITE")) return KnownColor.GhostWhite;
break;
case 'L':
if (colorUpper.Equals("LIGHTCORAL")) return KnownColor.LightCoral;
if (colorUpper.Equals("LIGHTGREEN")) return KnownColor.LightGreen;
break;
case 'M':
if (colorUpper.Equals("MEDIUMBLUE")) return KnownColor.MediumBlue;
break;
case 'P':
if (colorUpper.Equals("PAPAYAWHIP")) return KnownColor.PapayaWhip;
if (colorUpper.Equals("POWDERBLUE")) return KnownColor.PowderBlue;
break;
case 'S':
if (colorUpper.Equals("SANDYBROWN")) return KnownColor.SandyBrown;
break;
case 'W':
if (colorUpper.Equals("WHITESMOKE")) return KnownColor.WhiteSmoke;
break;
}
break;
case 11:
switch(colorUpper[0])
{
case 'D':
if (colorUpper.Equals("DARKMAGENTA")) return KnownColor.DarkMagenta;
if (colorUpper.Equals("DEEPSKYBLUE")) return KnownColor.DeepSkyBlue;
break;
case 'F':
if (colorUpper.Equals("FLORALWHITE")) return KnownColor.FloralWhite;
if (colorUpper.Equals("FORESTGREEN")) return KnownColor.ForestGreen;
break;
case 'G':
if (colorUpper.Equals("GREENYELLOW")) return KnownColor.GreenYellow;
break;
case 'L':
if (colorUpper.Equals("LIGHTSALMON")) return KnownColor.LightSalmon;
if (colorUpper.Equals("LIGHTYELLOW")) return KnownColor.LightYellow;
break;
case 'N':
if (colorUpper.Equals("NAVAJOWHITE")) return KnownColor.NavajoWhite;
break;
case 'S':
if (colorUpper.Equals("SADDLEBROWN")) return KnownColor.SaddleBrown;
if (colorUpper.Equals("SPRINGGREEN")) return KnownColor.SpringGreen;
break;
case 'T':
if (colorUpper.Equals("TRANSPARENT")) return KnownColor.Transparent;
break;
case 'Y':
if (colorUpper.Equals("YELLOWGREEN")) return KnownColor.YellowGreen;
break;
}
break;
case 12:
switch(colorUpper[0])
{
case 'A':
if (colorUpper.Equals("ANTIQUEWHITE")) return KnownColor.AntiqueWhite;
break;
case 'D':
if (colorUpper.Equals("DARKSEAGREEN")) return KnownColor.DarkSeaGreen;
break;
case 'L':
if (colorUpper.Equals("LIGHTSKYBLUE")) return KnownColor.LightSkyBlue;
if (colorUpper.Equals("LEMONCHIFFON")) return KnownColor.LemonChiffon;
break;
case 'M':
if (colorUpper.Equals("MEDIUMORCHID")) return KnownColor.MediumOrchid;
if (colorUpper.Equals("MEDIUMPURPLE")) return KnownColor.MediumPurple;
if (colorUpper.Equals("MIDNIGHTBLUE")) return KnownColor.MidnightBlue;
break;
}
break;
case 13:
switch(colorUpper[0])
{
case 'D':
if (colorUpper.Equals("DARKSLATEBLUE")) return KnownColor.DarkSlateBlue;
if (colorUpper.Equals("DARKSLATEGRAY")) return KnownColor.DarkSlateGray;
if (colorUpper.Equals("DARKGOLDENROD")) return KnownColor.DarkGoldenrod;
if (colorUpper.Equals("DARKTURQUOISE")) return KnownColor.DarkTurquoise;
break;
case 'L':
if (colorUpper.Equals("LIGHTSEAGREEN")) return KnownColor.LightSeaGreen;
if (colorUpper.Equals("LAVENDERBLUSH")) return KnownColor.LavenderBlush;
break;
case 'P':
if (colorUpper.Equals("PALEGOLDENROD")) return KnownColor.PaleGoldenrod;
if (colorUpper.Equals("PALETURQUOISE")) return KnownColor.PaleTurquoise;
if (colorUpper.Equals("PALEVIOLETRED")) return KnownColor.PaleVioletRed;
break;
}
break;
case 14:
switch(colorUpper[0])
{
case 'B':
if (colorUpper.Equals("BLANCHEDALMOND")) return KnownColor.BlanchedAlmond;
break;
case 'C':
if (colorUpper.Equals("CORNFLOWERBLUE")) return KnownColor.CornflowerBlue;
break;
case 'D':
if (colorUpper.Equals("DARKOLIVEGREEN")) return KnownColor.DarkOliveGreen;
break;
case 'L':
if (colorUpper.Equals("LIGHTSLATEGRAY")) return KnownColor.LightSlateGray;
if (colorUpper.Equals("LIGHTSTEELBLUE")) return KnownColor.LightSteelBlue;
break;
case 'M':
if (colorUpper.Equals("MEDIUMSEAGREEN")) return KnownColor.MediumSeaGreen;
break;
}
break;
case 15:
if (colorUpper.Equals("MEDIUMSLATEBLUE")) return KnownColor.MediumSlateBlue;
if (colorUpper.Equals("MEDIUMTURQUOISE")) return KnownColor.MediumTurquoise;
if (colorUpper.Equals("MEDIUMVIOLETRED")) return KnownColor.MediumVioletRed;
break;
case 16:
if (colorUpper.Equals("MEDIUMAQUAMARINE")) return KnownColor.MediumAquamarine;
break;
case 17:
if (colorUpper.Equals("MEDIUMSPRINGGREEN")) return KnownColor.MediumSpringGreen;
break;
case 20:
if (colorUpper.Equals("LIGHTGOLDENRODYELLOW")) return KnownColor.LightGoldenrodYellow;
break;
}
}
// colorString was null or not found
return KnownColor.UnknownColor;
}
#if !PBTCOMPILER
internal static KnownColor ArgbStringToKnownColor(string argbString)
{
string argbUpper = argbString.Trim().ToUpper(System.Globalization.CultureInfo.InvariantCulture);
KnownColor color;
if (s_knownArgbColors.TryGetValue(argbUpper, out color))
return color;
return KnownColor.UnknownColor;
}
#if DEBUG
private static int s_count = 0;
#endif
private static Dictionary<uint, SolidColorBrush> s_solidColorBrushCache = new Dictionary<uint, SolidColorBrush>();
private static Dictionary<string, KnownColor> s_knownArgbColors = new Dictionary<string, KnownColor>();
#endif
}
#if !PBTCOMPILER
/// <summary>
/// Colors - A collection of well-known Colors
/// </summary>
public sealed class Colors
{
#region Constructors
// Colors only has static members, so it shouldn't be constructable.
private Colors()
{
}
#endregion Constructors
#region static Known Colors
/// <summary>
/// Well-known color: AliceBlue
/// </summary>
public static Color AliceBlue
{
get
{
return Color.FromUInt32((uint)KnownColor.AliceBlue);
}
}
/// <summary>
/// Well-known color: AntiqueWhite
/// </summary>
public static Color AntiqueWhite
{
get
{
return Color.FromUInt32((uint)KnownColor.AntiqueWhite);
}
}
/// <summary>
/// Well-known color: Aqua
/// </summary>
public static Color Aqua
{
get
{
return Color.FromUInt32((uint)KnownColor.Aqua);
}
}
/// <summary>
/// Well-known color: Aquamarine
/// </summary>
public static Color Aquamarine
{
get
{
return Color.FromUInt32((uint)KnownColor.Aquamarine);
}
}
/// <summary>
/// Well-known color: Azure
/// </summary>
public static Color Azure
{
get
{
return Color.FromUInt32((uint)KnownColor.Azure);
}
}
/// <summary>
/// Well-known color: Beige
/// </summary>
public static Color Beige
{
get
{
return Color.FromUInt32((uint)KnownColor.Beige);
}
}
/// <summary>
/// Well-known color: Bisque
/// </summary>
public static Color Bisque
{
get
{
return Color.FromUInt32((uint)KnownColor.Bisque);
}
}
/// <summary>
/// Well-known color: Black
/// </summary>
public static Color Black
{
get
{
return Color.FromUInt32((uint)KnownColor.Black);
}
}
/// <summary>
/// Well-known color: BlanchedAlmond
/// </summary>
public static Color BlanchedAlmond
{
get
{
return Color.FromUInt32((uint)KnownColor.BlanchedAlmond);
}
}
/// <summary>
/// Well-known color: Blue
/// </summary>
public static Color Blue
{
get
{
return Color.FromUInt32((uint)KnownColor.Blue);
}
}
/// <summary>
/// Well-known color: BlueViolet
/// </summary>
public static Color BlueViolet
{
get
{
return Color.FromUInt32((uint)KnownColor.BlueViolet);
}
}
/// <summary>
/// Well-known color: Brown
/// </summary>
public static Color Brown
{
get
{
return Color.FromUInt32((uint)KnownColor.Brown);
}
}
/// <summary>
/// Well-known color: BurlyWood
/// </summary>
public static Color BurlyWood
{
get
{
return Color.FromUInt32((uint)KnownColor.BurlyWood);
}
}
/// <summary>
/// Well-known color: CadetBlue
/// </summary>
public static Color CadetBlue
{
get
{
return Color.FromUInt32((uint)KnownColor.CadetBlue);
}
}
/// <summary>
/// Well-known color: Chartreuse
/// </summary>
public static Color Chartreuse
{
get
{
return Color.FromUInt32((uint)KnownColor.Chartreuse);
}
}
/// <summary>
/// Well-known color: Chocolate
/// </summary>
public static Color Chocolate
{
get
{
return Color.FromUInt32((uint)KnownColor.Chocolate);
}
}
/// <summary>
/// Well-known color: Coral
/// </summary>
public static Color Coral
{
get
{
return Color.FromUInt32((uint)KnownColor.Coral);
}
}
/// <summary>
/// Well-known color: CornflowerBlue
/// </summary>
public static Color CornflowerBlue
{
get
{
return Color.FromUInt32((uint)KnownColor.CornflowerBlue);
}
}
/// <summary>
/// Well-known color: Cornsilk
/// </summary>
public static Color Cornsilk
{
get
{
return Color.FromUInt32((uint)KnownColor.Cornsilk);
}
}
/// <summary>
/// Well-known color: Crimson
/// </summary>
public static Color Crimson
{
get
{
return Color.FromUInt32((uint)KnownColor.Crimson);
}
}
/// <summary>
/// Well-known color: Cyan
/// </summary>
public static Color Cyan
{
get
{
return Color.FromUInt32((uint)KnownColor.Cyan);
}
}
/// <summary>
/// Well-known color: DarkBlue
/// </summary>
public static Color DarkBlue
{
get
{
return Color.FromUInt32((uint)KnownColor.DarkBlue);
}
}
/// <summary>
/// Well-known color: DarkCyan
/// </summary>
public static Color DarkCyan
{
get
{
return Color.FromUInt32((uint)KnownColor.DarkCyan);
}
}
/// <summary>
/// Well-known color: DarkGoldenrod
/// </summary>
public static Color DarkGoldenrod
{
get
{
return Color.FromUInt32((uint)KnownColor.DarkGoldenrod);
}
}
/// <summary>
/// Well-known color: DarkGray
/// </summary>
public static Color DarkGray
{
get
{
return Color.FromUInt32((uint)KnownColor.DarkGray);
}
}
/// <summary>
/// Well-known color: DarkGreen
/// </summary>
public static Color DarkGreen
{
get
{
return Color.FromUInt32((uint)KnownColor.DarkGreen);
}
}
/// <summary>
/// Well-known color: DarkKhaki
/// </summary>
public static Color DarkKhaki
{
get
{
return Color.FromUInt32((uint)KnownColor.DarkKhaki);
}
}
/// <summary>
/// Well-known color: DarkMagenta
/// </summary>
public static Color DarkMagenta
{
get
{
return Color.FromUInt32((uint)KnownColor.DarkMagenta);
}
}
/// <summary>
/// Well-known color: DarkOliveGreen
/// </summary>
public static Color DarkOliveGreen
{
get
{
return Color.FromUInt32((uint)KnownColor.DarkOliveGreen);
}
}
/// <summary>
/// Well-known color: DarkOrange
/// </summary>
public static Color DarkOrange
{
get
{
return Color.FromUInt32((uint)KnownColor.DarkOrange);
}
}
/// <summary>
/// Well-known color: DarkOrchid
/// </summary>
public static Color DarkOrchid
{
get
{
return Color.FromUInt32((uint)KnownColor.DarkOrchid);
}
}
/// <summary>
/// Well-known color: DarkRed
/// </summary>
public static Color DarkRed
{
get
{
return Color.FromUInt32((uint)KnownColor.DarkRed);
}
}
/// <summary>
/// Well-known color: DarkSalmon
/// </summary>
public static Color DarkSalmon
{
get
{
return Color.FromUInt32((uint)KnownColor.DarkSalmon);
}
}
/// <summary>
/// Well-known color: DarkSeaGreen
/// </summary>
public static Color DarkSeaGreen
{
get
{
return Color.FromUInt32((uint)KnownColor.DarkSeaGreen);
}
}
/// <summary>
/// Well-known color: DarkSlateBlue
/// </summary>
public static Color DarkSlateBlue
{
get
{
return Color.FromUInt32((uint)KnownColor.DarkSlateBlue);
}
}
/// <summary>
/// Well-known color: DarkSlateGray
/// </summary>
public static Color DarkSlateGray
{
get
{
return Color.FromUInt32((uint)KnownColor.DarkSlateGray);
}
}
/// <summary>
/// Well-known color: DarkTurquoise
/// </summary>
public static Color DarkTurquoise
{
get
{
return Color.FromUInt32((uint)KnownColor.DarkTurquoise);
}
}
/// <summary>
/// Well-known color: DarkViolet
/// </summary>
public static Color DarkViolet
{
get
{
return Color.FromUInt32((uint)KnownColor.DarkViolet);
}
}
/// <summary>
/// Well-known color: DeepPink
/// </summary>
public static Color DeepPink
{
get
{
return Color.FromUInt32((uint)KnownColor.DeepPink);
}
}
/// <summary>
/// Well-known color: DeepSkyBlue
/// </summary>
public static Color DeepSkyBlue
{
get
{
return Color.FromUInt32((uint)KnownColor.DeepSkyBlue);
}
}
/// <summary>
/// Well-known color: DimGray
/// </summary>
public static Color DimGray
{
get
{
return Color.FromUInt32((uint)KnownColor.DimGray);
}
}
/// <summary>
/// Well-known color: DodgerBlue
/// </summary>
public static Color DodgerBlue
{
get
{
return Color.FromUInt32((uint)KnownColor.DodgerBlue);
}
}
/// <summary>
/// Well-known color: Firebrick
/// </summary>
public static Color Firebrick
{
get
{
return Color.FromUInt32((uint)KnownColor.Firebrick);
}
}
/// <summary>
/// Well-known color: FloralWhite
/// </summary>
public static Color FloralWhite
{
get
{
return Color.FromUInt32((uint)KnownColor.FloralWhite);
}
}
/// <summary>
/// Well-known color: ForestGreen
/// </summary>
public static Color ForestGreen
{
get
{
return Color.FromUInt32((uint)KnownColor.ForestGreen);
}
}
/// <summary>
/// Well-known color: Fuchsia
/// </summary>
public static Color Fuchsia
{
get
{
return Color.FromUInt32((uint)KnownColor.Fuchsia);
}
}
/// <summary>
/// Well-known color: Gainsboro
/// </summary>
public static Color Gainsboro
{
get
{
return Color.FromUInt32((uint)KnownColor.Gainsboro);
}
}
/// <summary>
/// Well-known color: GhostWhite
/// </summary>
public static Color GhostWhite
{
get
{
return Color.FromUInt32((uint)KnownColor.GhostWhite);
}
}
/// <summary>
/// Well-known color: Gold
/// </summary>
public static Color Gold
{
get
{
return Color.FromUInt32((uint)KnownColor.Gold);
}
}
/// <summary>
/// Well-known color: Goldenrod
/// </summary>
public static Color Goldenrod
{
get
{
return Color.FromUInt32((uint)KnownColor.Goldenrod);
}
}
/// <summary>
/// Well-known color: Gray
/// </summary>
public static Color Gray
{
get
{
return Color.FromUInt32((uint)KnownColor.Gray);
}
}
/// <summary>
/// Well-known color: Green
/// </summary>
public static Color Green
{
get
{
return Color.FromUInt32((uint)KnownColor.Green);
}
}
/// <summary>
/// Well-known color: GreenYellow
/// </summary>
public static Color GreenYellow
{
get
{
return Color.FromUInt32((uint)KnownColor.GreenYellow);
}
}
/// <summary>
/// Well-known color: Honeydew
/// </summary>
public static Color Honeydew
{
get
{
return Color.FromUInt32((uint)KnownColor.Honeydew);
}
}
/// <summary>
/// Well-known color: HotPink
/// </summary>
public static Color HotPink
{
get
{
return Color.FromUInt32((uint)KnownColor.HotPink);
}
}
/// <summary>
/// Well-known color: IndianRed
/// </summary>
public static Color IndianRed
{
get
{
return Color.FromUInt32((uint)KnownColor.IndianRed);
}
}
/// <summary>
/// Well-known color: Indigo
/// </summary>
public static Color Indigo
{
get
{
return Color.FromUInt32((uint)KnownColor.Indigo);
}
}
/// <summary>
/// Well-known color: Ivory
/// </summary>
public static Color Ivory
{
get
{
return Color.FromUInt32((uint)KnownColor.Ivory);
}
}
/// <summary>
/// Well-known color: Khaki
/// </summary>
public static Color Khaki
{
get
{
return Color.FromUInt32((uint)KnownColor.Khaki);
}
}
/// <summary>
/// Well-known color: Lavender
/// </summary>
public static Color Lavender
{
get
{
return Color.FromUInt32((uint)KnownColor.Lavender);
}
}
/// <summary>
/// Well-known color: LavenderBlush
/// </summary>
public static Color LavenderBlush
{
get
{
return Color.FromUInt32((uint)KnownColor.LavenderBlush);
}
}
/// <summary>
/// Well-known color: LawnGreen
/// </summary>
public static Color LawnGreen
{
get
{
return Color.FromUInt32((uint)KnownColor.LawnGreen);
}
}
/// <summary>
/// Well-known color: LemonChiffon
/// </summary>
public static Color LemonChiffon
{
get
{
return Color.FromUInt32((uint)KnownColor.LemonChiffon);
}
}
/// <summary>
/// Well-known color: LightBlue
/// </summary>
public static Color LightBlue
{
get
{
return Color.FromUInt32((uint)KnownColor.LightBlue);
}
}
/// <summary>
/// Well-known color: LightCoral
/// </summary>
public static Color LightCoral
{
get
{
return Color.FromUInt32((uint)KnownColor.LightCoral);
}
}
/// <summary>
/// Well-known color: LightCyan
/// </summary>
public static Color LightCyan
{
get
{
return Color.FromUInt32((uint)KnownColor.LightCyan);
}
}
/// <summary>
/// Well-known color: LightGoldenrodYellow
/// </summary>
public static Color LightGoldenrodYellow
{
get
{
return Color.FromUInt32((uint)KnownColor.LightGoldenrodYellow);
}
}
/// <summary>
/// Well-known color: LightGray
/// </summary>
public static Color LightGray
{
get
{
return Color.FromUInt32((uint)KnownColor.LightGray);
}
}
/// <summary>
/// Well-known color: LightGreen
/// </summary>
public static Color LightGreen
{
get
{
return Color.FromUInt32((uint)KnownColor.LightGreen);
}
}
/// <summary>
/// Well-known color: LightPink
/// </summary>
public static Color LightPink
{
get
{
return Color.FromUInt32((uint)KnownColor.LightPink);
}
}
/// <summary>
/// Well-known color: LightSalmon
/// </summary>
public static Color LightSalmon
{
get
{
return Color.FromUInt32((uint)KnownColor.LightSalmon);
}
}
/// <summary>
/// Well-known color: LightSeaGreen
/// </summary>
public static Color LightSeaGreen
{
get
{
return Color.FromUInt32((uint)KnownColor.LightSeaGreen);
}
}
/// <summary>
/// Well-known color: LightSkyBlue
/// </summary>
public static Color LightSkyBlue
{
get
{
return Color.FromUInt32((uint)KnownColor.LightSkyBlue);
}
}
/// <summary>
/// Well-known color: LightSlateGray
/// </summary>
public static Color LightSlateGray
{
get
{
return Color.FromUInt32((uint)KnownColor.LightSlateGray);
}
}
/// <summary>
/// Well-known color: LightSteelBlue
/// </summary>
public static Color LightSteelBlue
{
get
{
return Color.FromUInt32((uint)KnownColor.LightSteelBlue);
}
}
/// <summary>
/// Well-known color: LightYellow
/// </summary>
public static Color LightYellow
{
get
{
return Color.FromUInt32((uint)KnownColor.LightYellow);
}
}
/// <summary>
/// Well-known color: Lime
/// </summary>
public static Color Lime
{
get
{
return Color.FromUInt32((uint)KnownColor.Lime);
}
}
/// <summary>
/// Well-known color: LimeGreen
/// </summary>
public static Color LimeGreen
{
get
{
return Color.FromUInt32((uint)KnownColor.LimeGreen);
}
}
/// <summary>
/// Well-known color: Linen
/// </summary>
public static Color Linen
{
get
{
return Color.FromUInt32((uint)KnownColor.Linen);
}
}
/// <summary>
/// Well-known color: Magenta
/// </summary>
public static Color Magenta
{
get
{
return Color.FromUInt32((uint)KnownColor.Magenta);
}
}
/// <summary>
/// Well-known color: Maroon
/// </summary>
public static Color Maroon
{
get
{
return Color.FromUInt32((uint)KnownColor.Maroon);
}
}
/// <summary>
/// Well-known color: MediumAquamarine
/// </summary>
public static Color MediumAquamarine
{
get
{
return Color.FromUInt32((uint)KnownColor.MediumAquamarine);
}
}
/// <summary>
/// Well-known color: MediumBlue
/// </summary>
public static Color MediumBlue
{
get
{
return Color.FromUInt32((uint)KnownColor.MediumBlue);
}
}
/// <summary>
/// Well-known color: MediumOrchid
/// </summary>
public static Color MediumOrchid
{
get
{
return Color.FromUInt32((uint)KnownColor.MediumOrchid);
}
}
/// <summary>
/// Well-known color: MediumPurple
/// </summary>
public static Color MediumPurple
{
get
{
return Color.FromUInt32((uint)KnownColor.MediumPurple);
}
}
/// <summary>
/// Well-known color: MediumSeaGreen
/// </summary>
public static Color MediumSeaGreen
{
get
{
return Color.FromUInt32((uint)KnownColor.MediumSeaGreen);
}
}
/// <summary>
/// Well-known color: MediumSlateBlue
/// </summary>
public static Color MediumSlateBlue
{
get
{
return Color.FromUInt32((uint)KnownColor.MediumSlateBlue);
}
}
/// <summary>
/// Well-known color: MediumSpringGreen
/// </summary>
public static Color MediumSpringGreen
{
get
{
return Color.FromUInt32((uint)KnownColor.MediumSpringGreen);
}
}
/// <summary>
/// Well-known color: MediumTurquoise
/// </summary>
public static Color MediumTurquoise
{
get
{
return Color.FromUInt32((uint)KnownColor.MediumTurquoise);
}
}
/// <summary>
/// Well-known color: MediumVioletRed
/// </summary>
public static Color MediumVioletRed
{
get
{
return Color.FromUInt32((uint)KnownColor.MediumVioletRed);
}
}
/// <summary>
/// Well-known color: MidnightBlue
/// </summary>
public static Color MidnightBlue
{
get
{
return Color.FromUInt32((uint)KnownColor.MidnightBlue);
}
}
/// <summary>
/// Well-known color: MintCream
/// </summary>
public static Color MintCream
{
get
{
return Color.FromUInt32((uint)KnownColor.MintCream);
}
}
/// <summary>
/// Well-known color: MistyRose
/// </summary>
public static Color MistyRose
{
get
{
return Color.FromUInt32((uint)KnownColor.MistyRose);
}
}
/// <summary>
/// Well-known color: Moccasin
/// </summary>
public static Color Moccasin
{
get
{
return Color.FromUInt32((uint)KnownColor.Moccasin);
}
}
/// <summary>
/// Well-known color: NavajoWhite
/// </summary>
public static Color NavajoWhite
{
get
{
return Color.FromUInt32((uint)KnownColor.NavajoWhite);
}
}
/// <summary>
/// Well-known color: Navy
/// </summary>
public static Color Navy
{
get
{
return Color.FromUInt32((uint)KnownColor.Navy);
}
}
/// <summary>
/// Well-known color: OldLace
/// </summary>
public static Color OldLace
{
get
{
return Color.FromUInt32((uint)KnownColor.OldLace);
}
}
/// <summary>
/// Well-known color: Olive
/// </summary>
public static Color Olive
{
get
{
return Color.FromUInt32((uint)KnownColor.Olive);
}
}
/// <summary>
/// Well-known color: OliveDrab
/// </summary>
public static Color OliveDrab
{
get
{
return Color.FromUInt32((uint)KnownColor.OliveDrab);
}
}
/// <summary>
/// Well-known color: Orange
/// </summary>
public static Color Orange
{
get
{
return Color.FromUInt32((uint)KnownColor.Orange);
}
}
/// <summary>
/// Well-known color: OrangeRed
/// </summary>
public static Color OrangeRed
{
get
{
return Color.FromUInt32((uint)KnownColor.OrangeRed);
}
}
/// <summary>
/// Well-known color: Orchid
/// </summary>
public static Color Orchid
{
get
{
return Color.FromUInt32((uint)KnownColor.Orchid);
}
}
/// <summary>
/// Well-known color: PaleGoldenrod
/// </summary>
public static Color PaleGoldenrod
{
get
{
return Color.FromUInt32((uint)KnownColor.PaleGoldenrod);
}
}
/// <summary>
/// Well-known color: PaleGreen
/// </summary>
public static Color PaleGreen
{
get
{
return Color.FromUInt32((uint)KnownColor.PaleGreen);
}
}
/// <summary>
/// Well-known color: PaleTurquoise
/// </summary>
public static Color PaleTurquoise
{
get
{
return Color.FromUInt32((uint)KnownColor.PaleTurquoise);
}
}
/// <summary>
/// Well-known color: PaleVioletRed
/// </summary>
public static Color PaleVioletRed
{
get
{
return Color.FromUInt32((uint)KnownColor.PaleVioletRed);
}
}
/// <summary>
/// Well-known color: PapayaWhip
/// </summary>
public static Color PapayaWhip
{
get
{
return Color.FromUInt32((uint)KnownColor.PapayaWhip);
}
}
/// <summary>
/// Well-known color: PeachPuff
/// </summary>
public static Color PeachPuff
{
get
{
return Color.FromUInt32((uint)KnownColor.PeachPuff);
}
}
/// <summary>
/// Well-known color: Peru
/// </summary>
public static Color Peru
{
get
{
return Color.FromUInt32((uint)KnownColor.Peru);
}
}
/// <summary>
/// Well-known color: Pink
/// </summary>
public static Color Pink
{
get
{
return Color.FromUInt32((uint)KnownColor.Pink);
}
}
/// <summary>
/// Well-known color: Plum
/// </summary>
public static Color Plum
{
get
{
return Color.FromUInt32((uint)KnownColor.Plum);
}
}
/// <summary>
/// Well-known color: PowderBlue
/// </summary>
public static Color PowderBlue
{
get
{
return Color.FromUInt32((uint)KnownColor.PowderBlue);
}
}
/// <summary>
/// Well-known color: Purple
/// </summary>
public static Color Purple
{
get
{
return Color.FromUInt32((uint)KnownColor.Purple);
}
}
/// <summary>
/// Well-known color: Red
/// </summary>
public static Color Red
{
get
{
return Color.FromUInt32((uint)KnownColor.Red);
}
}
/// <summary>
/// Well-known color: RosyBrown
/// </summary>
public static Color RosyBrown
{
get
{
return Color.FromUInt32((uint)KnownColor.RosyBrown);
}
}
/// <summary>
/// Well-known color: RoyalBlue
/// </summary>
public static Color RoyalBlue
{
get
{
return Color.FromUInt32((uint)KnownColor.RoyalBlue);
}
}
/// <summary>
/// Well-known color: SaddleBrown
/// </summary>
public static Color SaddleBrown
{
get
{
return Color.FromUInt32((uint)KnownColor.SaddleBrown);
}
}
/// <summary>
/// Well-known color: Salmon
/// </summary>
public static Color Salmon
{
get
{
return Color.FromUInt32((uint)KnownColor.Salmon);
}
}
/// <summary>
/// Well-known color: SandyBrown
/// </summary>
public static Color SandyBrown
{
get
{
return Color.FromUInt32((uint)KnownColor.SandyBrown);
}
}
/// <summary>
/// Well-known color: SeaGreen
/// </summary>
public static Color SeaGreen
{
get
{
return Color.FromUInt32((uint)KnownColor.SeaGreen);
}
}
/// <summary>
/// Well-known color: SeaShell
/// </summary>
public static Color SeaShell
{
get
{
return Color.FromUInt32((uint)KnownColor.SeaShell);
}
}
/// <summary>
/// Well-known color: Sienna
/// </summary>
public static Color Sienna
{
get
{
return Color.FromUInt32((uint)KnownColor.Sienna);
}
}
/// <summary>
/// Well-known color: Silver
/// </summary>
public static Color Silver
{
get
{
return Color.FromUInt32((uint)KnownColor.Silver);
}
}
/// <summary>
/// Well-known color: SkyBlue
/// </summary>
public static Color SkyBlue
{
get
{
return Color.FromUInt32((uint)KnownColor.SkyBlue);
}
}
/// <summary>
/// Well-known color: SlateBlue
/// </summary>
public static Color SlateBlue
{
get
{
return Color.FromUInt32((uint)KnownColor.SlateBlue);
}
}
/// <summary>
/// Well-known color: SlateGray
/// </summary>
public static Color SlateGray
{
get
{
return Color.FromUInt32((uint)KnownColor.SlateGray);
}
}
/// <summary>
/// Well-known color: Snow
/// </summary>
public static Color Snow
{
get
{
return Color.FromUInt32((uint)KnownColor.Snow);
}
}
/// <summary>
/// Well-known color: SpringGreen
/// </summary>
public static Color SpringGreen
{
get
{
return Color.FromUInt32((uint)KnownColor.SpringGreen);
}
}
/// <summary>
/// Well-known color: SteelBlue
/// </summary>
public static Color SteelBlue
{
get
{
return Color.FromUInt32((uint)KnownColor.SteelBlue);
}
}
/// <summary>
/// Well-known color: Tan
/// </summary>
public static Color Tan
{
get
{
return Color.FromUInt32((uint)KnownColor.Tan);
}
}
/// <summary>
/// Well-known color: Teal
/// </summary>
public static Color Teal
{
get
{
return Color.FromUInt32((uint)KnownColor.Teal);
}
}
/// <summary>
/// Well-known color: Thistle
/// </summary>
public static Color Thistle
{
get
{
return Color.FromUInt32((uint)KnownColor.Thistle);
}
}
/// <summary>
/// Well-known color: Tomato
/// </summary>
public static Color Tomato
{
get
{
return Color.FromUInt32((uint)KnownColor.Tomato);
}
}
/// <summary>
/// Well-known color: Transparent
/// </summary>
public static Color Transparent
{
get
{
return Color.FromUInt32((uint)KnownColor.Transparent);
}
}
/// <summary>
/// Well-known color: Turquoise
/// </summary>
public static Color Turquoise
{
get
{
return Color.FromUInt32((uint)KnownColor.Turquoise);
}
}
/// <summary>
/// Well-known color: Violet
/// </summary>
public static Color Violet
{
get
{
return Color.FromUInt32((uint)KnownColor.Violet);
}
}
/// <summary>
/// Well-known color: Wheat
/// </summary>
public static Color Wheat
{
get
{
return Color.FromUInt32((uint)KnownColor.Wheat);
}
}
/// <summary>
/// Well-known color: White
/// </summary>
public static Color White
{
get
{
return Color.FromUInt32((uint)KnownColor.White);
}
}
/// <summary>
/// Well-known color: WhiteSmoke
/// </summary>
public static Color WhiteSmoke
{
get
{
return Color.FromUInt32((uint)KnownColor.WhiteSmoke);
}
}
/// <summary>
/// Well-known color: Yellow
/// </summary>
public static Color Yellow
{
get
{
return Color.FromUInt32((uint)KnownColor.Yellow);
}
}
/// <summary>
/// Well-known color: YellowGreen
/// </summary>
public static Color YellowGreen
{
get
{
return Color.FromUInt32((uint)KnownColor.YellowGreen);
}
}
#endregion static Known Colors
}
#endif
}
| |
//------------------------------------------------------------------------------
// <copyright file="XhtmlBasicPageAdapter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Web;
using System.Collections;
using System.Collections.Specialized;
using System.Web.UI;
using System.IO;
using System.Security.Permissions;
using System.Text;
using System.Web.Mobile;
using System.Web.UI.MobileControls;
using System.Web.UI.MobileControls.Adapters;
using System.Diagnostics;
using System.Globalization;
#if COMPILING_FOR_SHIPPED_SOURCE
namespace System.Web.UI.MobileControls.ShippedAdapterSource.XhtmlAdapters
#else
namespace System.Web.UI.MobileControls.Adapters.XhtmlAdapters
#endif
{
/// <include file='doc\XhtmlBasicPageAdapter.uex' path='docs/doc[@for="XhtmlPageAdapter"]/*' />
[AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal)]
[Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")]
public class XhtmlPageAdapter : XhtmlControlAdapter, IPageAdapter {
private static readonly TimeSpan _cacheExpirationTime = new TimeSpan(0, 20, 0);
private const int DefaultPageWeight = 4000;
private IDictionary _cookielessDataDictionary = null;
private int _defaultPageWeight = DefaultPageWeight;
private int _optimumPageWeight = 0;
private MobilePage _page;
private bool _persistCookielessData = true;
private bool _pushedCssClassForBody = false;
public XhtmlPageAdapter() {
HtmlPageAdapter.SetPreferredEncodings(HttpContext.Current);
}
/// <include file='doc\XhtmlBasicPageAdapter.uex' path='docs/doc[@for="XhtmlPageAdapter.CacheVaryByHeaders"]/*' />
public virtual IList CacheVaryByHeaders {
get {
return null;
}
}
/// <include file='doc\XhtmlBasicPageAdapter.uex' path='docs/doc[@for="XhtmlPageAdapter.CookielessDataDictionary"]/*' />
public IDictionary CookielessDataDictionary {
get {
return _cookielessDataDictionary;
}
set {
_cookielessDataDictionary = value;
}
}
/// <include file='doc\XhtmlBasicPageAdapter.uex' path='docs/doc[@for="XhtmlPageAdapter.EventArgumentKey"]/*' />
public virtual String EventArgumentKey {
get {
return Constants.EventArgumentID;
}
}
/// <include file='doc\XhtmlBasicPageAdapter.uex' path='docs/doc[@for="XhtmlPageAdapter.EventSourceKey"]/*' />
public virtual String EventSourceKey {
get {
return Constants.EventSourceID;
}
}
/// <include file='doc\XhtmlBasicPageAdapter.uex' path='docs/doc[@for="XhtmlPageAdapter.OptimumPageWeight"]/*' />
public virtual int OptimumPageWeight {
get {
if (_optimumPageWeight == 0) {
_optimumPageWeight = CalculateOptimumPageWeight(_defaultPageWeight);
}
return _optimumPageWeight;
}
}
/// <include file='doc\XhtmlBasicPageAdapter.uex' path='docs/doc[@for="XhtmlPageAdapter.Page"]/*' />
public override MobilePage Page {
get {
return _page;
}
set {
_page = value;
}
}
/// <include file='doc\XhtmlBasicPageAdapter.uex' path='docs/doc[@for="XhtmlPageAdapter.PersistCookielessData"]/*' />
public bool PersistCookielessData {
get {
return _persistCookielessData;
}
set {
_persistCookielessData = value;
}
}
// Helper function to add multiple values for the same key
private void AddValues(NameValueCollection sourceCollection,
String sourceKey,
NameValueCollection targetCollection) {
String [] values = sourceCollection.GetValues(sourceKey);
foreach (String value in values) {
targetCollection.Add(sourceKey, value);
}
}
private NameValueCollection CollectionFromForm(
NameValueCollection form,
String postEventSourceID,
String postEventArgumentID) {
int i;
int count = form.Count;
NameValueCollection collection = new NameValueCollection();
bool isPostBack = false;
for (i = 0; i < count; i++) {
String name = form.GetKey(i);
if (name == null || name.Length == 0) {
continue;
}
// Pager navigation is rendered by buttons which have the
// targeted page number appended to the form id after
// PagePrefix which is a constant string to identify this
// special case. E.g. ControlID__PG_2
int index = name.LastIndexOf(Constants.PagePrefix, StringComparison.Ordinal);
if (index != -1) {
// We need to associate the form id with the event source
// id and the page number with the event argument id in
// order to have the event raised properly by ASP.NET
int pageBeginPos = index + Constants.PagePrefix.Length;
collection.Add(postEventSourceID,
name.Substring(0, index));
collection.Add(postEventArgumentID,
name.Substring(pageBeginPos,
name.Length - pageBeginPos));
continue;
}
// This is to determine if the request is a postback from
// the same mobile page.
if (name == MobilePage.ViewStateID ||
name == EventSourceKey) {
isPostBack = true;
}
// Default case, just preserve the value(s)
AddValues(form, name, collection);
}
if (collection.Count == 0 || !isPostBack) {
// Returning null to indicate this is not a postback
return null;
}
else {
return collection;
}
}
private NameValueCollection CollectionFromQueryString(
NameValueCollection queryString,
String postEventSourceID,
String postEventArgumentID) {
NameValueCollection collection = new NameValueCollection();
bool isPostBack = false;
for (int i = 0; i < queryString.Count; i++) {
String name = queryString.GetKey(i);
// ASSUMPTION: In query string, besides the expected
// name/value pairs (ViewStateID, EventSource and
// EventArgument), there are hidden variables, control
// id/value pairs (if the form submit method is GET), unique
// file path suffix variable and custom query string text.
// They will be in the above order if any of them present.
// Hidden variables and control id/value pairs should be added
// back to the collection intactly, but the other 2 items
// should not be added to the collection.
// name can be null if there is a query name without equal
// sign appended. We should just ignored it in this case.
if (name == null) {
continue;
}
else if (name == MobilePage.ViewStateID) {
collection.Add(MobilePage.ViewStateID, queryString.Get(i));
isPostBack = true;
}
else if (name == Constants.EventSourceID) {
collection.Add(postEventSourceID, queryString.Get(i));
isPostBack = true;
}
else if (name == Constants.EventArgumentID) {
collection.Add(postEventArgumentID, queryString.Get(i));
}
else if (Constants.UniqueFilePathSuffixVariable.StartsWith(name, StringComparison.Ordinal)) {
// At this point we know that the rest of them is
// the custom query string text, so we are done.
break;
}
else {
AddValues(queryString, name, collection);
}
}
if (collection.Count == 0 || !isPostBack) {
// Returning null to indicate this is not a postback
return null;
}
else {
return collection;
}
}
private void ConditionalRenderLinkElement (XhtmlMobileTextWriter writer) {
if (DoesDeviceRequireCssSuppression()) {
return;
}
String cssLocation = (String) Page.ActiveForm.CustomAttributes[XhtmlConstants.StyleSheetLocationCustomAttribute];
if (cssLocation != null &&
cssLocation.Length != 0) {
writer.WriteBeginTag ("link");
writer.WriteAttribute ("type", "text/css");
writer.WriteAttribute ("rel", "stylesheet");
writer.WriteAttribute("href", cssLocation, true);
writer.WriteLine("/>");
}
else if (!writer.IsStyleSheetEmpty () && CssLocation!=StyleSheetLocation.Internal) {
writer.WriteLine ();
writer.WriteBeginTag ("link");
writer.WriteAttribute ("type", "text/css");
writer.WriteAttribute ("rel", "stylesheet");
String queryStringValue = GetCssQueryStringValue(writer);
writer.Write(" href=\"" + XhtmlConstants.CssMappedFileName + "?" + XhtmlConstants.CssQueryStringName + "=" + queryStringValue + "\"/>");
writer.WriteLine();
}
}
private void ConditionalRenderStyleElement (XhtmlMobileTextWriter writer) {
if (!writer.IsStyleSheetEmpty () && CssLocation == StyleSheetLocation.Internal) {
bool requiresComments = (String)Device["requiresCommentInStyleElement"] == "true";
writer.WriteLine();
writer.WriteBeginTag("style");
writer.Write(" type=\"text/css\">");
writer.WriteLine();
if (requiresComments) {
writer.WriteLine("<!--");
}
writer.Write(writer.GetStyles());
if (requiresComments) {
writer.WriteLine("-->");
}
writer.WriteEndTag("style");
writer.WriteLine();
}
}
/// <include file='doc\XhtmlBasicPageAdapter.uex' path='docs/doc[@for="XhtmlPageAdapter.CreateTextWriter"]/*' />
public virtual HtmlTextWriter CreateTextWriter( TextWriter writer) {
return new XhtmlMobileTextWriter (writer, Device);
}
// Similar to CHTML.
/// <include file='doc\XhtmlBasicPageAdapter.uex' path='docs/doc[@for="XhtmlPageAdapter.DeterminePostBackMode"]/*' />
public virtual NameValueCollection DeterminePostBackMode(
HttpRequest request,
String postEventSourceID,
String postEventArgumentID,
NameValueCollection baseCollection) {
if (baseCollection != null && baseCollection[EventSourceKey] == XhtmlConstants.PostedFromOtherFile) {
return null;
}
else if (request == null) {
return baseCollection;
}
else if (String.Compare(request.HttpMethod, "POST", StringComparison.OrdinalIgnoreCase) == 0) {
return CollectionFromForm(request.Form,
postEventSourceID,
postEventArgumentID);
}
else if (request.QueryString.Count == 0) {
return baseCollection;
}
else {
return CollectionFromQueryString(request.QueryString,
postEventSourceID,
postEventArgumentID);
}
}
/// <include file='doc\XhtmlBasicPageAdapter.uex' path='docs/doc[@for="XhtmlPageAdapter.DeviceQualifies"]/*' />
public static bool DeviceQualifies(HttpContext context) {
String type = ((MobileCapabilities)context.Request.Browser).PreferredRenderingType;
return String.Equals(type, "xhtml-basic", StringComparison.OrdinalIgnoreCase) ||
String.Equals(type, "xhtml-mp", StringComparison.OrdinalIgnoreCase) ||
String.Equals(type, "wml20", StringComparison.OrdinalIgnoreCase);
}
private bool DoesDeviceRequireCssSuppression() {
return(String)Device[XhtmlConstants.RequiresXhtmlCssSuppression] == "true";
}
private String GetCssQueryStringValue(XhtmlMobileTextWriter writer) {
if (CssLocation == StyleSheetLocation.ApplicationCache) {
// Initialize the cache key
writer.SetCacheKey(Page.Cache);
return writer.CacheKey;
}
else if (CssLocation == StyleSheetLocation.SessionState) {
writer.SetSessionKey(Page.Session);
return writer.SessionKey;
}
Debug.Assert (StyleSheetLocationAttributeValue != null);
return StyleSheetLocationAttributeValue;
}
/// <include file='doc\XhtmlBasicPageAdapter.uex' path='docs/doc[@for="XhtmlPageAdapter.HandleError"]/*' />
public virtual bool HandleError (Exception e, HtmlTextWriter writer) {
return false;
}
/// <include file='doc\XhtmlBasicPageAdapter.uex' path='docs/doc[@for="XhtmlPageAdapter.HandlePagePostBackEvent"]/*' />
public virtual bool HandlePagePostBackEvent (string eventSource, string eventArgument) {
return false;
}
/// <include file='doc\XhtmlBasicPageAdapter.uex' path='docs/doc[@for="XhtmlPageAdapter.InitWriterState"]/*' />
protected virtual void InitWriterState(XhtmlMobileTextWriter writer) {
writer.UseDivsForBreaks = (String)Device[XhtmlConstants.BreaksOnInlineElements] == "true";
writer.SuppressNewLine = (String)Device[XhtmlConstants.RequiresNewLineSuppression] == "true";
writer.SupportsNoWrapStyle = (String)Device[XhtmlConstants.SupportsNoWrapStyle] != "false";
}
/// <include file='doc\XhtmlBasicPageAdapter.uex' path='docs/doc[@for="XhtmlPageAdapter.OnPreRender"]/*' />
public override void OnPreRender(EventArgs e) {
if (Page.ActiveForm.Paginate && Page.ActiveForm.Action.Length > 0) {
Page.ActiveForm.Paginate = false;
}
base.OnPreRender(e);
}
/// <include file='doc\XhtmlBasicPageAdapter.uex' path='docs/doc[@for="XhtmlPageAdapter.Render"]/*' />
public override void Render (XhtmlMobileTextWriter writer) {
writer.BeginResponse ();
if (Page.Request.Browser["requiresPragmaNoCacheHeader"] == "true") {
Page.Response.AppendHeader("Pragma", "no-cache");
}
InitWriterState(writer);
writer.BeginCachedRendering ();
// For consistency with HTML, we render the form style with body tag.
RenderOpeningBodyElement(writer);
// Certain WML 2.0 devices require that we write an onevent onenterforward setvar snippet.
// We cannot know the relevant variables until after the form is rendered, so we mark this
// position. The setvar elements will be inserted into the cached rendering here.
writer.MarkWmlOnEventLocation ();
Page.ActiveForm.RenderControl(writer);
RenderClosingBodyElement(writer);
writer.ClearPendingBreak ();
writer.EndCachedRendering ();
// Note: first and third arguments are not used.
writer.BeginFile (Page.Request.Url.ToString (), Page.Device.PreferredRenderingMime, Page.Response.Charset);
String supportsXmlDeclaration = Device["supportsXmlDeclaration"];
// Invariant culture not needed, included for best practices compliance.
if (supportsXmlDeclaration == null ||
!String.Equals(supportsXmlDeclaration, "false", StringComparison.OrdinalIgnoreCase)) {
writer.WriteXmlDeclaration ();
}
writer.WriteDoctypeDeclaration(DocumentType);
// Review: Hard coded xmlns.
writer.WriteFullBeginTag ("html xmlns=\"http://www.w3.org/1999/xhtml\"");
writer.WriteLine ();
writer.WriteFullBeginTag ("head");
writer.WriteLine ();
writer.WriteFullBeginTag ("title");
if (Page.ActiveForm.Title != null) {
writer.WriteEncodedText(Page.ActiveForm.Title);
}
writer.WriteEndTag ("title");
ConditionalRenderLinkElement (writer);
ConditionalRenderStyleElement (writer);
writer.WriteEndTag ("head");
writer.WriteLine ();
writer.WriteCachedMarkup (); // includes body tag.
writer.WriteLine ();
writer.WriteEndTag ("html");
writer.EndFile ();
if (!DoesDeviceRequireCssSuppression()) {
if (CssLocation == StyleSheetLocation.ApplicationCache && !writer.IsStyleSheetEmpty()) {
// Recall that Page.Cache has application scope
Page.Cache.Insert(writer.CacheKey, writer.GetStyles (), null, DateTime.MaxValue, _cacheExpirationTime);
}
else if (CssLocation == StyleSheetLocation.SessionState && !writer.IsStyleSheetEmpty()) {
Page.Session[writer.SessionKey] = writer.GetStyles();
}
}
writer.EndResponse ();
}
private void RenderClosingBodyElement(XhtmlMobileTextWriter writer) {
Style formStyle = ((ControlAdapter)Page.ActiveForm.Adapter).Style;
if (CssLocation == StyleSheetLocation.PhysicalFile) {
writer.WriteEndTag("body");
if (_pushedCssClassForBody) {
writer.PopPhysicalCssClass();
}
}
else if ((String)Device[XhtmlConstants.RequiresXhtmlCssSuppression] != "true" &&
(String)Device[XhtmlConstants.SupportsBodyClassAttribute] != "false") {
writer.ExitStyle(formStyle); // writes the closing body element.
}
else {
writer.WriteEndTag ("body");
}
}
private void RenderHiddenVariablesInUrl(XhtmlMobileTextWriter writer) {
if (Page.HasHiddenVariables()) {
String hiddenVariablePrefix = MobilePage.HiddenVariablePrefix;
foreach (DictionaryEntry entry in Page.HiddenVariables) {
writer.Write("&");
writer.WriteUrlParameter(hiddenVariablePrefix + (String)entry.Key,
(String)entry.Value);
}
}
}
private void RenderOpeningBodyElement(XhtmlMobileTextWriter writer) {
Form activeForm = Page.ActiveForm;
Style formStyle = ((ControlAdapter)activeForm.Adapter).Style;
if (CssLocation == StyleSheetLocation.PhysicalFile) {
String cssClass = (String) activeForm.CustomAttributes[XhtmlConstants.CssClassCustomAttribute];
writer.WriteBeginTag("body");
if (cssClass != null && (String)Device["supportsBodyClassAttribute"] != "false") {
writer.WriteAttribute("class", cssClass, true /* encode */);
writer.PushPhysicalCssClass(cssClass);
_pushedCssClassForBody = true;
}
writer.Write(">");
}
else if ((String)Device[XhtmlConstants.RequiresXhtmlCssSuppression] != "true" &&
(String)Device[XhtmlConstants.SupportsBodyClassAttribute] != "false") {
writer.EnterStyle(formStyle, "body");
}
else {
writer.WriteFullBeginTag("body");
if ((String)Device[XhtmlConstants.RequiresXhtmlCssSuppression] != "true" &&
(String)Device[XhtmlConstants.SupportsBodyClassAttribute] == "false") {
writer.SetBodyStyle(formStyle);
}
}
}
/// <include file='doc\XhtmlBasicPageAdapter.uex' path='docs/doc[@for="XhtmlPageAdapter.RenderUrlPostBackEvent"]/*' />
public virtual void RenderUrlPostBackEvent (XhtmlMobileTextWriter writer,
String target,
String argument) {
String amp = (String)Device[XhtmlConstants.SupportsUrlAttributeEncoding] == "false" ? "&" : "&";
if ((String)Device["requiresAbsolutePostbackUrl"] == "true") {
writer.WriteEncodedUrl(Page.AbsoluteFilePath);
}
else {
writer.WriteEncodedUrl(Page.RelativeFilePath);
}
writer.Write ("?");
// Encode ViewStateID=.....&__ET=controlid&__EA=value in URL
// Note: the encoding needs to be agreed with the page
// adapter which handles the post back info
String pageState = Page.ClientViewState;
if (pageState != null) {
writer.WriteUrlParameter (MobilePage.ViewStateID, pageState);
writer.Write (amp);
}
writer.WriteUrlParameter (EventSourceKey, target);
writer.Write (amp);
writer.WriteUrlParameter (EventArgumentKey, argument);
RenderHiddenVariablesInUrl (writer);
// Unique file path suffix is used for identify if query
// string text is present. Corresponding code needs to agree
// on this. Even if the query string is empty, we still need
// to output the suffix to indicate this. (this corresponds
// to the code that handles the postback)
writer.Write(amp);
writer.Write(Constants.UniqueFilePathSuffixVariable);
String queryStringText = PreprocessQueryString(Page.QueryStringText);
if (queryStringText != null && queryStringText.Length > 0) {
writer.Write (amp);
if ((String)Device[XhtmlConstants.SupportsUrlAttributeEncoding] != "false") {
writer.WriteEncodedAttributeValue(queryStringText);
}
else {
writer.Write (queryStringText);
}
}
}
}
}
| |
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
namespace Elasticsearch.Client
{
public partial class ElasticsearchClient
{
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MtermvectorsGet(Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = "/_mtermvectors";
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return mConnection.Execute("GET", uri);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MtermvectorsGetAsync(Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = "/_mtermvectors";
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("GET", uri);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="body">Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MtermvectorsGet(Stream body, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = "/_mtermvectors";
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return mConnection.Execute("GET", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="body">Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MtermvectorsGetAsync(Stream body, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = "/_mtermvectors";
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("GET", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="body">Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MtermvectorsGet(byte[] body, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = "/_mtermvectors";
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return mConnection.Execute("GET", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="body">Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MtermvectorsGetAsync(byte[] body, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = "/_mtermvectors";
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("GET", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="body">Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MtermvectorsGetString(string body, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = "/_mtermvectors";
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return mConnection.Execute("GET", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="body">Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MtermvectorsGetStringAsync(string body, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = "/_mtermvectors";
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("GET", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MtermvectorsPost(Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = "/_mtermvectors";
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MtermvectorsPostAsync(Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = "/_mtermvectors";
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="body">Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MtermvectorsPost(Stream body, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = "/_mtermvectors";
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="body">Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MtermvectorsPostAsync(Stream body, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = "/_mtermvectors";
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="body">Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MtermvectorsPost(byte[] body, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = "/_mtermvectors";
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="body">Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MtermvectorsPostAsync(byte[] body, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = "/_mtermvectors";
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="body">Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MtermvectorsPostString(string body, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = "/_mtermvectors";
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="body">Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MtermvectorsPostStringAsync(string body, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = "/_mtermvectors";
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="index">The index in which the document resides.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MtermvectorsGet(string index, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = string.Format("/{0}/_mtermvectors", index);
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return mConnection.Execute("GET", uri);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="index">The index in which the document resides.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MtermvectorsGetAsync(string index, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = string.Format("/{0}/_mtermvectors", index);
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("GET", uri);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="index">The index in which the document resides.</param>
///<param name="body">Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MtermvectorsGet(string index, Stream body, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = string.Format("/{0}/_mtermvectors", index);
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return mConnection.Execute("GET", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="index">The index in which the document resides.</param>
///<param name="body">Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MtermvectorsGetAsync(string index, Stream body, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = string.Format("/{0}/_mtermvectors", index);
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("GET", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="index">The index in which the document resides.</param>
///<param name="body">Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MtermvectorsGet(string index, byte[] body, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = string.Format("/{0}/_mtermvectors", index);
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return mConnection.Execute("GET", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="index">The index in which the document resides.</param>
///<param name="body">Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MtermvectorsGetAsync(string index, byte[] body, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = string.Format("/{0}/_mtermvectors", index);
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("GET", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="index">The index in which the document resides.</param>
///<param name="body">Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MtermvectorsGetString(string index, string body, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = string.Format("/{0}/_mtermvectors", index);
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return mConnection.Execute("GET", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="index">The index in which the document resides.</param>
///<param name="body">Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MtermvectorsGetStringAsync(string index, string body, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = string.Format("/{0}/_mtermvectors", index);
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("GET", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="index">The index in which the document resides.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MtermvectorsPost(string index, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = string.Format("/{0}/_mtermvectors", index);
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="index">The index in which the document resides.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MtermvectorsPostAsync(string index, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = string.Format("/{0}/_mtermvectors", index);
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="index">The index in which the document resides.</param>
///<param name="body">Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MtermvectorsPost(string index, Stream body, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = string.Format("/{0}/_mtermvectors", index);
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="index">The index in which the document resides.</param>
///<param name="body">Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MtermvectorsPostAsync(string index, Stream body, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = string.Format("/{0}/_mtermvectors", index);
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="index">The index in which the document resides.</param>
///<param name="body">Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MtermvectorsPost(string index, byte[] body, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = string.Format("/{0}/_mtermvectors", index);
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="index">The index in which the document resides.</param>
///<param name="body">Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MtermvectorsPostAsync(string index, byte[] body, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = string.Format("/{0}/_mtermvectors", index);
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="index">The index in which the document resides.</param>
///<param name="body">Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MtermvectorsPostString(string index, string body, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = string.Format("/{0}/_mtermvectors", index);
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="index">The index in which the document resides.</param>
///<param name="body">Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MtermvectorsPostStringAsync(string index, string body, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = string.Format("/{0}/_mtermvectors", index);
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="index">The index in which the document resides.</param>
///<param name="type">The type of the document.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MtermvectorsGet(string index, string type, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mtermvectors", index, type);
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return mConnection.Execute("GET", uri);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="index">The index in which the document resides.</param>
///<param name="type">The type of the document.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MtermvectorsGetAsync(string index, string type, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mtermvectors", index, type);
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("GET", uri);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="index">The index in which the document resides.</param>
///<param name="type">The type of the document.</param>
///<param name="body">Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MtermvectorsGet(string index, string type, Stream body, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mtermvectors", index, type);
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return mConnection.Execute("GET", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="index">The index in which the document resides.</param>
///<param name="type">The type of the document.</param>
///<param name="body">Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MtermvectorsGetAsync(string index, string type, Stream body, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mtermvectors", index, type);
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("GET", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="index">The index in which the document resides.</param>
///<param name="type">The type of the document.</param>
///<param name="body">Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MtermvectorsGet(string index, string type, byte[] body, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mtermvectors", index, type);
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return mConnection.Execute("GET", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="index">The index in which the document resides.</param>
///<param name="type">The type of the document.</param>
///<param name="body">Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MtermvectorsGetAsync(string index, string type, byte[] body, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mtermvectors", index, type);
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("GET", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="index">The index in which the document resides.</param>
///<param name="type">The type of the document.</param>
///<param name="body">Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MtermvectorsGetString(string index, string type, string body, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mtermvectors", index, type);
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return mConnection.Execute("GET", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="index">The index in which the document resides.</param>
///<param name="type">The type of the document.</param>
///<param name="body">Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MtermvectorsGetStringAsync(string index, string type, string body, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mtermvectors", index, type);
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("GET", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="index">The index in which the document resides.</param>
///<param name="type">The type of the document.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MtermvectorsPost(string index, string type, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mtermvectors", index, type);
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="index">The index in which the document resides.</param>
///<param name="type">The type of the document.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MtermvectorsPostAsync(string index, string type, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mtermvectors", index, type);
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="index">The index in which the document resides.</param>
///<param name="type">The type of the document.</param>
///<param name="body">Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MtermvectorsPost(string index, string type, Stream body, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mtermvectors", index, type);
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="index">The index in which the document resides.</param>
///<param name="type">The type of the document.</param>
///<param name="body">Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MtermvectorsPostAsync(string index, string type, Stream body, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mtermvectors", index, type);
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="index">The index in which the document resides.</param>
///<param name="type">The type of the document.</param>
///<param name="body">Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MtermvectorsPost(string index, string type, byte[] body, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mtermvectors", index, type);
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="index">The index in which the document resides.</param>
///<param name="type">The type of the document.</param>
///<param name="body">Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MtermvectorsPostAsync(string index, string type, byte[] body, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mtermvectors", index, type);
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="index">The index in which the document resides.</param>
///<param name="type">The type of the document.</param>
///<param name="body">Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation.</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage MtermvectorsPostString(string index, string type, string body, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mtermvectors", index, type);
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html"/></summary>
///<param name="index">The index in which the document resides.</param>
///<param name="type">The type of the document.</param>
///<param name="body">Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation.</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> MtermvectorsPostStringAsync(string index, string type, string body, Func<MtermvectorsParameters, MtermvectorsParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mtermvectors", index, type);
if (options != null)
{
uri = options.Invoke(new MtermvectorsParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri, body);
}
}
}
| |
/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov
*
* 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 Microsoft.Win32.SafeHandles;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
namespace Alphaleonis.Win32.Filesystem
{
internal static partial class NativeMethods
{
/// <summary>Defines, redefines, or deletes MS-DOS device names.</summary>
/// <returns>
/// If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero. To get extended error information, call GetLastError.
/// </returns>
/// <remarks>Minimum supported client: Windows XP [desktop apps only]</remarks>
/// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only]</remarks>
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "DefineDosDeviceW"), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool DefineDosDevice(DosDeviceAttributes dwFlags, [MarshalAs(UnmanagedType.LPWStr)] string lpDeviceName, [MarshalAs(UnmanagedType.LPWStr)] string lpTargetPath);
/// <summary>Deletes a drive letter or mounted folder.</summary>
/// <returns>
/// If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero. To get extended error information, call GetLastError.
/// </returns>
/// <remarks>Minimum supported client: Windows XP [desktop apps only]</remarks>
/// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only]</remarks>
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "DeleteVolumeMountPointW"), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool DeleteVolumeMountPoint([MarshalAs(UnmanagedType.LPWStr)] string lpszVolumeMountPoint);
/// <summary>Retrieves the name of a volume on a computer. FindFirstVolume is used to begin scanning the volumes of a computer.</summary>
/// <returns>
/// If the function succeeds, the return value is a search handle used in a subsequent call to the FindNextVolume and FindVolumeClose functions.
/// If the function fails to find any volumes, the return value is the INVALID_HANDLE_VALUE error code. To get extended error information, call GetLastError.
/// </returns>
/// <remarks>Minimum supported client: Windows XP [desktop apps only]</remarks>
/// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only]</remarks>
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "FindFirstVolumeW"), SuppressUnmanagedCodeSecurity]
internal static extern SafeFindVolumeHandle FindFirstVolume(StringBuilder lpszVolumeName, [MarshalAs(UnmanagedType.U4)] uint cchBufferLength);
/// <summary>Retrieves the name of a mounted folder on the specified volume. FindFirstVolumeMountPoint is used to begin scanning the mounted folders on a volume.</summary>
/// <returns>
/// If the function succeeds, the return value is a search handle used in a subsequent call to the FindNextVolumeMountPoint and FindVolumeMountPointClose functions.
/// If the function fails to find a mounted folder on the volume, the return value is the INVALID_HANDLE_VALUE error code.
/// </returns>
/// <remarks>Minimum supported client: Windows XP [desktop apps only]</remarks>
/// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only]</remarks>
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "FindFirstVolumeMountPointW"), SuppressUnmanagedCodeSecurity]
internal static extern SafeFindVolumeMountPointHandle FindFirstVolumeMountPoint([MarshalAs(UnmanagedType.LPWStr)] string lpszRootPathName, StringBuilder lpszVolumeMountPoint, [MarshalAs(UnmanagedType.U4)] uint cchBufferLength);
/// <summary>Continues a volume search started by a call to the FindFirstVolume function. FindNextVolume finds one volume per call.</summary>
/// <returns>
/// If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero. To get extended error information, call GetLastError.
/// </returns>
/// <remarks>Minimum supported client: Windows XP [desktop apps only]</remarks>
/// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only]</remarks>
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "FindNextVolumeW"), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool FindNextVolume(SafeFindVolumeHandle hFindVolume, StringBuilder lpszVolumeName, [MarshalAs(UnmanagedType.U4)] uint cchBufferLength);
/// <summary>Continues a mounted folder search started by a call to the FindFirstVolumeMountPoint function. FindNextVolumeMountPoint finds one mounted folder per call.</summary>
/// <returns>
/// If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero. To get extended error information, call GetLastError. If no more mounted folders can be found, the GetLastError function returns the ERROR_NO_MORE_FILES error code.
/// In that case, close the search with the FindVolumeMountPointClose function.
/// </returns>
/// <remarks>Minimum supported client: Windows XP</remarks>
/// <remarks>Minimum supported server: Windows Server 2003</remarks>
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "FindNextVolumeMountPointW"), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool FindNextVolumeMountPoint(SafeFindVolumeMountPointHandle hFindVolume, StringBuilder lpszVolumeName, [MarshalAs(UnmanagedType.U4)] uint cchBufferLength);
/// <summary>Closes the specified volume search handle.</summary>
/// <remarks>
/// <para>SetLastError is set to <c>false</c>.</para>
/// Minimum supported client: Windows XP [desktop apps only]. Minimum supported server: Windows Server 2003 [desktop apps only].
/// </remarks>
/// <returns>
/// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error
/// information, call GetLastError.
/// </returns>
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool FindVolumeClose(IntPtr hFindVolume);
/// <summary>Closes the specified mounted folder search handle.</summary>
/// <remarks>
/// <para>SetLastError is set to <c>false</c>.</para>
/// <para>Minimum supported client: Windows XP</para>
/// <para>Minimum supported server: Windows Server 2003</para>
/// </remarks>
/// <returns>
/// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error
/// information, call GetLastError.
/// </returns>
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool FindVolumeMountPointClose(IntPtr hFindVolume);
/// <summary>
/// Determines whether a disk drive is a removable, fixed, CD-ROM, RAM disk, or network drive.
/// <para>To determine whether a drive is a USB-type drive, call <see cref="SetupDiGetDeviceRegistryProperty"/> and specify the
/// SPDRP_REMOVAL_POLICY property.</para>
/// </summary>
/// <remarks>
/// <para>SMB does not support volume management functions.</para>
/// <para>Minimum supported client: Windows XP [desktop apps only]</para>
/// <para>Minimum supported server: Windows Server 2003 [desktop apps only]</para>
/// </remarks>
/// <param name="lpRootPathName">Full pathname of the root file.</param>
/// <returns>
/// <para>The return value specifies the type of drive, see <see cref="DriveType"/>.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call GetLastError.</para>
/// </returns>
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetDriveTypeW"), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.U4)]
internal static extern DriveType GetDriveType([MarshalAs(UnmanagedType.LPWStr)] string lpRootPathName);
/// <summary>
/// Retrieves a bitmask representing the currently available disk drives.
/// </summary>
/// <remarks>
/// <para>SMB does not support volume management functions.</para>
/// <para>Minimum supported client: Windows XP [desktop apps only]</para>
/// <para>Minimum supported server: Windows Server 2003 [desktop apps only]</para>
/// </remarks>
/// <returns>
/// <para>If the function succeeds, the return value is a bitmask representing the currently available disk drives.</para>
/// <para>Bit position 0 (the least-significant bit) is drive A, bit position 1 is drive B, bit position 2 is drive C, and so on.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call GetLastError.</para>
/// </returns>
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.U4)]
internal static extern uint GetLogicalDrives();
/// <summary>Retrieves information about the file system and volume associated with the specified root directory.</summary>
/// <returns>
/// If all the requested information is retrieved, the return value is nonzero.
/// If not all the requested information is retrieved, the return value is zero.
/// </returns>
/// <remarks>Minimum supported client: Windows XP [desktop apps only]</remarks>
/// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only]</remarks>
/// <remarks>"lpRootPathName" must end with a trailing backslash.</remarks>
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetVolumeInformationW"), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetVolumeInformation([MarshalAs(UnmanagedType.LPWStr)] string lpRootPathName, StringBuilder lpVolumeNameBuffer, [MarshalAs(UnmanagedType.U4)] uint nVolumeNameSize, [MarshalAs(UnmanagedType.U4)] out uint lpVolumeSerialNumber, [MarshalAs(UnmanagedType.U4)] out int lpMaximumComponentLength, [MarshalAs(UnmanagedType.U4)] out VOLUME_INFO_FLAGS lpFileSystemAttributes, StringBuilder lpFileSystemNameBuffer, [MarshalAs(UnmanagedType.U4)] uint nFileSystemNameSize);
/// <summary>Retrieves information about the file system and volume associated with the specified file.</summary>
/// <returns>
/// If all the requested information is retrieved, the return value is nonzero.
/// If not all the requested information is retrieved, the return value is zero. To get extended error information, call GetLastError.
/// </returns>
/// <remarks>To retrieve the current compression state of a file or directory, use FSCTL_GET_COMPRESSION.</remarks>
/// <remarks>SMB does not support volume management functions.</remarks>
/// <remarks>Minimum supported client: Windows Vista [desktop apps only]</remarks>
/// <remarks>Minimum supported server: Windows Server 2008 [desktop apps only]</remarks>
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetVolumeInformationByHandleW"), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetVolumeInformationByHandle(SafeFileHandle hFile, StringBuilder lpVolumeNameBuffer, [MarshalAs(UnmanagedType.U4)] uint nVolumeNameSize, [MarshalAs(UnmanagedType.U4)] out uint lpVolumeSerialNumber, [MarshalAs(UnmanagedType.U4)] out int lpMaximumComponentLength, out VOLUME_INFO_FLAGS lpFileSystemAttributes, StringBuilder lpFileSystemNameBuffer, [MarshalAs(UnmanagedType.U4)] uint nFileSystemNameSize);
/// <summary>Retrieves a volume GUID path for the volume that is associated with the specified volume mount point (drive letter, volume GUID path, or mounted folder).</summary>
/// <returns>
/// If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero. To get extended error information, call GetLastError.
/// </returns>
/// <remarks>Use GetVolumeNameForVolumeMountPoint to obtain a volume GUID path for use with functions such as SetVolumeMountPoint and FindFirstVolumeMountPoint that require a volume GUID path as an input parameter.</remarks>
/// <remarks>SMB does not support volume management functions.</remarks>
/// <remarks>Mount points aren't supported by ReFS volumes.</remarks>
/// <remarks>Minimum supported client: Windows XP [desktop apps only]</remarks>
/// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only]</remarks>
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetVolumeNameForVolumeMountPointW"), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetVolumeNameForVolumeMountPoint([MarshalAs(UnmanagedType.LPWStr)] string lpszVolumeMountPoint, StringBuilder lpszVolumeName, [MarshalAs(UnmanagedType.U4)] uint cchBufferLength);
/// <summary>Retrieves the volume mount point where the specified path is mounted.</summary>
/// <remarks>
/// <para>If a specified path is passed, GetVolumePathName returns the path to the volume mount point, which means that it returns the
/// root of the volume where the end point of the specified path is located.</para>
/// <para>For example, assume that you have volume D mounted at C:\Mnt\Ddrive and volume E mounted at "C:\Mnt\Ddrive\Mnt\Edrive". Also
/// assume that you have a file with the path "E:\Dir\Subdir\MyFile".</para>
/// <para>If you pass "C:\Mnt\Ddrive\Mnt\Edrive\Dir\Subdir\MyFile" to GetVolumePathName, it returns the path "C:\Mnt\Ddrive\Mnt\Edrive\".</para>
/// <para>If a network share is specified, GetVolumePathName returns the shortest path for which GetDriveType returns DRIVE_REMOTE,
/// which means that the path is validated as a remote drive that exists, which the current user can access.</para>
/// <para>Minimum supported client: Windows XP [desktop apps only]</para>
/// <para>Minimum supported server: Windows Server 2003 [desktop apps only]</para>
/// </remarks>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call GetLastError.</para>
/// </returns>
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetVolumePathNameW"), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetVolumePathName([MarshalAs(UnmanagedType.LPWStr)] string lpszFileName, StringBuilder lpszVolumePathName, [MarshalAs(UnmanagedType.U4)] uint cchBufferLength);
/// <summary>Retrieves a list of drive letters and mounted folder paths for the specified volume.</summary>
/// <remarks>Minimum supported client: Windows XP.</remarks>
/// <remarks>Minimum supported server: Windows Server 2003.</remarks>
/// <returns>
/// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error
/// information, call GetLastError.
/// </returns>
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetVolumePathNamesForVolumeNameW"), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetVolumePathNamesForVolumeName([MarshalAs(UnmanagedType.LPWStr)] string lpszVolumeName, char[] lpszVolumePathNames, [MarshalAs(UnmanagedType.U4)] uint cchBuferLength, [MarshalAs(UnmanagedType.U4)] out uint lpcchReturnLength);
/// <summary>Sets the label of a file system volume.</summary>
/// <remarks>Minimum supported client: Windows XP [desktop apps only].</remarks>
/// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only].</remarks>
/// <remarks>"lpRootPathName" must end with a trailing backslash.</remarks>
/// <returns>
/// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error
/// information, call GetLastError.
/// </returns>
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "SetVolumeLabelW"), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool SetVolumeLabel([MarshalAs(UnmanagedType.LPWStr)] string lpRootPathName, [MarshalAs(UnmanagedType.LPWStr)] string lpVolumeName);
/// <summary>Associates a volume with a drive letter or a directory on another volume.</summary>
/// <remarks>Minimum supported client: Windows XP [desktop apps only].</remarks>
/// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only].</remarks>
/// <returns>
/// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error
/// information, call GetLastError.
/// </returns>
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "SetVolumeMountPointW"), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool SetVolumeMountPoint([MarshalAs(UnmanagedType.LPWStr)] string lpszVolumeMountPoint, [MarshalAs(UnmanagedType.LPWStr)] string lpszVolumeName);
/// <summary>Retrieves information about MS-DOS device names.</summary>
/// <remarks>Minimum supported client: Windows XP [desktop apps only].</remarks>
/// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only].</remarks>
/// <returns>
/// If the function succeeds, the return value is the number of TCHARs stored into the buffer pointed to by lpTargetPath. If the
/// function fails, the return value is zero. To get extended error information, call GetLastError. If the buffer is too small, the
/// function fails and the last error code is ERROR_INSUFFICIENT_BUFFER.
/// </returns>
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "QueryDosDeviceW"), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.U4)]
internal static extern uint QueryDosDevice([MarshalAs(UnmanagedType.LPWStr)] string lpDeviceName, char[] lpTargetPath, [MarshalAs(UnmanagedType.U4)] uint ucchMax);
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gatv = Google.Area120.Tables.V1Alpha1;
using sys = System;
namespace Google.Area120.Tables.V1Alpha1
{
/// <summary>Resource name for the <c>Table</c> resource.</summary>
public sealed partial class TableName : gax::IResourceName, sys::IEquatable<TableName>
{
/// <summary>The possible contents of <see cref="TableName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>tables/{table}</c>.</summary>
Table = 1,
}
private static gax::PathTemplate s_table = new gax::PathTemplate("tables/{table}");
/// <summary>Creates a <see cref="TableName"/> 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="TableName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static TableName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new TableName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>Creates a <see cref="TableName"/> with the pattern <c>tables/{table}</c>.</summary>
/// <param name="tableId">The <c>Table</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="TableName"/> constructed from the provided ids.</returns>
public static TableName FromTable(string tableId) =>
new TableName(ResourceNameType.Table, tableId: gax::GaxPreconditions.CheckNotNullOrEmpty(tableId, nameof(tableId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="TableName"/> with pattern
/// <c>tables/{table}</c>.
/// </summary>
/// <param name="tableId">The <c>Table</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="TableName"/> with pattern <c>tables/{table}</c>.
/// </returns>
public static string Format(string tableId) => FormatTable(tableId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="TableName"/> with pattern
/// <c>tables/{table}</c>.
/// </summary>
/// <param name="tableId">The <c>Table</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="TableName"/> with pattern <c>tables/{table}</c>.
/// </returns>
public static string FormatTable(string tableId) =>
s_table.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(tableId, nameof(tableId)));
/// <summary>Parses the given resource name string into a new <see cref="TableName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>tables/{table}</c></description></item></list>
/// </remarks>
/// <param name="tableName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="TableName"/> if successful.</returns>
public static TableName Parse(string tableName) => Parse(tableName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="TableName"/> 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>tables/{table}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="tableName">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="TableName"/> if successful.</returns>
public static TableName Parse(string tableName, bool allowUnparsed) =>
TryParse(tableName, allowUnparsed, out TableName 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="TableName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>tables/{table}</c></description></item></list>
/// </remarks>
/// <param name="tableName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="TableName"/>, 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 tableName, out TableName result) => TryParse(tableName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="TableName"/> 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>tables/{table}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="tableName">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="TableName"/>, 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 tableName, bool allowUnparsed, out TableName result)
{
gax::GaxPreconditions.CheckNotNull(tableName, nameof(tableName));
gax::TemplatedResourceName resourceName;
if (s_table.TryParseName(tableName, out resourceName))
{
result = FromTable(resourceName[0]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(tableName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private TableName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string tableId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
TableId = tableId;
}
/// <summary>
/// Constructs a new instance of a <see cref="TableName"/> class from the component parts of pattern
/// <c>tables/{table}</c>
/// </summary>
/// <param name="tableId">The <c>Table</c> ID. Must not be <c>null</c> or empty.</param>
public TableName(string tableId) : this(ResourceNameType.Table, tableId: gax::GaxPreconditions.CheckNotNullOrEmpty(tableId, nameof(tableId)))
{
}
/// <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>Table</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string TableId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.Table: return s_table.Expand(TableId);
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 TableName);
/// <inheritdoc/>
public bool Equals(TableName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(TableName a, TableName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(TableName a, TableName b) => !(a == b);
}
/// <summary>Resource name for the <c>Row</c> resource.</summary>
public sealed partial class RowName : gax::IResourceName, sys::IEquatable<RowName>
{
/// <summary>The possible contents of <see cref="RowName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>tables/{table}/rows/{row}</c>.</summary>
TableRow = 1,
}
private static gax::PathTemplate s_tableRow = new gax::PathTemplate("tables/{table}/rows/{row}");
/// <summary>Creates a <see cref="RowName"/> 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="RowName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static RowName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new RowName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>Creates a <see cref="RowName"/> with the pattern <c>tables/{table}/rows/{row}</c>.</summary>
/// <param name="tableId">The <c>Table</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="rowId">The <c>Row</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="RowName"/> constructed from the provided ids.</returns>
public static RowName FromTableRow(string tableId, string rowId) =>
new RowName(ResourceNameType.TableRow, tableId: gax::GaxPreconditions.CheckNotNullOrEmpty(tableId, nameof(tableId)), rowId: gax::GaxPreconditions.CheckNotNullOrEmpty(rowId, nameof(rowId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="RowName"/> with pattern
/// <c>tables/{table}/rows/{row}</c>.
/// </summary>
/// <param name="tableId">The <c>Table</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="rowId">The <c>Row</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="RowName"/> with pattern <c>tables/{table}/rows/{row}</c>.
/// </returns>
public static string Format(string tableId, string rowId) => FormatTableRow(tableId, rowId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="RowName"/> with pattern
/// <c>tables/{table}/rows/{row}</c>.
/// </summary>
/// <param name="tableId">The <c>Table</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="rowId">The <c>Row</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="RowName"/> with pattern <c>tables/{table}/rows/{row}</c>.
/// </returns>
public static string FormatTableRow(string tableId, string rowId) =>
s_tableRow.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(tableId, nameof(tableId)), gax::GaxPreconditions.CheckNotNullOrEmpty(rowId, nameof(rowId)));
/// <summary>Parses the given resource name string into a new <see cref="RowName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>tables/{table}/rows/{row}</c></description></item></list>
/// </remarks>
/// <param name="rowName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="RowName"/> if successful.</returns>
public static RowName Parse(string rowName) => Parse(rowName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="RowName"/> 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>tables/{table}/rows/{row}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="rowName">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="RowName"/> if successful.</returns>
public static RowName Parse(string rowName, bool allowUnparsed) =>
TryParse(rowName, allowUnparsed, out RowName 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="RowName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>tables/{table}/rows/{row}</c></description></item></list>
/// </remarks>
/// <param name="rowName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="RowName"/>, 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 rowName, out RowName result) => TryParse(rowName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="RowName"/> 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>tables/{table}/rows/{row}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="rowName">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="RowName"/>, 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 rowName, bool allowUnparsed, out RowName result)
{
gax::GaxPreconditions.CheckNotNull(rowName, nameof(rowName));
gax::TemplatedResourceName resourceName;
if (s_tableRow.TryParseName(rowName, out resourceName))
{
result = FromTableRow(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(rowName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private RowName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string rowId = null, string tableId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
RowId = rowId;
TableId = tableId;
}
/// <summary>
/// Constructs a new instance of a <see cref="RowName"/> class from the component parts of pattern
/// <c>tables/{table}/rows/{row}</c>
/// </summary>
/// <param name="tableId">The <c>Table</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="rowId">The <c>Row</c> ID. Must not be <c>null</c> or empty.</param>
public RowName(string tableId, string rowId) : this(ResourceNameType.TableRow, tableId: gax::GaxPreconditions.CheckNotNullOrEmpty(tableId, nameof(tableId)), rowId: gax::GaxPreconditions.CheckNotNullOrEmpty(rowId, nameof(rowId)))
{
}
/// <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>Row</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string RowId { get; }
/// <summary>
/// The <c>Table</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string TableId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.TableRow: return s_tableRow.Expand(TableId, RowId);
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 RowName);
/// <inheritdoc/>
public bool Equals(RowName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(RowName a, RowName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(RowName a, RowName b) => !(a == b);
}
/// <summary>Resource name for the <c>Workspace</c> resource.</summary>
public sealed partial class WorkspaceName : gax::IResourceName, sys::IEquatable<WorkspaceName>
{
/// <summary>The possible contents of <see cref="WorkspaceName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>workspaces/{workspace}</c>.</summary>
Workspace = 1,
}
private static gax::PathTemplate s_workspace = new gax::PathTemplate("workspaces/{workspace}");
/// <summary>Creates a <see cref="WorkspaceName"/> 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="WorkspaceName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static WorkspaceName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new WorkspaceName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>Creates a <see cref="WorkspaceName"/> with the pattern <c>workspaces/{workspace}</c>.</summary>
/// <param name="workspaceId">The <c>Workspace</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="WorkspaceName"/> constructed from the provided ids.</returns>
public static WorkspaceName FromWorkspace(string workspaceId) =>
new WorkspaceName(ResourceNameType.Workspace, workspaceId: gax::GaxPreconditions.CheckNotNullOrEmpty(workspaceId, nameof(workspaceId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="WorkspaceName"/> with pattern
/// <c>workspaces/{workspace}</c>.
/// </summary>
/// <param name="workspaceId">The <c>Workspace</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="WorkspaceName"/> with pattern <c>workspaces/{workspace}</c>.
/// </returns>
public static string Format(string workspaceId) => FormatWorkspace(workspaceId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="WorkspaceName"/> with pattern
/// <c>workspaces/{workspace}</c>.
/// </summary>
/// <param name="workspaceId">The <c>Workspace</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="WorkspaceName"/> with pattern <c>workspaces/{workspace}</c>.
/// </returns>
public static string FormatWorkspace(string workspaceId) =>
s_workspace.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(workspaceId, nameof(workspaceId)));
/// <summary>Parses the given resource name string into a new <see cref="WorkspaceName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>workspaces/{workspace}</c></description></item></list>
/// </remarks>
/// <param name="workspaceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="WorkspaceName"/> if successful.</returns>
public static WorkspaceName Parse(string workspaceName) => Parse(workspaceName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="WorkspaceName"/> 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>workspaces/{workspace}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="workspaceName">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="WorkspaceName"/> if successful.</returns>
public static WorkspaceName Parse(string workspaceName, bool allowUnparsed) =>
TryParse(workspaceName, allowUnparsed, out WorkspaceName 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="WorkspaceName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>workspaces/{workspace}</c></description></item></list>
/// </remarks>
/// <param name="workspaceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="WorkspaceName"/>, 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 workspaceName, out WorkspaceName result) => TryParse(workspaceName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="WorkspaceName"/> 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>workspaces/{workspace}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="workspaceName">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="WorkspaceName"/>, 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 workspaceName, bool allowUnparsed, out WorkspaceName result)
{
gax::GaxPreconditions.CheckNotNull(workspaceName, nameof(workspaceName));
gax::TemplatedResourceName resourceName;
if (s_workspace.TryParseName(workspaceName, out resourceName))
{
result = FromWorkspace(resourceName[0]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(workspaceName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private WorkspaceName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string workspaceId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
WorkspaceId = workspaceId;
}
/// <summary>
/// Constructs a new instance of a <see cref="WorkspaceName"/> class from the component parts of pattern
/// <c>workspaces/{workspace}</c>
/// </summary>
/// <param name="workspaceId">The <c>Workspace</c> ID. Must not be <c>null</c> or empty.</param>
public WorkspaceName(string workspaceId) : this(ResourceNameType.Workspace, workspaceId: gax::GaxPreconditions.CheckNotNullOrEmpty(workspaceId, nameof(workspaceId)))
{
}
/// <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>Workspace</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string WorkspaceId { 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.Workspace: return s_workspace.Expand(WorkspaceId);
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 WorkspaceName);
/// <inheritdoc/>
public bool Equals(WorkspaceName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(WorkspaceName a, WorkspaceName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(WorkspaceName a, WorkspaceName b) => !(a == b);
}
public partial class GetTableRequest
{
/// <summary>
/// <see cref="gatv::TableName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gatv::TableName TableName
{
get => string.IsNullOrEmpty(Name) ? null : gatv::TableName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class GetWorkspaceRequest
{
/// <summary>
/// <see cref="gatv::WorkspaceName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gatv::WorkspaceName WorkspaceName
{
get => string.IsNullOrEmpty(Name) ? null : gatv::WorkspaceName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class GetRowRequest
{
/// <summary>
/// <see cref="gatv::RowName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gatv::RowName RowName
{
get => string.IsNullOrEmpty(Name) ? null : gatv::RowName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class DeleteRowRequest
{
/// <summary>
/// <see cref="gatv::RowName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gatv::RowName RowName
{
get => string.IsNullOrEmpty(Name) ? null : gatv::RowName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class BatchDeleteRowsRequest
{
/// <summary><see cref="TableName"/>-typed view over the <see cref="Parent"/> resource name property.</summary>
public TableName ParentAsTableName
{
get => string.IsNullOrEmpty(Parent) ? null : TableName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary><see cref="RowName"/>-typed view over the <see cref="Names"/> resource name property.</summary>
public gax::ResourceNameList<RowName> RowNames
{
get => new gax::ResourceNameList<RowName>(Names, s => string.IsNullOrEmpty(s) ? null : RowName.Parse(s, allowUnparsed: true));
}
}
public partial class Table
{
/// <summary>
/// <see cref="gatv::TableName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gatv::TableName TableName
{
get => string.IsNullOrEmpty(Name) ? null : gatv::TableName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class Row
{
/// <summary>
/// <see cref="gatv::RowName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gatv::RowName RowName
{
get => string.IsNullOrEmpty(Name) ? null : gatv::RowName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class Workspace
{
/// <summary>
/// <see cref="gatv::WorkspaceName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gatv::WorkspaceName WorkspaceName
{
get => string.IsNullOrEmpty(Name) ? null : gatv::WorkspaceName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// ReSharper disable SpecifyACultureInStringConversionExplicitly
// ReSharper disable UnusedAutoPropertyAccessor.Global
namespace Apache.Ignite.Core.Tests.Compute
{
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Impl;
using Apache.Ignite.Core.Resource;
using NUnit.Framework;
/// <summary>
/// Tests for compute.
/// </summary>
public class ComputeApiTest
{
/** Echo task name. */
public const string EchoTask = "org.apache.ignite.platform.PlatformComputeEchoTask";
/** Binary argument task name. */
public const string BinaryArgTask = "org.apache.ignite.platform.PlatformComputeBinarizableArgTask";
/** Broadcast task name. */
public const string BroadcastTask = "org.apache.ignite.platform.PlatformComputeBroadcastTask";
/** Broadcast task name. */
private const string DecimalTask = "org.apache.ignite.platform.PlatformComputeDecimalTask";
/** Java binary class name. */
private const string JavaBinaryCls = "PlatformComputeJavaBinarizable";
/** Echo type: null. */
private const int EchoTypeNull = 0;
/** Echo type: byte. */
private const int EchoTypeByte = 1;
/** Echo type: bool. */
private const int EchoTypeBool = 2;
/** Echo type: short. */
private const int EchoTypeShort = 3;
/** Echo type: char. */
private const int EchoTypeChar = 4;
/** Echo type: int. */
private const int EchoTypeInt = 5;
/** Echo type: long. */
private const int EchoTypeLong = 6;
/** Echo type: float. */
private const int EchoTypeFloat = 7;
/** Echo type: double. */
private const int EchoTypeDouble = 8;
/** Echo type: array. */
private const int EchoTypeArray = 9;
/** Echo type: collection. */
private const int EchoTypeCollection = 10;
/** Echo type: map. */
private const int EchoTypeMap = 11;
/** Echo type: binarizable. */
public const int EchoTypeBinarizable = 12;
/** Echo type: binary (Java only). */
private const int EchoTypeBinarizableJava = 13;
/** Type: object array. */
private const int EchoTypeObjArray = 14;
/** Type: binary object array. */
private const int EchoTypeBinarizableArray = 15;
/** Type: enum. */
private const int EchoTypeEnum = 16;
/** Type: enum array. */
private const int EchoTypeEnumArray = 17;
/** Type: enum field. */
private const int EchoTypeEnumField = 18;
/** Type: affinity key. */
public const int EchoTypeAffinityKey = 19;
/** Type: enum from cache. */
private const int EchoTypeEnumFromCache = 20;
/** Type: enum array from cache. */
private const int EchoTypeEnumArrayFromCache = 21;
/** Echo type: IgniteUuid. */
private const int EchoTypeIgniteUuid = 22;
/** Echo type: binary enum (created with builder). */
private const int EchoTypeBinaryEnum = 23;
/** */
private const string DefaultCacheName = "default";
/** First node. */
private IIgnite _grid1;
/** Second node. */
private IIgnite _grid2;
/** Third node. */
private IIgnite _grid3;
/// <summary>
/// Initialization routine.
/// </summary>
[TestFixtureSetUp]
public void InitClient()
{
TestUtils.KillProcesses();
var configs = GetConfigs();
_grid1 = Ignition.Start(Configuration(configs.Item1));
_grid2 = Ignition.Start(Configuration(configs.Item2));
_grid3 = Ignition.Start(Configuration(configs.Item3));
}
/// <summary>
/// Gets the configs.
/// </summary>
protected virtual Tuple<string, string, string> GetConfigs()
{
return Tuple.Create(
"config\\compute\\compute-grid1.xml",
"config\\compute\\compute-grid2.xml",
"config\\compute\\compute-grid3.xml");
}
/// <summary>
/// Gets the expected compact footers setting.
/// </summary>
protected virtual bool CompactFooter
{
get { return true; }
}
[TestFixtureTearDown]
public void StopClient()
{
Ignition.StopAll(true);
}
[TearDown]
public void AfterTest()
{
TestUtils.AssertHandleRegistryIsEmpty(1000, _grid1, _grid2, _grid3);
}
/// <summary>
/// Test that it is possible to get projection from grid.
/// </summary>
[Test]
public void TestProjection()
{
IClusterGroup prj = _grid1.GetCluster();
Assert.NotNull(prj);
Assert.AreEqual(prj, prj.Ignite);
// Check that default Compute projection excludes client nodes.
CollectionAssert.AreEquivalent(prj.ForServers().GetNodes(), prj.GetCompute().ClusterGroup.GetNodes());
}
/// <summary>
/// Test non-existent cache.
/// </summary>
[Test]
public void TestNonExistentCache()
{
Assert.Catch(typeof(ArgumentException), () =>
{
_grid1.GetCache<int, int>("bad_name");
});
}
/// <summary>
/// Test node content.
/// </summary>
[Test]
public void TestNodeContent()
{
ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes();
foreach (IClusterNode node in nodes)
{
Assert.NotNull(node.Addresses);
Assert.IsTrue(node.Addresses.Count > 0);
Assert.Throws<NotSupportedException>(() => node.Addresses.Add("addr"));
Assert.NotNull(node.GetAttributes());
Assert.IsTrue(node.GetAttributes().Count > 0);
Assert.Throws<NotSupportedException>(() => node.GetAttributes().Add("key", "val"));
Assert.NotNull(node.HostNames);
Assert.Throws<NotSupportedException>(() => node.HostNames.Add("h"));
Assert.IsTrue(node.Id != Guid.Empty);
Assert.IsTrue(node.Order > 0);
Assert.NotNull(node.GetMetrics());
}
}
/// <summary>
/// Test cluster metrics.
/// </summary>
[Test]
public void TestClusterMetrics()
{
var cluster = _grid1.GetCluster();
IClusterMetrics metrics = cluster.GetMetrics();
Assert.IsNotNull(metrics);
Assert.AreEqual(cluster.GetNodes().Count, metrics.TotalNodes);
Thread.Sleep(2000);
IClusterMetrics newMetrics = cluster.GetMetrics();
Assert.IsFalse(metrics == newMetrics);
Assert.IsTrue(metrics.LastUpdateTime < newMetrics.LastUpdateTime);
}
/// <summary>
/// Test cluster metrics.
/// </summary>
[Test]
public void TestNodeMetrics()
{
var node = _grid1.GetCluster().GetNode();
IClusterMetrics metrics = node.GetMetrics();
Assert.IsNotNull(metrics);
Assert.IsTrue(metrics == node.GetMetrics());
Thread.Sleep(2000);
IClusterMetrics newMetrics = node.GetMetrics();
Assert.IsFalse(metrics == newMetrics);
Assert.IsTrue(metrics.LastUpdateTime < newMetrics.LastUpdateTime);
}
/// <summary>
/// Test cluster metrics.
/// </summary>
[Test]
public void TestResetMetrics()
{
var cluster = _grid1.GetCluster();
Thread.Sleep(2000);
var metrics1 = cluster.GetMetrics();
cluster.ResetMetrics();
var metrics2 = cluster.GetMetrics();
Assert.IsNotNull(metrics1);
Assert.IsNotNull(metrics2);
}
/// <summary>
/// Test node ping.
/// </summary>
[Test]
public void TestPingNode()
{
var cluster = _grid1.GetCluster();
Assert.IsTrue(cluster.GetNodes().Select(node => node.Id).All(cluster.PingNode));
Assert.IsFalse(cluster.PingNode(Guid.NewGuid()));
}
/// <summary>
/// Tests the topology version.
/// </summary>
[Test]
public void TestTopologyVersion()
{
var cluster = _grid1.GetCluster();
var topVer = cluster.TopologyVersion;
Ignition.Stop(_grid3.Name, true);
Assert.AreEqual(topVer + 1, _grid1.GetCluster().TopologyVersion);
_grid3 = Ignition.Start(Configuration(GetConfigs().Item3));
Assert.AreEqual(topVer + 2, _grid1.GetCluster().TopologyVersion);
}
/// <summary>
/// Tests the topology by version.
/// </summary>
[Test]
public void TestTopology()
{
var cluster = _grid1.GetCluster();
Assert.AreEqual(1, cluster.GetTopology(1).Count);
Assert.AreEqual(null, cluster.GetTopology(int.MaxValue));
// Check that Nodes and Topology return the same for current version
var topVer = cluster.TopologyVersion;
var top = cluster.GetTopology(topVer);
var nodes = cluster.GetNodes();
Assert.AreEqual(top.Count, nodes.Count);
Assert.IsTrue(top.All(nodes.Contains));
// Stop/start node to advance version and check that history is still correct
Assert.IsTrue(Ignition.Stop(_grid2.Name, true));
try
{
top = cluster.GetTopology(topVer);
Assert.AreEqual(top.Count, nodes.Count);
Assert.IsTrue(top.All(nodes.Contains));
}
finally
{
_grid2 = Ignition.Start(Configuration(GetConfigs().Item2));
}
}
/// <summary>
/// Test nodes in full topology.
/// </summary>
[Test]
public void TestNodes()
{
Assert.IsNotNull(_grid1.GetCluster().GetNode());
ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes();
Assert.IsTrue(nodes.Count == 3);
// Check subsequent call on the same topology.
nodes = _grid1.GetCluster().GetNodes();
Assert.IsTrue(nodes.Count == 3);
Assert.IsTrue(Ignition.Stop(_grid2.Name, true));
// Check subsequent calls on updating topologies.
nodes = _grid1.GetCluster().GetNodes();
Assert.IsTrue(nodes.Count == 2);
nodes = _grid1.GetCluster().GetNodes();
Assert.IsTrue(nodes.Count == 2);
_grid2 = Ignition.Start(Configuration(GetConfigs().Item2));
nodes = _grid1.GetCluster().GetNodes();
Assert.IsTrue(nodes.Count == 3);
}
/// <summary>
/// Test "ForNodes" and "ForNodeIds".
/// </summary>
[Test]
public void TestForNodes()
{
ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes();
IClusterNode first = nodes.ElementAt(0);
IClusterNode second = nodes.ElementAt(1);
IClusterGroup singleNodePrj = _grid1.GetCluster().ForNodeIds(first.Id);
Assert.AreEqual(1, singleNodePrj.GetNodes().Count);
Assert.AreEqual(first.Id, singleNodePrj.GetNodes().First().Id);
singleNodePrj = _grid1.GetCluster().ForNodeIds(new List<Guid> { first.Id });
Assert.AreEqual(1, singleNodePrj.GetNodes().Count);
Assert.AreEqual(first.Id, singleNodePrj.GetNodes().First().Id);
singleNodePrj = _grid1.GetCluster().ForNodes(first);
Assert.AreEqual(1, singleNodePrj.GetNodes().Count);
Assert.AreEqual(first.Id, singleNodePrj.GetNodes().First().Id);
singleNodePrj = _grid1.GetCluster().ForNodes(new List<IClusterNode> { first });
Assert.AreEqual(1, singleNodePrj.GetNodes().Count);
Assert.AreEqual(first.Id, singleNodePrj.GetNodes().First().Id);
IClusterGroup multiNodePrj = _grid1.GetCluster().ForNodeIds(first.Id, second.Id);
Assert.AreEqual(2, multiNodePrj.GetNodes().Count);
Assert.IsTrue(multiNodePrj.GetNodes().Contains(first));
Assert.IsTrue(multiNodePrj.GetNodes().Contains(second));
multiNodePrj = _grid1.GetCluster().ForNodeIds(new[] {first, second}.Select(x => x.Id));
Assert.AreEqual(2, multiNodePrj.GetNodes().Count);
Assert.IsTrue(multiNodePrj.GetNodes().Contains(first));
Assert.IsTrue(multiNodePrj.GetNodes().Contains(second));
multiNodePrj = _grid1.GetCluster().ForNodes(first, second);
Assert.AreEqual(2, multiNodePrj.GetNodes().Count);
Assert.IsTrue(multiNodePrj.GetNodes().Contains(first));
Assert.IsTrue(multiNodePrj.GetNodes().Contains(second));
multiNodePrj = _grid1.GetCluster().ForNodes(new List<IClusterNode> { first, second });
Assert.AreEqual(2, multiNodePrj.GetNodes().Count);
Assert.IsTrue(multiNodePrj.GetNodes().Contains(first));
Assert.IsTrue(multiNodePrj.GetNodes().Contains(second));
}
/// <summary>
/// Test "ForNodes" and "ForNodeIds". Make sure lazy enumerables are enumerated only once.
/// </summary>
[Test]
public void TestForNodesLaziness()
{
var nodes = _grid1.GetCluster().GetNodes().Take(2).ToArray();
var callCount = 0;
Func<IClusterNode, IClusterNode> nodeSelector = node =>
{
callCount++;
return node;
};
Func<IClusterNode, Guid> idSelector = node =>
{
callCount++;
return node.Id;
};
var projection = _grid1.GetCluster().ForNodes(nodes.Select(nodeSelector));
Assert.AreEqual(2, projection.GetNodes().Count);
Assert.AreEqual(2, callCount);
projection = _grid1.GetCluster().ForNodeIds(nodes.Select(idSelector));
Assert.AreEqual(2, projection.GetNodes().Count);
Assert.AreEqual(4, callCount);
}
/// <summary>
/// Test for local node projection.
/// </summary>
[Test]
public void TestForLocal()
{
IClusterGroup prj = _grid1.GetCluster().ForLocal();
Assert.AreEqual(1, prj.GetNodes().Count);
Assert.AreEqual(_grid1.GetCluster().GetLocalNode(), prj.GetNodes().First());
}
/// <summary>
/// Test for remote nodes projection.
/// </summary>
[Test]
public void TestForRemotes()
{
ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes();
IClusterGroup prj = _grid1.GetCluster().ForRemotes();
Assert.AreEqual(2, prj.GetNodes().Count);
Assert.IsTrue(nodes.Contains(prj.GetNodes().ElementAt(0)));
Assert.IsTrue(nodes.Contains(prj.GetNodes().ElementAt(1)));
}
/// <summary>
/// Test for daemon nodes projection.
/// </summary>
[Test]
public void TestForDaemons()
{
Assert.AreEqual(0, _grid1.GetCluster().ForDaemons().GetNodes().Count);
using (var ignite = Ignition.Start(new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
SpringConfigUrl = GetConfigs().Item1,
IgniteInstanceName = "daemonGrid",
IsDaemon = true
})
)
{
var prj = _grid1.GetCluster().ForDaemons();
Assert.AreEqual(1, prj.GetNodes().Count);
Assert.AreEqual(ignite.GetCluster().GetLocalNode().Id, prj.GetNode().Id);
Assert.IsTrue(prj.GetNode().IsDaemon);
Assert.IsTrue(ignite.GetCluster().GetLocalNode().IsDaemon);
}
}
/// <summary>
/// Test for host nodes projection.
/// </summary>
[Test]
public void TestForHost()
{
ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes();
IClusterGroup prj = _grid1.GetCluster().ForHost(nodes.First());
Assert.AreEqual(3, prj.GetNodes().Count);
Assert.IsTrue(nodes.Contains(prj.GetNodes().ElementAt(0)));
Assert.IsTrue(nodes.Contains(prj.GetNodes().ElementAt(1)));
Assert.IsTrue(nodes.Contains(prj.GetNodes().ElementAt(2)));
}
/// <summary>
/// Test for oldest, youngest and random projections.
/// </summary>
[Test]
public void TestForOldestYoungestRandom()
{
ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes();
IClusterGroup prj = _grid1.GetCluster().ForYoungest();
Assert.AreEqual(1, prj.GetNodes().Count);
Assert.IsTrue(nodes.Contains(prj.GetNode()));
prj = _grid1.GetCluster().ForOldest();
Assert.AreEqual(1, prj.GetNodes().Count);
Assert.IsTrue(nodes.Contains(prj.GetNode()));
prj = _grid1.GetCluster().ForRandom();
Assert.AreEqual(1, prj.GetNodes().Count);
Assert.IsTrue(nodes.Contains(prj.GetNode()));
}
/// <summary>
/// Tests ForServers projection.
/// </summary>
[Test]
public void TestForServers()
{
var cluster = _grid1.GetCluster();
var servers = cluster.ForServers().GetNodes();
Assert.AreEqual(2, servers.Count);
Assert.IsTrue(servers.All(x => !x.IsClient));
var serverAndClient =
cluster.ForNodeIds(new[] { _grid2, _grid3 }.Select(x => x.GetCluster().GetLocalNode().Id));
Assert.AreEqual(1, serverAndClient.ForServers().GetNodes().Count);
var client = cluster.ForNodeIds(new[] { _grid3 }.Select(x => x.GetCluster().GetLocalNode().Id));
Assert.AreEqual(0, client.ForServers().GetNodes().Count);
}
/// <summary>
/// Test for attribute projection.
/// </summary>
[Test]
public void TestForAttribute()
{
ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes();
IClusterGroup prj = _grid1.GetCluster().ForAttribute("my_attr", "value1");
Assert.AreEqual(1, prj.GetNodes().Count);
Assert.IsTrue(nodes.Contains(prj.GetNode()));
Assert.AreEqual("value1", prj.GetNodes().First().GetAttribute<string>("my_attr"));
}
/// <summary>
/// Test for cache/data/client projections.
/// </summary>
[Test]
public void TestForCacheNodes()
{
ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes();
// Cache nodes.
IClusterGroup prjCache = _grid1.GetCluster().ForCacheNodes("cache1");
Assert.AreEqual(2, prjCache.GetNodes().Count);
Assert.IsTrue(nodes.Contains(prjCache.GetNodes().ElementAt(0)));
Assert.IsTrue(nodes.Contains(prjCache.GetNodes().ElementAt(1)));
// Data nodes.
IClusterGroup prjData = _grid1.GetCluster().ForDataNodes("cache1");
Assert.AreEqual(2, prjData.GetNodes().Count);
Assert.IsTrue(prjCache.GetNodes().Contains(prjData.GetNodes().ElementAt(0)));
Assert.IsTrue(prjCache.GetNodes().Contains(prjData.GetNodes().ElementAt(1)));
// Client nodes.
IClusterGroup prjClient = _grid1.GetCluster().ForClientNodes("cache1");
Assert.AreEqual(0, prjClient.GetNodes().Count);
}
/// <summary>
/// Test for cache predicate.
/// </summary>
[Test]
public void TestForPredicate()
{
IClusterGroup prj1 = _grid1.GetCluster().ForPredicate(new NotAttributePredicate("value1").Apply);
Assert.AreEqual(2, prj1.GetNodes().Count);
IClusterGroup prj2 = prj1.ForPredicate(new NotAttributePredicate("value2").Apply);
Assert.AreEqual(1, prj2.GetNodes().Count);
string val;
prj2.GetNodes().First().TryGetAttribute("my_attr", out val);
Assert.IsTrue(val == null || (!val.Equals("value1") && !val.Equals("value2")));
}
/// <summary>
/// Attribute predicate.
/// </summary>
private class NotAttributePredicate
{
/** Required attribute value. */
private readonly string _attrVal;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="attrVal">Required attribute value.</param>
public NotAttributePredicate(string attrVal)
{
_attrVal = attrVal;
}
/** <inhreitDoc /> */
public bool Apply(IClusterNode node)
{
string val;
node.TryGetAttribute("my_attr", out val);
return val == null || !val.Equals(_attrVal);
}
}
/// <summary>
/// Test echo with decimals.
/// </summary>
[Test]
public void TestEchoDecimal()
{
decimal val;
Assert.AreEqual(val = decimal.Zero, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(0, 0, 1, false, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(0, 0, 1, true, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(0, 0, 1, false, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(0, 0, 1, true, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(0, 0, 1, false, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(0, 0, 1, true, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(0, 0, int.MinValue, false, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(0, 0, int.MinValue, true, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(0, 0, int.MinValue, false, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(0, 0, int.MinValue, true, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(0, 0, int.MinValue, false, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(0, 0, int.MinValue, true, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(0, 0, int.MaxValue, false, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(0, 0, int.MaxValue, true, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(0, 0, int.MaxValue, false, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(0, 0, int.MaxValue, true, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(0, 0, int.MaxValue, false, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(0, 0, int.MaxValue, true, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(0, 1, 0, false, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(0, 1, 0, true, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(0, 1, 0, false, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(0, 1, 0, true, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(0, 1, 0, false, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(0, 1, 0, true, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(0, int.MinValue, 0, false, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(0, int.MinValue, 0, true, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(0, int.MinValue, 0, false, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(0, int.MinValue, 0, true, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(0, int.MinValue, 0, false, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(0, int.MinValue, 0, true, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(0, int.MaxValue, 0, false, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(0, int.MaxValue, 0, true, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(0, int.MaxValue, 0, false, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(0, int.MaxValue, 0, true, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(0, int.MaxValue, 0, false, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(0, int.MaxValue, 0, true, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(1, 0, 0, false, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(1, 0, 0, true, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(1, 0, 0, false, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(1, 0, 0, true, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(1, 0, 0, false, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(1, 0, 0, true, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(int.MinValue, 0, 0, false, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(int.MinValue, 0, 0, true, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(int.MinValue, 0, 0, false, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(int.MinValue, 0, 0, true, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(int.MinValue, 0, 0, false, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(int.MinValue, 0, 0, true, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(int.MaxValue, 0, 0, false, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(int.MaxValue, 0, 0, true, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(int.MaxValue, 0, 0, false, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(int.MaxValue, 0, 0, true, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(int.MaxValue, 0, 0, false, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(int.MaxValue, 0, 0, true, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(1, 1, 1, false, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(1, 1, 1, true, 0), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(1, 1, 1, false, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(1, 1, 1, true, 0) - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(1, 1, 1, false, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = new decimal(1, 1, 1, true, 0) + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = decimal.Parse("65536"), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = decimal.Parse("-65536"), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = decimal.Parse("65536") - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = decimal.Parse("-65536") - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = decimal.Parse("65536") + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = decimal.Parse("-65536") + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = decimal.Parse("4294967296"), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = decimal.Parse("-4294967296"), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = decimal.Parse("4294967296") - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = decimal.Parse("-4294967296") - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = decimal.Parse("4294967296") + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = decimal.Parse("-4294967296") + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = decimal.Parse("281474976710656"), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = decimal.Parse("-281474976710656"), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = decimal.Parse("281474976710656") - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = decimal.Parse("-281474976710656") - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = decimal.Parse("281474976710656") + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = decimal.Parse("-281474976710656") + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = decimal.Parse("18446744073709551616"), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = decimal.Parse("-18446744073709551616"), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = decimal.Parse("18446744073709551616") - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = decimal.Parse("-18446744073709551616") - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = decimal.Parse("18446744073709551616") + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = decimal.Parse("-18446744073709551616") + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = decimal.Parse("1208925819614629174706176"), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = decimal.Parse("-1208925819614629174706176"), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = decimal.Parse("1208925819614629174706176") - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = decimal.Parse("-1208925819614629174706176") - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = decimal.Parse("1208925819614629174706176") + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = decimal.Parse("-1208925819614629174706176") + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = decimal.MaxValue, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = decimal.MinValue, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = decimal.MaxValue - 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = decimal.MinValue + 1, _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = decimal.Parse("11,12"), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
Assert.AreEqual(val = decimal.Parse("-11,12"), _grid1.GetCompute().ExecuteJavaTask<object>(DecimalTask, new object[] { val, val.ToString() }));
// Test echo with overflow.
var ex = Assert.Throws<BinaryObjectException>(() => _grid1.GetCompute()
.ExecuteJavaTask<object>(DecimalTask, new object[] {null, decimal.MaxValue.ToString() + 1}));
Assert.AreEqual("Decimal magnitude overflow (must be less than 96 bits): 104", ex.Message);
// Negative scale. 1E+1 parses to "1 scale -1" on Java side.
ex = Assert.Throws<BinaryObjectException>(() => _grid1.GetCompute()
.ExecuteJavaTask<object>(DecimalTask, new object[] {null, "1E+1"}));
Assert.AreEqual("Decimal value scale overflow (must be between 0 and 28): -1", ex.Message);
}
/// <summary>
/// Test echo task returning null.
/// </summary>
[Test]
public void TestEchoTaskNull()
{
Assert.IsNull(_grid1.GetCompute().ExecuteJavaTask<object>(EchoTask, EchoTypeNull));
}
/// <summary>
/// Test echo task returning various primitives.
/// </summary>
[Test]
public void TestEchoTaskPrimitives()
{
Assert.AreEqual(1, _grid1.GetCompute().ExecuteJavaTask<byte>(EchoTask, EchoTypeByte));
Assert.AreEqual(true, _grid1.GetCompute().ExecuteJavaTask<bool>(EchoTask, EchoTypeBool));
Assert.AreEqual(1, _grid1.GetCompute().ExecuteJavaTask<short>(EchoTask, EchoTypeShort));
Assert.AreEqual((char)1, _grid1.GetCompute().ExecuteJavaTask<char>(EchoTask, EchoTypeChar));
Assert.AreEqual(1, _grid1.GetCompute().ExecuteJavaTask<int>(EchoTask, EchoTypeInt));
Assert.AreEqual(1, _grid1.GetCompute().ExecuteJavaTask<long>(EchoTask, EchoTypeLong));
Assert.AreEqual((float)1, _grid1.GetCompute().ExecuteJavaTask<float>(EchoTask, EchoTypeFloat));
Assert.AreEqual((double)1, _grid1.GetCompute().ExecuteJavaTask<double>(EchoTask, EchoTypeDouble));
}
/// <summary>
/// Test echo task returning compound types.
/// </summary>
[Test]
public void TestEchoTaskCompound()
{
int[] res1 = _grid1.GetCompute().ExecuteJavaTask<int[]>(EchoTask, EchoTypeArray);
Assert.AreEqual(1, res1.Length);
Assert.AreEqual(1, res1[0]);
var res2 = _grid1.GetCompute().ExecuteJavaTask<IList>(EchoTask, EchoTypeCollection);
Assert.AreEqual(1, res2.Count);
Assert.AreEqual(1, res2[0]);
var res3 = _grid1.GetCompute().ExecuteJavaTask<IDictionary>(EchoTask, EchoTypeMap);
Assert.AreEqual(1, res3.Count);
Assert.AreEqual(1, res3[1]);
}
/// <summary>
/// Test echo task returning binary object.
/// </summary>
[Test]
public void TestEchoTaskBinarizable()
{
var res = _grid1.GetCompute().ExecuteJavaTask<PlatformComputeBinarizable>(EchoTask, EchoTypeBinarizable);
Assert.AreEqual(1, res.Field);
}
/// <summary>
/// Test echo task returning binary object with no corresponding class definition.
/// </summary>
[Test]
public void TestEchoTaskBinarizableNoClass()
{
ICompute compute = _grid1.GetCompute();
compute.WithKeepBinary();
IBinaryObject res = compute.ExecuteJavaTask<IBinaryObject>(EchoTask, EchoTypeBinarizableJava);
Assert.AreEqual(1, res.GetField<int>("field"));
// This call must fail because "keepBinary" flag is reset.
var ex = Assert.Throws<BinaryObjectException>(() =>
{
compute.ExecuteJavaTask<IBinaryObject>(EchoTask, EchoTypeBinarizableJava);
});
Assert.AreEqual("Unknown pair [platformId=1, typeId=2009791293]", ex.Message);
}
/// <summary>
/// Tests the echo task returning object array.
/// </summary>
[Test]
public void TestEchoTaskObjectArray()
{
var res = _grid1.GetCompute().ExecuteJavaTask<string[]>(EchoTask, EchoTypeObjArray);
Assert.AreEqual(new[] {"foo", "bar", "baz"}, res);
}
/// <summary>
/// Tests the echo task returning binary array.
/// </summary>
[Test]
public void TestEchoTaskBinarizableArray()
{
var res = _grid1.GetCompute().ExecuteJavaTask<object[]>(EchoTask, EchoTypeBinarizableArray);
Assert.AreEqual(3, res.Length);
for (var i = 0; i < res.Length; i++)
Assert.AreEqual(i + 1, ((PlatformComputeBinarizable) res[i]).Field);
}
/// <summary>
/// Tests the echo task returning enum.
/// </summary>
[Test]
public void TestEchoTaskEnum()
{
var res = _grid1.GetCompute().ExecuteJavaTask<PlatformComputeEnum>(EchoTask, EchoTypeEnum);
Assert.AreEqual(PlatformComputeEnum.Bar, res);
}
/// <summary>
/// Tests the echo task returning enum.
/// </summary>
[Test]
public void TestEchoTaskBinaryEnum()
{
var res = _grid1.GetCompute().WithKeepBinary()
.ExecuteJavaTask<IBinaryObject>(EchoTask, EchoTypeBinaryEnum);
Assert.AreEqual("JavaFoo", res.EnumName);
Assert.AreEqual(1, res.EnumValue);
var binType = res.GetBinaryType();
Assert.IsTrue(binType.IsEnum);
Assert.AreEqual("JavaDynEnum", binType.TypeName);
var vals = binType.GetEnumValues().OrderBy(x => x.EnumValue).ToArray();
Assert.AreEqual(new[] {1, 2}, vals.Select(x => x.EnumValue));
Assert.AreEqual(new[] {"JavaFoo", "JavaBar"}, vals.Select(x => x.EnumName));
}
/// <summary>
/// Tests the echo task returning enum.
/// </summary>
[Test]
public void TestEchoTaskEnumFromCache()
{
var cache = _grid1.GetCache<int, PlatformComputeEnum>(DefaultCacheName);
foreach (PlatformComputeEnum val in Enum.GetValues(typeof(PlatformComputeEnum)))
{
cache[EchoTypeEnumFromCache] = val;
var res = _grid1.GetCompute().ExecuteJavaTask<PlatformComputeEnum>(EchoTask, EchoTypeEnumFromCache);
Assert.AreEqual(val, res);
}
}
/// <summary>
/// Tests the echo task returning enum.
/// </summary>
[Test]
public void TestEchoTaskEnumArray()
{
var res = _grid1.GetCompute().ExecuteJavaTask<PlatformComputeEnum[]>(EchoTask, EchoTypeEnumArray);
Assert.AreEqual(new[]
{
PlatformComputeEnum.Bar,
PlatformComputeEnum.Baz,
PlatformComputeEnum.Foo
}, res);
}
/// <summary>
/// Tests the echo task returning enum.
/// </summary>
[Test]
public void TestEchoTaskEnumArrayFromCache()
{
var cache = _grid1.GetCache<int, PlatformComputeEnum[]>(DefaultCacheName);
foreach (var val in new[]
{
new[] {PlatformComputeEnum.Bar, PlatformComputeEnum.Baz, PlatformComputeEnum.Foo },
new[] {PlatformComputeEnum.Foo, PlatformComputeEnum.Baz},
new[] {PlatformComputeEnum.Bar}
})
{
cache[EchoTypeEnumArrayFromCache] = val;
var res = _grid1.GetCompute().ExecuteJavaTask<PlatformComputeEnum[]>(
EchoTask, EchoTypeEnumArrayFromCache);
Assert.AreEqual(val, res);
}
}
/// <summary>
/// Tests the echo task reading enum from a binary object field.
/// Ensures that Java can understand enums written by .NET.
/// </summary>
[Test]
public void TestEchoTaskEnumField()
{
var enumVal = PlatformComputeEnum.Baz;
_grid1.GetCache<int, InteropComputeEnumFieldTest>(DefaultCacheName)
.Put(EchoTypeEnumField, new InteropComputeEnumFieldTest {InteropEnum = enumVal});
var res = _grid1.GetCompute().ExecuteJavaTask<PlatformComputeEnum>(EchoTask, EchoTypeEnumField);
var enumMeta = _grid1.GetBinary().GetBinaryType(typeof (PlatformComputeEnum));
Assert.IsTrue(enumMeta.IsEnum);
Assert.AreEqual(enumMeta.TypeName, typeof(PlatformComputeEnum).Name);
Assert.AreEqual(0, enumMeta.Fields.Count);
Assert.AreEqual(enumVal, res);
}
/// <summary>
/// Tests that IgniteGuid in .NET maps to IgniteUuid in Java.
/// </summary>
[Test]
public void TestEchoTaskIgniteUuid()
{
var guid = Guid.NewGuid();
_grid1.GetCache<int, object>(DefaultCacheName)[EchoTypeIgniteUuid] = new IgniteGuid(guid, 25);
var res = _grid1.GetCompute().ExecuteJavaTask<IgniteGuid>(EchoTask, EchoTypeIgniteUuid);
Assert.AreEqual(guid, res.GlobalId);
Assert.AreEqual(25, res.LocalId);
}
/// <summary>
/// Test for binary argument in Java.
/// </summary>
[Test]
public void TestBinarizableArgTask()
{
ICompute compute = _grid1.GetCompute();
compute.WithKeepBinary();
PlatformComputeNetBinarizable arg = new PlatformComputeNetBinarizable {Field = 100};
int res = compute.ExecuteJavaTask<int>(BinaryArgTask, arg);
Assert.AreEqual(arg.Field, res);
}
/// <summary>
/// Test running broadcast task.
/// </summary>
[Test]
public void TestBroadcastTask([Values(false, true)] bool isAsync)
{
var execTask =
isAsync
? (Func<ICompute, List<Guid>>) (
c => c.ExecuteJavaTaskAsync<ICollection>(BroadcastTask, null).Result.OfType<Guid>().ToList())
: c => c.ExecuteJavaTask<ICollection>(BroadcastTask, null).OfType<Guid>().ToList();
var res = execTask(_grid1.GetCompute());
Assert.AreEqual(2, res.Count);
Assert.AreEqual(1, _grid1.GetCluster().ForNodeIds(res.ElementAt(0)).GetNodes().Count);
Assert.AreEqual(1, _grid1.GetCluster().ForNodeIds(res.ElementAt(1)).GetNodes().Count);
var prj = _grid1.GetCluster().ForPredicate(node => res.Take(2).Contains(node.Id));
Assert.AreEqual(2, prj.GetNodes().Count);
var filteredRes = execTask(prj.GetCompute());
Assert.AreEqual(2, filteredRes.Count);
Assert.IsTrue(filteredRes.Contains(res.ElementAt(0)));
Assert.IsTrue(filteredRes.Contains(res.ElementAt(1)));
}
/// <summary>
/// Tests the action broadcast.
/// </summary>
[Test]
public void TestBroadcastAction()
{
var id = Guid.NewGuid();
_grid1.GetCompute().Broadcast(new ComputeAction(id));
Assert.AreEqual(2, ComputeAction.InvokeCount(id));
id = Guid.NewGuid();
_grid1.GetCompute().BroadcastAsync(new ComputeAction(id)).Wait();
Assert.AreEqual(2, ComputeAction.InvokeCount(id));
}
/// <summary>
/// Tests single action run.
/// </summary>
[Test]
public void TestRunAction()
{
var id = Guid.NewGuid();
_grid1.GetCompute().Run(new ComputeAction(id));
Assert.AreEqual(1, ComputeAction.InvokeCount(id));
id = Guid.NewGuid();
_grid1.GetCompute().RunAsync(new ComputeAction(id)).Wait();
Assert.AreEqual(1, ComputeAction.InvokeCount(id));
}
/// <summary>
/// Tests single action run.
/// </summary>
[Test]
public void TestRunActionAsyncCancel()
{
using (var cts = new CancellationTokenSource())
{
// Cancel while executing
var task = _grid1.GetCompute().RunAsync(new ComputeAction(), cts.Token);
cts.Cancel();
Assert.IsTrue(task.IsCanceled);
// Use cancelled token
task = _grid1.GetCompute().RunAsync(new ComputeAction(), cts.Token);
Assert.IsTrue(task.IsCanceled);
}
}
/// <summary>
/// Tests multiple actions run.
/// </summary>
[Test]
public void TestRunActions()
{
var id = Guid.NewGuid();
_grid1.GetCompute().Run(Enumerable.Range(0, 10).Select(x => new ComputeAction(id)));
Assert.AreEqual(10, ComputeAction.InvokeCount(id));
var id2 = Guid.NewGuid();
_grid1.GetCompute().RunAsync(Enumerable.Range(0, 10).Select(x => new ComputeAction(id2))).Wait();
Assert.AreEqual(10, ComputeAction.InvokeCount(id2));
}
/// <summary>
/// Tests affinity run.
/// </summary>
[Test]
public void TestAffinityRun()
{
const string cacheName = DefaultCacheName;
// Test keys for non-client nodes
var nodes = new[] {_grid1, _grid2}.Select(x => x.GetCluster().GetLocalNode());
var aff = _grid1.GetAffinity(cacheName);
foreach (var node in nodes)
{
var primaryKey = TestUtils.GetPrimaryKey(_grid1, cacheName, node);
var affinityKey = aff.GetAffinityKey<int, int>(primaryKey);
_grid1.GetCompute().AffinityRun(cacheName, affinityKey, new ComputeAction());
Assert.AreEqual(node.Id, ComputeAction.LastNodeId);
_grid1.GetCompute().AffinityRunAsync(cacheName, affinityKey, new ComputeAction()).Wait();
Assert.AreEqual(node.Id, ComputeAction.LastNodeId);
}
}
/// <summary>
/// Tests affinity call.
/// </summary>
[Test]
public void TestAffinityCall()
{
const string cacheName = DefaultCacheName;
// Test keys for non-client nodes
var nodes = new[] { _grid1, _grid2 }.Select(x => x.GetCluster().GetLocalNode());
var aff = _grid1.GetAffinity(cacheName);
foreach (var node in nodes)
{
var primaryKey = TestUtils.GetPrimaryKey(_grid1, cacheName, node);
var affinityKey = aff.GetAffinityKey<int, int>(primaryKey);
var result = _grid1.GetCompute().AffinityCall(cacheName, affinityKey, new ComputeFunc());
Assert.AreEqual(result, ComputeFunc.InvokeCount);
Assert.AreEqual(node.Id, ComputeFunc.LastNodeId);
// Async.
ComputeFunc.InvokeCount = 0;
result = _grid1.GetCompute().AffinityCallAsync(cacheName, affinityKey, new ComputeFunc()).Result;
Assert.AreEqual(result, ComputeFunc.InvokeCount);
Assert.AreEqual(node.Id, ComputeFunc.LastNodeId);
}
}
/// <summary>
/// Test "withNoFailover" feature.
/// </summary>
[Test]
public void TestWithNoFailover()
{
var res = _grid1.GetCompute().WithNoFailover().ExecuteJavaTask<ICollection>(BroadcastTask, null)
.OfType<Guid>().ToList();
Assert.AreEqual(2, res.Count);
Assert.AreEqual(1, _grid1.GetCluster().ForNodeIds(res.ElementAt(0)).GetNodes().Count);
Assert.AreEqual(1, _grid1.GetCluster().ForNodeIds(res.ElementAt(1)).GetNodes().Count);
}
/// <summary>
/// Test "withTimeout" feature.
/// </summary>
[Test]
public void TestWithTimeout()
{
var res = _grid1.GetCompute().WithTimeout(1000).ExecuteJavaTask<ICollection>(BroadcastTask, null)
.OfType<Guid>().ToList();
Assert.AreEqual(2, res.Count);
Assert.AreEqual(1, _grid1.GetCluster().ForNodeIds(res.ElementAt(0)).GetNodes().Count);
Assert.AreEqual(1, _grid1.GetCluster().ForNodeIds(res.ElementAt(1)).GetNodes().Count);
}
/// <summary>
/// Test simple dotNet task execution.
/// </summary>
[Test]
public void TestNetTaskSimple()
{
Assert.AreEqual(2, _grid1.GetCompute()
.Execute<NetSimpleJobArgument, NetSimpleJobResult, NetSimpleTaskResult>(
typeof(NetSimpleTask), new NetSimpleJobArgument(1)).Res);
Assert.AreEqual(2, _grid1.GetCompute()
.ExecuteAsync<NetSimpleJobArgument, NetSimpleJobResult, NetSimpleTaskResult>(
typeof(NetSimpleTask), new NetSimpleJobArgument(1)).Result.Res);
Assert.AreEqual(4, _grid1.GetCompute().Execute(new NetSimpleTask(), new NetSimpleJobArgument(2)).Res);
Assert.AreEqual(6, _grid1.GetCompute().ExecuteAsync(new NetSimpleTask(), new NetSimpleJobArgument(3))
.Result.Res);
}
/// <summary>
/// Tests the exceptions.
/// </summary>
[Test]
public void TestExceptions()
{
Assert.Throws<AggregateException>(() => _grid1.GetCompute().Broadcast(new InvalidComputeAction()));
Assert.Throws<AggregateException>(
() => _grid1.GetCompute().Execute<NetSimpleJobArgument, NetSimpleJobResult, NetSimpleTaskResult>(
typeof (NetSimpleTask), new NetSimpleJobArgument(-1)));
// Local.
var ex = Assert.Throws<AggregateException>(() =>
_grid1.GetCluster().ForLocal().GetCompute().Broadcast(new ExceptionalComputeAction()));
Assert.IsNotNull(ex.InnerException);
Assert.AreEqual("Compute job has failed on local node, examine InnerException for details.",
ex.InnerException.Message);
Assert.IsNotNull(ex.InnerException.InnerException);
Assert.AreEqual(ExceptionalComputeAction.ErrorText, ex.InnerException.InnerException.Message);
// Remote.
ex = Assert.Throws<AggregateException>(() =>
_grid1.GetCluster().ForRemotes().GetCompute().Broadcast(new ExceptionalComputeAction()));
Assert.IsNotNull(ex.InnerException);
Assert.AreEqual("Compute job has failed on remote node, examine InnerException for details.",
ex.InnerException.Message);
Assert.IsNotNull(ex.InnerException.InnerException);
Assert.AreEqual(ExceptionalComputeAction.ErrorText, ex.InnerException.InnerException.Message);
}
/// <summary>
/// Tests the footer setting.
/// </summary>
[Test]
public void TestFooterSetting()
{
Assert.AreEqual(CompactFooter, ((Ignite)_grid1).Marshaller.CompactFooter);
foreach (var g in new[] {_grid1, _grid2, _grid3})
Assert.AreEqual(CompactFooter, g.GetConfiguration().BinaryConfiguration.CompactFooter);
}
/// <summary>
/// Create configuration.
/// </summary>
/// <param name="path">XML config path.</param>
private static IgniteConfiguration Configuration(string path)
{
return new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
BinaryConfiguration = new BinaryConfiguration
{
TypeConfigurations = new List<BinaryTypeConfiguration>
{
new BinaryTypeConfiguration(typeof(PlatformComputeBinarizable)),
new BinaryTypeConfiguration(typeof(PlatformComputeNetBinarizable)),
new BinaryTypeConfiguration(JavaBinaryCls),
new BinaryTypeConfiguration(typeof(PlatformComputeEnum)),
new BinaryTypeConfiguration(typeof(InteropComputeEnumFieldTest))
},
NameMapper = BinaryBasicNameMapper.SimpleNameInstance
},
SpringConfigUrl = path
};
}
}
class PlatformComputeBinarizable
{
public int Field
{
get;
set;
}
}
class PlatformComputeNetBinarizable : PlatformComputeBinarizable
{
}
[Serializable]
class NetSimpleTask : IComputeTask<NetSimpleJobArgument, NetSimpleJobResult, NetSimpleTaskResult>
{
/** <inheritDoc /> */
public IDictionary<IComputeJob<NetSimpleJobResult>, IClusterNode> Map(IList<IClusterNode> subgrid,
NetSimpleJobArgument arg)
{
var jobs = new Dictionary<IComputeJob<NetSimpleJobResult>, IClusterNode>();
for (int i = 0; i < subgrid.Count; i++)
{
var job = arg.Arg > 0 ? new NetSimpleJob {Arg = arg} : new InvalidNetSimpleJob();
jobs[job] = subgrid[i];
}
return jobs;
}
/** <inheritDoc /> */
public ComputeJobResultPolicy OnResult(IComputeJobResult<NetSimpleJobResult> res,
IList<IComputeJobResult<NetSimpleJobResult>> rcvd)
{
return ComputeJobResultPolicy.Wait;
}
/** <inheritDoc /> */
public NetSimpleTaskResult Reduce(IList<IComputeJobResult<NetSimpleJobResult>> results)
{
return new NetSimpleTaskResult(results.Sum(res => res.Data.Res));
}
}
[Serializable]
class NetSimpleJob : IComputeJob<NetSimpleJobResult>
{
public NetSimpleJobArgument Arg;
/** <inheritDoc /> */
public NetSimpleJobResult Execute()
{
return new NetSimpleJobResult(Arg.Arg);
}
/** <inheritDoc /> */
public void Cancel()
{
// No-op.
}
}
class InvalidNetSimpleJob : NetSimpleJob, IBinarizable
{
public void WriteBinary(IBinaryWriter writer)
{
throw new BinaryObjectException("Expected");
}
public void ReadBinary(IBinaryReader reader)
{
throw new BinaryObjectException("Expected");
}
}
[Serializable]
class NetSimpleJobArgument
{
public int Arg;
public NetSimpleJobArgument(int arg)
{
Arg = arg;
}
}
[Serializable]
class NetSimpleTaskResult
{
public int Res;
public NetSimpleTaskResult(int res)
{
Res = res;
}
}
[Serializable]
class NetSimpleJobResult
{
public int Res;
public NetSimpleJobResult(int res)
{
Res = res;
}
}
[Serializable]
class ComputeAction : IComputeAction
{
[InstanceResource]
#pragma warning disable 649
private IIgnite _grid;
public static ConcurrentBag<Guid> Invokes = new ConcurrentBag<Guid>();
public static Guid LastNodeId;
public Guid Id { get; set; }
public ComputeAction()
{
// No-op.
}
public ComputeAction(Guid id)
{
Id = id;
}
public void Invoke()
{
Thread.Sleep(10);
Invokes.Add(Id);
LastNodeId = _grid.GetCluster().GetLocalNode().Id;
}
public static int InvokeCount(Guid id)
{
return Invokes.Count(x => x == id);
}
}
class InvalidComputeAction : ComputeAction, IBinarizable
{
public void WriteBinary(IBinaryWriter writer)
{
throw new BinaryObjectException("Expected");
}
public void ReadBinary(IBinaryReader reader)
{
throw new BinaryObjectException("Expected");
}
}
class ExceptionalComputeAction : IComputeAction
{
public const string ErrorText = "Expected user exception";
public void Invoke()
{
throw new OverflowException(ErrorText);
}
}
interface IUserInterface<out T>
{
T Invoke();
}
interface INestedComputeFunc : IComputeFunc<int>
{
}
[Serializable]
class ComputeFunc : INestedComputeFunc, IUserInterface<int>
{
[InstanceResource]
private IIgnite _grid;
public static int InvokeCount;
public static Guid LastNodeId;
int IComputeFunc<int>.Invoke()
{
Thread.Sleep(10);
InvokeCount++;
LastNodeId = _grid.GetCluster().GetLocalNode().Id;
return InvokeCount;
}
int IUserInterface<int>.Invoke()
{
// Same signature as IComputeFunc<int>, but from different interface
throw new Exception("Invalid method");
}
public int Invoke()
{
// Same signature as IComputeFunc<int>, but due to explicit interface implementation this is a wrong method
throw new Exception("Invalid method");
}
}
public enum PlatformComputeEnum : ushort
{
Foo,
Bar,
Baz
}
public class InteropComputeEnumFieldTest
{
public PlatformComputeEnum InteropEnum { get; set; }
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using Hyak.Common;
using System;
using System.Net.Http;
namespace Microsoft.Azure.Management.Csm
{
public partial class ResourceManagementClient : ServiceClient<ResourceManagementClient>, IResourceManagementClient
{
private string _apiVersion;
/// <summary>
/// Gets the API version.
/// </summary>
public string ApiVersion
{
get { return this._apiVersion; }
}
private Uri _baseUri;
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
public Uri BaseUri
{
get { return this._baseUri; }
}
private SubscriptionCloudCredentials _credentials;
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft
/// Azure subscription. The subscription ID forms part of the URI for
/// every service call.
/// </summary>
public SubscriptionCloudCredentials Credentials
{
get { return this._credentials; }
}
private int _longRunningOperationInitialTimeout;
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationInitialTimeout
{
get { return this._longRunningOperationInitialTimeout; }
set { this._longRunningOperationInitialTimeout = value; }
}
private int _longRunningOperationRetryTimeout;
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationRetryTimeout
{
get { return this._longRunningOperationRetryTimeout; }
set { this._longRunningOperationRetryTimeout = value; }
}
private IProviderOperations _providers;
/// <summary>
/// Operations for managing providers.
/// </summary>
public virtual IProviderOperations Providers
{
get { return this._providers; }
}
/// <summary>
/// Initializes a new instance of the ResourceManagementClient class.
/// </summary>
public ResourceManagementClient()
: base()
{
this._providers = new ProviderOperations(this);
this._apiVersion = "2014-04-01-preview";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the ResourceManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public ResourceManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the ResourceManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
public ResourceManagementClient(SubscriptionCloudCredentials credentials)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com/");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the ResourceManagementClient class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
public ResourceManagementClient(HttpClient httpClient)
: base(httpClient)
{
this._providers = new ProviderOperations(this);
this._apiVersion = "2014-04-01-preview";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the ResourceManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public ResourceManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the ResourceManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public ResourceManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com/");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another
/// ResourceManagementClient instance
/// </summary>
/// <param name='client'>
/// Instance of ResourceManagementClient to clone to
/// </param>
protected override void Clone(ServiceClient<ResourceManagementClient> client)
{
base.Clone(client);
if (client is ResourceManagementClient)
{
ResourceManagementClient clonedClient = ((ResourceManagementClient)client);
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._apiVersion = this._apiVersion;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
}
}
| |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2017 FUJIWARA, Yusuke
//
// 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 -- License Terms --
using System;
using System.Globalization;
using System.Linq;
using MsgPack.Serialization;
#if !MSTEST
using NUnit.Framework;
#else
using TestFixtureAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using TestAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
using TimeoutAttribute = NUnit.Framework.TimeoutAttribute;
using Assert = NUnit.Framework.Assert;
using Is = NUnit.Framework.Is;
#endif
namespace MsgPack
{
partial class TimestampTest
{
[Test]
public void TestEncode_Min32()
{
Assert.That(
new Timestamp( 0L, 0 ).Encode(),
Is.EqualTo( MessagePackExtendedTypeObject.Unpack( 0xFF, new byte[]{ 0, 0, 0, 0 } ) )
);
}
[Test]
public void TestEncode_Max32()
{
Assert.That(
new Timestamp( 4294967295L, 0 ).Encode(),
Is.EqualTo( MessagePackExtendedTypeObject.Unpack( 0xFF, new byte[]{ 0xFF, 0xFF, 0xFF, 0xFF } ) )
);
}
[Test]
public void TestEncode_Min64()
{
Assert.That(
new Timestamp( 0L, 1 ).Encode(),
Is.EqualTo( MessagePackExtendedTypeObject.Unpack( 0xFF, new byte[]{ 0, 0, 0, 0x4, 0, 0, 0, 0 } ) )
);
}
[Test]
public void TestEncode_Max64()
{
Assert.That(
new Timestamp( 17179869183L, 999999999 ).Encode(),
Is.EqualTo( MessagePackExtendedTypeObject.Unpack( 0xFF, new byte[]{ 0xEE, 0x6B, 0x27, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF } ) )
);
}
[Test]
public void TestEncode_Min96()
{
Assert.That(
new Timestamp( -9223372036854775808L, 0 ).Encode(),
Is.EqualTo( MessagePackExtendedTypeObject.Unpack( 0xFF, new byte[] { 0, 0, 0, 0, 0x80, 0, 0, 0, 0, 0, 0, 0 } ) )
);
}
[Test]
public void TestEncode_Max96()
{
Assert.That(
new Timestamp( 9223372036854775807L, 999999999 ).Encode(),
Is.EqualTo( MessagePackExtendedTypeObject.Unpack( 0xFF, new byte[] { 0x3B, 0x9A, 0xC9, 0xFF, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF } ) )
);
}
[Test]
public void TestDecode_Min32()
{
var result = Timestamp.Decode( MessagePackSerializer.UnpackMessagePackObject( new byte[] { 0xD6, 0xFF }.Concat( new byte[]{ 0, 0, 0, 0 } ).ToArray() ).AsMessagePackExtendedTypeObject() );
Assert.That( result.UnixEpochSecondsPart, Is.EqualTo( 0L ) );
Assert.That( result.NanosecondsPart, Is.EqualTo( 0 ) );
Assert.That( result.ToString(), Is.EqualTo( "1970-01-01T00:00:00.000000000Z" ) );
}
[Test]
public void TestDecode_Max32()
{
var result = Timestamp.Decode( MessagePackSerializer.UnpackMessagePackObject( new byte[] { 0xD6, 0xFF }.Concat( new byte[]{ 0xFF, 0xFF, 0xFF, 0xFF } ).ToArray() ).AsMessagePackExtendedTypeObject() );
Assert.That( result.UnixEpochSecondsPart, Is.EqualTo( 4294967295L ) );
Assert.That( result.NanosecondsPart, Is.EqualTo( 0 ) );
Assert.That( result.ToString(), Is.EqualTo( "2106-02-07T06:28:15.000000000Z" ) );
}
[Test]
public void TestDecode_Min64()
{
var result = Timestamp.Decode( MessagePackSerializer.UnpackMessagePackObject( new byte[] { 0xD7, 0xFF }.Concat( new byte[]{ 0, 0, 0, 0x4, 0, 0, 0, 0 } ).ToArray() ).AsMessagePackExtendedTypeObject() );
Assert.That( result.UnixEpochSecondsPart, Is.EqualTo( 0L ) );
Assert.That( result.NanosecondsPart, Is.EqualTo( 1 ) );
Assert.That( result.ToString(), Is.EqualTo( "1970-01-01T00:00:00.000000001Z" ) );
}
[Test]
public void TestDecode_Max64()
{
var result = Timestamp.Decode( MessagePackSerializer.UnpackMessagePackObject( new byte[] { 0xD7, 0xFF }.Concat( new byte[]{ 0xEE, 0x6B, 0x27, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF } ).ToArray() ).AsMessagePackExtendedTypeObject() );
Assert.That( result.UnixEpochSecondsPart, Is.EqualTo( 17179869183L ) );
Assert.That( result.NanosecondsPart, Is.EqualTo( 999999999 ) );
Assert.That( result.ToString(), Is.EqualTo( "2514-05-30T01:53:03.999999999Z" ) );
}
[Test]
public void TestDecode_Min96()
{
var result = Timestamp.Decode( MessagePackSerializer.UnpackMessagePackObject( new byte[] { 0xC7, 12, 0xFF }.Concat( new byte[] { 0, 0, 0, 0, 0x80, 0, 0, 0, 0, 0, 0, 0 } ).ToArray() ).AsMessagePackExtendedTypeObject() );
Assert.That( result.UnixEpochSecondsPart, Is.EqualTo( -9223372036854775808L ) );
Assert.That( result.NanosecondsPart, Is.EqualTo( 0 ) );
Assert.That( result.ToString(), Is.EqualTo( "-292277022657-01-27T08:29:52.000000000Z" ) );
}
[Test]
public void TestDecode_Max96()
{
var result = Timestamp.Decode( MessagePackSerializer.UnpackMessagePackObject( new byte[] { 0xC7, 12, 0xFF }.Concat( new byte[] { 0x3B, 0x9A, 0xC9, 0xFF, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF } ).ToArray() ).AsMessagePackExtendedTypeObject() );
Assert.That( result.UnixEpochSecondsPart, Is.EqualTo( 9223372036854775807L ) );
Assert.That( result.NanosecondsPart, Is.EqualTo( 999999999 ) );
Assert.That( result.ToString(), Is.EqualTo( "292277026596-12-04T15:30:07.999999999Z" ) );
}
[Test]
public void TestDecode_Min64_AllZero()
{
var result = Timestamp.Decode( MessagePackSerializer.UnpackMessagePackObject( new byte[] { 0xD7, 0xFF, 0, 0, 0, 0, 0, 0, 0, 0 } ).AsMessagePackExtendedTypeObject() );
Assert.That( result.UnixEpochSecondsPart, Is.EqualTo( 0 ) );
Assert.That( result.NanosecondsPart, Is.EqualTo( 0 ) );
Assert.That( result.ToString(), Is.EqualTo( "1970-01-01T00:00:00.000000000Z" ) );
}
[Test]
public void TestDecode_Min64_MinSeconds()
{
var result = Timestamp.Decode( MessagePackSerializer.UnpackMessagePackObject( new byte[] { 0xD7, 0xFF, 0, 0, 0, 0x1, 0, 0, 0, 0 } ).AsMessagePackExtendedTypeObject() );
Assert.That( result.UnixEpochSecondsPart, Is.EqualTo( 0x100000000L ) );
Assert.That( result.NanosecondsPart, Is.EqualTo( 0 ) );
Assert.That( result.ToString(), Is.EqualTo( "2106-02-07T06:28:16.000000000Z" ) );
}
[Test]
public void TestDecode_InvalidLength_0()
{
Assert.Throws<ArgumentException>( () => Timestamp.Decode( MessagePackExtendedTypeObject.Unpack( 0xFF, new byte [ 0 ] ) ) );
}
[Test]
public void TestDecode_InvalidLength_3()
{
Assert.Throws<ArgumentException>( () => Timestamp.Decode( MessagePackExtendedTypeObject.Unpack( 0xFF, new byte [ 3 ] ) ) );
}
[Test]
public void TestDecode_InvalidLength_5()
{
Assert.Throws<ArgumentException>( () => Timestamp.Decode( MessagePackExtendedTypeObject.Unpack( 0xFF, new byte [ 5 ] ) ) );
}
[Test]
public void TestDecode_InvalidLength_7()
{
Assert.Throws<ArgumentException>( () => Timestamp.Decode( MessagePackExtendedTypeObject.Unpack( 0xFF, new byte [ 7 ] ) ) );
}
[Test]
public void TestDecode_InvalidLength_9()
{
Assert.Throws<ArgumentException>( () => Timestamp.Decode( MessagePackExtendedTypeObject.Unpack( 0xFF, new byte [ 9 ] ) ) );
}
[Test]
public void TestDecode_InvalidLength_11()
{
Assert.Throws<ArgumentException>( () => Timestamp.Decode( MessagePackExtendedTypeObject.Unpack( 0xFF, new byte [ 11 ] ) ) );
}
[Test]
public void TestDecode_InvalidLength_13()
{
Assert.Throws<ArgumentException>( () => Timestamp.Decode( MessagePackExtendedTypeObject.Unpack( 0xFF, new byte [ 13 ] ) ) );
}
[Test]
public void TestDecode_InvalidTypeCode()
{
Assert.Throws<ArgumentException>( () => Timestamp.Decode( default( MessagePackExtendedTypeObject ) ) );
}
}
}
| |
// Copyright 2018 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 Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.v201809;
using Google.Api.Ads.Common.Util;
using System;
namespace Google.Api.Ads.AdWords.Examples.CSharp.v201809
{
/// <summary>
/// This code example adds an image representing the ad using the MediaService
/// and then adds a responsive display ad to an ad group. To get ad groups,
/// run GetAdGroups.cs.
/// </summary>
public class AddResponsiveDisplayAd : ExampleBase
{
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
/// <param name="args">The command line arguments.</param>
public static void Main(string[] args)
{
AddResponsiveDisplayAd codeExample = new AddResponsiveDisplayAd();
Console.WriteLine(codeExample.Description);
try
{
long adGroupId = long.Parse("INSERT_ADGROUP_ID_HERE");
codeExample.Run(new AdWordsUser(), adGroupId);
}
catch (Exception e)
{
Console.WriteLine("An exception occurred while running this code example. {0}",
ExampleUtilities.FormatException(e));
}
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description
{
get
{
return
"This code example adds an image representing the ad using the MediaService " +
"and then adds a responsive display ad to an ad group. To get ad groups, " +
"run GetAdGroups.cs.";
}
}
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="user">The AdWords user.</param>
/// <param name="adGroupId">Id of the ad group to which ads are added.
/// </param>
public void Run(AdWordsUser user, long adGroupId)
{
using (AdGroupAdService adGroupAdService =
(AdGroupAdService) user.GetService(AdWordsService.v201809.AdGroupAdService))
{
try
{
// Create a responsive display ad.
ResponsiveDisplayAd responsiveDisplayAd = new ResponsiveDisplayAd
{
// This ad format does not allow the creation of an image using the
// Image.data field. An image must first be created using the MediaService,
// and Image.mediaId must be populated when creating the ad.
marketingImage = new Image()
{
mediaId = UploadImage(user, "https://goo.gl/3b9Wfh")
},
shortHeadline = "Travel",
longHeadline = "Travel the World",
description = "Take to the air!",
businessName = "Google",
finalUrls = new string[]
{
"http://www.example.com"
},
// Optional: Create a square marketing image using MediaService, and set it
// to the ad.
squareMarketingImage = new Image()
{
mediaId = UploadImage(user, "https://goo.gl/mtt54n"),
},
// Optional: set call to action text.
callToActionText = "Shop Now",
// Optional: Set dynamic display ad settings, composed of landscape logo
// image, promotion text, and price prefix.
dynamicDisplayAdSettings = CreateDynamicDisplayAdSettings(user)
};
// Whitelisted accounts only: Set color settings using hexadecimal values.
// Set allowFlexibleColor to false if you want your ads to render by always
// using your colors strictly.
// responsiveDisplayAd.mainColor = "#0000ff";
// responsiveDisplayAd.accentColor = "#ffff00";
// responsiveDisplayAd.allowFlexibleColor = false;
// Whitelisted accounts only: Set the format setting that the ad will be
// served in.
// responsiveDisplayAd.formatSetting = DisplayAdFormatSetting.NON_NATIVE;
// Create ad group ad.
AdGroupAd adGroupAd = new AdGroupAd()
{
adGroupId = adGroupId,
ad = responsiveDisplayAd,
status = AdGroupAdStatus.PAUSED
};
// Create operation.
AdGroupAdOperation operation = new AdGroupAdOperation()
{
operand = adGroupAd,
@operator = Operator.ADD
};
// Make the mutate request.
AdGroupAdReturnValue result = adGroupAdService.mutate(new AdGroupAdOperation[]
{
operation
});
// Display results.
if (result != null && result.value != null)
{
foreach (AdGroupAd newAdGroupAd in result.value)
{
ResponsiveDisplayAd newAd = newAdGroupAd.ad as ResponsiveDisplayAd;
Console.WriteLine(
"Responsive display ad with ID '{0}' and short headline '{1}'" +
" was added.", newAd.id, newAd.shortHeadline);
}
}
else
{
Console.WriteLine("No responsive display ads were created.");
}
}
catch (Exception e)
{
throw new System.ApplicationException("Failed to create responsive display ad.",
e);
}
}
}
/// <summary>
/// Creates the dynamic display ad settings.
/// </summary>
/// <param name="user">The AdWords user.</param>
/// <returns></returns>
private static DynamicSettings CreateDynamicDisplayAdSettings(AdWordsUser user)
{
long logoImageMediaId = UploadImage(user, "https://goo.gl/dEvQeF");
Image logo = new Image()
{
mediaId = logoImageMediaId
};
return new DynamicSettings()
{
landscapeLogoImage = logo,
pricePrefix = "as low as",
promoText = "Free shipping!"
};
}
/// <summary>
/// Uploads the image from the specified <paramref name="url"/>.
/// </summary>
/// <param name="user">The AdWords user.</param>
/// <param name="url">The image URL.</param>
/// <returns>ID of the uploaded image.</returns>
private static long UploadImage(AdWordsUser user, string url)
{
using (MediaService mediaService =
(MediaService) user.GetService(AdWordsService.v201809.MediaService))
{
// Create the image.
Image image = new Image()
{
data = MediaUtilities.GetAssetDataFromUrl(url, user.Config),
type = MediaMediaType.IMAGE
};
// Upload the image and return the ID.
return mediaService.upload(new Media[]
{
image
})[0].mediaId;
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagve = Google.Ads.GoogleAds.V9.Enums;
using gagvr = Google.Ads.GoogleAds.V9.Resources;
using gaxgrpc = Google.Api.Gax.Grpc;
using gr = Google.Rpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using NUnit.Framework;
using Google.Ads.GoogleAds.V9.Services;
namespace Google.Ads.GoogleAds.Tests.V9.Services
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedAdGroupExtensionSettingServiceClientTest
{
[Category("Autogenerated")][Test]
public void GetAdGroupExtensionSettingRequestObject()
{
moq::Mock<AdGroupExtensionSettingService.AdGroupExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<AdGroupExtensionSettingService.AdGroupExtensionSettingServiceClient>(moq::MockBehavior.Strict);
GetAdGroupExtensionSettingRequest request = new GetAdGroupExtensionSettingRequest
{
ResourceNameAsAdGroupExtensionSettingName = gagvr::AdGroupExtensionSettingName.FromCustomerAdGroupExtensionType("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[EXTENSION_TYPE]"),
};
gagvr::AdGroupExtensionSetting expectedResponse = new gagvr::AdGroupExtensionSetting
{
ResourceNameAsAdGroupExtensionSettingName = gagvr::AdGroupExtensionSettingName.FromCustomerAdGroupExtensionType("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[EXTENSION_TYPE]"),
ExtensionType = gagve::ExtensionTypeEnum.Types.ExtensionType.Promotion,
Device = gagve::ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice.Unknown,
AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
ExtensionFeedItemsAsExtensionFeedItemNames =
{
gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"),
},
};
mockGrpcClient.Setup(x => x.GetAdGroupExtensionSetting(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AdGroupExtensionSettingServiceClient client = new AdGroupExtensionSettingServiceClientImpl(mockGrpcClient.Object, null);
gagvr::AdGroupExtensionSetting response = client.GetAdGroupExtensionSetting(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetAdGroupExtensionSettingRequestObjectAsync()
{
moq::Mock<AdGroupExtensionSettingService.AdGroupExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<AdGroupExtensionSettingService.AdGroupExtensionSettingServiceClient>(moq::MockBehavior.Strict);
GetAdGroupExtensionSettingRequest request = new GetAdGroupExtensionSettingRequest
{
ResourceNameAsAdGroupExtensionSettingName = gagvr::AdGroupExtensionSettingName.FromCustomerAdGroupExtensionType("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[EXTENSION_TYPE]"),
};
gagvr::AdGroupExtensionSetting expectedResponse = new gagvr::AdGroupExtensionSetting
{
ResourceNameAsAdGroupExtensionSettingName = gagvr::AdGroupExtensionSettingName.FromCustomerAdGroupExtensionType("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[EXTENSION_TYPE]"),
ExtensionType = gagve::ExtensionTypeEnum.Types.ExtensionType.Promotion,
Device = gagve::ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice.Unknown,
AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
ExtensionFeedItemsAsExtensionFeedItemNames =
{
gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"),
},
};
mockGrpcClient.Setup(x => x.GetAdGroupExtensionSettingAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AdGroupExtensionSetting>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AdGroupExtensionSettingServiceClient client = new AdGroupExtensionSettingServiceClientImpl(mockGrpcClient.Object, null);
gagvr::AdGroupExtensionSetting responseCallSettings = await client.GetAdGroupExtensionSettingAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::AdGroupExtensionSetting responseCancellationToken = await client.GetAdGroupExtensionSettingAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetAdGroupExtensionSetting()
{
moq::Mock<AdGroupExtensionSettingService.AdGroupExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<AdGroupExtensionSettingService.AdGroupExtensionSettingServiceClient>(moq::MockBehavior.Strict);
GetAdGroupExtensionSettingRequest request = new GetAdGroupExtensionSettingRequest
{
ResourceNameAsAdGroupExtensionSettingName = gagvr::AdGroupExtensionSettingName.FromCustomerAdGroupExtensionType("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[EXTENSION_TYPE]"),
};
gagvr::AdGroupExtensionSetting expectedResponse = new gagvr::AdGroupExtensionSetting
{
ResourceNameAsAdGroupExtensionSettingName = gagvr::AdGroupExtensionSettingName.FromCustomerAdGroupExtensionType("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[EXTENSION_TYPE]"),
ExtensionType = gagve::ExtensionTypeEnum.Types.ExtensionType.Promotion,
Device = gagve::ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice.Unknown,
AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
ExtensionFeedItemsAsExtensionFeedItemNames =
{
gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"),
},
};
mockGrpcClient.Setup(x => x.GetAdGroupExtensionSetting(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AdGroupExtensionSettingServiceClient client = new AdGroupExtensionSettingServiceClientImpl(mockGrpcClient.Object, null);
gagvr::AdGroupExtensionSetting response = client.GetAdGroupExtensionSetting(request.ResourceName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetAdGroupExtensionSettingAsync()
{
moq::Mock<AdGroupExtensionSettingService.AdGroupExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<AdGroupExtensionSettingService.AdGroupExtensionSettingServiceClient>(moq::MockBehavior.Strict);
GetAdGroupExtensionSettingRequest request = new GetAdGroupExtensionSettingRequest
{
ResourceNameAsAdGroupExtensionSettingName = gagvr::AdGroupExtensionSettingName.FromCustomerAdGroupExtensionType("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[EXTENSION_TYPE]"),
};
gagvr::AdGroupExtensionSetting expectedResponse = new gagvr::AdGroupExtensionSetting
{
ResourceNameAsAdGroupExtensionSettingName = gagvr::AdGroupExtensionSettingName.FromCustomerAdGroupExtensionType("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[EXTENSION_TYPE]"),
ExtensionType = gagve::ExtensionTypeEnum.Types.ExtensionType.Promotion,
Device = gagve::ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice.Unknown,
AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
ExtensionFeedItemsAsExtensionFeedItemNames =
{
gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"),
},
};
mockGrpcClient.Setup(x => x.GetAdGroupExtensionSettingAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AdGroupExtensionSetting>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AdGroupExtensionSettingServiceClient client = new AdGroupExtensionSettingServiceClientImpl(mockGrpcClient.Object, null);
gagvr::AdGroupExtensionSetting responseCallSettings = await client.GetAdGroupExtensionSettingAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::AdGroupExtensionSetting responseCancellationToken = await client.GetAdGroupExtensionSettingAsync(request.ResourceName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetAdGroupExtensionSettingResourceNames()
{
moq::Mock<AdGroupExtensionSettingService.AdGroupExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<AdGroupExtensionSettingService.AdGroupExtensionSettingServiceClient>(moq::MockBehavior.Strict);
GetAdGroupExtensionSettingRequest request = new GetAdGroupExtensionSettingRequest
{
ResourceNameAsAdGroupExtensionSettingName = gagvr::AdGroupExtensionSettingName.FromCustomerAdGroupExtensionType("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[EXTENSION_TYPE]"),
};
gagvr::AdGroupExtensionSetting expectedResponse = new gagvr::AdGroupExtensionSetting
{
ResourceNameAsAdGroupExtensionSettingName = gagvr::AdGroupExtensionSettingName.FromCustomerAdGroupExtensionType("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[EXTENSION_TYPE]"),
ExtensionType = gagve::ExtensionTypeEnum.Types.ExtensionType.Promotion,
Device = gagve::ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice.Unknown,
AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
ExtensionFeedItemsAsExtensionFeedItemNames =
{
gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"),
},
};
mockGrpcClient.Setup(x => x.GetAdGroupExtensionSetting(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AdGroupExtensionSettingServiceClient client = new AdGroupExtensionSettingServiceClientImpl(mockGrpcClient.Object, null);
gagvr::AdGroupExtensionSetting response = client.GetAdGroupExtensionSetting(request.ResourceNameAsAdGroupExtensionSettingName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetAdGroupExtensionSettingResourceNamesAsync()
{
moq::Mock<AdGroupExtensionSettingService.AdGroupExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<AdGroupExtensionSettingService.AdGroupExtensionSettingServiceClient>(moq::MockBehavior.Strict);
GetAdGroupExtensionSettingRequest request = new GetAdGroupExtensionSettingRequest
{
ResourceNameAsAdGroupExtensionSettingName = gagvr::AdGroupExtensionSettingName.FromCustomerAdGroupExtensionType("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[EXTENSION_TYPE]"),
};
gagvr::AdGroupExtensionSetting expectedResponse = new gagvr::AdGroupExtensionSetting
{
ResourceNameAsAdGroupExtensionSettingName = gagvr::AdGroupExtensionSettingName.FromCustomerAdGroupExtensionType("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[EXTENSION_TYPE]"),
ExtensionType = gagve::ExtensionTypeEnum.Types.ExtensionType.Promotion,
Device = gagve::ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice.Unknown,
AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
ExtensionFeedItemsAsExtensionFeedItemNames =
{
gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"),
},
};
mockGrpcClient.Setup(x => x.GetAdGroupExtensionSettingAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AdGroupExtensionSetting>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AdGroupExtensionSettingServiceClient client = new AdGroupExtensionSettingServiceClientImpl(mockGrpcClient.Object, null);
gagvr::AdGroupExtensionSetting responseCallSettings = await client.GetAdGroupExtensionSettingAsync(request.ResourceNameAsAdGroupExtensionSettingName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::AdGroupExtensionSetting responseCancellationToken = await client.GetAdGroupExtensionSettingAsync(request.ResourceNameAsAdGroupExtensionSettingName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateAdGroupExtensionSettingsRequestObject()
{
moq::Mock<AdGroupExtensionSettingService.AdGroupExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<AdGroupExtensionSettingService.AdGroupExtensionSettingServiceClient>(moq::MockBehavior.Strict);
MutateAdGroupExtensionSettingsRequest request = new MutateAdGroupExtensionSettingsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new AdGroupExtensionSettingOperation(),
},
PartialFailure = false,
ValidateOnly = true,
};
MutateAdGroupExtensionSettingsResponse expectedResponse = new MutateAdGroupExtensionSettingsResponse
{
Results =
{
new MutateAdGroupExtensionSettingResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateAdGroupExtensionSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AdGroupExtensionSettingServiceClient client = new AdGroupExtensionSettingServiceClientImpl(mockGrpcClient.Object, null);
MutateAdGroupExtensionSettingsResponse response = client.MutateAdGroupExtensionSettings(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateAdGroupExtensionSettingsRequestObjectAsync()
{
moq::Mock<AdGroupExtensionSettingService.AdGroupExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<AdGroupExtensionSettingService.AdGroupExtensionSettingServiceClient>(moq::MockBehavior.Strict);
MutateAdGroupExtensionSettingsRequest request = new MutateAdGroupExtensionSettingsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new AdGroupExtensionSettingOperation(),
},
PartialFailure = false,
ValidateOnly = true,
};
MutateAdGroupExtensionSettingsResponse expectedResponse = new MutateAdGroupExtensionSettingsResponse
{
Results =
{
new MutateAdGroupExtensionSettingResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateAdGroupExtensionSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateAdGroupExtensionSettingsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AdGroupExtensionSettingServiceClient client = new AdGroupExtensionSettingServiceClientImpl(mockGrpcClient.Object, null);
MutateAdGroupExtensionSettingsResponse responseCallSettings = await client.MutateAdGroupExtensionSettingsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateAdGroupExtensionSettingsResponse responseCancellationToken = await client.MutateAdGroupExtensionSettingsAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateAdGroupExtensionSettings()
{
moq::Mock<AdGroupExtensionSettingService.AdGroupExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<AdGroupExtensionSettingService.AdGroupExtensionSettingServiceClient>(moq::MockBehavior.Strict);
MutateAdGroupExtensionSettingsRequest request = new MutateAdGroupExtensionSettingsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new AdGroupExtensionSettingOperation(),
},
};
MutateAdGroupExtensionSettingsResponse expectedResponse = new MutateAdGroupExtensionSettingsResponse
{
Results =
{
new MutateAdGroupExtensionSettingResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateAdGroupExtensionSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AdGroupExtensionSettingServiceClient client = new AdGroupExtensionSettingServiceClientImpl(mockGrpcClient.Object, null);
MutateAdGroupExtensionSettingsResponse response = client.MutateAdGroupExtensionSettings(request.CustomerId, request.Operations);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateAdGroupExtensionSettingsAsync()
{
moq::Mock<AdGroupExtensionSettingService.AdGroupExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<AdGroupExtensionSettingService.AdGroupExtensionSettingServiceClient>(moq::MockBehavior.Strict);
MutateAdGroupExtensionSettingsRequest request = new MutateAdGroupExtensionSettingsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new AdGroupExtensionSettingOperation(),
},
};
MutateAdGroupExtensionSettingsResponse expectedResponse = new MutateAdGroupExtensionSettingsResponse
{
Results =
{
new MutateAdGroupExtensionSettingResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateAdGroupExtensionSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateAdGroupExtensionSettingsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AdGroupExtensionSettingServiceClient client = new AdGroupExtensionSettingServiceClientImpl(mockGrpcClient.Object, null);
MutateAdGroupExtensionSettingsResponse responseCallSettings = await client.MutateAdGroupExtensionSettingsAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateAdGroupExtensionSettingsResponse responseCancellationToken = await client.MutateAdGroupExtensionSettingsAsync(request.CustomerId, request.Operations, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Windows.Media;
using System.Xml.Linq;
using WpfMath.Parsers.PredefinedFormulae;
namespace WpfMath
{
// Parses definitions of predefined formulas from XML file.
internal class TexPredefinedFormulaParser
{
private static readonly string resourceName = TexUtilities.ResourcesDataDirectory + "PredefinedTexFormulas.xml";
private static readonly IDictionary<string, Type> typeMappings;
private static readonly IDictionary<string, IArgumentValueParser> argValueParsers;
private static readonly IDictionary<string, IActionParser> actionParsers;
static TexPredefinedFormulaParser()
{
typeMappings = new Dictionary<string, Type>();
argValueParsers = new Dictionary<string, IArgumentValueParser>();
actionParsers = new Dictionary<string, IActionParser>();
typeMappings.Add("Formula", typeof(TexFormula));
typeMappings.Add("string", typeof(string));
typeMappings.Add("double", typeof(double));
typeMappings.Add("int", typeof(int));
typeMappings.Add("bool", typeof(bool));
typeMappings.Add("char", typeof(char));
typeMappings.Add("Color", typeof(Color));
typeMappings.Add("Unit", typeof(TexUnit));
typeMappings.Add("AtomType", typeof(TexAtomType));
actionParsers.Add("CreateFormula", new CreateTeXFormulaParser());
actionParsers.Add("MethodInvocation", new MethodInvocationParser());
actionParsers.Add("Return", new ReturnParser());
argValueParsers.Add("Formula", new TeXFormulaValueParser());
argValueParsers.Add("string", new StringValueParser());
argValueParsers.Add("double", new DoubleValueParser());
argValueParsers.Add("int", new IntValueParser());
argValueParsers.Add("bool", new BooleanValueParser());
argValueParsers.Add("char", new CharValueParser());
argValueParsers.Add("Color", new ColorConstantValueParser());
argValueParsers.Add("Unit", new EnumParser(typeof(TexUnit)));
argValueParsers.Add("AtomType", new EnumParser(typeof(TexAtomType)));
}
private static Type[] GetArgumentTypes(IEnumerable<XElement> args)
{
var result = new List<Type>();
foreach (var curArg in args)
{
var typeName = curArg.AttributeValue("type");
var type = typeMappings[typeName];
Debug.Assert(type != null);
result.Add(type);
}
return result.ToArray();
}
private static object?[] GetArgumentValues(IEnumerable<XElement> args, PredefinedFormulaContext context)
{
var result = new List<object?>();
foreach (var curArg in args)
{
var typeName = curArg.AttributeValue("type");
var value = curArg.AttributeValue("value");
var parser = argValueParsers[typeName];
result.Add(parser.Parse(value, context));
}
return result.ToArray();
}
private XElement rootElement;
public TexPredefinedFormulaParser()
{
var doc = XDocument.Load(new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)!));
this.rootElement = doc.Root;
}
public void Parse(IDictionary<string, Func<SourceSpan, TexFormula?>> predefinedTeXFormulas)
{
var rootEnabled = rootElement.AttributeBooleanValue("enabled", true);
if (rootEnabled)
{
foreach (var formulaElement in rootElement.Elements("Formula"))
{
var enabled = formulaElement.AttributeBooleanValue("enabled", true);
if (enabled)
{
var formulaName = formulaElement.AttributeValue("name");
predefinedTeXFormulas.Add(formulaName, source => this.ParseFormula(source, formulaElement));
}
}
}
}
private TexFormula? ParseFormula(SourceSpan source, XElement formulaElement)
{
var context = new PredefinedFormulaContext();
foreach (var element in formulaElement.Elements())
{
var parser = actionParsers[element.Name.ToString()];
if (parser == null)
continue;
parser.Parse(source, element, context);
if (parser is ReturnParser)
return ((ReturnParser)parser).Result;
}
return null;
}
private class MethodInvocationParser : IActionParser
{
public void Parse(SourceSpan source, XElement element, PredefinedFormulaContext context)
{
var methodName = element.AttributeValue("name");
var objectName = element.AttributeValue("formula");
var args = element.Elements("Argument");
var formula = context[objectName];
Debug.Assert(formula != null);
var argTypes = GetArgumentTypes(args);
var argValues = GetArgumentValues(args, context);
var helper = new TexFormulaHelper(formula, source);
var methodInvocation = typeof(TexFormulaHelper).GetMethod(methodName, argTypes)!;
methodInvocation.Invoke(helper, argValues);
}
}
private class CreateTeXFormulaParser : IActionParser
{
public void Parse(SourceSpan source, XElement element, PredefinedFormulaContext context)
{
var name = element.AttributeValue("name");
var args = element.Elements("Argument");
var argValues = GetArgumentValues(args, context);
Debug.Assert(argValues.Length == 1 || argValues.Length == 0);
TexFormula formula;
if (argValues.Length == 1)
{
var parser = new TexFormulaParser();
formula = parser.Parse((string)argValues[0]!); // Nullable TODO: This might need null checking
}
else
{
formula = new TexFormula { Source = source };
}
context.AddFormula(name, formula);
}
}
private class ReturnParser : IActionParser
{
public TexFormula? Result
{
get;
private set;
}
public void Parse(SourceSpan source, XElement element, PredefinedFormulaContext context)
{
var name = element.AttributeValue("name");
var result = context[name];
Debug.Assert(result != null);
this.Result = result;
}
}
private class DoubleValueParser : IArgumentValueParser
{
public object Parse(string value, PredefinedFormulaContext context)
{
return double.Parse(value, CultureInfo.InvariantCulture);
}
}
private class CharValueParser : IArgumentValueParser
{
public object Parse(string value, PredefinedFormulaContext context)
{
Debug.Assert(value.Length == 1);
return value[0];
}
}
private class BooleanValueParser : IArgumentValueParser
{
public object Parse(string value, PredefinedFormulaContext context)
{
return bool.Parse(value);
}
}
private class IntValueParser : IArgumentValueParser
{
public object Parse(string value, PredefinedFormulaContext context)
{
return int.Parse(value, CultureInfo.InvariantCulture);
}
}
private class StringValueParser : IArgumentValueParser
{
public object Parse(string value, PredefinedFormulaContext context)
{
return value;
}
}
private class TeXFormulaValueParser : IArgumentValueParser
{
public object? Parse(string value, PredefinedFormulaContext context)
{
if (value == null)
return null;
var formula = context[value];
Debug.Assert(formula != null);
return formula;
}
}
private class ColorConstantValueParser : IArgumentValueParser
{
public object? Parse(string value, PredefinedFormulaContext context)
{
return typeof(Color).GetField(value)!.GetValue(null);
}
}
private class EnumParser : IArgumentValueParser
{
private Type enumType;
public EnumParser(Type enumType)
{
this.enumType = enumType;
}
public object Parse(string value, PredefinedFormulaContext context)
{
return Enum.Parse(this.enumType, value);
}
}
private interface IActionParser
{
void Parse(SourceSpan source, XElement element, PredefinedFormulaContext context);
}
private interface IArgumentValueParser
{
object? Parse(string value, PredefinedFormulaContext context);
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
namespace DiscUtils.Compression
{
using System;
using System.IO;
using System.IO.Compression;
/// <summary>
/// Implementation of the Zlib compression algorithm.
/// </summary>
/// <remarks>Only decompression is currently implemented.</remarks>
public class ZlibStream : Stream
{
private Stream _stream;
private CompressionMode _mode;
private DeflateStream _deflateStream;
private Adler32 _adler32;
/// <summary>
/// Initializes a new instance of the ZlibStream class.
/// </summary>
/// <param name="stream">The stream to compress of decompress.</param>
/// <param name="mode">Whether to compress or decompress.</param>
/// <param name="leaveOpen">Whether closing this stream should leave <c>stream</c> open.</param>
public ZlibStream(Stream stream, CompressionMode mode, bool leaveOpen)
{
_stream = stream;
_mode = mode;
if (mode == CompressionMode.Decompress)
{
// We just sanity check against expected header values...
byte[] headerBuffer = Utilities.ReadFully(stream, 2);
ushort header = Utilities.ToUInt16BigEndian(headerBuffer, 0);
if ((header % 31) != 0)
{
throw new IOException("Invalid Zlib header found");
}
if ((header & 0x0F00) != (8 << 8))
{
throw new NotSupportedException("Zlib compression not using DEFLATE algorithm");
}
if ((header & 0x0020) != 0)
{
throw new NotSupportedException("Zlib compression using preset dictionary");
}
}
else
{
ushort header =
(8 << 8) // DEFLATE
| (7 << 12) // 32K window size
| 0x80; // Default algorithm
header |= (ushort)(31 - (header % 31));
byte[] headerBuffer = new byte[2];
Utilities.WriteBytesBigEndian(header, headerBuffer, 0);
stream.Write(headerBuffer, 0, 2);
}
_deflateStream = new DeflateStream(stream, mode, leaveOpen);
_adler32 = new Adler32();
}
/// <summary>
/// Gets whether the stream can be read.
/// </summary>
public override bool CanRead
{
get { return _deflateStream.CanRead; }
}
/// <summary>
/// Gets whether the stream pointer can be changed.
/// </summary>
public override bool CanSeek
{
get { return false; }
}
/// <summary>
/// Gets whether the stream can be written to.
/// </summary>
public override bool CanWrite
{
get { return _deflateStream.CanWrite; }
}
/// <summary>
/// Gets the length of the stream.
/// </summary>
public override long Length
{
get { throw new NotSupportedException(); }
}
/// <summary>
/// Gets and sets the stream position.
/// </summary>
public override long Position
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
/// <summary>
/// Closes the stream.
/// </summary>
public override void Close()
{
if (_mode == CompressionMode.Decompress)
{
// Can only check Adler checksum on seekable streams. Since DeflateStream
// aggresively caches input, it normally has already consumed the footer.
if (_stream.CanSeek)
{
_stream.Seek(-4, SeekOrigin.End);
byte[] footerBuffer = Utilities.ReadFully(_stream, 4);
if (Utilities.ToInt32BigEndian(footerBuffer, 0) != _adler32.Value)
{
throw new InvalidDataException("Corrupt decompressed data detected");
}
}
_deflateStream.Close();
}
else
{
_deflateStream.Close();
byte[] footerBuffer = new byte[4];
Utilities.WriteBytesBigEndian(_adler32.Value, footerBuffer, 0);
_stream.Write(footerBuffer, 0, 4);
}
}
/// <summary>
/// Flushes the stream.
/// </summary>
public override void Flush()
{
_deflateStream.Flush();
}
/// <summary>
/// Reads data from the stream.
/// </summary>
/// <param name="buffer">The buffer to populate.</param>
/// <param name="offset">The first byte to write.</param>
/// <param name="count">The number of bytes requested.</param>
/// <returns>The number of bytes read.</returns>
public override int Read(byte[] buffer, int offset, int count)
{
CheckParams(buffer, offset, count);
int numRead = _deflateStream.Read(buffer, offset, count);
_adler32.Process(buffer, offset, numRead);
return numRead;
}
/// <summary>
/// Seeks to a new position.
/// </summary>
/// <param name="offset">Relative position to seek to.</param>
/// <param name="origin">The origin of the seek.</param>
/// <returns>The new position.</returns>
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
/// <summary>
/// Changes the length of the stream.
/// </summary>
/// <param name="value">The new desired length of the stream.</param>
public override void SetLength(long value)
{
throw new NotSupportedException();
}
/// <summary>
/// Writes data to the stream.
/// </summary>
/// <param name="buffer">Buffer containing the data to write.</param>
/// <param name="offset">Offset of the first byte to write.</param>
/// <param name="count">Number of bytes to write.</param>
public override void Write(byte[] buffer, int offset, int count)
{
CheckParams(buffer, offset, count);
_adler32.Process(buffer, offset, count);
_deflateStream.Write(buffer, offset, count);
}
private static void CheckParams(byte[] buffer, int offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (offset < 0 || offset > buffer.Length)
{
throw new ArgumentException("Offset outside of array bounds", "offset");
}
if (count < 0 || offset + count > buffer.Length)
{
throw new ArgumentException("Array index out of bounds", "count");
}
}
}
}
| |
/*
* 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;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "LocalGridServicesConnector")]
public class LocalGridServicesConnector : ISharedRegionModule, IGridService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private static string LogHeader = "[LOCAL GRID SERVICE CONNECTOR]";
private IGridService m_GridService;
private ThreadedClasses.RwLockedDictionary<UUID, RegionCache> m_LocalCache = new ThreadedClasses.RwLockedDictionary<UUID, RegionCache>();
private bool m_Enabled;
public LocalGridServicesConnector()
{
m_log.DebugFormat("{0} LocalGridServicesConnector no parms.", LogHeader);
}
public LocalGridServicesConnector(IConfigSource source)
{
m_log.DebugFormat("{0} LocalGridServicesConnector instantiated directly.", LogHeader);
InitialiseService(source);
}
#region ISharedRegionModule
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "LocalGridServicesConnector"; }
}
public void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("GridServices", "");
if (name == Name)
{
InitialiseService(source);
m_log.Info("[LOCAL GRID SERVICE CONNECTOR]: Local grid connector enabled");
}
}
}
private void InitialiseService(IConfigSource source)
{
IConfig config = source.Configs["GridService"];
if (config == null)
{
m_log.Error("[LOCAL GRID SERVICE CONNECTOR]: GridService missing from OpenSim.ini");
return;
}
string serviceDll = config.GetString("LocalServiceModule", String.Empty);
if (serviceDll == String.Empty)
{
m_log.Error("[LOCAL GRID SERVICE CONNECTOR]: No LocalServiceModule named in section GridService");
return;
}
Object[] args = new Object[] { source };
m_GridService =
ServerUtils.LoadPlugin<IGridService>(serviceDll,
args);
if (m_GridService == null)
{
m_log.Error("[LOCAL GRID SERVICE CONNECTOR]: Can't load grid service");
return;
}
m_Enabled = true;
}
public void PostInitialise()
{
// FIXME: We will still add this command even if we aren't enabled since RemoteGridServiceConnector
// will have instantiated us directly.
MainConsole.Instance.Commands.AddCommand("Regions", false, "show neighbours",
"show neighbours",
"Shows the local regions' neighbours", HandleShowNeighboursCommand);
}
public void Close()
{
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
scene.RegisterModuleInterface<IGridService>(this);
try
{
m_LocalCache.AddIfNotExists(scene.RegionInfo.RegionID, delegate() { return new RegionCache(scene); });
}
catch(ThreadedClasses.RwLockedDictionary<UUID, RegionCache>.KeyAlreadyExistsException)
{
m_log.ErrorFormat("[LOCAL GRID SERVICE CONNECTOR]: simulator seems to have more than one region with the same UUID. Please correct this!");
}
}
public void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
m_LocalCache[scene.RegionInfo.RegionID].Clear();
m_LocalCache.Remove(scene.RegionInfo.RegionID);
}
public void RegionLoaded(Scene scene)
{
}
#endregion
#region IGridService
public string RegisterRegion(UUID scopeID, GridRegion regionInfo)
{
return m_GridService.RegisterRegion(scopeID, regionInfo);
}
public bool DeregisterRegion(UUID regionID)
{
return m_GridService.DeregisterRegion(regionID);
}
public List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID)
{
return m_GridService.GetNeighbours(scopeID, regionID);
}
public GridRegion GetRegionByUUID(UUID scopeID, UUID regionID)
{
return m_GridService.GetRegionByUUID(scopeID, regionID);
}
// Get a region given its base coordinates.
// NOTE: this is NOT 'get a region by some point in the region'. The coordinate MUST
// be the base coordinate of the region.
public GridRegion GetRegionByPosition(UUID scopeID, int x, int y)
{
GridRegion region = null;
// First see if it's a neighbour, even if it isn't on this sim.
// Neighbour data is cached in memory, so this is fast
try
{
m_LocalCache.ForEach(delegate(RegionCache rcache)
{
region = rcache.GetRegionByPosition(x, y);
if (region != null)
{
// m_log.DebugFormat("{0} GetRegionByPosition. Found region {1} in cache. Pos=<{2},{3}>",
// LogHeader, region.RegionName, x, y);
throw new ThreadedClasses.ReturnValueException<GridRegion>(region);
}
});
}
catch(ThreadedClasses.ReturnValueException<GridRegion> e)
{
region = e.Value;
}
// Then try on this sim (may be a lookup in DB if this is using MySql).
if (region == null)
{
region = m_GridService.GetRegionByPosition(scopeID, x, y);
/*
if (region == null)
m_log.DebugFormat("{0} GetRegionByPosition. Region not found by grid service. Pos=<{1},{2}>",
LogHeader, x, y);
else
m_log.DebugFormat("{0} GetRegionByPosition. Requested region {1} from grid service. Pos=<{2},{3}>",
LogHeader, region.RegionName, x, y);
*/
}
return region;
}
public GridRegion GetRegionByName(UUID scopeID, string regionName)
{
return m_GridService.GetRegionByName(scopeID, regionName);
}
public List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber)
{
return m_GridService.GetRegionsByName(scopeID, name, maxNumber);
}
public List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax)
{
return m_GridService.GetRegionRange(scopeID, xmin, xmax, ymin, ymax);
}
public List<GridRegion> GetDefaultRegions(UUID scopeID)
{
return m_GridService.GetDefaultRegions(scopeID);
}
public List<GridRegion> GetDefaultHypergridRegions(UUID scopeID)
{
return m_GridService.GetDefaultHypergridRegions(scopeID);
}
public List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y)
{
return m_GridService.GetFallbackRegions(scopeID, x, y);
}
public List<GridRegion> GetHyperlinks(UUID scopeID)
{
return m_GridService.GetHyperlinks(scopeID);
}
public int GetRegionFlags(UUID scopeID, UUID regionID)
{
return m_GridService.GetRegionFlags(scopeID, regionID);
}
public Dictionary<string, object> GetExtraFeatures()
{
return m_GridService.GetExtraFeatures();
}
#endregion
public void HandleShowNeighboursCommand(string module, string[] cmdparams)
{
System.Text.StringBuilder caps = new System.Text.StringBuilder();
m_LocalCache.ForEach(delegate(KeyValuePair<UUID, RegionCache> kvp)
{
caps.AppendFormat("*** Neighbours of {0} ({1}) ***\n", kvp.Value.RegionName, kvp.Key);
List<GridRegion> regions = kvp.Value.GetNeighbours();
foreach (GridRegion r in regions)
caps.AppendFormat(" {0} @ {1}-{2}\n", r.RegionName, Util.WorldToRegionLoc((uint)r.RegionLocX), Util.WorldToRegionLoc((uint)r.RegionLocY));
});
MainConsole.Instance.Output(caps.ToString());
}
}
}
| |
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 ImageGallery.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>();
}
/// <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 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 get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and 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))
{
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="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <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,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[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;
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type InferenceClassificationOverrideRequest.
/// </summary>
public partial class InferenceClassificationOverrideRequest : BaseRequest, IInferenceClassificationOverrideRequest
{
/// <summary>
/// Constructs a new InferenceClassificationOverrideRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public InferenceClassificationOverrideRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified InferenceClassificationOverride using POST.
/// </summary>
/// <param name="inferenceClassificationOverrideToCreate">The InferenceClassificationOverride to create.</param>
/// <returns>The created InferenceClassificationOverride.</returns>
public System.Threading.Tasks.Task<InferenceClassificationOverride> CreateAsync(InferenceClassificationOverride inferenceClassificationOverrideToCreate)
{
return this.CreateAsync(inferenceClassificationOverrideToCreate, CancellationToken.None);
}
/// <summary>
/// Creates the specified InferenceClassificationOverride using POST.
/// </summary>
/// <param name="inferenceClassificationOverrideToCreate">The InferenceClassificationOverride to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created InferenceClassificationOverride.</returns>
public async System.Threading.Tasks.Task<InferenceClassificationOverride> CreateAsync(InferenceClassificationOverride inferenceClassificationOverrideToCreate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
var newEntity = await this.SendAsync<InferenceClassificationOverride>(inferenceClassificationOverrideToCreate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(newEntity);
return newEntity;
}
/// <summary>
/// Deletes the specified InferenceClassificationOverride.
/// </summary>
/// <returns>The task to await.</returns>
public System.Threading.Tasks.Task DeleteAsync()
{
return this.DeleteAsync(CancellationToken.None);
}
/// <summary>
/// Deletes the specified InferenceClassificationOverride.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken)
{
this.Method = "DELETE";
await this.SendAsync<InferenceClassificationOverride>(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified InferenceClassificationOverride.
/// </summary>
/// <returns>The InferenceClassificationOverride.</returns>
public System.Threading.Tasks.Task<InferenceClassificationOverride> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the specified InferenceClassificationOverride.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The InferenceClassificationOverride.</returns>
public async System.Threading.Tasks.Task<InferenceClassificationOverride> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var retrievedEntity = await this.SendAsync<InferenceClassificationOverride>(null, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(retrievedEntity);
return retrievedEntity;
}
/// <summary>
/// Updates the specified InferenceClassificationOverride using PATCH.
/// </summary>
/// <param name="inferenceClassificationOverrideToUpdate">The InferenceClassificationOverride to update.</param>
/// <returns>The updated InferenceClassificationOverride.</returns>
public System.Threading.Tasks.Task<InferenceClassificationOverride> UpdateAsync(InferenceClassificationOverride inferenceClassificationOverrideToUpdate)
{
return this.UpdateAsync(inferenceClassificationOverrideToUpdate, CancellationToken.None);
}
/// <summary>
/// Updates the specified InferenceClassificationOverride using PATCH.
/// </summary>
/// <param name="inferenceClassificationOverrideToUpdate">The InferenceClassificationOverride to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The updated InferenceClassificationOverride.</returns>
public async System.Threading.Tasks.Task<InferenceClassificationOverride> UpdateAsync(InferenceClassificationOverride inferenceClassificationOverrideToUpdate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "PATCH";
var updatedEntity = await this.SendAsync<InferenceClassificationOverride>(inferenceClassificationOverrideToUpdate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(updatedEntity);
return updatedEntity;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IInferenceClassificationOverrideRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IInferenceClassificationOverrideRequest Expand(Expression<Func<InferenceClassificationOverride, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IInferenceClassificationOverrideRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IInferenceClassificationOverrideRequest Select(Expression<Func<InferenceClassificationOverride, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Initializes any collection properties after deserialization, like next requests for paging.
/// </summary>
/// <param name="inferenceClassificationOverrideToInitialize">The <see cref="InferenceClassificationOverride"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(InferenceClassificationOverride inferenceClassificationOverrideToInitialize)
{
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Configuration;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;
namespace CvrService.Service
{
public abstract class BaseServiceClient
{
#region Fields
/// <summary>
/// A locking object for caching a channel factory.
/// </summary>
private static object channelFactoryLock = new object();
/// <summary>
/// Dictionary to hold cached factories
/// </summary>
private static Dictionary<string, object> factoryDictionary = new Dictionary<string, object>();
/// <summary>
/// The current service context.
/// </summary>
private SPServiceContext currentServiceContext;
/// <summary>
/// The current service application proxy.
/// </summary>
private CvrServiceApplicationProxy currentProxy;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="BaseServiceClient"/> class.
/// </summary>
protected BaseServiceClient()
: this(null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BaseServiceClient"/> class.
/// </summary>
/// <param name="serviceContext">A <see cref="Microsoft.SharePoint.SPServiceContext"/> instance.</param>
protected BaseServiceClient(SPServiceContext serviceContext)
{
if (serviceContext == null)
{
if (SPServiceContext.Current != null)
{
this.currentServiceContext = SPServiceContext.Current;
}
else
{
this.currentServiceContext = SPServiceContext.GetContext(SPServiceApplicationProxyGroup.Default, new SPSiteSubscriptionIdentifier(Guid.Empty));
}
}
else
{
this.currentServiceContext = serviceContext;
}
if (this.currentServiceContext == null)
{
throw new ArgumentNullException("serviceContext");
}
}
#endregion
#region Delegates
/// <summary>
/// Delegate method that gets executed in the service application tier.
/// </summary>
/// <typeparam name="TChannel">The type of Channel.</typeparam>
/// <param name="channel">The current channel to execute across.</param>
protected delegate void CodeToExecuteOnChannel<TChannel>(TChannel channel);
#endregion
#region Properties
/// <summary>
/// Gets the current Service Application Proxy
/// </summary>
internal CvrServiceApplicationProxy Proxy
{
get
{
if (this.currentProxy == null)
{
this.currentProxy = (CvrServiceApplicationProxy)this.currentServiceContext.GetDefaultProxy(typeof(CvrServiceApplicationProxy));
}
return this.currentProxy;
}
}
/// <summary>
/// Gets the name and extension of the .svc service file.
/// </summary>
protected abstract string EndPoint { get; }
#endregion
#region Methods
/// <summary>
/// This is the method that will execute the WCF service operation across the WCF channel.
/// </summary>
/// <param name="codeToExecute">A delegate, pointing to the method on the Service Contract interface that you want to run.</param>
/// <param name="asProcess">Whether to run as the passed-through identity of the user (supported in claims mode), or the app pool account.</param>
/// <typeparam name="TChannel">The type of channel.</typeparam>
/// <remarks>
/// This is a good place to use an SPMonitoredScope so that you can
/// monitor execution times of your service calls.
/// This method sets up the load balancer, and calls into the service application.
/// If an exception occurs during the load balancer operation, make sure to report it as a failure if it is due to a
/// communication issue. Otherwise, if it is an exception in your application logic or execution, do not report the failure
/// to ensure that the server is not taken out of the load balancer.
/// </remarks>
protected void ExecuteOnChannel<TChannel>(CodeToExecuteOnChannel<TChannel> codeToExecute, bool asProcess)
{
if (codeToExecute == null)
{
throw new ArgumentNullException("codeToExecute");
}
if (this.Proxy == null)
{
throw new EndpointNotFoundException("Could not find an endpoint because the proxy was not found.");
}
using (new SPMonitoredScope(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", this.EndPoint, codeToExecute.Method.Name)))
{
SPServiceLoadBalancer loadBalancer = this.Proxy.LoadBalancer;
if (loadBalancer == null)
{
throw new InvalidOperationException("No Load Balancer was available.");
}
SPServiceLoadBalancerContext loadBalancerContext = loadBalancer.BeginOperation();
try
{
using (new SPServiceContextScope(this.currentServiceContext))
{
ICommunicationObject channel = (ICommunicationObject)this.GetChannel<TChannel>(loadBalancerContext, asProcess);
try
{
codeToExecute((TChannel)channel);
channel.Close();
}
finally
{
if (channel.State != CommunicationState.Closed)
{
channel.Abort();
}
}
}
}
catch (TimeoutException)
{
loadBalancerContext.Status = SPServiceLoadBalancerStatus.Failed;
throw;
}
catch (EndpointNotFoundException)
{
loadBalancerContext.Status = SPServiceLoadBalancerStatus.Failed;
throw;
}
catch (ServerTooBusyException)
{
loadBalancerContext.Status = SPServiceLoadBalancerStatus.Failed;
throw;
}
catch (CommunicationException exception)
{
if (!(exception is FaultException))
{
loadBalancerContext.Status = SPServiceLoadBalancerStatus.Failed;
}
throw;
}
finally
{
loadBalancerContext.EndOperation();
}
}
}
/// <summary>
/// Gets the endpoint configuration name for a given endpoint address.
/// </summary>
/// <param name="address">Endpoint address.</param>
/// <returns>The endpoint configuration name.</returns>
/// <remarks>The returned endpoint must match one of the endpoint element names in the client.config file.</remarks>
private static string GetEndpointConfigurationName(Uri address)
{
if (address == null)
{
throw new ArgumentNullException("address");
}
if (address.Scheme == Uri.UriSchemeNetTcp)
{
if (address.AbsolutePath.EndsWith("/secure", StringComparison.OrdinalIgnoreCase))
{
return "tcp-ssl";
}
else
{
return "tcp";
}
}
else if (address.Scheme == Uri.UriSchemeHttps)
{
return "https";
}
else if (address.Scheme == Uri.UriSchemeHttp)
{
return "http";
}
else
{
throw new NotSupportedException("Unsupported endpoint address.");
}
}
/// <summary>
/// This method gets the end point address to the WCF service. This is where you can support multiple .svc files per service application,
/// by looking for the default end point name defined in the ServiceApplication class, and swapping it for the EndPoint property that you
/// set in your Service Client.
/// </summary>
/// <param name="loadBalancerContext">The LoadBalancer context obtained from the Service Application proxy</param>
/// <param name="asProcess">Whether to run as the user or the app pool account.</param>
/// <typeparam name="TChannel">The type of channel.</typeparam>
/// <returns>A WCF Communication channel to execute across</returns>
private TChannel GetChannel<TChannel>(SPServiceLoadBalancerContext loadBalancerContext, bool asProcess)
{
TChannel channel = default(TChannel);
EndpointAddress endPointAddress = new EndpointAddress(new Uri(loadBalancerContext.EndpointAddress.AbsoluteUri.Replace("ReplaceableEndPointName.svc", this.EndPoint)), new AddressHeader[0]);
string endPointConfigurationName = BaseServiceClient.GetEndpointConfigurationName(endPointAddress.Uri);
ChannelFactory<TChannel> channelFactory = this.GetChannelFactory<TChannel>(endPointConfigurationName, this.EndPoint);
if (!asProcess)
{
channel = channelFactory.CreateChannelActingAsLoggedOnUser<TChannel>(endPointAddress);
}
else
{
channel = channelFactory.CreateChannelAsProcess<TChannel>(endPointAddress);
}
((ICommunicationObject)channel).Open();
return channel;
}
/// <summary>
/// Gets the channel factory necessary for acquiring a channel.
/// </summary>
/// <param name="endPointConfigurationName">The end point configuration name, which will typically be TCP, HTTPS, HTTP, etc.</param>
/// <param name="endPointName">Name of end point, used as key for dictionary to cached channel factories.</param>
/// <typeparam name="TChannel">The type of channel.</typeparam>
/// <returns>A <see cref="ChannelFactory" /> class.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Channel factory is cached for the lifetime of the app domain,and does not require disposal.")]
private ChannelFactory<TChannel> GetChannelFactory<TChannel>(string endPointConfigurationName, string endPointName)
{
ChannelFactory<TChannel> currentFactory = null;
if (factoryDictionary.ContainsKey(endPointName))
{
currentFactory = factoryDictionary[endPointName] as ChannelFactory<TChannel>;
}
if (currentFactory == null)
{
lock (channelFactoryLock)
{
// Make sure that a channel factory wasn't created during the time it took us to get a lock
if (factoryDictionary.ContainsKey(endPointName))
{
currentFactory = factoryDictionary[endPointName] as ChannelFactory<TChannel>;
}
if (currentFactory == null)
{
// Create a channel factory to be cached
currentFactory = new ConfigurationChannelFactory<TChannel>(
endPointConfigurationName,
this.Proxy.Configuration,
null);
// Configure the channel factory for claims-based authentication
currentFactory.ConfigureCredentials(SPServiceAuthenticationMode.Claims);
factoryDictionary[endPointName] = currentFactory;
}
}
}
return currentFactory;
}
#endregion
}
}
| |
using System;
using System.Linq.Expressions;
namespace SimpleStack.Orm.Expressions.Statements.Typed
{
public sealed class TypedSelectStatement<T> : TypedWhereStatement<T>
{
private readonly IDialectProvider _dialectProvider;
private readonly ModelDefinition _modelDefinition;
public TypedSelectStatement(IDialectProvider dialectProvider)
: base(dialectProvider)
{
_dialectProvider = dialectProvider;
_modelDefinition = ModelDefinition<T>.Definition;
Statement.TableName = _dialectProvider.GetQuotedTableName(_modelDefinition);
Statement.Columns.AddRange(_dialectProvider.GetColumnNames(_modelDefinition));
}
public SelectStatement Statement { get; } = new SelectStatement();
protected override WhereStatement GetWhereStatement()
{
return Statement;
}
private TableWhereExpresionVisitor<T> GetExpressionVisitor()
{
return new TableWhereExpresionVisitor<T>(_dialectProvider, Statement.Parameters, _modelDefinition);
}
private TableWFieldsExpresionVisitor<T> GetFieldsExpressionVisitor(bool addAliasSpecification = false)
{
return new TableWFieldsExpresionVisitor<T>(_dialectProvider, Statement.Parameters, _modelDefinition,
addAliasSpecification);
}
public TypedSelectStatement<T> Distinct(bool distinct = true)
{
Statement.IsDistinct = distinct;
return this;
}
/// <summary>Fields to be selected.</summary>
/// <typeparam name="TKey">objectWithProperties.</typeparam>
/// <param name="fields">x=> x.SomeProperty1 or x=> new{ x.SomeProperty1, x.SomeProperty2}</param>
/// <returns>A SqlExpressionVisitor<T></returns>
public TypedSelectStatement<T> Select<TKey>(Expression<Func<T, TKey>> fields)
{
Statement.Columns.Clear();
Statement.Columns.AddRange(GetFieldsExpressionVisitor(true).VisitExpression(fields).Split(','));
return this;
}
/// <summary>Fields to be selected.</summary>
/// <typeparam name="TKey">objectWithProperties.</typeparam>
/// <param name="fields">x=> x.SomeProperty1 or x=> new{ x.SomeProperty1, x.SomeProperty2}</param>
/// <returns>A SqlExpressionVisitor<T></returns>
public TypedSelectStatement<T> SelectAlso<TKey>(Expression<Func<T, TKey>> fields)
{
Statement.Columns.AddRange(GetFieldsExpressionVisitor(true).VisitExpression(fields).Split(','));
return this;
}
/// <summary>Select distinct.</summary>
/// <typeparam name="TKey">Type of the key.</typeparam>
/// <param name="fields">x=> x.SomeProperty1 or x=> new{ x.SomeProperty1, x.SomeProperty2}</param>
/// <returns>A SqlExpressionVisitor<T></returns>
public TypedSelectStatement<T> SelectDistinct<TKey>(Expression<Func<T, TKey>> fields)
{
Statement.Columns.Clear();
Select(fields);
Distinct();
return this;
}
public new TypedSelectStatement<T> Clear()
{
Statement.Clear();
return this;
}
/// <summary>Wheres the given predicate.</summary>
/// <param name="predicate">The predicate.</param>
/// <returns>A SqlExpressionVisitor<T></returns>
public new TypedSelectStatement<T> Where(Expression<Func<T, bool>> predicate)
{
base.And(predicate);
return this;
}
/// <summary>Ands the given predicate.</summary>
/// <param name="predicate">The predicate.</param>
/// <returns>A SqlExpressionVisitor<T></returns>
public new TypedSelectStatement<T> And(Expression<Func<T, bool>> predicate)
{
base.Where(GetExpressionVisitor(), predicate);
return this;
}
/// <summary>Ors the given predicate.</summary>
/// <param name="predicate">The predicate.</param>
/// <returns>A SqlExpressionVisitor<T></returns>
public new TypedSelectStatement<T> Or(Expression<Func<T, bool>> predicate)
{
base.Where(GetExpressionVisitor(), predicate, "OR");
return this;
}
/// <summary>Group by.</summary>
/// <param name="groupBy">Describes who group this object.</param>
/// <returns>A SqlExpressionVisitor<T></returns>
public TypedSelectStatement<T> GroupBy(string groupBy)
{
if (Statement.GroupByExpression.Length > 0)
{
Statement.GroupByExpression.Append(",");
}
Statement.GroupByExpression.Append(groupBy);
return this;
}
/// <summary>Group by.</summary>
/// <typeparam name="TKey">Type of the key.</typeparam>
/// <param name="keySelector">The key selector.</param>
/// <returns>A SqlExpressionVisitor<T></returns>
public TypedSelectStatement<T> GroupBy<TKey>(Expression<Func<T, TKey>> keySelector)
{
GroupBy(GetFieldsExpressionVisitor().VisitExpression(keySelector));
return this;
}
/// <summary>Having the given predicate.</summary>
/// <param name="predicate">The predicate.</param>
/// <returns>A SqlExpressionVisitor<T></returns>
public TypedSelectStatement<T> Having(Expression<Func<T, bool>> predicate)
{
if (Statement.HavingExpression.Length > 0)
{
Statement.HavingExpression.Append(",");
}
Statement.HavingExpression.Append(GetExpressionVisitor().VisitExpression(predicate));
return this;
}
/// <summary>Order by.</summary>
/// <typeparam name="TKey">Type of the key.</typeparam>
/// <param name="keySelector">The key selector.</param>
/// <returns>A SqlExpressionVisitor<T></returns>
public TypedSelectStatement<T> OrderBy<TKey>(Expression<Func<T, TKey>> keySelector)
{
Statement.OrderByExpression.Clear();
Statement.OrderByExpression.Append(GetFieldsExpressionVisitor().VisitExpression(keySelector) + " ASC");
return this;
}
/// <summary>Then by.</summary>
/// <typeparam name="TKey">Type of the key.</typeparam>
/// <param name="keySelector">The key selector.</param>
/// <returns>A SqlExpressionVisitor<T></returns>
public TypedSelectStatement<T> ThenBy<TKey>(Expression<Func<T, TKey>> keySelector)
{
if (Statement.OrderByExpression.Length > 0)
{
Statement.OrderByExpression.Append(",");
}
Statement.OrderByExpression.Append(GetFieldsExpressionVisitor().VisitExpression(keySelector) + " ASC");
return this;
}
/// <summary>Order by descending.</summary>
/// <typeparam name="TKey">Type of the key.</typeparam>
/// <param name="keySelector">The key selector.</param>
/// <returns>A SqlExpressionVisitor<T></returns>
public TypedSelectStatement<T> OrderByDescending<TKey>(Expression<Func<T, TKey>> keySelector)
{
if (Statement.OrderByExpression.Length > 0)
{
Statement.OrderByExpression.Append(",");
}
Statement.OrderByExpression.Append(GetFieldsExpressionVisitor().VisitExpression(keySelector) + " DESC");
return this;
}
/// <summary>Then by descending.</summary>
/// <typeparam name="TKey">Type of the key.</typeparam>
/// <param name="keySelector">The key selector.</param>
/// <returns>A SqlExpressionVisitor<T></returns>
public TypedSelectStatement<T> ThenByDescending<TKey>(Expression<Func<T, TKey>> keySelector)
{
if (Statement.OrderByExpression.Length > 0)
{
Statement.OrderByExpression.Append(",");
}
Statement.OrderByExpression.Append(GetFieldsExpressionVisitor().VisitExpression(keySelector) + " DESC");
return this;
}
/// <summary>Set the specified offset and rows for SQL Limit clause.</summary>
/// <param name="skip">Offset of the first row to return. The offset of the initial row is 0.</param>
/// <param name="rows">Number of rows returned by a SELECT statement.</param>
/// <returns>A SqlExpressionVisitor<T></returns>
public TypedSelectStatement<T> Limit(int skip, int rows)
{
Statement.MaxRows = rows;
Statement.Offset = skip;
return this;
}
/// <summary>Set the specified rows for Sql Limit clause.</summary>
/// <param name="rows">Number of rows returned by a SELECT statement.</param>
/// <returns>A SqlExpressionVisitor<T></returns>
public TypedSelectStatement<T> Limit(int rows)
{
Statement.MaxRows = rows;
Statement.Offset = null;
return this;
}
/// <summary>Clear Sql Limit clause.</summary>
/// <returns>A SqlExpressionVisitor<T></returns>
public TypedSelectStatement<T> Limit()
{
Statement.Offset = null;
Statement.MaxRows = null;
return this;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// The RegexBoyerMoore object precomputes the Boyer-Moore
// tables for fast string scanning. These tables allow
// you to scan for the first occurrence of a string within
// a large body of text without examining every character.
// The performance of the heuristic depends on the actual
// string and the text being searched, but usually, the longer
// the string that is being searched for, the fewer characters
// need to be examined.
using System.Diagnostics;
using System.Globalization;
using System.IO;
namespace System.Text.RegularExpressions
{
internal sealed class RegexBoyerMoore
{
private readonly int[] _positive;
private readonly int[] _negativeASCII;
private readonly int[][] _negativeUnicode;
private readonly String _pattern;
private readonly int _lowASCII;
private readonly int _highASCII;
private readonly bool _rightToLeft;
private readonly bool _caseInsensitive;
private readonly CultureInfo _culture;
/// <summary>
/// Constructs a Boyer-Moore state machine for searching for the string
/// pattern. The string must not be zero-length.
/// </summary>
internal RegexBoyerMoore(String pattern, bool caseInsensitive, bool rightToLeft, CultureInfo culture)
{
// Sorry, you just can't use Boyer-Moore to find an empty pattern.
// We're doing this for your own protection. (Really, for speed.)
Debug.Assert(pattern.Length != 0, "RegexBoyerMoore called with an empty string. This is bad for perf");
int beforefirst;
int last;
int bump;
int examine;
int scan;
int match;
char ch;
// We do the ToLower character by character for consistency. With surrogate chars, doing
// a ToLower on the entire string could actually change the surrogate pair. This is more correct
// linguistically, but since Regex doesn't support surrogates, it's more important to be
// consistent.
if (caseInsensitive)
{
StringBuilder sb = StringBuilderCache.Acquire(pattern.Length);
for (int i = 0; i < pattern.Length; i++)
sb.Append(culture.TextInfo.ToLower(pattern[i]));
pattern = StringBuilderCache.GetStringAndRelease(sb);
}
_pattern = pattern;
_rightToLeft = rightToLeft;
_caseInsensitive = caseInsensitive;
_culture = culture;
if (!rightToLeft)
{
beforefirst = -1;
last = pattern.Length - 1;
bump = 1;
}
else
{
beforefirst = pattern.Length;
last = 0;
bump = -1;
}
// PART I - the good-suffix shift table
//
// compute the positive requirement:
// if char "i" is the first one from the right that doesn't match,
// then we know the matcher can advance by _positive[i].
//
// This algorithm is a simplified variant of the standard
// Boyer-Moore good suffix calculation.
_positive = new int[pattern.Length];
examine = last;
ch = pattern[examine];
_positive[examine] = bump;
examine -= bump;
for (; ;)
{
// find an internal char (examine) that matches the tail
for (; ;)
{
if (examine == beforefirst)
goto OuterloopBreak;
if (pattern[examine] == ch)
break;
examine -= bump;
}
match = last;
scan = examine;
// find the length of the match
for (; ;)
{
if (scan == beforefirst || pattern[match] != pattern[scan])
{
// at the end of the match, note the difference in _positive
// this is not the length of the match, but the distance from the internal match
// to the tail suffix.
if (_positive[match] == 0)
_positive[match] = match - scan;
// System.Diagnostics.Debug.WriteLine("Set positive[" + match + "] to " + (match - scan));
break;
}
scan -= bump;
match -= bump;
}
examine -= bump;
}
OuterloopBreak:
match = last - bump;
// scan for the chars for which there are no shifts that yield a different candidate
// The inside of the if statement used to say
// "_positive[match] = last - beforefirst;"
// This is slightly less aggressive in how much we skip, but at worst it
// should mean a little more work rather than skipping a potential match.
while (match != beforefirst)
{
if (_positive[match] == 0)
_positive[match] = bump;
match -= bump;
}
// PART II - the bad-character shift table
//
// compute the negative requirement:
// if char "ch" is the reject character when testing position "i",
// we can slide up by _negative[ch];
// (_negative[ch] = str.Length - 1 - str.LastIndexOf(ch))
//
// the lookup table is divided into ASCII and Unicode portions;
// only those parts of the Unicode 16-bit code set that actually
// appear in the string are in the table. (Maximum size with
// Unicode is 65K; ASCII only case is 512 bytes.)
_negativeASCII = new int[128];
for (int i = 0; i < 128; i++)
_negativeASCII[i] = last - beforefirst;
_lowASCII = 127;
_highASCII = 0;
for (examine = last; examine != beforefirst; examine -= bump)
{
ch = pattern[examine];
if (ch < 128)
{
if (_lowASCII > ch)
_lowASCII = ch;
if (_highASCII < ch)
_highASCII = ch;
if (_negativeASCII[ch] == last - beforefirst)
_negativeASCII[ch] = last - examine;
}
else
{
int i = ch >> 8;
int j = ch & 0xFF;
if (_negativeUnicode == null)
{
_negativeUnicode = new int[256][];
}
if (_negativeUnicode[i] == null)
{
int[] newarray = new int[256];
for (int k = 0; k < 256; k++)
newarray[k] = last - beforefirst;
if (i == 0)
{
System.Array.Copy(_negativeASCII, 0, newarray, 0, 128);
_negativeASCII = newarray;
}
_negativeUnicode[i] = newarray;
}
if (_negativeUnicode[i][j] == last - beforefirst)
_negativeUnicode[i][j] = last - examine;
}
}
}
private bool MatchPattern(string text, int index)
{
if (_caseInsensitive)
{
if (text.Length - index < _pattern.Length)
{
return false;
}
TextInfo textinfo = _culture.TextInfo;
for (int i = 0; i < _pattern.Length; i++)
{
Debug.Assert(textinfo.ToLower(_pattern[i]) == _pattern[i], "pattern should be converted to lower case in constructor!");
if (textinfo.ToLower(text[index + i]) != _pattern[i])
{
return false;
}
}
return true;
}
else
{
return (0 == String.CompareOrdinal(_pattern, 0, text, index, _pattern.Length));
}
}
/// <summary>
/// When a regex is anchored, we can do a quick IsMatch test instead of a Scan
/// </summary>
internal bool IsMatch(String text, int index, int beglimit, int endlimit)
{
if (!_rightToLeft)
{
if (index < beglimit || endlimit - index < _pattern.Length)
return false;
return MatchPattern(text, index);
}
else
{
if (index > endlimit || index - beglimit < _pattern.Length)
return false;
return MatchPattern(text, index - _pattern.Length);
}
}
/// <summary>
/// Scan uses the Boyer-Moore algorithm to find the first occurrence
/// of the specified string within text, beginning at index, and
/// constrained within beglimit and endlimit.
///
/// The direction and case-sensitivity of the match is determined
/// by the arguments to the RegexBoyerMoore constructor.
/// </summary>
internal int Scan(String text, int index, int beglimit, int endlimit)
{
int test;
int test2;
int match;
int startmatch;
int endmatch;
int advance;
int defadv;
int bump;
char chMatch;
char chTest;
int[] unicodeLookup;
if (!_rightToLeft)
{
defadv = _pattern.Length;
startmatch = _pattern.Length - 1;
endmatch = 0;
test = index + defadv - 1;
bump = 1;
}
else
{
defadv = -_pattern.Length;
startmatch = 0;
endmatch = -defadv - 1;
test = index + defadv;
bump = -1;
}
chMatch = _pattern[startmatch];
for (; ;)
{
if (test >= endlimit || test < beglimit)
return -1;
chTest = text[test];
if (_caseInsensitive)
chTest = _culture.TextInfo.ToLower(chTest);
if (chTest != chMatch)
{
if (chTest < 128)
advance = _negativeASCII[chTest];
else if (null != _negativeUnicode && (null != (unicodeLookup = _negativeUnicode[chTest >> 8])))
advance = unicodeLookup[chTest & 0xFF];
else
advance = defadv;
test += advance;
}
else
{ // if (chTest == chMatch)
test2 = test;
match = startmatch;
for (; ;)
{
if (match == endmatch)
return (_rightToLeft ? test2 + 1 : test2);
match -= bump;
test2 -= bump;
chTest = text[test2];
if (_caseInsensitive)
chTest = _culture.TextInfo.ToLower(chTest);
if (chTest != _pattern[match])
{
advance = _positive[match];
if ((chTest & 0xFF80) == 0)
test2 = (match - startmatch) + _negativeASCII[chTest];
else if (null != _negativeUnicode && (null != (unicodeLookup = _negativeUnicode[chTest >> 8])))
test2 = (match - startmatch) + unicodeLookup[chTest & 0xFF];
else
{
test += advance;
break;
}
if (_rightToLeft ? test2 < advance : test2 > advance)
advance = test2;
test += advance;
break;
}
}
}
}
}
/// <summary>
/// Used when dumping for debugging.
/// </summary>
public override String ToString()
{
return _pattern;
}
#if DEBUG
public String Dump(String indent)
{
StringBuilder sb = new StringBuilder();
sb.Append(indent + "BM Pattern: " + _pattern + "\n");
sb.Append(indent + "Positive: ");
for (int i = 0; i < _positive.Length; i++)
{
sb.Append(_positive[i].ToString(CultureInfo.InvariantCulture) + " ");
}
sb.Append("\n");
if (_negativeASCII != null)
{
sb.Append(indent + "Negative table\n");
for (int i = 0; i < _negativeASCII.Length; i++)
{
if (_negativeASCII[i] != _pattern.Length)
{
sb.Append(indent + " " + Regex.Escape(Convert.ToString((char)i, CultureInfo.InvariantCulture)) + " " + _negativeASCII[i].ToString(CultureInfo.InvariantCulture) + "\n");
}
}
}
return sb.ToString();
}
#endif
}
}
| |
using System;
using OpenTK;
namespace Bearded.Utilities.Math
{
/// <summary>
/// Math extension methods.
/// </summary>
public static class Extensions
{
#region Clamped
/// <summary>
/// Clamps the value to a specified range.
/// </summary>
/// <param name="value">The value that should be restricted to the specified range.</param>
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
/// <returns>The clamped value.</returns>
public static int Clamped(this int value, int min, int max)
{
if (value <= min)
return min;
if (value >= max)
return max;
return value;
}
/// <summary>
/// Clamps the value to a specified range.
/// </summary>
/// <param name="value">The value that should be restricted to the specified range.</param>
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
/// <returns>The clamped value.</returns>
public static float Clamped(this float value, float min, float max)
{
if (value <= min)
return min;
if (value >= max)
return max;
return value;
}
/// <summary>
/// Clamps the value to a specified range.
/// </summary>
/// <param name="value">The value that should be restricted to the specified range.</param>
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
/// <returns>The clamped value.</returns>
public static double Clamped(this double value, double min, double max)
{
if (value <= min)
return min;
if (value >= max)
return max;
return value;
}
#endregion
#region Modulo
/// <summary>
/// Gives the number projected to Zn.
/// </summary>
/// <param name="a">The number.</param>
/// <param name="n">The modulo.</param>
/// <returns>a (mod n)</returns>
public static int ModuloN(this int a, int n)
{
return ((a % n) + n) % n;
}
#endregion
#region (Austin?) Powers
/// <summary>
/// Squares an integer.
/// </summary>
/// <param name="i">The integer.</param>
/// <returns>The square.</returns>
public static int Squared(this int i)
{
return i * i;
}
/// <summary>
/// Squares a float.
/// </summary>
/// <param name="f">The float.</param>
/// <returns>The square.</returns>
public static float Squared(this float f)
{
return f * f;
}
/// <summary>
/// Squares a double.
/// </summary>
/// <param name="d">The double.</param>
/// <returns>The square.</returns>
public static double Squared(this double d)
{
return d * d;
}
/// <summary>
/// Cubes an integer.
/// </summary>
/// <param name="i">The integer.</param>
/// <returns>The cube.</returns>
public static int Cubed(this int i)
{
return i * i.Squared();
}
/// <summary>
/// Squares a float.
/// </summary>
/// <param name="f">The float.</param>
/// <returns>The square.</returns>
public static float Cubed(this float f)
{
return f * f.Squared();
}
/// <summary>
/// Squares a double.
/// </summary>
/// <param name="d">The double.</param>
/// <returns>The cube.</returns>
public static double Cubed(this double d)
{
return d * d.Squared();
}
#endregion
#region Float math
/// <summary>
/// Returns the cosine of the specified angle.
/// </summary>
/// <param name="f"></param>
/// <returns></returns>
public static float Cos(this float f)
{
return (float)System.Math.Cos(f);
}
/// <summary>
/// Returns the sine of the specified angle.
/// </summary>
/// <param name="f"></param>
/// <returns></returns>
public static float Sin(this float f)
{
return (float)System.Math.Sin(f);
}
/// <summary>
/// Returns the tangent of the specified angle.
/// </summary>
/// <param name="f"></param>
/// <returns></returns>
public static float Tan(this float f)
{
return (float)System.Math.Tan(f);
}
/// <summary>
/// Returns the angle whose cosine is the specified number.
/// </summary>
/// <param name="f"></param>
/// <returns></returns>
public static float Acos(this float f)
{
return (float)System.Math.Acos(f);
}
/// <summary>
/// Returns the angle whose sine is the specified number.
/// </summary>
/// <param name="f"></param>
/// <returns></returns>
public static float Asin(this float f)
{
return (float)System.Math.Asin(f);
}
/// <summary>
/// Returns the angle whose tangent is the specified number.
/// </summary>
/// <param name="f"></param>
/// <returns></returns>
public static float Atan(this float f)
{
return (float)System.Math.Atan(f);
}
/// <summary>
/// Returns the square root of the specified number.
/// </summary>
/// <param name="f"></param>
/// <returns></returns>
public static float Sqrted(this float f)
{
return (float)System.Math.Sqrt(f);
}
/// <summary>
/// Returns a specified number raised to the specified power.
/// </summary>
/// <param name="b"></param>
/// <param name="power"></param>
/// <returns></returns>
public static float Powed(this float b, float power)
{
return (float)System.Math.Pow(b, power);
}
/// <summary>
/// Returns the lowest integral number higher than or equal to the specified number.
/// </summary>
/// <param name="f"></param>
/// <returns></returns>
public static int CeiledToInt(float f)
{
return (int)System.Math.Ceiling(f);
}
/// <summary>
/// Returns the highest integral number lower than or equal to the specified number.
/// </summary>
/// <param name="f"></param>
/// <returns></returns>
public static int FlooredToInt(float f)
{
return (int)System.Math.Floor(f);
}
/// <summary>
/// Returns the integral number closest to the specified number.
/// </summary>
/// <param name="f"></param>
/// <returns></returns>
public static int RoundedToInt(float f)
{
return (int)System.Math.Round(f);
}
/// <summary>
/// Returns the lowest integral number higher than or equal to the specified number.
/// </summary>
/// <param name="d"></param>
/// <returns></returns>
public static int CeiledToInt(double d)
{
return (int)System.Math.Ceiling(d);
}
/// <summary>
/// Returns the highest integral number lower than or equal to the specified number.
/// </summary>
/// <param name="d"></param>
/// <returns></returns>
public static int FlooredToInt(double d)
{
return (int)System.Math.Floor(d);
}
/// <summary>
/// Returns the integral number closest to the specified number.
/// </summary>
/// <param name="d"></param>
/// <returns></returns>
public static int RoundedToInt(double d)
{
return (int)System.Math.Round(d);
}
#endregion
#region NaN sanity checks
/// <summary>
/// Throws an exception if the specified float is NaN.
/// </summary>
/// <param name="f">The float to check.</param>
/// <param name="exceptionString">The string message for the exception.</param>
public static void ThrowIfNaN(this float f,
string exceptionString = "Float is NaN while it is not allowed to.")
{
if (float.IsNaN(f))
throw new Exception(exceptionString);
}
/// <summary>
/// Throws an exception if any of the vector components is NaN.
/// </summary>
/// <param name="vector">The vector to check.</param>
/// <param name="exceptionString">The string message for the exception.</param>
public static void ThrowIfNaN(this Vector2 vector,
string exceptionString = "Vector is NaN while it is not allowed to.")
{
if (vector.IsNaN())
throw new Exception(exceptionString);
}
/// <summary>
/// Throws an exception if any of the vector components is NaN.
/// </summary>
/// <param name="vector">The vector to check.</param>
/// <param name="exceptionString">The string message for the exception.</param>
public static void ThrowIfNaN(this Vector3 vector,
string exceptionString = "Vector is NaN while it is not allowed to.")
{
if (vector.IsNaN())
throw new Exception(exceptionString);
}
/// <summary>
/// Throws an exception if any of the vector components is NaN.
/// </summary>
/// <param name="vector">The vector to check.</param>
/// <param name="exceptionString">The string message for the exception.</param>
public static void ThrowIfNaN(this Vector4 vector,
string exceptionString = "Vector is NaN while it is not allowed to.")
{
if (vector.IsNaN())
throw new Exception(exceptionString);
}
/// <summary>
/// Checks whether any of the vector components is NaN.
/// </summary>
/// <param name="vector">The vector to check.</param>
/// <returns>True if any of the components is NaN.</returns>
public static bool IsNaN(this Vector2 vector)
{
return float.IsNaN(vector.X) || float.IsNaN(vector.Y);
}
/// <summary>
/// Checks whether any of the vector components is NaN.
/// </summary>
/// <param name="vector">The vector to check.</param>
/// <returns>True if any of the components is NaN.</returns>
public static bool IsNaN(this Vector3 vector)
{
return float.IsNaN(vector.X) || float.IsNaN(vector.Y) || float.IsNaN(vector.Z);
}
/// <summary>
/// Checks whether any of the vector components is NaN.
/// </summary>
/// <param name="vector">The vector to check.</param>
/// <returns>True if any of the components is NaN.</returns>
public static bool IsNaN(this Vector4 vector)
{
return float.IsNaN(vector.X) || float.IsNaN(vector.Y) || float.IsNaN(vector.Z) || float.IsNaN(vector.W);
}
#endregion
#region Vector
/// <summary>
/// Turns the vector into a three-dimensional vector.
/// </summary>
/// <param name="xy">Original vector.</param>
/// <param name="z">z-coordinate of the new vector.</param>
/// <returns>A three-dimensional vector.</returns>
public static Vector3 WithZ(this Vector2 xy, float z = 0)
{
return new Vector3(xy.X, xy.Y, z);
}
/// <summary>
/// Turns the vector into a homogenuous vector.
/// </summary>
/// <param name="xyz">Original vector.</param>
/// <param name="w">w-coordinate of the new vector.</param>
/// <returns>A homogenuous vector.</returns>
public static Vector4 WithW(this Vector3 xyz, float w)
{
return new Vector4(xyz, w);
}
/// <summary>
/// Turns the vector into a homogenuous vector.
/// </summary>
/// <param name="xy">Original vector.</param>
/// <param name="z">z-coordinate of the new vector.</param>
/// <param name="w">w-coordinate of the new vector.</param>
/// <returns>A homogenuous vector.</returns>
public static Vector4 WithZw(this Vector2 xy, float z, float w)
{
return new Vector4(xy.X, xy.Y, z, w);
}
/// <summary>
/// Normalizes a vector. If all components of the vector are zero, no exception is thrown. Instead the zero vector is returned.
/// </summary>
/// <param name="vector">The vector to normalize.</param>
/// <returns>The zero vector if the input is a zero vector. Otherwise a unit vector in the same direction as the input.</returns>
public static Vector2 NormalizedSafe(this Vector2 vector)
{
var lSqrd = vector.LengthSquared;
return lSqrd == 0 ? new Vector2() : vector / lSqrd.Sqrted();
}
/// <summary>
/// Normalizes a vector. If all components of the vector are zero, no exception is thrown. Instead the zero vector is returned.
/// </summary>
/// <param name="vector">The vector to normalize.</param>
/// <returns>The zero vector if the input is a zero vector. Otherwise a unit vector in the same direction as the input.</returns>
public static Vector3 NormalizedSafe(this Vector3 vector)
{
var lSqrd = vector.LengthSquared;
return lSqrd == 0 ? new Vector3() : vector / lSqrd.Sqrted();
}
/// <summary>
/// Normalizes a vector. If all components of the vector are zero, no exception is thrown. Instead the zero vector is returned.
/// </summary>
/// <param name="vector">The vector to normalize.</param>
/// <returns>The zero vector if the input is a zero vector. Otherwise a unit vector in the same direction as the input.</returns>
public static Vector4 NormalizedSafe(this Vector4 vector)
{
var lSqrd = vector.LengthSquared;
return lSqrd == 0 ? new Vector4() : vector / lSqrd.Sqrted();
}
#endregion
#region Geometric
/// <summary>
/// Converts floating point value into a type safe angle representation in radians.
/// </summary>
public static Angle Radians(this float radians)
{
return Angle.FromRadians(radians);
}
/// <summary>
/// Converts floating point value into a type safe angle representation in degrees.
/// </summary>
public static Angle Degrees(this float degrees)
{
return Angle.FromDegrees(degrees);
}
/// <summary>
/// Converts an integer value into a type safe angle representation in degrees.
/// </summary>
public static Angle Degrees(this int degrees)
{
return Angle.FromDegrees(degrees);
}
#endregion
}
}
| |
// -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*-
//
// StringBuilderTest.dll - NUnit Test Cases for the System.Text.StringBuilder class
//
// Author: Marcin Szczepanski (marcins@zipworld.com.au)
//
// NOTES: I've also run all these tests against the MS implementation of
// System.Text.StringBuilder to confirm that they return the same results
// and they do.
//
// TODO: Add tests for the AppendFormat methods once the AppendFormat methods
// are implemented in the StringBuilder class itself
//
// TODO: Potentially add more variations on Insert / Append tests for all the
// possible types. I don't really think that's necessary as they all
// pretty much just do .ToString().ToCharArray() and then use the Append / Insert
// CharArray function. The ToString() bit for each type should be in the unit
// tests for those types, and the unit test for ToCharArray should be in the
// string test type. If someone wants to add those tests here for completness
// (and some double checking) then feel free :)
//
using NUnit.Framework;
using System.Text;
using System;
namespace MonoTests.System.Text {
[TestFixture]
public class StringBuilderTest : Assertion {
private StringBuilder sb;
public void TestConstructor1()
{
// check the parameterless ctor
sb = new StringBuilder();
AssertEquals(String.Empty, sb.ToString());
AssertEquals(0, sb.Length);
AssertEquals(16, sb.Capacity);
}
public void TestConstructor2()
{
// check ctor that specifies the capacity
sb = new StringBuilder(10);
AssertEquals(String.Empty, sb.ToString());
AssertEquals(0, sb.Length);
// check that capacity is not less than default
AssertEquals(10, sb.Capacity);
sb = new StringBuilder(42);
AssertEquals(String.Empty, sb.ToString());
AssertEquals(0, sb.Length);
// check that capacity is set
AssertEquals(42, sb.Capacity);
}
public void TestConstructor3() {
// check ctor that specifies the capacity & maxCapacity
sb = new StringBuilder(444, 1234);
AssertEquals(String.Empty, sb.ToString());
AssertEquals(0, sb.Length);
AssertEquals(444, sb.Capacity);
AssertEquals(1234, sb.MaxCapacity);
}
public void TestConstructor4()
{
// check for exception in ctor that specifies the capacity & maxCapacity
try {
sb = new StringBuilder(9999, 15);
}
catch (ArgumentOutOfRangeException) {
return;
}
// if we didn't catch an exception, then we have a problem Houston.
NUnit.Framework.Assertion.Fail("Capacity exeeds MaxCapacity");
}
public void TestConstructor5() {
String someString = null;
sb = new StringBuilder(someString);
AssertEquals("Should be empty string", String.Empty, sb.ToString());
}
public void TestConstructor6() {
// check for exception in ctor that prevents startIndex less than zero
try {
String someString = "someString";
sb = new StringBuilder(someString, -1, 3, 18);
}
catch (ArgumentOutOfRangeException) {
return;
}
// if we didn't catch an exception, then we have a problem Houston.
NUnit.Framework.Assertion.Fail("StartIndex not allowed to be less than zero.");
}
public void TestConstructor7() {
// check for exception in ctor that prevents length less than zero
try {
String someString = "someString";
sb = new StringBuilder(someString, 2, -222, 18);
}
catch (ArgumentOutOfRangeException) {
return;
}
// if we didn't catch an exception, then we have a problem Houston.
NUnit.Framework.Assertion.Fail("Length not allowed to be less than zero.");
}
public void TestConstructor8() {
// check for exception in ctor that ensures substring is contained in given string
// check that startIndex is not too big
try {
String someString = "someString";
sb = new StringBuilder(someString, 10000, 4, 18);
}
catch (ArgumentOutOfRangeException) {
return;
}
// if we didn't catch an exception, then we have a problem Houston.
NUnit.Framework.Assertion.Fail("StartIndex and length must refer to a location within the string.");
}
public void TestConstructor9() {
// check for exception in ctor that ensures substring is contained in given string
// check that length doesn't go beyond end of string
try {
String someString = "someString";
sb = new StringBuilder(someString, 4, 4000, 18);
}
catch (ArgumentOutOfRangeException) {
return;
}
// if we didn't catch an exception, then we have a problem Houston.
NUnit.Framework.Assertion.Fail("StartIndex and length must refer to a location within the string.");
}
public void TestConstructor10() {
// check that substring is taken properly and made into a StringBuilder
String someString = "someString";
sb = new StringBuilder(someString, 4, 6, 18);
string expected = "String";
AssertEquals( expected, sb.ToString());
}
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void TestConstructor11 () {
new StringBuilder (-1);
}
public void TestAppend() {
StringBuilder sb = new StringBuilder( "Foo" );
sb.Append( "Two" );
string expected = "FooTwo";
AssertEquals( expected, sb.ToString() );
}
public void TestInsert() {
StringBuilder sb = new StringBuilder();
AssertEquals( String.Empty, sb.ToString() );
/* Test empty StringBuilder conforms to spec */
sb.Insert( 0, "Foo" ); /* Test insert at start of empty string */
AssertEquals( "Foo", sb.ToString() );
sb.Insert( 1, "!!" ); /* Test insert not at start of string */
AssertEquals( "F!!oo", sb.ToString() );
sb.Insert( 5, ".." ); /* Test insert at end of string */
AssertEquals( "F!!oo..", sb.ToString() );
sb.Insert( 0, 1234 ); /* Test insert of a number (at start of string) */
// FIX: Why does this test fail?
//AssertEquals( "1234F!!oo..", sb.ToString() );
sb.Insert( 5, 1.5 ); /* Test insert of a decimal (and end of string) */
// FIX: Why does this test fail?
//AssertEquals( "1234F1.5!!oo..", sb.ToString() );
sb.Insert( 4, 'A' ); /* Test char insert in middle of string */
// FIX: Why does this test fail?
//AssertEquals( "1234AF1.5!!oo..", sb.ToString() );
}
public void TestReplace() {
StringBuilder sb = new StringBuilder( "Foobarbaz" );
sb.Replace( "bar", "!!!" ); /* Test same length replace in middle of string */
AssertEquals( "Foo!!!baz", sb.ToString() );
sb.Replace( "Foo", "ABcD" ); /* Test longer replace at start of string */
AssertEquals( "ABcD!!!baz", sb.ToString() );
sb.Replace( "baz", "00" ); /* Test shorter replace at end of string */
AssertEquals( "ABcD!!!00", sb.ToString() );
sb.Replace( sb.ToString(), null ); /* Test string clear as in spec */
AssertEquals( String.Empty, sb.ToString() );
/* | 10 20 30
/* |0123456789012345678901234567890| */
sb.Append( "abc this is testing abc the abc abc partial replace abc" );
sb.Replace( "abc", "!!!", 0, 31 ); /* Partial replace at start of string */
AssertEquals( "!!! this is testing !!! the !!! abc partial replace abc", sb.ToString() );
sb.Replace( "testing", "", 0, 15 ); /* Test replace across boundary */
AssertEquals( "!!! this is testing !!! the !!! abc partial replace abc", sb.ToString() );
sb.Replace( "!!!", "" ); /* Test replace with empty string */
AssertEquals(" this is testing the abc partial replace abc", sb.ToString() );
}
public void TestAppendFormat() {
}
[Test]
public void MoreReplace ()
{
StringBuilder sb = new StringBuilder ();
sb.Append ("First");
sb.Append ("Second");
sb.Append ("Third");
sb.Replace ("Second", "Gone", 2, sb.Length-2);
AssertEquals ("#01", "FirstGoneThird", sb.ToString ());
sb.Length = 0;
sb.Append ("This, is, a, list");
sb.Replace (",", "comma-separated", 11, sb.Length-11);
AssertEquals ("#02", "This, is, acomma-separated list", sb.ToString ());
}
[Test]
public void Insert0 ()
{
StringBuilder sb = new StringBuilder();
sb.Append("testtesttest");
sb.Insert(0, '^');
AssertEquals ("#01", "^testtesttest", sb.ToString ());
}
[Test]
public void AppendToEmpty ()
{
StringBuilder sb = new StringBuilder();
char [] ca = new char [] { 'c' };
sb.Append (ca);
AssertEquals ("#01", "c", sb.ToString ());
}
[Test]
public void TestRemove ()
{
StringBuilder b = new StringBuilder ();
b.Append ("Hello, I am a StringBuilder");
b.Remove (0, 7); // Should remove "Hello, "
AssertEquals ("#01", "I am a StringBuilder", b.ToString ());
}
[Test]
public void Insert1 ()
{
StringBuilder sb = new StringBuilder();
sb.Insert(0, "aa");
AssertEquals ("#01", "aa", sb.ToString ());
char [] charArr = new char [] { 'b', 'c', 'd' };
sb.Insert(1, charArr, 1, 1);
AssertEquals ("#02", "aca", sb.ToString ());
sb.Insert (1, null, 0, 0);
AssertEquals ("#03", "aca", sb.ToString ());
try {
sb.Insert (1, null, 1, 1);
Assertion.Fail ("#04: Value must not be null if startIndex and charCount > 0");
} catch (ArgumentNullException) {}
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void Constructor_StartIndexOverflow ()
{
new StringBuilder ("Mono", Int32.MaxValue, 1, 0);
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void Constructor_LengthOverflow ()
{
new StringBuilder ("Mono", 1, Int32.MaxValue, 0);
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void ToString_StartIndexOverflow ()
{
StringBuilder sb = new StringBuilder ("Mono");
sb.ToString (Int32.MaxValue, 1);
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void ToString_LengthOverflow ()
{
StringBuilder sb = new StringBuilder ("Mono");
sb.ToString (1, Int32.MaxValue);
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void Remove_StartIndexOverflow ()
{
StringBuilder sb = new StringBuilder ("Mono");
sb.Remove (Int32.MaxValue, 1);
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void Remove_LengthOverflow ()
{
StringBuilder sb = new StringBuilder ("Mono");
sb.Remove (1, Int32.MaxValue);
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void ReplaceChar_StartIndexOverflow ()
{
StringBuilder sb = new StringBuilder ("Mono");
sb.Replace ('o', '0', Int32.MaxValue, 1);
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void ReplaceChar_CountOverflow ()
{
StringBuilder sb = new StringBuilder ("Mono");
sb.Replace ('0', '0', 1, Int32.MaxValue);
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void ReplaceString_StartIndexOverflow ()
{
StringBuilder sb = new StringBuilder ("Mono");
sb.Replace ("o", "0", Int32.MaxValue, 1);
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void ReplaceString_CountOverflow ()
{
StringBuilder sb = new StringBuilder ("Mono");
sb.Replace ("o", "0", 1, Int32.MaxValue);
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void AppendCharArray_StartIndexOverflow ()
{
StringBuilder sb = new StringBuilder ("Mono");
sb.Append (new char[2], Int32.MaxValue, 1);
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void AppendCharArray_CharCountOverflow ()
{
StringBuilder sb = new StringBuilder ("Mono");
sb.Append (new char[2], 1, Int32.MaxValue);
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void AppendString_StartIndexOverflow ()
{
StringBuilder sb = new StringBuilder ("Mono");
sb.Append ("!", Int32.MaxValue, 1);
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void AppendString_CountOverflow ()
{
StringBuilder sb = new StringBuilder ("Mono");
sb.Append ("!", 1, Int32.MaxValue);
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void InsertCharArray_StartIndexOverflow ()
{
StringBuilder sb = new StringBuilder ("Mono");
sb.Insert (0, new char[2], Int32.MaxValue, 1);
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void InsertCharArray_CharCountOverflow ()
{
StringBuilder sb = new StringBuilder ("Mono");
sb.Insert (0, new char[2], 1, Int32.MaxValue);
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void MaxCapacity_Overflow1 ()
{
StringBuilder sb = new StringBuilder (2, 3);
sb.Append ("Mono");
}
[Test]
public void MaxCapacity_Overflow2 ()
{
StringBuilder sb = new StringBuilder (2, 3);
try {
sb.Append ("Mono");
} catch (ArgumentOutOfRangeException) {
}
AssertEquals (2, sb.Capacity);
AssertEquals (3, sb.MaxCapacity);
}
[Test]
public void MaxCapacity_Overflow3 ()
{
//
// When the capacity (4) gets doubled, it is greater than the
// max capacity. This makes sure that before throwing an exception
// we first attempt to go for a smaller size.
//
new StringBuilder(4, 7).Append ("foo").Append ("bar");
new StringBuilder(4, 6).Append ("foo").Append ("bar");
}
[Test]
public void CapacityFromString ()
{
StringBuilder sb = new StringBuilder ("hola").Append ("lala");
AssertEquals ("#01", "holalala", sb.ToString ());
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Globalization;
using System.Runtime.Serialization.Formatters;
using Newtonsoft.Json.Utilities;
using System.Runtime.Serialization;
namespace Newtonsoft.Json.Serialization
{
internal class JsonSerializerProxy : JsonSerializer
{
private readonly JsonSerializerInternalReader _serializerReader;
private readonly JsonSerializerInternalWriter _serializerWriter;
private readonly JsonSerializer _serializer;
public override event EventHandler<ErrorEventArgs> Error
{
add { _serializer.Error += value; }
remove { _serializer.Error -= value; }
}
public override IReferenceResolver ReferenceResolver
{
get { return _serializer.ReferenceResolver; }
set { _serializer.ReferenceResolver = value; }
}
public override ITraceWriter TraceWriter
{
get { return _serializer.TraceWriter; }
set { _serializer.TraceWriter = value; }
}
public override JsonConverterCollection Converters
{
get { return _serializer.Converters; }
}
public override DefaultValueHandling DefaultValueHandling
{
get { return _serializer.DefaultValueHandling; }
set { _serializer.DefaultValueHandling = value; }
}
public override IContractResolver ContractResolver
{
get { return _serializer.ContractResolver; }
set { _serializer.ContractResolver = value; }
}
public override MissingMemberHandling MissingMemberHandling
{
get { return _serializer.MissingMemberHandling; }
set { _serializer.MissingMemberHandling = value; }
}
public override NullValueHandling NullValueHandling
{
get { return _serializer.NullValueHandling; }
set { _serializer.NullValueHandling = value; }
}
public override ObjectCreationHandling ObjectCreationHandling
{
get { return _serializer.ObjectCreationHandling; }
set { _serializer.ObjectCreationHandling = value; }
}
public override ReferenceLoopHandling ReferenceLoopHandling
{
get { return _serializer.ReferenceLoopHandling; }
set { _serializer.ReferenceLoopHandling = value; }
}
public override PreserveReferencesHandling PreserveReferencesHandling
{
get { return _serializer.PreserveReferencesHandling; }
set { _serializer.PreserveReferencesHandling = value; }
}
public override TypeNameHandling TypeNameHandling
{
get { return _serializer.TypeNameHandling; }
set { _serializer.TypeNameHandling = value; }
}
public override FormatterAssemblyStyle TypeNameAssemblyFormat
{
get { return _serializer.TypeNameAssemblyFormat; }
set { _serializer.TypeNameAssemblyFormat = value; }
}
public override ConstructorHandling ConstructorHandling
{
get { return _serializer.ConstructorHandling; }
set { _serializer.ConstructorHandling = value; }
}
public override SerializationBinder Binder
{
get { return _serializer.Binder; }
set { _serializer.Binder = value; }
}
public override StreamingContext Context
{
get { return _serializer.Context; }
set { _serializer.Context = value; }
}
public override Formatting Formatting
{
get { return _serializer.Formatting; }
set { _serializer.Formatting = value; }
}
public override DateFormatHandling DateFormatHandling
{
get { return _serializer.DateFormatHandling; }
set { _serializer.DateFormatHandling = value; }
}
public override DateTimeZoneHandling DateTimeZoneHandling
{
get { return _serializer.DateTimeZoneHandling; }
set { _serializer.DateTimeZoneHandling = value; }
}
public override DateParseHandling DateParseHandling
{
get { return _serializer.DateParseHandling; }
set { _serializer.DateParseHandling = value; }
}
public override FloatFormatHandling FloatFormatHandling
{
get { return _serializer.FloatFormatHandling; }
set { _serializer.FloatFormatHandling = value; }
}
public override FloatParseHandling FloatParseHandling
{
get { return _serializer.FloatParseHandling; }
set { _serializer.FloatParseHandling = value; }
}
public override StringEscapeHandling StringEscapeHandling
{
get { return _serializer.StringEscapeHandling; }
set { _serializer.StringEscapeHandling = value; }
}
public override string DateFormatString
{
get { return _serializer.DateFormatString; }
set { _serializer.DateFormatString = value; }
}
public override CultureInfo Culture
{
get { return _serializer.Culture; }
set { _serializer.Culture = value; }
}
public override int? MaxDepth
{
get { return _serializer.MaxDepth; }
set { _serializer.MaxDepth = value; }
}
public override bool CheckAdditionalContent
{
get { return _serializer.CheckAdditionalContent; }
set { _serializer.CheckAdditionalContent = value; }
}
internal JsonSerializerInternalBase GetInternalSerializer()
{
if (_serializerReader != null)
return _serializerReader;
else
return _serializerWriter;
}
public JsonSerializerProxy(JsonSerializerInternalReader serializerReader)
{
ValidationUtils.ArgumentNotNull(serializerReader, "serializerReader");
_serializerReader = serializerReader;
_serializer = serializerReader.Serializer;
}
public JsonSerializerProxy(JsonSerializerInternalWriter serializerWriter)
{
ValidationUtils.ArgumentNotNull(serializerWriter, "serializerWriter");
_serializerWriter = serializerWriter;
_serializer = serializerWriter.Serializer;
}
internal override object DeserializeInternal(JsonReader reader, Type objectType)
{
if (_serializerReader != null)
return _serializerReader.Deserialize(reader, objectType, false);
else
return _serializer.Deserialize(reader, objectType);
}
internal override void PopulateInternal(JsonReader reader, object target)
{
if (_serializerReader != null)
_serializerReader.Populate(reader, target);
else
_serializer.Populate(reader, target);
}
internal override void SerializeInternal(JsonWriter jsonWriter, object value, Type rootType)
{
if (_serializerWriter != null)
_serializerWriter.Serialize(jsonWriter, value, rootType);
else
_serializer.Serialize(jsonWriter, value);
}
}
}
| |
// 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 Microsoft.Win32;
namespace System.Diagnostics.Eventing.Reader
{
/// <summary>
/// Log Type
/// </summary>
public enum EventLogType
{
Administrative = 0,
Operational,
Analytical,
Debug
}
/// <summary>
/// Log Isolation
/// </summary>
public enum EventLogIsolation
{
Application = 0,
System,
Custom
}
/// <summary>
/// Log Mode
/// </summary>
public enum EventLogMode
{
Circular = 0,
AutoBackup,
Retain
}
/// <summary>
/// Provides access to static log information and configures
/// log publishing and log file properties.
/// </summary>
public class EventLogConfiguration : IDisposable
{
private EventLogHandle _handle = EventLogHandle.Zero;
private EventLogSession _session = null;
public EventLogConfiguration(string logName) : this(logName, null) { }
public EventLogConfiguration(string logName, EventLogSession session)
{
if (session == null)
session = EventLogSession.GlobalSession;
_session = session;
LogName = logName;
_handle = NativeWrapper.EvtOpenChannelConfig(_session.Handle, LogName, 0);
}
public string LogName { get; }
public EventLogType LogType
{
get
{
return (EventLogType)((uint)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigType));
}
}
public EventLogIsolation LogIsolation
{
get
{
return (EventLogIsolation)((uint)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigIsolation));
}
}
public bool IsEnabled
{
get
{
return (bool)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigEnabled);
}
set
{
NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigEnabled, (object)value);
}
}
public bool IsClassicLog
{
get
{
return (bool)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigClassicEventlog);
}
}
public string SecurityDescriptor
{
get
{
return (string)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigAccess);
}
set
{
NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigAccess, (object)value);
}
}
public string LogFilePath
{
get
{
return (string)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigLogFilePath);
}
set
{
NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigLogFilePath, (object)value);
}
}
public long MaximumSizeInBytes
{
get
{
return (long)((ulong)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigMaxSize));
}
set
{
NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigMaxSize, (object)value);
}
}
public EventLogMode LogMode
{
get
{
object nativeRetentionObject = NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigRetention);
object nativeAutoBackupObject = NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigAutoBackup);
bool nativeRetention = nativeRetentionObject == null ? false : (bool)nativeRetentionObject;
bool nativeAutoBackup = nativeAutoBackupObject == null ? false : (bool)nativeAutoBackupObject;
if (nativeAutoBackup)
return EventLogMode.AutoBackup;
if (nativeRetention)
return EventLogMode.Retain;
return EventLogMode.Circular;
}
set
{
switch (value)
{
case EventLogMode.Circular:
NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigAutoBackup, (object)false);
NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigRetention, (object)false);
break;
case EventLogMode.AutoBackup:
NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigAutoBackup, (object)true);
NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigRetention, (object)true);
break;
case EventLogMode.Retain:
NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigAutoBackup, (object)false);
NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigRetention, (object)true);
break;
}
}
}
public string OwningProviderName
{
get
{
return (string)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigOwningPublisher);
}
}
public IEnumerable<string> ProviderNames
{
get
{
return (string[])NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublisherList);
}
}
public int? ProviderLevel
{
get
{
return (int?)((uint?)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigLevel));
}
set
{
NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigLevel, (object)value);
}
}
public long? ProviderKeywords
{
get
{
return (long?)((ulong?)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigKeywords));
}
set
{
NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigKeywords, (object)value);
}
}
public int? ProviderBufferSize
{
get
{
return (int?)((uint?)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigBufferSize));
}
}
public int? ProviderMinimumNumberOfBuffers
{
get
{
return (int?)((uint?)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigMinBuffers));
}
}
public int? ProviderMaximumNumberOfBuffers
{
get
{
return (int?)((uint?)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigMaxBuffers));
}
}
public int? ProviderLatency
{
get
{
return (int?)((uint?)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigLatency));
}
}
public Guid? ProviderControlGuid
{
get
{
return (Guid?)(NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigControlGuid));
}
}
public void SaveChanges()
{
NativeWrapper.EvtSaveChannelConfig(_handle, 0);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_handle != null && !_handle.IsInvalid)
_handle.Dispose();
}
}
}
| |
using System.Diagnostics;
namespace Lucene.Net.Util.Packed
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Non-specialized <see cref="BulkOperation"/> for <see cref="PackedInt32s.Format.PACKED"/>.
/// </summary>
internal class BulkOperationPacked : BulkOperation
{
private readonly int bitsPerValue;
private readonly int longBlockCount;
private readonly int longValueCount;
private readonly int byteBlockCount;
private readonly int byteValueCount;
private readonly long mask;
private readonly int intMask;
public BulkOperationPacked(int bitsPerValue)
{
this.bitsPerValue = bitsPerValue;
Debug.Assert(bitsPerValue > 0 && bitsPerValue <= 64);
int blocks = bitsPerValue;
while ((blocks & 1) == 0)
{
blocks = (int)((uint)blocks >> 1);
}
this.longBlockCount = blocks;
this.longValueCount = 64 * longBlockCount / bitsPerValue;
int byteBlockCount = 8 * longBlockCount;
int byteValueCount = longValueCount;
while ((byteBlockCount & 1) == 0 && (byteValueCount & 1) == 0)
{
byteBlockCount = (int)((uint)byteBlockCount >> 1);
byteValueCount = (int)((uint)byteValueCount >> 1);
}
this.byteBlockCount = byteBlockCount;
this.byteValueCount = byteValueCount;
if (bitsPerValue == 64)
{
this.mask = ~0L;
}
else
{
this.mask = (1L << bitsPerValue) - 1;
}
this.intMask = (int)mask;
Debug.Assert(longValueCount * bitsPerValue == 64 * longBlockCount);
}
/// <summary>
/// NOTE: This was longBlockCount() in Lucene.
/// </summary>
public override int Int64BlockCount
{
get { return longBlockCount; }
}
/// <summary>
/// NOTE: This was longValueCount() in Lucene.
/// </summary>
public override int Int64ValueCount
{
get { return longValueCount; }
}
public override int ByteBlockCount
{
get { return byteBlockCount; }
}
public override int ByteValueCount
{
get { return byteValueCount; }
}
public override void Decode(long[] blocks, int blocksOffset, long[] values, int valuesOffset, int iterations)
{
int bitsLeft = 64;
for (int i = 0; i < longValueCount * iterations; ++i)
{
bitsLeft -= bitsPerValue;
if (bitsLeft < 0)
{
values[valuesOffset++] = ((blocks[blocksOffset++] & ((1L << (bitsPerValue + bitsLeft)) - 1)) << -bitsLeft) | ((long)((ulong)blocks[blocksOffset] >> (64 + bitsLeft)));
bitsLeft += 64;
}
else
{
values[valuesOffset++] = ((long)((ulong)blocks[blocksOffset] >> bitsLeft)) & mask;
}
}
}
public override void Decode(byte[] blocks, int blocksOffset, long[] values, int valuesOffset, int iterations)
{
long nextValue = 0L;
int bitsLeft = bitsPerValue;
for (int i = 0; i < iterations * byteBlockCount; ++i)
{
long bytes = blocks[blocksOffset++] & 0xFFL;
if (bitsLeft > 8)
{
// just buffer
bitsLeft -= 8;
nextValue |= bytes << bitsLeft;
}
else
{
// flush
int bits = 8 - bitsLeft;
values[valuesOffset++] = nextValue | ((long)((ulong)bytes >> bits));
while (bits >= bitsPerValue)
{
bits -= bitsPerValue;
values[valuesOffset++] = ((long)((ulong)bytes >> bits)) & mask;
}
// then buffer
bitsLeft = bitsPerValue - bits;
nextValue = (bytes & ((1L << bits) - 1)) << bitsLeft;
}
}
Debug.Assert(bitsLeft == bitsPerValue);
}
public override void Decode(long[] blocks, int blocksOffset, int[] values, int valuesOffset, int iterations)
{
if (bitsPerValue > 32)
{
throw new System.NotSupportedException("Cannot decode " + bitsPerValue + "-bits values into an int[]");
}
int bitsLeft = 64;
for (int i = 0; i < longValueCount * iterations; ++i)
{
bitsLeft -= bitsPerValue;
if (bitsLeft < 0)
{
values[valuesOffset++] = (int)(((blocks[blocksOffset++] & ((1L << (bitsPerValue + bitsLeft)) - 1)) << -bitsLeft) | ((long)((ulong)blocks[blocksOffset] >> (64 + bitsLeft))));
bitsLeft += 64;
}
else
{
values[valuesOffset++] = (int)(((long)((ulong)blocks[blocksOffset] >> bitsLeft)) & mask);
}
}
}
public override void Decode(byte[] blocks, int blocksOffset, int[] values, int valuesOffset, int iterations)
{
int nextValue = 0;
int bitsLeft = bitsPerValue;
for (int i = 0; i < iterations * byteBlockCount; ++i)
{
int bytes = blocks[blocksOffset++] & 0xFF;
if (bitsLeft > 8)
{
// just buffer
bitsLeft -= 8;
nextValue |= bytes << bitsLeft;
}
else
{
// flush
int bits = 8 - bitsLeft;
values[valuesOffset++] = nextValue | ((int)((uint)bytes >> bits));
while (bits >= bitsPerValue)
{
bits -= bitsPerValue;
values[valuesOffset++] = ((int)((uint)bytes >> bits)) & intMask;
}
// then buffer
bitsLeft = bitsPerValue - bits;
nextValue = (bytes & ((1 << bits) - 1)) << bitsLeft;
}
}
Debug.Assert(bitsLeft == bitsPerValue);
}
public override void Encode(long[] values, int valuesOffset, long[] blocks, int blocksOffset, int iterations)
{
long nextBlock = 0;
int bitsLeft = 64;
for (int i = 0; i < longValueCount * iterations; ++i)
{
bitsLeft -= bitsPerValue;
if (bitsLeft > 0)
{
nextBlock |= values[valuesOffset++] << bitsLeft;
}
else if (bitsLeft == 0)
{
nextBlock |= values[valuesOffset++];
blocks[blocksOffset++] = nextBlock;
nextBlock = 0;
bitsLeft = 64;
} // bitsLeft < 0
else
{
nextBlock |= (long)((ulong)values[valuesOffset] >> -bitsLeft);
blocks[blocksOffset++] = nextBlock;
nextBlock = (values[valuesOffset++] & ((1L << -bitsLeft) - 1)) << (64 + bitsLeft);
bitsLeft += 64;
}
}
}
public override void Encode(int[] values, int valuesOffset, long[] blocks, int blocksOffset, int iterations)
{
long nextBlock = 0;
int bitsLeft = 64;
for (int i = 0; i < longValueCount * iterations; ++i)
{
bitsLeft -= bitsPerValue;
if (bitsLeft > 0)
{
nextBlock |= (values[valuesOffset++] & 0xFFFFFFFFL) << bitsLeft;
}
else if (bitsLeft == 0)
{
nextBlock |= (values[valuesOffset++] & 0xFFFFFFFFL);
blocks[blocksOffset++] = nextBlock;
nextBlock = 0;
bitsLeft = 64;
} // bitsLeft < 0
else
{
nextBlock |= ((uint)(values[valuesOffset] & 0xFFFFFFFFL) >> -bitsLeft);
blocks[blocksOffset++] = nextBlock;
nextBlock = (values[valuesOffset++] & ((1L << -bitsLeft) - 1)) << (64 + bitsLeft);
bitsLeft += 64;
}
}
}
public override void Encode(long[] values, int valuesOffset, byte[] blocks, int blocksOffset, int iterations)
{
int nextBlock = 0;
int bitsLeft = 8;
for (int i = 0; i < byteValueCount * iterations; ++i)
{
long v = values[valuesOffset++];
Debug.Assert(bitsPerValue == 64 || PackedInt32s.BitsRequired(v) <= bitsPerValue);
if (bitsPerValue < bitsLeft)
{
// just buffer
nextBlock |= (int)(v << (bitsLeft - bitsPerValue));
bitsLeft -= bitsPerValue;
}
else
{
// flush as many blocks as possible
int bits = bitsPerValue - bitsLeft;
blocks[blocksOffset++] = (byte)((uint)nextBlock | ((long)((ulong)v >> bits)));
while (bits >= 8)
{
bits -= 8;
blocks[blocksOffset++] = (byte)((long)((ulong)v >> bits));
}
// then buffer
bitsLeft = 8 - bits;
nextBlock = (int)((v & ((1L << bits) - 1)) << bitsLeft);
}
}
Debug.Assert(bitsLeft == 8);
}
public override void Encode(int[] values, int valuesOffset, byte[] blocks, int blocksOffset, int iterations)
{
int nextBlock = 0;
int bitsLeft = 8;
for (int i = 0; i < byteValueCount * iterations; ++i)
{
int v = values[valuesOffset++];
Debug.Assert(PackedInt32s.BitsRequired(v & 0xFFFFFFFFL) <= bitsPerValue);
if (bitsPerValue < bitsLeft)
{
// just buffer
nextBlock |= v << (bitsLeft - bitsPerValue);
bitsLeft -= bitsPerValue;
}
else
{
// flush as many blocks as possible
int bits = bitsPerValue - bitsLeft;
blocks[blocksOffset++] = (byte)(nextBlock | ((int)((uint)v >> bits)));
while (bits >= 8)
{
bits -= 8;
blocks[blocksOffset++] = (byte)((int)((uint)v >> bits));
}
// then buffer
bitsLeft = 8 - bits;
nextBlock = (v & ((1 << bits) - 1)) << bitsLeft;
}
}
Debug.Assert(bitsLeft == 8);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Orleans.Runtime;
using Orleans.TestingHost.Utils;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Memory;
using Orleans.Configuration;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Hosting;
namespace Orleans.TestingHost
{
/// <summary>
/// A host class for local testing with Orleans using in-process silos.
/// Runs a Primary and optionally secondary silos in separate app domains, and client in the main app domain.
/// Additional silos can also be started in-process on demand if required for particular test cases.
/// </summary>
/// <remarks>
/// Make sure that your test project references your test grains and test grain interfaces
/// projects, and has CopyLocal=True set on those references [which should be the default].
/// </remarks>
public class TestCluster : IDisposable, IAsyncDisposable
{
private readonly List<SiloHandle> additionalSilos = new List<SiloHandle>();
private readonly TestClusterOptions options;
private readonly StringBuilder log = new StringBuilder();
private bool _disposed;
private int startedInstances;
/// <summary>
/// Primary silo handle, if applicable.
/// </summary>
/// <remarks>This handle is valid only when using Grain-based membership.</remarks>
public SiloHandle Primary { get; private set; }
/// <summary>
/// List of handles to the secondary silos.
/// </summary>
public IReadOnlyList<SiloHandle> SecondarySilos
{
get
{
lock (this.additionalSilos)
{
return new List<SiloHandle>(this.additionalSilos);
}
}
}
/// <summary>
/// Collection of all known silos.
/// </summary>
public ReadOnlyCollection<SiloHandle> Silos
{
get
{
var result = new List<SiloHandle>();
if (this.Primary != null)
{
result.Add(this.Primary);
}
lock (this.additionalSilos)
{
result.AddRange(this.additionalSilos);
}
return result.AsReadOnly();
}
}
/// <summary>
/// Options used to configure the test cluster.
/// </summary>
/// <remarks>This is the options you configured your test cluster with, or the default one.
/// If the cluster is being configured via ClusterConfiguration, then this object may not reflect the true settings.
/// </remarks>
public TestClusterOptions Options => this.options;
/// <summary>
/// The internal client interface.
/// </summary>
internal IHost ClientHost { get; private set; }
/// <summary>
/// The internal client interface.
/// </summary>
internal IInternalClusterClient InternalClient => ClientHost?.Services.GetRequiredService<IInternalClusterClient>();
/// <summary>
/// The client.
/// </summary>
public IClusterClient Client => this.InternalClient;
/// <summary>
/// GrainFactory to use in the tests
/// </summary>
public IGrainFactory GrainFactory => this.Client;
/// <summary>
/// GrainFactory to use in the tests
/// </summary>
internal IInternalGrainFactory InternalGrainFactory => this.InternalClient;
/// <summary>
/// Client-side <see cref="IServiceProvider"/> to use in the tests.
/// </summary>
public IServiceProvider ServiceProvider => this.Client.ServiceProvider;
/// <summary>
/// Delegate used to create and start an individual silo.
/// </summary>
public Func<string, IConfiguration, Task<SiloHandle>> CreateSiloAsync { private get; set; } = InProcessSiloHandle.CreateAsync;
/// <summary>
/// The port allocator.
/// </summary>
public ITestClusterPortAllocator PortAllocator { get; }
/// <summary>
/// Configures the test cluster plus client in-process.
/// </summary>
public TestCluster(
TestClusterOptions options,
IReadOnlyList<IConfigurationSource> configurationSources,
ITestClusterPortAllocator portAllocator)
{
this.options = options;
this.ConfigurationSources = configurationSources.ToArray();
this.PortAllocator = portAllocator;
}
/// <summary>
/// Deploys the cluster using the specified configuration and starts the client in-process.
/// It will start the number of silos defined in <see cref="TestClusterOptions.InitialSilosCount"/>.
/// </summary>
public void Deploy()
{
this.DeployAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Deploys the cluster using the specified configuration and starts the client in-process.
/// </summary>
public async Task DeployAsync()
{
if (this.Primary != null || this.additionalSilos.Count > 0) throw new InvalidOperationException("Cluster host already deployed.");
AppDomain.CurrentDomain.UnhandledException += ReportUnobservedException;
try
{
string startMsg = "----------------------------- STARTING NEW UNIT TEST SILO HOST: " + GetType().FullName + " -------------------------------------";
WriteLog(startMsg);
await InitializeAsync();
if (this.options.InitializeClientOnDeploy)
{
await WaitForInitialStabilization();
}
}
catch (TimeoutException te)
{
FlushLogToConsole();
throw new TimeoutException("Timeout during test initialization", te);
}
catch (Exception ex)
{
await StopAllSilosAsync();
Exception baseExc = ex.GetBaseException();
FlushLogToConsole();
if (baseExc is TimeoutException)
{
throw new TimeoutException("Timeout during test initialization", ex);
}
// IMPORTANT:
// Do NOT re-throw the original exception here, also not as an internal exception inside AggregateException
// Due to the way MS tests works, if the original exception is an Orleans exception,
// it's assembly might not be loaded yet in this phase of the test.
// As a result, we will get "MSTest: Unit Test Adapter threw exception: Type is not resolved for member XXX"
// and will loose the original exception. This makes debugging tests super hard!
// The root cause has to do with us initializing our tests from Test constructor and not from TestInitialize method.
// More details: http://dobrzanski.net/2010/09/20/mstest-unit-test-adapter-threw-exception-type-is-not-resolved-for-member/
//throw new Exception(
// string.Format("Exception during test initialization: {0}",
// LogFormatter.PrintException(baseExc)));
throw;
}
}
private async Task WaitForInitialStabilization()
{
// Poll each silo to check that it knows the expected number of active silos.
// If any silo does not have the expected number of active silos in its cluster membership oracle, try again.
// If the cluster membership has not stabilized after a certain period of time, give up and continue anyway.
var totalWait = Stopwatch.StartNew();
while (true)
{
var silos = this.Silos;
var expectedCount = silos.Count;
var remainingSilos = expectedCount;
foreach (var silo in silos)
{
var hooks = this.InternalClient.GetTestHooks(silo);
var statuses = await hooks.GetApproximateSiloStatuses();
var activeCount = statuses.Count(s => s.Value == SiloStatus.Active);
if (activeCount != expectedCount) break;
remainingSilos--;
}
if (remainingSilos == 0)
{
totalWait.Stop();
break;
}
WriteLog($"{remainingSilos} silos do not have a consistent cluster view, waiting until stabilization.");
await Task.Delay(TimeSpan.FromMilliseconds(100));
if (totalWait.Elapsed < TimeSpan.FromSeconds(60))
{
WriteLog($"Warning! {remainingSilos} silos do not have a consistent cluster view after {totalWait.ElapsedMilliseconds}ms, continuing without stabilization.");
break;
}
}
}
/// <summary>
/// Get the list of current active silos.
/// </summary>
/// <returns>List of current silos.</returns>
public IEnumerable<SiloHandle> GetActiveSilos()
{
var additional = new List<SiloHandle>();
lock (additionalSilos)
{
additional.AddRange(additionalSilos);
}
WriteLog("GetActiveSilos: Primary={0} + {1} Additional={2}",
Primary, additional.Count, Runtime.Utils.EnumerableToString(additional));
if (Primary?.IsActive == true) yield return Primary;
if (additional.Count > 0)
foreach (var s in additional)
if (s?.IsActive == true)
yield return s;
}
/// <summary>
/// Find the silo handle for the specified silo address.
/// </summary>
/// <param name="siloAddress">Silo address to be found.</param>
/// <returns>SiloHandle of the appropriate silo, or <c>null</c> if not found.</returns>
public SiloHandle GetSiloForAddress(SiloAddress siloAddress)
{
var activeSilos = GetActiveSilos().ToList();
var ret = activeSilos.FirstOrDefault(s => s.SiloAddress.Equals(siloAddress));
return ret;
}
/// <summary>
/// Wait for the silo liveness sub-system to detect and act on any recent cluster membership changes.
/// </summary>
/// <param name="didKill">Whether recent membership changes we done by graceful Stop.</param>
public async Task WaitForLivenessToStabilizeAsync(bool didKill = false)
{
var clusterMembershipOptions = this.ServiceProvider.GetRequiredService<IOptions<ClusterMembershipOptions>>().Value;
TimeSpan stabilizationTime = GetLivenessStabilizationTime(clusterMembershipOptions, didKill);
WriteLog(Environment.NewLine + Environment.NewLine + "WaitForLivenessToStabilize is about to sleep for {0}", stabilizationTime);
await Task.Delay(stabilizationTime);
WriteLog("WaitForLivenessToStabilize is done sleeping");
}
/// <summary>
/// Get the timeout value to use to wait for the silo liveness sub-system to detect and act on any recent cluster membership changes.
/// <seealso cref="WaitForLivenessToStabilizeAsync"/>
/// </summary>
public static TimeSpan GetLivenessStabilizationTime(ClusterMembershipOptions clusterMembershipOptions, bool didKill = false)
{
TimeSpan stabilizationTime = TimeSpan.Zero;
if (didKill)
{
// in case of hard kill (kill and not Stop), we should give silos time to detect failures first.
stabilizationTime = TestingUtils.Multiply(clusterMembershipOptions.ProbeTimeout, clusterMembershipOptions.NumMissedProbesLimit);
}
if (clusterMembershipOptions.UseLivenessGossip)
{
stabilizationTime += TimeSpan.FromSeconds(5);
}
else
{
stabilizationTime += TestingUtils.Multiply(clusterMembershipOptions.TableRefreshTimeout, 2);
}
return stabilizationTime;
}
/// <summary>
/// Start an additional silo, so that it joins the existing cluster.
/// </summary>
/// <returns>SiloHandle for the newly started silo.</returns>
public SiloHandle StartAdditionalSilo(bool startAdditionalSiloOnNewPort = false)
{
return StartAdditionalSiloAsync(startAdditionalSiloOnNewPort).GetAwaiter().GetResult();
}
/// <summary>
/// Start an additional silo, so that it joins the existing cluster.
/// </summary>
/// <returns>SiloHandle for the newly started silo.</returns>
public async Task<SiloHandle> StartAdditionalSiloAsync(bool startAdditionalSiloOnNewPort = false)
{
return (await this.StartAdditionalSilosAsync(1, startAdditionalSiloOnNewPort)).Single();
}
/// <summary>
/// Start a number of additional silo, so that they join the existing cluster.
/// </summary>
/// <param name="silosToStart">Number of silos to start.</param>
/// <param name="startAdditionalSiloOnNewPort"></param>
/// <returns>List of SiloHandles for the newly started silos.</returns>
public async Task<List<SiloHandle>> StartAdditionalSilosAsync(int silosToStart, bool startAdditionalSiloOnNewPort = false)
{
var instances = new List<SiloHandle>();
if (silosToStart > 0)
{
var siloStartTasks = Enumerable.Range(this.startedInstances, silosToStart)
.Select(instanceNumber => Task.Run(() => StartSiloAsync((short)instanceNumber, this.options, startSiloOnNewPort: startAdditionalSiloOnNewPort))).ToArray();
try
{
await Task.WhenAll(siloStartTasks);
}
catch (Exception)
{
lock (additionalSilos)
{
this.additionalSilos.AddRange(siloStartTasks.Where(t => t.Exception == null).Select(t => t.Result));
}
throw;
}
instances.AddRange(siloStartTasks.Select(t => t.Result));
lock (additionalSilos)
{
this.additionalSilos.AddRange(instances);
}
}
return instances;
}
/// <summary>
/// Stop any additional silos, not including the default Primary silo.
/// </summary>
public async Task StopSecondarySilosAsync()
{
foreach (var instance in this.additionalSilos.ToList())
{
await StopSiloAsync(instance);
}
}
/// <summary>
/// Stops the default Primary silo.
/// </summary>
public async Task StopPrimarySiloAsync()
{
if (Primary == null) throw new InvalidOperationException("There is no primary silo");
await StopClusterClientAsync();
await StopSiloAsync(Primary);
}
public async Task StopClusterClientAsync()
{
var client = this.ClientHost;
try
{
if (client is not null)
{
await client.StopAsync().ConfigureAwait(false);
}
}
catch (Exception exc)
{
WriteLog("Exception stopping client: {0}", exc);
}
finally
{
await DisposeAsync(client).ConfigureAwait(false);
ClientHost = null;
}
}
/// <summary>
/// Stop all current silos.
/// </summary>
public void StopAllSilos()
{
StopAllSilosAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Stop all current silos.
/// </summary>
public async Task StopAllSilosAsync()
{
await StopClusterClientAsync();
await StopSecondarySilosAsync();
if (Primary != null)
{
await StopPrimarySiloAsync();
}
AppDomain.CurrentDomain.UnhandledException -= ReportUnobservedException;
}
/// <summary>
/// Do a semi-graceful Stop of the specified silo.
/// </summary>
/// <param name="instance">Silo to be stopped.</param>
public async Task StopSiloAsync(SiloHandle instance)
{
if (instance != null)
{
await StopSiloAsync(instance, true);
if (Primary == instance)
{
Primary = null;
}
else
{
lock (additionalSilos)
{
additionalSilos.Remove(instance);
}
}
}
}
/// <summary>
/// Do an immediate Kill of the specified silo.
/// </summary>
/// <param name="instance">Silo to be killed.</param>
public async Task KillSiloAsync(SiloHandle instance)
{
if (instance != null)
{
// do NOT stop, just kill directly, to simulate crash.
await StopSiloAsync(instance, false);
if (Primary == instance)
{
Primary = null;
}
else
{
lock (additionalSilos)
{
additionalSilos.Remove(instance);
}
}
}
}
/// <summary>
/// Performs a hard kill on client. Client will not cleanup resources.
/// </summary>
public async Task KillClientAsync()
{
var client = ClientHost;
if (client != null)
{
var cancelled = new CancellationTokenSource();
cancelled.Cancel();
try
{
await client.StopAsync(cancelled.Token).ConfigureAwait(false);
}
finally
{
await DisposeAsync(client);
ClientHost = null;
}
}
}
/// <summary>
/// Do a Stop or Kill of the specified silo, followed by a restart.
/// </summary>
/// <param name="instance">Silo to be restarted.</param>
public async Task<SiloHandle> RestartSiloAsync(SiloHandle instance)
{
if (instance != null)
{
var instanceNumber = instance.InstanceNumber;
var siloName = instance.Name;
await StopSiloAsync(instance);
var newInstance = await StartSiloAsync(instanceNumber, this.options);
if (siloName == Silo.PrimarySiloName)
{
Primary = newInstance;
}
else
{
lock (additionalSilos)
{
additionalSilos.Add(newInstance);
}
}
return newInstance;
}
return null;
}
/// <summary>
/// Restart a previously stopped.
/// </summary>
/// <param name="siloName">Silo to be restarted.</param>
public async Task<SiloHandle> RestartStoppedSecondarySiloAsync(string siloName)
{
if (siloName == null) throw new ArgumentNullException(nameof(siloName));
var siloHandle = this.Silos.Single(s => s.Name.Equals(siloName, StringComparison.Ordinal));
var newInstance = await this.StartSiloAsync(this.Silos.IndexOf(siloHandle), this.options);
lock (additionalSilos)
{
additionalSilos.Add(newInstance);
}
return newInstance;
}
/// <summary>
/// Initialize the grain client. This should be already done by <see cref="Deploy()"/> or <see cref="DeployAsync"/>
/// </summary>
public async Task InitializeClientAsync()
{
WriteLog("Initializing Cluster Client");
if (ClientHost is not null)
{
await StopClusterClientAsync();
}
this.ClientHost = TestClusterHostFactory.CreateClusterClient("MainClient", this.ConfigurationSources);
await this.ClientHost.StartAsync();
}
public IReadOnlyList<IConfigurationSource> ConfigurationSources { get; }
private async Task InitializeAsync()
{
short silosToStart = this.options.InitialSilosCount;
if (this.options.UseTestClusterMembership)
{
this.Primary = await StartSiloAsync(this.startedInstances, this.options);
silosToStart--;
}
if (silosToStart > 0)
{
await this.StartAdditionalSilosAsync(silosToStart);
}
WriteLog("Done initializing cluster");
if (this.options.InitializeClientOnDeploy)
{
await InitializeClientAsync();
}
}
/// <summary>
/// Start a new silo in the target cluster
/// </summary>
/// <param name="cluster">The TestCluster in which the silo should be deployed</param>
/// <param name="instanceNumber">The instance number to deploy</param>
/// <param name="clusterOptions">The options to use.</param>
/// <param name="configurationOverrides">Configuration overrides.</param>
/// <param name="startSiloOnNewPort">Whether we start this silo on a new port, instead of the default one</param>
/// <returns>A handle to the silo deployed</returns>
public static async Task<SiloHandle> StartSiloAsync(TestCluster cluster, int instanceNumber, TestClusterOptions clusterOptions, IReadOnlyList<IConfigurationSource> configurationOverrides = null, bool startSiloOnNewPort = false)
{
if (cluster == null) throw new ArgumentNullException(nameof(cluster));
return await cluster.StartSiloAsync(instanceNumber, clusterOptions, configurationOverrides, startSiloOnNewPort);
}
/// <summary>
/// Starts a new silo.
/// </summary>
/// <param name="instanceNumber">The instance number to deploy</param>
/// <param name="clusterOptions">The options to use.</param>
/// <param name="configurationOverrides">Configuration overrides.</param>
/// <param name="startSiloOnNewPort">Whether we start this silo on a new port, instead of the default one</param>
/// <returns>A handle to the deployed silo.</returns>
public async Task<SiloHandle> StartSiloAsync(int instanceNumber, TestClusterOptions clusterOptions, IReadOnlyList<IConfigurationSource> configurationOverrides = null, bool startSiloOnNewPort = false)
{
var configurationSources = this.ConfigurationSources.ToList();
// Add overrides.
if (configurationOverrides != null) configurationSources.AddRange(configurationOverrides);
var siloSpecificOptions = TestSiloSpecificOptions.Create(this, clusterOptions, instanceNumber, startSiloOnNewPort);
configurationSources.Add(new MemoryConfigurationSource
{
InitialData = siloSpecificOptions.ToDictionary()
});
var configurationBuilder = new ConfigurationBuilder();
foreach (var source in configurationSources)
{
configurationBuilder.Add(source);
}
var configuration = configurationBuilder.Build();
var handle = await this.CreateSiloAsync(siloSpecificOptions.SiloName, configuration);
handle.InstanceNumber = (short)instanceNumber;
Interlocked.Increment(ref this.startedInstances);
return handle;
}
private async Task StopSiloAsync(SiloHandle instance, bool stopGracefully)
{
try
{
await instance.StopSiloAsync(stopGracefully).ConfigureAwait(false);
}
finally
{
await DisposeAsync(instance).ConfigureAwait(false);
Interlocked.Decrement(ref this.startedInstances);
}
}
public string GetLog()
{
return this.log.ToString();
}
private void ReportUnobservedException(object sender, UnhandledExceptionEventArgs eventArgs)
{
Exception exception = (Exception)eventArgs.ExceptionObject;
this.WriteLog("Unobserved exception: {0}", exception);
}
private void WriteLog(string format, params object[] args)
{
log.AppendFormat(format + Environment.NewLine, args);
}
private void FlushLogToConsole()
{
Console.WriteLine(GetLog());
}
public async ValueTask DisposeAsync()
{
if (_disposed)
{
return;
}
await Task.Run(async () =>
{
foreach (var handle in this.SecondarySilos)
{
await DisposeAsync(handle).ConfigureAwait(false);
}
if (this.Primary is object)
{
await DisposeAsync(Primary).ConfigureAwait(false);
}
await DisposeAsync(ClientHost).ConfigureAwait(false);
ClientHost = null;
this.PortAllocator?.Dispose();
});
_disposed = true;
}
public void Dispose()
{
if (_disposed)
{
return;
}
foreach (var handle in this.SecondarySilos)
{
handle.Dispose();
}
this.Primary?.Dispose();
this.ClientHost?.Dispose();
this.PortAllocator?.Dispose();
_disposed = true;
}
private static async Task DisposeAsync(IDisposable value)
{
if (value is IAsyncDisposable asyncDisposable)
{
await asyncDisposable.DisposeAsync().ConfigureAwait(false);
}
else if (value is IDisposable disposable)
{
disposable.Dispose();
}
}
}
}
| |
// 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.Diagnostics;
namespace Internal.TypeSystem
{
static public class TypeSystemHelpers
{
static public InstantiatedType MakeInstantiatedType(this MetadataType typeDef, Instantiation instantiation)
{
return typeDef.Context.GetInstantiatedType(typeDef, instantiation);
}
static public InstantiatedType MakeInstantiatedType(this MetadataType typeDef, params TypeDesc[] genericParameters)
{
return typeDef.Context.GetInstantiatedType(typeDef, new Instantiation(genericParameters));
}
static public InstantiatedMethod MakeInstantiatedMethod(this MethodDesc methodDef, Instantiation instantiation)
{
return methodDef.Context.GetInstantiatedMethod(methodDef, instantiation);
}
static public InstantiatedMethod MakeInstantiatedMethod(this MethodDesc methodDef, params TypeDesc[] genericParameters)
{
return methodDef.Context.GetInstantiatedMethod(methodDef, new Instantiation(genericParameters));
}
static public ArrayType MakeArrayType(this TypeDesc type)
{
return type.Context.GetArrayType(type);
}
/// <summary>
/// Creates a multidimensional array type with the specified rank.
/// To create a vector, use the <see cref="MakeArrayType(TypeDesc)"/> overload.
/// </summary>
static public ArrayType MakeArrayType(this TypeDesc type, int rank)
{
return type.Context.GetArrayType(type, rank);
}
static public ByRefType MakeByRefType(this TypeDesc type)
{
return type.Context.GetByRefType(type);
}
static public PointerType MakePointerType(this TypeDesc type)
{
return type.Context.GetPointerType(type);
}
static public int GetElementSize(this TypeDesc type)
{
if (type.IsValueType)
{
return ((MetadataType)type).InstanceFieldSize;
}
else
{
return type.Context.Target.PointerSize;
}
}
static public MethodDesc GetDefaultConstructor(this TypeDesc type)
{
// TODO: Do we want check for specialname/rtspecialname? Maybe add another overload on GetMethod?
var sig = new MethodSignature(0, 0, type.Context.GetWellKnownType(WellKnownType.Void), Array.Empty<TypeDesc>());
return type.GetMethod(".ctor", sig);
}
static private MethodDesc FindMethodOnExactTypeWithMatchingTypicalMethod(this TypeDesc type, MethodDesc method)
{
MethodDesc methodTypicalDefinition = method.GetTypicalMethodDefinition();
var instantiatedType = type as InstantiatedType;
if (instantiatedType != null)
{
Debug.Assert(instantiatedType.GetTypeDefinition() == methodTypicalDefinition.OwningType);
return method.Context.GetMethodForInstantiatedType(methodTypicalDefinition, instantiatedType);
}
else
{
Debug.Assert(type == methodTypicalDefinition.OwningType);
return methodTypicalDefinition;
}
}
/// <summary>
/// Returns method as defined on a non-generic base class or on a base
/// instantiation.
/// For example, If Foo<T> : Bar<T> and overrides method M,
/// if method is Bar<string>.M(), then this returns Bar<T>.M()
/// but if Foo : Bar<string>, then this returns Bar<string>.M()
/// </summary>
/// <param name="targetType">A potentially derived type</param>
/// <param name="method">A base class's virtual method</param>
static public MethodDesc FindMethodOnTypeWithMatchingTypicalMethod(this TypeDesc targetType, MethodDesc method)
{
// If method is nongeneric and on a nongeneric type, then it is the matching method
if (!method.HasInstantiation && !method.OwningType.HasInstantiation)
{
return method;
}
// Since method is an instantiation that may or may not be the same as typeExamine's hierarchy,
// find a matching base class on an open type and then work from the instantiation in typeExamine's
// hierarchy
TypeDesc typicalTypeOfTargetMethod = method.GetTypicalMethodDefinition().OwningType;
TypeDesc targetOrBase = targetType;
do
{
TypeDesc openTargetOrBase = targetOrBase;
if (openTargetOrBase is InstantiatedType)
{
openTargetOrBase = openTargetOrBase.GetTypeDefinition();
}
if (openTargetOrBase == typicalTypeOfTargetMethod)
{
// Found an open match. Now find an equivalent method on the original target typeOrBase
MethodDesc matchingMethod = targetOrBase.FindMethodOnExactTypeWithMatchingTypicalMethod(method);
return matchingMethod;
}
targetOrBase = targetOrBase.BaseType;
} while (targetOrBase != null);
Debug.Assert(false, "method has no related type in the type hierarchy of type");
return null;
}
/// <summary>
/// Attempts to resolve constrained call to <paramref name="interfaceMethod"/> into a concrete non-unboxing
/// method on <paramref name="constrainedType"/>.
/// The ability to resolve constraint methods is affected by the degree of code sharing we are performing
/// for generic code.
/// </summary>
/// <returns>The resolved method or null if the constraint couldn't be resolved.</returns>
static public MethodDesc TryResolveConstraintMethodApprox(this TypeDesc constrainedType, TypeDesc interfaceType, MethodDesc interfaceMethod, out bool forceRuntimeLookup)
{
forceRuntimeLookup = false;
// We can't resolve constraint calls effectively for reference types, and there's
// not a lot of perf. benefit in doing it anyway.
if (!constrainedType.IsValueType)
{
return null;
}
// Non-virtual methods called through constraints simply resolve to the specified method without constraint resolution.
if (!interfaceMethod.IsVirtual)
{
return null;
}
MethodDesc method;
MethodDesc genInterfaceMethod = interfaceMethod.GetMethodDefinition();
if (genInterfaceMethod.OwningType.IsInterface)
{
// Sometimes (when compiling shared generic code)
// we don't have enough exact type information at JIT time
// even to decide whether we will be able to resolve to an unboxed entry point...
// To cope with this case we always go via the helper function if there's any
// chance of this happening by checking for all interfaces which might possibly
// be compatible with the call (verification will have ensured that
// at least one of them will be)
// Enumerate all potential interface instantiations
// TODO: this code assumes no shared generics
Debug.Assert(interfaceType == interfaceMethod.OwningType);
method = constrainedType.ResolveInterfaceMethodToVirtualMethodOnType(genInterfaceMethod);
}
else if (genInterfaceMethod.IsVirtual)
{
method = constrainedType.FindVirtualFunctionTargetMethodOnObjectType(genInterfaceMethod);
}
else
{
// The method will be null if calling a non-virtual instance
// methods on System.Object, i.e. when these are used as a constraint.
method = null;
}
if (method == null)
{
// Fall back to VSD
return null;
}
//#TryResolveConstraintMethodApprox_DoNotReturnParentMethod
// Only return a method if the value type itself declares the method,
// otherwise we might get a method from Object or System.ValueType
if (!method.OwningType.IsValueType)
{
// Fall back to VSD
return null;
}
// We've resolved the method, ignoring its generic method arguments
// If the method is a generic method then go and get the instantiated descriptor
if (interfaceMethod.HasInstantiation)
{
method = method.InstantiateSignature(interfaceType.Instantiation, interfaceMethod.Instantiation);
}
Debug.Assert(method != null);
//assert(!pMD->IsUnboxingStub());
return method;
}
/// <summary>
/// Retrieves the namespace qualified name of a <see cref="MetadataType"/>.
/// </summary>
public static string GetFullName(this MetadataType metadataType)
{
string ns = metadataType.Namespace;
return ns.Length > 0 ? String.Concat(ns, ".", metadataType.Name) : metadataType.Name;
}
/// <summary>
/// Enumerates all virtual methods introduced or overriden by '<paramref name="type"/>'.
/// Note that this is not just a convenience method. This method is capable of enumerating
/// virtual method injected by the type system host.
/// </summary>
public static IEnumerable<MethodDesc> GetAllVirtualMethods(this TypeDesc type)
{
return type.Context.GetVirtualMethodEnumerationAlgorithmForType(type).ComputeAllVirtualMethods(type);
}
public static IEnumerable<MethodDesc> EnumAllVirtualSlots(this TypeDesc type)
{
return type.Context.GetVirtualMethodAlgorithmForType(type).ComputeAllVirtualSlots(type);
}
/// <summary>
/// Resolves interface method '<paramref name="interfaceMethod"/>' to a method on '<paramref name="type"/>'
/// that implements the the method.
/// </summary>
public static MethodDesc ResolveInterfaceMethodToVirtualMethodOnType(this TypeDesc type, MethodDesc interfaceMethod)
{
return type.Context.GetVirtualMethodAlgorithmForType(type).ResolveInterfaceMethodToVirtualMethodOnType(interfaceMethod, type);
}
/// <summary>
/// Resolves a virtual method call.
/// </summary>
public static MethodDesc FindVirtualFunctionTargetMethodOnObjectType(this TypeDesc type, MethodDesc targetMethod)
{
return type.Context.GetVirtualMethodAlgorithmForType(type).FindVirtualFunctionTargetMethodOnObjectType(targetMethod, type);
}
/// <summary>
/// Given Foo<T>, returns Foo<!0>.
/// </summary>
private static InstantiatedType InstantiateAsOpen(this MetadataType type)
{
Debug.Assert(type.HasInstantiation);
Debug.Assert(type.IsTypeDefinition);
TypeSystemContext context = type.Context;
var inst = new TypeDesc[type.Instantiation.Length];
for (int i = 0; i < inst.Length; i++)
{
inst[i] = context.GetSignatureVariable(i, false);
}
return context.GetInstantiatedType(type, new Instantiation(inst));
}
/// <summary>
/// Creates an open instantiation of a method. Given Foo<T>.Method, returns
/// Foo<!0>.Method. If the owning type is not generic, returns the <paramref name="method"/>.
/// </summary>
public static MethodDesc InstantiateAsOpen(this MethodDesc method)
{
Debug.Assert(method.IsMethodDefinition && !method.HasInstantiation);
TypeDesc owner = method.OwningType;
if (owner.HasInstantiation)
{
MetadataType instantiatedOwner = ((MetadataType)owner).InstantiateAsOpen();
return method.Context.GetMethodForInstantiatedType(method, (InstantiatedType)instantiatedOwner);
}
return method;
}
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace RemoteTimerJob.Console
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Linq;
using Newtonsoft.Json;
using NUnit.Framework;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using System.Collections.Generic;
namespace QuantConnect.Tests.Common
{
[TestFixture]
public class SymbolJsonConverterTests
{
private JsonSerializerSettings Settings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All
};
[Test]
public void SurvivesRoundtripSerialization()
{
var sid = SecurityIdentifier.GenerateEquity("SPY", Market.USA);
var expected = new Symbol(sid, "value");
var json = JsonConvert.SerializeObject(expected, Settings);
var actual = JsonConvert.DeserializeObject<Symbol>(json, Settings);
Assert.AreEqual(expected, actual);
}
[Test]
public void SurvivesRoundtripSerializationOption()
{
var expected = Symbol.CreateOption("XLRE", Market.USA, OptionStyle.American, OptionRight.Call, 21m, new DateTime(2016, 08, 19));
var json = JsonConvert.SerializeObject(expected, Settings);
var actual = JsonConvert.DeserializeObject<Symbol>(json, Settings);
Assert.AreEqual(expected, actual);
Assert.AreEqual(expected.ID, actual.ID);
Assert.AreEqual(expected.Value, actual.Value);
Assert.AreEqual(expected.ID.Date, actual.ID.Date);
Assert.AreEqual(expected.ID.StrikePrice, actual.ID.StrikePrice);
Assert.AreEqual(expected.ID.OptionRight, actual.ID.OptionRight);
Assert.AreEqual(expected.ID.OptionStyle, actual.ID.OptionStyle);
Assert.AreEqual(expected.Underlying.ID, actual.Underlying.ID);
Assert.AreEqual(expected.Underlying.Value, actual.Underlying.Value);
}
[Test]
public void SurvivesRoundtripSerializationCanonicalOption()
{
var expected = Symbol.Create("SPY", SecurityType.Option, Market.USA);
var json = JsonConvert.SerializeObject(expected, Settings);
var actual = JsonConvert.DeserializeObject<Symbol>(json, Settings);
Assert.AreEqual(expected, actual);
Assert.AreEqual(SecurityIdentifier.DefaultDate, actual.ID.Date);
Assert.AreEqual(0m, actual.ID.StrikePrice);
Assert.AreEqual(default(OptionRight), actual.ID.OptionRight);
Assert.AreEqual(default(OptionStyle), actual.ID.OptionStyle);
Assert.AreNotEqual(default(Symbol), actual.Underlying);
}
[Test]
public void SurvivesRoundtripSerializationWithTypeNameHandling()
{
var sid = SecurityIdentifier.GenerateEquity("SPY", Market.USA);
var expected = new Symbol(sid, "value");
var json = JsonConvert.SerializeObject(expected, Settings);
var actual = JsonConvert.DeserializeObject<Symbol>(json);
Assert.AreEqual(expected, actual);
}
[Test]
public void HandlesListTicks()
{
const string json = @"{'$type':'System.Collections.Generic.List`1[[QuantConnect.Data.BaseData, QuantConnect.Common]], mscorlib',
'$values':[{'$type':'QuantConnect.Data.Market.Tick, QuantConnect.Common',
'TickType':0,'Quantity':1,'Exchange':'',
'SaleCondition':'',
'Suspicious':false,'BidPrice':0.72722,'AskPrice':0.7278,'BidSize':0,'AskSize':0,'LastPrice':0.72722,'DataType':2,'IsFillForward':false,'Time':'2015-09-18T16:52:37.379',
'EndTime':'2015-09-18T16:52:37.379',
'Symbol':{'$type':'QuantConnect.Symbol, QuantConnect.Common',
'Value':'EURGBP',
'ID':'EURGBP 5O'},'Value':0.72722,'Price':0.72722}]}";
var expected = new Symbol(SecurityIdentifier.GenerateForex("EURGBP", Market.FXCM), "EURGBP");
var settings = Settings;
var actual = JsonConvert.DeserializeObject<List<BaseData>>(json, settings);
Assert.AreEqual(expected, actual[0].Symbol);
}
[Test]
public void HandlesListTicksWithDifferentSymbols()
{
// the first serialized Tick object has a Symbol of EURGBP and the second has EURUSD, but the output
const string json =
"{'$type':'System.Collections.Generic.List`1[[QuantConnect.Data.BaseData, QuantConnect.Common]], mscorlib','$values':[" +
"{'$type':'QuantConnect.Data.Market.Tick, QuantConnect.Common'," +
"'TickType':0,'Quantity':1,'Exchange':'','SaleCondition':'','Suspicious':false," +
"'BidPrice':1.11895,'AskPrice':1.11898,'LastPrice':1.11895,'DataType':2,'IsFillForward':false," +
"'Time':'2015-09-22T01:26:44.676','EndTime':'2015-09-22T01:26:44.676'," +
"'Symbol':{'$type':'QuantConnect.Symbol, QuantConnect.Common','Value':'EURUSD', 'ID': 'EURUSD 5O'}," +
"'Value':1.11895,'Price':1.11895}," +
"{'$type':'QuantConnect.Data.Market.Tick, QuantConnect.Common'," +
"'TickType':0,'Quantity':1,'Exchange':'','SaleCondition':'','Suspicious':false," +
"'BidPrice':0.72157,'AskPrice':0.72162,'LastPrice':0.72157,'DataType':2,'IsFillForward':false," +
"'Time':'2015-09-22T01:26:44.675','EndTime':'2015-09-22T01:26:44.675'," +
"'Symbol':{'$type':'QuantConnect.Symbol, QuantConnect.Common','Value':'EURGBP', 'ID': 'EURGBP 5O'}," +
"'Value':0.72157,'Price':0.72157}," +
"]}";
var actual = JsonConvert.DeserializeObject<List<BaseData>>(json, Settings);
Assert.IsFalse(actual.All(x => x.Symbol == new Symbol(SecurityIdentifier.GenerateForex("EURUSD", Market.FXCM), "EURUSD")));
}
[Test]
public void SymbolTypeNameHandling()
{
const string json = @"{'$type':'QuantConnect.Symbol, QuantConnect.Common', 'Value':'EURGBP', 'ID': 'EURGBP 5O'}";
var expected = new Symbol(SecurityIdentifier.GenerateForex("EURGBP", Market.FXCM), "EURGBP");
var actual = JsonConvert.DeserializeObject<Symbol>(json, Settings);
Assert.AreEqual(expected, actual);
}
[Test]
public void TickRoundTrip()
{
var tick = new Tick
{
Symbol = Symbols.EURGBP,
AskPrice = 1,
Time = DateTime.Now,
Exchange = "",
Value = 2,
EndTime = DateTime.Now,
Quantity = 1,
BidPrice = 2,
SaleCondition = ""
};
var json = JsonConvert.SerializeObject(tick, Settings);
var actual = JsonConvert.DeserializeObject<Tick>(json, Settings);
Assert.AreEqual(tick.Symbol, actual.Symbol);
json = JsonConvert.SerializeObject(tick, Settings);
actual = JsonConvert.DeserializeObject<Tick>(json);
Assert.AreEqual(tick.Symbol, actual.Symbol);
}
[Test]
public void BackwardsCompatibleJson()
{
var symbol = new Symbol(SecurityIdentifier.GenerateForex("a", Market.FXCM), "a");
var json = JsonConvert.SerializeObject(symbol, new JsonSerializerSettings { Formatting = Formatting.Indented, TypeNameHandling = TypeNameHandling.All });
var oldSymbol = JsonConvert.DeserializeObject<OldSymbol>(json);
Assert.AreEqual("A", oldSymbol.Value);
Assert.AreEqual("A", oldSymbol.Permtick);
}
[TestCase("{\"value\":\"Fb 210618c00322500\",\"type\":\"2\"}", SecurityType.Option, "FB", OptionRight.Call, OptionStyle.American, 2021)]
[TestCase("{\"value\":\"aapl 210618C00129000\",\"type\":\"2\"}", SecurityType.Option, "AAPL", OptionRight.Call, OptionStyle.American, 2021)]
[TestCase("{\"value\":\"OGV1 C2040\",\"type\":\"8\"}", SecurityType.FutureOption, "GC", OptionRight.Call, OptionStyle.American, 2021)]
[TestCase("{\"value\":\"ESZ30 C3505\",\"type\":\"8\"}", SecurityType.FutureOption, "ES", OptionRight.Call, OptionStyle.American, 2030)]
[TestCase("{\"value\":\"SPXW 210618C04165000\",\"type\":\"10\"}", SecurityType.IndexOption, "SPXW", OptionRight.Call, OptionStyle.American, 2021)]
public void OptionUserFriendlyDeserialization(string jsonValue, SecurityType type, string underlying, OptionRight optionRight, OptionStyle optionStyle, int expirationYear)
{
var symbol = JsonConvert.DeserializeObject<Symbol>(jsonValue);
Assert.IsNotNull(symbol);
Assert.AreEqual(type, symbol.SecurityType);
Assert.AreEqual(underlying, symbol.ID.Underlying.Symbol);
Assert.AreEqual(optionRight, symbol.ID.OptionRight);
Assert.AreEqual(optionStyle, symbol.ID.OptionStyle);
Assert.AreEqual(expirationYear, symbol.ID.Date.Year);
}
[TestCase("{\"value\":\"GCV1\",\"type\":\"5\"}", SecurityType.Future, "GC", 10, Market.COMEX)]
[TestCase("{\"value\":\"ESZ1\",\"type\":\"5\"}", SecurityType.Future, "ES", 12, Market.CME)]
public void FutureUserFriendlyDeserialization(string jsonValue, SecurityType type, string symbolId, int month, string market)
{
var symbol = JsonConvert.DeserializeObject<Symbol>(jsonValue);
Assert.IsNotNull(symbol);
Assert.AreEqual(type, symbol.SecurityType);
Assert.AreEqual(symbolId, symbol.ID.Symbol);
Assert.AreEqual(month, symbol.ID.Date.Month);
Assert.AreEqual(market, symbol.ID.Market);
}
[TestCase("{\"value\":\"fb\",\"type\":\"1\"}", SecurityType.Equity, "FB", Market.USA)]
[TestCase("{\"value\":\"AAPL\",\"type\":\"1\"}", SecurityType.Equity, "AAPL", Market.USA)]
[TestCase("{\"value\":\"BTCUSD\",\"type\":\"7\",\"market\":\"gdax\"}", SecurityType.Crypto, "BTCUSD", Market.GDAX)]
[TestCase("{\"value\":\"BTCUSD\",\"type\":\"7\",\"market\":\"binance\"}", SecurityType.Crypto, "BTCUSD", Market.Binance)]
[TestCase("{\"value\":\"xauusd\",\"type\":\"6\",\"market\":\"oanda\"}", SecurityType.Cfd, "XAUUSD", Market.Oanda)]
[TestCase("{\"value\":\"eurusd\",\"type\":\"4\",\"market\":\"oanda\"}", SecurityType.Forex, "EURUSD", Market.Oanda)]
public void UserFriendlyDeserialization(string jsonValue, SecurityType type, string symbolTicker, string market)
{
var symbol = JsonConvert.DeserializeObject<Symbol>(jsonValue);
Assert.IsNotNull(symbol);
Assert.AreEqual(type, symbol.SecurityType);
Assert.AreEqual(symbolTicker, symbol.ID.Symbol);
Assert.AreEqual(market, symbol.ID.Market);
}
class OldSymbol
{
public string Value { get; set; }
public string Permtick { 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.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.CryptographicException))]
namespace System.Security.Cryptography
{
public abstract partial class AsymmetricAlgorithm : System.IDisposable
{
protected int KeySizeValue;
protected System.Security.Cryptography.KeySizes[] LegalKeySizesValue;
protected AsymmetricAlgorithm() { }
public virtual string KeyExchangeAlgorithm { get { throw null; } }
public virtual int KeySize { get { throw null; } set { } }
public virtual System.Security.Cryptography.KeySizes[] LegalKeySizes { get { throw null; } }
public virtual string SignatureAlgorithm { get { throw null; } }
public void Clear() { }
public static System.Security.Cryptography.AsymmetricAlgorithm Create() { throw null; }
public static System.Security.Cryptography.AsymmetricAlgorithm Create(string algName) { throw null; }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public virtual void FromXmlString(string xmlString) { }
public virtual string ToXmlString(bool includePrivateParameters) { throw null; }
}
public enum CipherMode
{
CBC = 1,
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
CFB = 4,
CTS = 5,
ECB = 2,
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
OFB = 3,
}
public static partial class CryptographicOperations
{
public static bool FixedTimeEquals(System.ReadOnlySpan<byte> left, System.ReadOnlySpan<byte> right) => throw null;
public static void ZeroMemory(System.Span<byte> buffer) => throw null;
}
public partial class CryptographicUnexpectedOperationException : System.Security.Cryptography.CryptographicException
{
public CryptographicUnexpectedOperationException() { }
protected CryptographicUnexpectedOperationException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public CryptographicUnexpectedOperationException(string message) { }
public CryptographicUnexpectedOperationException(string message, System.Exception inner) { }
public CryptographicUnexpectedOperationException(string format, string insert) { }
}
public partial class CryptoStream : System.IO.Stream, System.IDisposable
{
public CryptoStream(System.IO.Stream stream, System.Security.Cryptography.ICryptoTransform transform, System.Security.Cryptography.CryptoStreamMode mode) { }
public CryptoStream(System.IO.Stream stream, System.Security.Cryptography.ICryptoTransform transform, System.Security.Cryptography.CryptoStreamMode mode, bool leaveOpen) { }
public override bool CanRead { get { throw null; } }
public override bool CanSeek { get { throw null; } }
public override bool CanWrite { get { throw null; } }
public bool HasFlushedFinalBlock { get { throw null; } }
public override long Length { get { throw null; } }
public override long Position { get { throw null; } set { } }
public override System.IAsyncResult BeginRead(byte[] buffer, int offset, int count, System.AsyncCallback callback, object state) { throw null; }
public override System.IAsyncResult BeginWrite(byte[] buffer, int offset, int count, System.AsyncCallback callback, object state) { throw null; }
public void Clear() { }
protected override void Dispose(bool disposing) { }
public override int EndRead(System.IAsyncResult asyncResult) { throw null; }
public override void EndWrite(System.IAsyncResult asyncResult) { }
public override void Flush() { }
public override System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken) { throw null; }
public void FlushFinalBlock() { }
public override int Read(byte[] buffer, int offset, int count) { throw null; }
public override System.Threading.Tasks.Task<int> ReadAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { throw null; }
public override int ReadByte() { throw null; }
public override long Seek(long offset, System.IO.SeekOrigin origin) { throw null; }
public override void SetLength(long value) { }
public override void Write(byte[] buffer, int offset, int count) { }
public override System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { throw null; }
public override void WriteByte(byte value) { }
}
public enum CryptoStreamMode
{
Read = 0,
Write = 1,
}
public abstract partial class HashAlgorithm : System.IDisposable, System.Security.Cryptography.ICryptoTransform
{
protected int HashSizeValue;
protected internal byte[] HashValue;
protected int State;
protected HashAlgorithm() { }
public virtual bool CanReuseTransform { get { throw null; } }
public virtual bool CanTransformMultipleBlocks { get { throw null; } }
public virtual byte[] Hash { get { throw null; } }
public virtual int HashSize { get { throw null; } }
public virtual int InputBlockSize { get { throw null; } }
public virtual int OutputBlockSize { get { throw null; } }
public void Clear() { }
public byte[] ComputeHash(byte[] buffer) { throw null; }
public byte[] ComputeHash(byte[] buffer, int offset, int count) { throw null; }
public byte[] ComputeHash(System.IO.Stream inputStream) { throw null; }
public static System.Security.Cryptography.HashAlgorithm Create() { throw null; }
public static System.Security.Cryptography.HashAlgorithm Create(string hashName) { throw null; }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
protected abstract void HashCore(byte[] array, int ibStart, int cbSize);
protected virtual void HashCore(System.ReadOnlySpan<byte> source) { }
protected abstract byte[] HashFinal();
public abstract void Initialize();
public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { throw null; }
public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { throw null; }
public bool TryComputeHash(System.ReadOnlySpan<byte> source, System.Span<byte> destination, out int bytesWritten) { throw null; }
protected virtual bool TryHashFinal(System.Span<byte> destination, out int bytesWritten) { throw null; }
}
public readonly partial struct HashAlgorithmName : System.IEquatable<System.Security.Cryptography.HashAlgorithmName>
{
private readonly object _dummy;
public HashAlgorithmName(string name) { throw null; }
public static System.Security.Cryptography.HashAlgorithmName MD5 { get { throw null; } }
public string Name { get { throw null; } }
public static System.Security.Cryptography.HashAlgorithmName SHA1 { get { throw null; } }
public static System.Security.Cryptography.HashAlgorithmName SHA256 { get { throw null; } }
public static System.Security.Cryptography.HashAlgorithmName SHA384 { get { throw null; } }
public static System.Security.Cryptography.HashAlgorithmName SHA512 { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public bool Equals(System.Security.Cryptography.HashAlgorithmName other) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(System.Security.Cryptography.HashAlgorithmName left, System.Security.Cryptography.HashAlgorithmName right) { throw null; }
public static bool operator !=(System.Security.Cryptography.HashAlgorithmName left, System.Security.Cryptography.HashAlgorithmName right) { throw null; }
public override string ToString() { throw null; }
}
public abstract partial class HMAC : System.Security.Cryptography.KeyedHashAlgorithm
{
protected HMAC() { }
protected int BlockSizeValue { get { throw null; } set { } }
public string HashName { get { throw null; } set { } }
public override byte[] Key { get { throw null; } set { } }
public static new System.Security.Cryptography.HMAC Create() { throw null; }
public static new System.Security.Cryptography.HMAC Create(string algorithmName) { throw null; }
protected override void Dispose(bool disposing) { }
protected override void HashCore(byte[] rgb, int ib, int cb) { }
protected override void HashCore(System.ReadOnlySpan<byte> source) { }
protected override byte[] HashFinal() { throw null; }
public override void Initialize() { }
protected override bool TryHashFinal(System.Span<byte> destination, out int bytesWritten) { throw null; }
}
public partial interface ICryptoTransform : System.IDisposable
{
bool CanReuseTransform { get; }
bool CanTransformMultipleBlocks { get; }
int InputBlockSize { get; }
int OutputBlockSize { get; }
int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset);
byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount);
}
public abstract partial class KeyedHashAlgorithm : System.Security.Cryptography.HashAlgorithm
{
protected byte[] KeyValue;
protected KeyedHashAlgorithm() { }
public virtual byte[] Key { get { throw null; } set { } }
public static new System.Security.Cryptography.KeyedHashAlgorithm Create() { throw null; }
public static new System.Security.Cryptography.KeyedHashAlgorithm Create(string algName) { throw null; }
protected override void Dispose(bool disposing) { }
}
public sealed partial class KeySizes
{
public KeySizes(int minSize, int maxSize, int skipSize) { }
public int MaxSize { get { throw null; } }
public int MinSize { get { throw null; } }
public int SkipSize { get { throw null; } }
}
public enum PaddingMode
{
ANSIX923 = 4,
ISO10126 = 5,
None = 1,
PKCS7 = 2,
Zeros = 3,
}
public abstract partial class SymmetricAlgorithm : System.IDisposable
{
protected int BlockSizeValue;
protected int FeedbackSizeValue;
protected byte[] IVValue;
protected int KeySizeValue;
protected byte[] KeyValue;
protected System.Security.Cryptography.KeySizes[] LegalBlockSizesValue;
protected System.Security.Cryptography.KeySizes[] LegalKeySizesValue;
protected System.Security.Cryptography.CipherMode ModeValue;
protected System.Security.Cryptography.PaddingMode PaddingValue;
protected SymmetricAlgorithm() { }
public virtual int BlockSize { get { throw null; } set { } }
public virtual int FeedbackSize { get { throw null; } set { } }
public virtual byte[] IV { get { throw null; } set { } }
public virtual byte[] Key { get { throw null; } set { } }
public virtual int KeySize { get { throw null; } set { } }
public virtual System.Security.Cryptography.KeySizes[] LegalBlockSizes { get { throw null; } }
public virtual System.Security.Cryptography.KeySizes[] LegalKeySizes { get { throw null; } }
public virtual System.Security.Cryptography.CipherMode Mode { get { throw null; } set { } }
public virtual System.Security.Cryptography.PaddingMode Padding { get { throw null; } set { } }
public void Clear() { }
public static System.Security.Cryptography.SymmetricAlgorithm Create() { throw null; }
public static System.Security.Cryptography.SymmetricAlgorithm Create(string algName) { throw null; }
public virtual System.Security.Cryptography.ICryptoTransform CreateDecryptor() { throw null; }
public abstract System.Security.Cryptography.ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV);
public virtual System.Security.Cryptography.ICryptoTransform CreateEncryptor() { throw null; }
public abstract System.Security.Cryptography.ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV);
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public abstract void GenerateIV();
public abstract void GenerateKey();
public bool ValidKeySize(int bitLength) { throw null; }
}
}
| |
namespace FakeItEasy.Tests.Configuration
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using FakeItEasy.Configuration;
using FakeItEasy.Core;
using FakeItEasy.Tests;
using FakeItEasy.Tests.TestHelpers;
using FluentAssertions;
using Xunit;
public class RuleBuilderTests
{
private readonly RuleBuilder builder;
private readonly FakeManager fakeManager;
private readonly IFakeAsserter asserter;
private readonly BuildableCallRule ruleProducedByFactory;
public RuleBuilderTests()
{
this.asserter = A.Fake<IFakeAsserter>();
this.ruleProducedByFactory = A.Fake<BuildableCallRule>();
this.fakeManager = new FakeManager(typeof(object), new object(), null);
this.builder = this.CreateBuilder();
}
public static IEnumerable<object?[]> BehaviorDefinitionActionsForVoid =>
TestCases.FromObject<Action<IVoidArgumentValidationConfiguration>>(
configuration => configuration.CallsBaseMethod(),
configuration => configuration.DoesNothing(),
configuration => configuration.Throws<Exception>(),
configuration => configuration.Invokes(DoNothing),
configuration => configuration.AssignsOutAndRefParametersLazily(_ => Array.Empty<object>()));
public static IEnumerable<object?[]> BehaviorDefinitionActionsForNonVoid =>
TestCases.FromObject<Action<IAnyCallConfigurationWithReturnTypeSpecified<int>>>(
configuration => configuration.CallsBaseMethod(),
configuration => configuration.Throws<Exception>(),
configuration => configuration.Invokes(DoNothing),
configuration => configuration.ReturnsLazily(_ => 0));
public static IEnumerable<object?[]> CallSpecificationActionsForNonVoid =>
TestCases.FromObject<Action<IAnyCallConfigurationWithReturnTypeSpecified<int>>>(
configuration => configuration.WhenArgumentsMatch(args => true),
configuration => configuration.Where(call => true));
public static IEnumerable<object?[]> CallSpecificationActionsForVoid =>
TestCases.FromObject<Action<IVoidArgumentValidationConfiguration>>(
configuration => configuration.WhenArgumentsMatch(args => true));
[Fact]
public void Returns_with_call_function_should_be_properly_guarded()
{
var config = this.CreateTestableReturnConfiguration();
Expression<Action> call = () => config.ReturnsLazily(x => x.Arguments.Get<int>(0));
call.Should().BeNullGuarded();
}
[Fact]
public void NumberOfTimes_sets_number_of_times_to_interceptor()
{
this.builder.NumberOfTimes(10);
this.builder.RuleBeingBuilt.NumberOfTimesToCall.Should().Be(10);
}
[Theory]
[InlineData(0)]
[InlineData(-1)]
[InlineData(-100)]
[InlineData(int.MinValue)]
public void NumberOfTimes_throws_when_number_of_times_is_not_a_positive_integer(int numberOfTimes)
{
var exception = Record.Exception(() =>
this.builder.NumberOfTimes(numberOfTimes));
exception.Should().BeAnExceptionOfType<ArgumentOutOfRangeException>();
}
[Fact]
public void Invokes_should_add_action_to_list_of_actions()
{
Action<IFakeObjectCall> action = x => { };
this.builder.Invokes(action);
A.CallTo(() => this.builder.RuleBeingBuilt.Actions.Add(action)).MustHaveHappened();
}
[Fact]
public void Invokes_should_be_null_guarded()
{
Action<IFakeObjectCall> action = x => { };
Expression<Action> call = () => this.builder.Invokes(action);
call.Should().BeNullGuarded();
}
[Fact]
public void Invokes_on_return_value_configuration_should_add_action_to_list_of_actions()
{
var returnConfig = this.CreateTestableReturnConfiguration();
Action<IFakeObjectCall> action = x => { };
returnConfig.Invokes(action);
A.CallTo(() => this.builder.RuleBeingBuilt.Actions.Add(action)).MustHaveHappened();
}
[Fact]
public void Invokes_on_return_value_configuration_should_be_null_guarded()
{
var returnConfig = this.CreateTestableReturnConfiguration();
Action<IFakeObjectCall> action = x => { };
Expression<Action> call = () => returnConfig.Invokes(action);
call.Should().BeNullGuarded();
}
[Fact]
public void CallsBaseMethod_sets_CallBaseMethod_to_true_on_the_built_rule()
{
this.builder.CallsBaseMethod();
this.builder.RuleBeingBuilt.CallBaseMethod.Should().BeTrue();
}
[Fact]
public void CallsBaseMethod_for_function_calls_sets_CallBaseMethod_to_true_on_the_built_rule()
{
var config = this.CreateTestableReturnConfiguration();
config.CallsBaseMethod();
this.builder.RuleBeingBuilt.CallBaseMethod.Should().BeTrue();
}
[Fact]
public void WhenArgumentsMatches_should_call_UsePredicateToValidateArguments_on_built_rule()
{
Func<ArgumentCollection, bool> predicate = x => true;
var builtRule = A.Fake<BuildableCallRule>();
var config = this.CreateBuilder(builtRule);
config.WhenArgumentsMatch(predicate);
A.CallTo(() => builtRule.UsePredicateToValidateArguments(predicate)).MustHaveHappened();
}
[Fact]
public void WhenArgumentsMatches_should_be_null_guarded()
{
var builtRule = A.Fake<BuildableCallRule>();
var config = this.CreateBuilder(builtRule);
Expression<Action> call = () => config.WhenArgumentsMatch(x => true);
call.Should().BeNullGuarded();
}
[Fact]
public void WhenArgumentsMatches_with_function_call_should_call_UsePredicateToValidateArguments_on_built_rule()
{
var builtRule = A.Fake<BuildableCallRule>();
var config = this.CreateBuilder(builtRule);
var returnConfig = new RuleBuilder.ReturnValueConfiguration<bool>(config);
Func<ArgumentCollection, bool> predicate = x => true;
returnConfig.WhenArgumentsMatch(predicate);
A.CallTo(() => builtRule.UsePredicateToValidateArguments(predicate)).MustHaveHappened();
}
[Fact]
public void WhenArgumentsMatches_with_function_call_should_be_null_guarded()
{
var returnConfig = this.CreateTestableReturnConfiguration();
Expression<Action> call = () => returnConfig.WhenArgumentsMatch(x => true);
call.Should().BeNullGuarded();
}
[Fact]
public void AssignsOutAndRefParameters_should_be_null_guarded()
{
Expression<Action> call = () => this.builder.AssignsOutAndRefParameters();
call.Should().BeNullGuarded();
}
[Fact]
public void AssignsOutAndRefParametersLazily_should_be_null_guarded()
{
Expression<Action> call = () =>
this.builder.AssignsOutAndRefParametersLazily(A.Dummy<Func<object, object?[]>>());
call.Should().BeNullGuarded();
}
[Fact]
public void Where_should_apply_where_predicate_to_built_rule()
{
// Arrange
Func<IFakeObjectCall, bool> predicate = x => true;
Action<IOutputWriter> writer = x => { };
var returnConfig = new RuleBuilder.ReturnValueConfiguration<int>(this.builder);
// Act
returnConfig.Where(predicate, writer);
// Assert
A.CallTo(() => this.ruleProducedByFactory.ApplyWherePredicate(predicate, writer)).MustHaveHappened();
}
[Theory]
[MemberData(nameof(CallSpecificationActionsForVoid))]
public void Call_specification_method_for_void_should_not_add_rule_to_manager(Action<IVoidArgumentValidationConfiguration> configurationAction)
{
// Arrange
var initialRules = this.fakeManager.Rules.ToList();
// Act
configurationAction(this.builder);
// Assert
this.fakeManager.Rules.Should().Equal(initialRules);
}
[Theory]
[MemberData(nameof(CallSpecificationActionsForNonVoid))]
public void Call_specification_method_for_non_void_should_not_add_rule_to_manager(Action<IAnyCallConfigurationWithReturnTypeSpecified<int>> configurationAction)
{
// Arrange
var initialRules = this.fakeManager.Rules.ToList();
var returnConfig = this.CreateTestableReturnConfiguration();
// Act
configurationAction(returnConfig);
// Assert
this.fakeManager.Rules.Should().Equal(initialRules);
}
[Theory]
[MemberData(nameof(BehaviorDefinitionActionsForVoid))]
public void Behavior_definition_method_for_void_should_add_rule_to_manager(Action<IVoidArgumentValidationConfiguration> configurationAction)
{
// Arrange
var initialRules = this.fakeManager.Rules.ToList();
// Act
configurationAction(this.builder);
// Assert
this.fakeManager.Rules.Should().Equal(new[] { this.ruleProducedByFactory }.Concat(initialRules));
}
[Theory]
[MemberData(nameof(BehaviorDefinitionActionsForNonVoid))]
public void Behavior_definition_method_for_non_void_should_add_rule_to_manager(Action<IAnyCallConfigurationWithReturnTypeSpecified<int>> configurationAction)
{
// Arrange
var initialRules = this.fakeManager.Rules.ToList();
var returnConfig = this.CreateTestableReturnConfiguration();
// Act
configurationAction(returnConfig);
// Assert
this.fakeManager.Rules.Should().Equal(new[] { this.ruleProducedByFactory }.Concat(initialRules));
}
private static void DoNothing()
{
}
private RuleBuilder CreateBuilder()
{
return this.CreateBuilder(this.ruleProducedByFactory);
}
private RuleBuilder CreateBuilder(BuildableCallRule ruleBeingBuilt)
{
return new RuleBuilder(ruleBeingBuilt, this.fakeManager, (x, y) => this.asserter);
}
private RuleBuilder.ReturnValueConfiguration<int> CreateTestableReturnConfiguration()
{
return new RuleBuilder.ReturnValueConfiguration<int>(this.builder);
}
}
}
| |
// 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.Collections.Generic;
using System.Drawing;
namespace DotSpatial.Controls
{
/// <summary>
/// Southerland Hodgman polygon clipper.
/// </summary>
public class SoutherlandHodgman
{
#region Fields
private const int BoundBottom = 3;
private const int BoundLeft = 2;
private const int BoundRight = 0;
private const int BoundTop = 1;
private const int X = 0;
private const int Y = 1;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="SoutherlandHodgman"/> class.
/// </summary>
/// <param name="clipRect">The clipping rectangle.</param>
public SoutherlandHodgman(Rectangle clipRect)
{
ClippingRectangle = clipRect;
}
/// <summary>
/// Initializes a new instance of the <see cref="SoutherlandHodgman"/> class with a default clipping rectangle of -32000|64000 in both directions.
/// </summary>
public SoutherlandHodgman()
{
ClippingRectangle = new Rectangle(-32000, -32000, 64000, 64000);
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the clipping rectangle used in subsequent Clip calls.
/// </summary>
public Rectangle ClippingRectangle { get; set; }
#endregion
#region Methods
/// <summary>
/// Calculates the Southerland-Hodgman clip using the actual drawing coordinates.
/// This hopefully will be much faster than NTS which seems unncessarilly slow to calculate.
/// http://www.codeguru.com/cpp/misc/misc/graphics/article.php/c8965.
/// </summary>
/// <param name="points">Points that get clipped.</param>
/// <returns>A modified list of points that has been clipped to the drawing bounds.</returns>
public List<PointF> Clip(List<PointF> points)
{
List<PointF> result = points;
for (int direction = 0; direction < 4; direction++)
{
result = ClipDirection(result, direction);
}
return result;
}
/// <summary>
/// Calculates the Southerland-Hodgman clip using the actual drawing coordinates.
/// This specific overload works with arrays of doubles instead of PointF structures.
/// This hopefully will be much faster than NTS which seems unncessarilly slow to calculate.
/// http://www.codeguru.com/cpp/misc/misc/graphics/article.php/c8965.
/// </summary>
/// <param name="vertexValues">The list of arrays of doubles where the X index is 0 and the Y index is 1.</param>
/// <returns>A modified list of points that has been clipped to the drawing bounds.</returns>
public List<double[]> Clip(List<double[]> vertexValues)
{
List<double[]> result = vertexValues;
for (int direction = 0; direction < 4; direction++)
{
result = ClipDirection(result, direction);
}
return result;
}
private PointF BoundIntersection(PointF start, PointF end, int direction)
{
PointF result = default(PointF);
switch (direction)
{
case BoundRight:
result.X = ClippingRectangle.Right;
result.Y = start.Y + ((end.Y - start.Y) * (ClippingRectangle.Right - start.X) / (end.X - start.X));
break;
case BoundLeft:
result.X = ClippingRectangle.Left;
result.Y = start.Y + ((end.Y - start.Y) * (ClippingRectangle.Left - start.X) / (end.X - start.X));
break;
case BoundTop:
result.Y = ClippingRectangle.Top;
result.X = start.X + ((end.X - start.X) * (ClippingRectangle.Top - start.Y) / (end.Y - start.Y));
break;
case BoundBottom:
result.Y = ClippingRectangle.Bottom;
result.X = start.X + ((end.X - start.X) * (ClippingRectangle.Bottom - start.Y) / (end.Y - start.Y));
break;
}
return result;
}
private double[] BoundIntersection(double[] start, double[] end, int direction)
{
double[] result = new double[2];
switch (direction)
{
case BoundRight:
result[X] = ClippingRectangle.Right;
result[Y] = start[Y] + ((end[Y] - start[Y]) * (ClippingRectangle.Right - start[X]) / (end[X] - start[X]));
break;
case BoundLeft:
result[X] = ClippingRectangle.Left;
result[Y] = start[Y] + ((end[Y] - start[Y]) * (ClippingRectangle.Left - start[X]) / (end[X] - start[X]));
break;
case BoundTop:
result[Y] = ClippingRectangle.Top;
result[X] = start[X] + ((end[X] - start[X]) * (ClippingRectangle.Top - start[Y]) / (end[Y] - start[Y]));
break;
case BoundBottom:
result[Y] = ClippingRectangle.Bottom;
result[X] = start[X] + ((end[X] - start[X]) * (ClippingRectangle.Bottom - start[Y]) / (end[Y] - start[Y]));
break;
}
return result;
}
private List<PointF> ClipDirection(IEnumerable<PointF> points, int direction)
{
bool previousInside = true;
List<PointF> result = new List<PointF>();
PointF previous = PointF.Empty;
foreach (PointF point in points)
{
bool inside = IsInside(point, direction);
if (previousInside && inside)
{
// both points are inside, so simply add the current point
result.Add(point);
previous = point;
}
if (previousInside && !inside)
{
if (!previous.IsEmpty)
{
// crossing the boundary going out, so insert the intersection instead
result.Add(BoundIntersection(previous, point, direction));
}
previous = point;
}
if (!previousInside && inside)
{
// crossing the boundary going in, so insert the intersection AND the new point
result.Add(BoundIntersection(previous, point, direction));
result.Add(point);
previous = point;
}
if (!previousInside && !inside)
{
previous = point;
}
previousInside = inside;
}
// be sure to close the polygon if it is not closed
if (result.Count > 0)
{
if (result[0].X != result[result.Count - 1].X || result[0].Y != result[result.Count - 1].Y)
{
result.Add(new PointF(result[0].X, result[0].Y));
}
}
return result;
}
private List<double[]> ClipDirection(IEnumerable<double[]> points, int direction)
{
bool previousInside = true;
List<double[]> result = new List<double[]>();
double[] previous = new double[2];
bool isFirst = true;
foreach (double[] point in points)
{
bool inside = IsInside(point, direction);
if (previousInside && inside)
{
// both points are inside, so simply add the current point
result.Add(point);
previous = point;
}
if (previousInside && !inside)
{
if (!isFirst)
{
// crossing the boundary going out, so insert the intersection instead
result.Add(BoundIntersection(previous, point, direction));
}
previous = point;
}
if (!previousInside && inside)
{
// crossing the boundary going in, so insert the intersection AND the new point
result.Add(BoundIntersection(previous, point, direction));
result.Add(point);
previous = point;
}
if (!previousInside && !inside)
{
previous = point;
}
isFirst = false;
previousInside = inside;
}
// be sure to close the polygon if it is not closed
if (result.Count > 0)
{
if (result[0][X] != result[result.Count - 1][X] || result[0][Y] != result[result.Count - 1][Y])
{
result.Add(new[] { result[0][X], result[0][Y] });
}
}
return result;
}
private bool IsInside(PointF point, int direction)
{
switch (direction)
{
case BoundRight:
if (point.X <= ClippingRectangle.Right) return true;
return false;
case BoundLeft:
if (point.X >= ClippingRectangle.Left) return true;
return false;
case BoundTop:
if (point.Y >= ClippingRectangle.Top) return true;
return false;
case BoundBottom:
if (point.Y <= ClippingRectangle.Bottom) return true;
return false;
}
return false;
}
private bool IsInside(double[] point, int direction)
{
switch (direction)
{
case BoundRight:
if (point[X] <= ClippingRectangle.Right) return true;
return false;
case BoundLeft:
if (point[X] >= ClippingRectangle.Left) return true;
return false;
case BoundTop:
if (point[Y] >= ClippingRectangle.Top) return true;
return false;
case BoundBottom:
if (point[Y] <= ClippingRectangle.Bottom) return true;
return false;
}
return false;
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Microsoft.NetCore.Analyzers.InteropServices.RuntimePlatformCheckAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
namespace Microsoft.NetCore.Analyzers.InteropServices.UnitTests
{
public class RuntimePlatformCheckAnalyzerTests
{
private readonly string PlatformCheckApiSource = @"
namespace System.Runtime.InteropServices
{
public class RuntimeInformationHelper
{
public static bool IsOSPlatformOrLater(OSPlatform osPlatform, int major) => true;
public static bool IsOSPlatformOrLater(OSPlatform osPlatform, int major, int minor) => true;
public static bool IsOSPlatformOrLater(OSPlatform osPlatform, int major, int minor, int build) => true;
public static bool IsOSPlatformOrLater(OSPlatform osPlatform, int major, int minor, int build, int revision) => true;
public static bool IsOSPlatformEarlierThan(OSPlatform osPlatform, int major) => true;
public static bool IsOSPlatformEarlierThan(OSPlatform osPlatform, int major, int minor) => true;
public static bool IsOSPlatformEarlierThan(OSPlatform osPlatform, int major, int minor, int build) => true;
public static bool IsOSPlatformEarlierThan(OSPlatform osPlatform, int major, int minor, int build, int revision) => true;
}
}";
[Fact]
public async Task SimpleIfTest()
{
var source = @"
using System.Diagnostics;
using System.Runtime.InteropServices;
class Test
{
void M1()
{
{|#0:M2()|}; // Platform checks:''
if(RuntimeInformationHelper.IsOSPlatformOrLater(OSPlatform.Windows, 1))
{
{|#1:M2()|}; // Platform checks:'IsOSPlatformOrLater;Windows;1'
}
if(RuntimeInformationHelper.IsOSPlatformEarlierThan(OSPlatform.Windows, 1, 1))
{
{|#2:M2()|}; // Platform checks:'IsOSPlatformEarlierThan;Windows;1.1'
}
{|#3:M2()|}; // Platform checks:''
}
void M2()
{
}
}" + PlatformCheckApiSource;
await VerifyCS.VerifyAnalyzerAsync(source,
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(0).WithArguments(""),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(1).WithArguments("IsOSPlatformOrLater;Windows;1"),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(2).WithArguments("IsOSPlatformEarlierThan;Windows;1.1"),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(3).WithArguments(""));
}
[Fact]
public async Task SimpleIfTest_02()
{
var source = @"
using System.Diagnostics;
using System.Runtime.InteropServices;
class Test
{
void M1()
{
if(RuntimeInformationHelper.IsOSPlatformOrLater(OSPlatform.Windows, 1))
{
{|#0:M2()|}; // Platform checks:'IsOSPlatformOrLater;Windows;1'
}
if(RuntimeInformationHelper.IsOSPlatformEarlierThan(OSPlatform.Windows, 1, 1))
{
{|#1:M2()|}; // Platform checks:'IsOSPlatformEarlierThan;Windows;1.1'
}
{|#2:M2()|}; // Platform checks:''
}
void M2()
{
}
}" + PlatformCheckApiSource;
await VerifyCS.VerifyAnalyzerAsync(source,
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(0).WithArguments("IsOSPlatformOrLater;Windows;1"),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(1).WithArguments("IsOSPlatformEarlierThan;Windows;1.1"),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(2).WithArguments(""));
}
[Fact]
public async Task SimpleIfElseTest()
{
var source = @"
using System.Diagnostics;
using System.Runtime.InteropServices;
class Test
{
void M1()
{
{|#0:M2()|}; // Platform checks:''
if(RuntimeInformationHelper.IsOSPlatformOrLater(OSPlatform.Windows, 1))
{
{|#1:M2()|}; // Platform checks:'IsOSPlatformOrLater;Windows;1'
}
else
{
{|#2:M2()|}; // Platform checks:'!IsOSPlatformOrLater;Windows;1'
}
{|#3:M2()|}; // Platform checks:''
}
void M2()
{
}
}" + PlatformCheckApiSource;
await VerifyCS.VerifyAnalyzerAsync(source,
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(0).WithArguments(""),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(1).WithArguments("IsOSPlatformOrLater;Windows;1"),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(2).WithArguments("!IsOSPlatformOrLater;Windows;1"),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(3).WithArguments(""));
}
[Fact]
public async Task SimpleIfElseIfElseTest()
{
var source = @"
using System.Diagnostics;
using System.Runtime.InteropServices;
class Test
{
void M1()
{
{|#0:M2()|}; // Platform checks:''
if(RuntimeInformationHelper.IsOSPlatformOrLater(OSPlatform.Windows, 1))
{
{|#1:M2()|}; // Platform checks:'IsOSPlatformOrLater;Windows;1'
}
else if(RuntimeInformationHelper.IsOSPlatformEarlierThan(OSPlatform.Linux, 1, 1))
{
{|#2:M2()|}; // Platform checks:'!IsOSPlatformOrLater;Windows;1 && IsOSPlatformEarlierThan;Linux;1.1'
}
else
{
{|#3:M2()|}; // Platform checks:'!IsOSPlatformEarlierThan;Linux;1.1 && !IsOSPlatformOrLater;Windows;1'
}
{|#4:M2()|}; // Platform checks:''
}
void M2()
{
}
}" + PlatformCheckApiSource;
await VerifyCS.VerifyAnalyzerAsync(source,
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(0).WithArguments(""),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(1).WithArguments("IsOSPlatformOrLater;Windows;1"),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(2).WithArguments("!IsOSPlatformOrLater;Windows;1 && IsOSPlatformEarlierThan;Linux;1.1"),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(3).WithArguments("!IsOSPlatformEarlierThan;Linux;1.1 && !IsOSPlatformOrLater;Windows;1"),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(4).WithArguments(""));
}
[Fact]
public async Task SimpleIfTestWithNegation()
{
var source = @"
using System.Diagnostics;
using System.Runtime.InteropServices;
class Test
{
void M1()
{
{|#0:M2()|}; // Platform checks:''
if(!RuntimeInformationHelper.IsOSPlatformOrLater(OSPlatform.Windows, 1))
{
{|#1:M2()|}; // Platform checks:'!IsOSPlatformOrLater;Windows;1'
}
if(!RuntimeInformationHelper.IsOSPlatformEarlierThan(OSPlatform.Windows, 1, 1))
{
{|#2:M2()|}; // Platform checks:'!IsOSPlatformEarlierThan;Windows;1.1'
}
{|#3:M2()|}; // Platform checks:''
}
void M2()
{
}
}" + PlatformCheckApiSource;
await VerifyCS.VerifyAnalyzerAsync(source,
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(0).WithArguments(""),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(1).WithArguments("!IsOSPlatformOrLater;Windows;1"),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(2).WithArguments("!IsOSPlatformEarlierThan;Windows;1.1"),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(3).WithArguments(""));
}
[Fact]
public async Task SimpleIfElseTestWithNegation()
{
var source = @"
using System.Diagnostics;
using System.Runtime.InteropServices;
class Test
{
void M1()
{
{|#0:M2()|}; // Platform checks:''
if(!RuntimeInformationHelper.IsOSPlatformOrLater(OSPlatform.Windows, 1))
{
{|#1:M2()|}; // Platform checks:'!IsOSPlatformOrLater;Windows;1'
}
else
{
{|#2:M2()|}; // Platform checks:'IsOSPlatformOrLater;Windows;1'
}
{|#3:M2()|}; // Platform checks:''
}
void M2()
{
}
}" + PlatformCheckApiSource;
await VerifyCS.VerifyAnalyzerAsync(source,
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(0).WithArguments(""),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(1).WithArguments("!IsOSPlatformOrLater;Windows;1"),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(2).WithArguments("IsOSPlatformOrLater;Windows;1"),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(3).WithArguments(""));
}
[Fact]
public async Task SimpleIfElseIfElseTestWithNegation()
{
var source = @"
using System.Diagnostics;
using System.Runtime.InteropServices;
class Test
{
void M1()
{
{|#0:M2()|}; // Platform checks:''
if(!RuntimeInformationHelper.IsOSPlatformOrLater(OSPlatform.Windows, 1))
{
{|#1:M2()|}; // Platform checks:'!IsOSPlatformOrLater;Windows;1'
}
else if(RuntimeInformationHelper.IsOSPlatformEarlierThan(OSPlatform.Linux, 1, 1))
{
{|#2:M2()|}; // Platform checks:'IsOSPlatformEarlierThan;Linux;1.1 && IsOSPlatformOrLater;Windows;1'
}
else
{
{|#3:M2()|}; // Platform checks:'!IsOSPlatformEarlierThan;Linux;1.1 && IsOSPlatformOrLater;Windows;1'
}
{|#4:M2()|}; // Platform checks:''
}
void M2()
{
}
}" + PlatformCheckApiSource;
await VerifyCS.VerifyAnalyzerAsync(source,
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(0).WithArguments(""),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(1).WithArguments("!IsOSPlatformOrLater;Windows;1"),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(2).WithArguments("IsOSPlatformEarlierThan;Linux;1.1 && IsOSPlatformOrLater;Windows;1"),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(3).WithArguments("!IsOSPlatformEarlierThan;Linux;1.1 && IsOSPlatformOrLater;Windows;1"),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(4).WithArguments(""));
}
[Fact]
public async Task SimpleIfTestWithLogicalAnd()
{
var source = @"
using System.Diagnostics;
using System.Runtime.InteropServices;
class Test
{
void M1()
{
{|#0:M2()|}; // Platform checks:''
if(RuntimeInformationHelper.IsOSPlatformOrLater(OSPlatform.Windows, 1) &&
RuntimeInformationHelper.IsOSPlatformEarlierThan(OSPlatform.Windows, 2))
{
{|#1:M2()|}; // Platform checks:'IsOSPlatformEarlierThan;Windows;2 && IsOSPlatformOrLater;Windows;1'
}
{|#2:M2()|}; // Platform checks:''
}
void M2()
{
}
}" + PlatformCheckApiSource;
await VerifyCS.VerifyAnalyzerAsync(source,
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(0).WithArguments(""),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(1).WithArguments("IsOSPlatformEarlierThan;Windows;2 && IsOSPlatformOrLater;Windows;1"),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(2).WithArguments(""));
}
[Fact]
public async Task SimpleIfElseTestWithLogicalAnd()
{
var source = @"
using System.Diagnostics;
using System.Runtime.InteropServices;
class Test
{
void M1()
{
{|#0:M2()|}; // Platform checks:''
if(RuntimeInformationHelper.IsOSPlatformOrLater(OSPlatform.Windows, 1) &&
RuntimeInformationHelper.IsOSPlatformOrLater(OSPlatform.Linux, 1))
{
{|#1:M2()|}; // Platform checks:'IsOSPlatformOrLater;Linux;1 && IsOSPlatformOrLater;Windows;1'
}
else
{
{|#2:M2()|}; // Platform checks:''
}
{|#3:M2()|}; // Platform checks:''
}
void M2()
{
}
}" + PlatformCheckApiSource;
await VerifyCS.VerifyAnalyzerAsync(source,
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(0).WithArguments(""),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(1).WithArguments("IsOSPlatformOrLater;Linux;1 && IsOSPlatformOrLater;Windows;1"),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(2).WithArguments(""),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(3).WithArguments(""));
}
[Fact]
public async Task SimpleIfTestWithLogicalOr()
{
var source = @"
using System.Diagnostics;
using System.Runtime.InteropServices;
class Test
{
void M1()
{
{|#0:M2()|}; // Platform checks:''
if(RuntimeInformationHelper.IsOSPlatformOrLater(OSPlatform.Windows, 1) ||
RuntimeInformationHelper.IsOSPlatformOrLater(OSPlatform.Linux, 1))
{
{|#1:M2()|}; // Platform checks:'(!IsOSPlatformOrLater;Windows;1 && IsOSPlatformOrLater;Linux;1 || IsOSPlatformOrLater;Windows;1)'
}
{|#2:M2()|}; // Platform checks:''
}
void M2()
{
}
}" + PlatformCheckApiSource;
await VerifyCS.VerifyAnalyzerAsync(source,
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(0).WithArguments(""),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(1).WithArguments("(!IsOSPlatformOrLater;Windows;1 && IsOSPlatformOrLater;Linux;1 || IsOSPlatformOrLater;Windows;1)"),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(2).WithArguments(""));
}
[Fact]
public async Task SimpleIfElseTestWithLogicalOr()
{
var source = @"
using System.Diagnostics;
using System.Runtime.InteropServices;
class Test
{
void M1()
{
{|#0:M2()|}; // Platform checks:''
if(RuntimeInformationHelper.IsOSPlatformOrLater(OSPlatform.Windows, 1) ||
RuntimeInformationHelper.IsOSPlatformOrLater(OSPlatform.Linux, 1))
{
{|#1:M2()|}; // Platform checks:'(!IsOSPlatformOrLater;Windows;1 && IsOSPlatformOrLater;Linux;1 || IsOSPlatformOrLater;Windows;1)'
}
else
{
{|#2:M2()|}; // Platform checks:'!IsOSPlatformOrLater;Linux;1 && !IsOSPlatformOrLater;Windows;1'
}
{|#3:M2()|}; // Platform checks:''
}
void M2()
{
}
}" + PlatformCheckApiSource;
await VerifyCS.VerifyAnalyzerAsync(source,
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(0).WithArguments(""),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(1).WithArguments("(!IsOSPlatformOrLater;Windows;1 && IsOSPlatformOrLater;Linux;1 || IsOSPlatformOrLater;Windows;1)"),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(2).WithArguments("!IsOSPlatformOrLater;Linux;1 && !IsOSPlatformOrLater;Windows;1"),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(3).WithArguments(""));
}
[Fact]
public async Task SimpleIfElseIfElseTestWithLogicalOr()
{
var source = @"
using System.Diagnostics;
using System.Runtime.InteropServices;
class Test
{
void M1()
{
{|#0:M2()|}; // Platform checks:''
if(RuntimeInformationHelper.IsOSPlatformOrLater(OSPlatform.Windows, 1) ||
RuntimeInformationHelper.IsOSPlatformOrLater(OSPlatform.Linux, 1))
{
{|#1:M2()|}; // Platform checks:'(!IsOSPlatformOrLater;Windows;1 && IsOSPlatformOrLater;Linux;1 || IsOSPlatformOrLater;Windows;1)'
}
else if (RuntimeInformationHelper.IsOSPlatformOrLater(OSPlatform.Windows, 3))
{
{|#2:M2()|}; // Platform checks:'!IsOSPlatformOrLater;Linux;1 && !IsOSPlatformOrLater;Windows;1 && IsOSPlatformOrLater;Windows;3'
}
else
{
{|#3:M2()|}; // Platform checks:'!IsOSPlatformOrLater;Linux;1 && !IsOSPlatformOrLater;Windows;1 && !IsOSPlatformOrLater;Windows;3'
}
{|#4:M2()|}; // Platform checks:''
}
void M2()
{
}
}" + PlatformCheckApiSource;
await VerifyCS.VerifyAnalyzerAsync(source,
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(0).WithArguments(""),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(1).WithArguments("(!IsOSPlatformOrLater;Windows;1 && IsOSPlatformOrLater;Linux;1 || IsOSPlatformOrLater;Windows;1)"),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(2).WithArguments("!IsOSPlatformOrLater;Linux;1 && !IsOSPlatformOrLater;Windows;1 && IsOSPlatformOrLater;Windows;3"),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(3).WithArguments("!IsOSPlatformOrLater;Linux;1 && !IsOSPlatformOrLater;Windows;1 && !IsOSPlatformOrLater;Windows;3"),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(4).WithArguments(""));
}
[Fact]
public async Task SimpleIfElseIfTestWithLogicalOr_02()
{
var source = @"
using System.Diagnostics;
using System.Runtime.InteropServices;
class Test
{
void M1()
{
{|#0:M2()|}; // Platform checks:''
if((RuntimeInformationHelper.IsOSPlatformOrLater(OSPlatform.Windows, 1) ||
RuntimeInformationHelper.IsOSPlatformOrLater(OSPlatform.Linux, 1)) &&
(RuntimeInformationHelper.IsOSPlatformOrLater(OSPlatform.Windows, 2) ||
RuntimeInformationHelper.IsOSPlatformOrLater(OSPlatform.Linux, 2)))
{
{|#1:M2()|}; // Platform checks:'((!IsOSPlatformOrLater;Windows;1 && IsOSPlatformOrLater;Linux;1 || IsOSPlatformOrLater;Windows;1) && !IsOSPlatformOrLater;Windows;2 && IsOSPlatformOrLater;Linux;2 || (!IsOSPlatformOrLater;Windows;1 && IsOSPlatformOrLater;Linux;1 || IsOSPlatformOrLater;Windows;1) && IsOSPlatformOrLater;Windows;2)'
}
else if (RuntimeInformationHelper.IsOSPlatformOrLater(OSPlatform.Windows, 3) ||
RuntimeInformationHelper.IsOSPlatformOrLater(OSPlatform.Linux, 3) ||
RuntimeInformationHelper.IsOSPlatformOrLater(OSPlatform.Linux, 4))
{
{|#2:M2()|}; // Platform checks:'(!IsOSPlatformOrLater;Linux;3 && !IsOSPlatformOrLater;Windows;3 && IsOSPlatformOrLater;Linux;4 || (!IsOSPlatformOrLater;Windows;3 && IsOSPlatformOrLater;Linux;3 || IsOSPlatformOrLater;Windows;3))'
}
{|#3:M2()|}; // Platform checks:''
}
void M2()
{
}
}" + PlatformCheckApiSource;
await VerifyCS.VerifyAnalyzerAsync(source,
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(0).WithArguments(""),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(1).WithArguments("((!IsOSPlatformOrLater;Windows;1 && IsOSPlatformOrLater;Linux;1 || IsOSPlatformOrLater;Windows;1) && !IsOSPlatformOrLater;Windows;2 && IsOSPlatformOrLater;Linux;2 || (!IsOSPlatformOrLater;Windows;1 && IsOSPlatformOrLater;Linux;1 || IsOSPlatformOrLater;Windows;1) && IsOSPlatformOrLater;Windows;2)"),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(2).WithArguments("(!IsOSPlatformOrLater;Linux;3 && !IsOSPlatformOrLater;Windows;3 && IsOSPlatformOrLater;Linux;4 || (!IsOSPlatformOrLater;Windows;3 && IsOSPlatformOrLater;Linux;3 || IsOSPlatformOrLater;Windows;3))"),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(3).WithArguments(""));
}
[Fact]
public async Task ControlFlowAndMultipleChecks()
{
var source = @"
using System.Runtime.InteropServices;
class Test
{
void M1()
{
{|#0:M2()|}; // Platform checks:''
if (RuntimeInformationHelper.IsOSPlatformOrLater(OSPlatform.Linux, 1))
{
{|#1:M2()|}; // Platform checks:'IsOSPlatformOrLater;Linux;1'
if (RuntimeInformationHelper.IsOSPlatformOrLater(OSPlatform.Linux, 2, 0))
{
{|#2:M2()|}; // Platform checks:'IsOSPlatformOrLater;Linux;1 && IsOSPlatformOrLater;Linux;2'
}
else if (!RuntimeInformationHelper.IsOSPlatformEarlierThan(OSPlatform.Windows, 3, 1, 1))
{
{|#3:M2()|}; // Platform checks:'!IsOSPlatformEarlierThan;Windows;3.1.1 && !IsOSPlatformOrLater;Linux;2 && IsOSPlatformOrLater;Linux;1'
}
{|#4:M2()|}; // Platform checks:'IsOSPlatformOrLater;Linux;1'
}
else
{
{|#5:M2()|}; // Platform checks:'!IsOSPlatformOrLater;Linux;1'
}
{|#6:M2()|}; // Platform checks:''
if ({|#7:IsWindows3OrLater()|}) // Platform checks:''
{
{|#8:M2()|}; // Platform checks:''
}
{|#9:M2()|}; // Platform checks:''
}
void M2()
{
}
bool IsWindows3OrLater()
{
return RuntimeInformationHelper.IsOSPlatformOrLater(OSPlatform.Windows, 3, 0, 0, 0);
}
}" + PlatformCheckApiSource;
await VerifyCS.VerifyAnalyzerAsync(source,
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(0).WithArguments(""),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(1).WithArguments("IsOSPlatformOrLater;Linux;1"),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(2).WithArguments("IsOSPlatformOrLater;Linux;1 && IsOSPlatformOrLater;Linux;2"),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(3).WithArguments("!IsOSPlatformEarlierThan;Windows;3.1.1 && !IsOSPlatformOrLater;Linux;2 && IsOSPlatformOrLater;Linux;1"),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(4).WithArguments("IsOSPlatformOrLater;Linux;1"),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(5).WithArguments("!IsOSPlatformOrLater;Linux;1"),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(6).WithArguments(""),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(7).WithArguments(""),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(8).WithArguments(""),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(9).WithArguments(""));
}
[Fact]
public async Task DebugAssertAnalysisTest()
{
var source = @"
using System.Diagnostics;
using System.Runtime.InteropServices;
class Test
{
void M1()
{
{|#0:M2()|}; // Platform checks:''
{|#1:Debug.Assert(RuntimeInformationHelper.IsOSPlatformOrLater(OSPlatform.Windows, 3, 0, 0, 0))|}; // Platform checks:'IsOSPlatformOrLater;Windows;3'
{|#2:M2()|}; // Platform checks:'IsOSPlatformOrLater;Windows;3'
}
void M2()
{
}
}" + PlatformCheckApiSource;
await VerifyCS.VerifyAnalyzerAsync(source,
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(0).WithArguments(""),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(1).WithArguments("IsOSPlatformOrLater;Windows;3"),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(2).WithArguments("IsOSPlatformOrLater;Windows;3"));
}
[Fact]
public async Task ResultSavedInLocal()
{
var source = @"
using System.Diagnostics;
using System.Runtime.InteropServices;
class Test
{
void M1()
{
{|#0:M2()|}; // Platform checks:''
var x1 = RuntimeInformationHelper.IsOSPlatformOrLater(OSPlatform.Windows, 1);
var x2 = RuntimeInformationHelper.IsOSPlatformOrLater(OSPlatform.Linux, 1);
if (x1 || x2)
{
{|#1:M2()|}; // Platform checks:'(!IsOSPlatformOrLater;Windows;1 && IsOSPlatformOrLater;Linux;1 || IsOSPlatformOrLater;Windows;1)'
}
{|#2:M2()|}; // Platform checks:''
}
void M2()
{
}
}" + PlatformCheckApiSource;
await VerifyCS.VerifyAnalyzerAsync(source,
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(0).WithArguments(""),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(1).WithArguments("(!IsOSPlatformOrLater;Windows;1 && IsOSPlatformOrLater;Linux;1 || IsOSPlatformOrLater;Windows;1)"),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(2).WithArguments(""));
}
[Fact]
public async Task VersionSavedInLocal()
{
var source = @"
using System.Diagnostics;
using System.Runtime.InteropServices;
class Test
{
void M1()
{
{|#0:M2()|}; // Platform checks:''
var v1 = 1;
if (RuntimeInformationHelper.IsOSPlatformOrLater(OSPlatform.Windows, v1))
{
{|#1:M2()|}; // Platform checks:'IsOSPlatformOrLater;Windows;1'
}
{|#2:M2()|}; // Platform checks:''
}
void M2()
{
}
}" + PlatformCheckApiSource;
await VerifyCS.VerifyAnalyzerAsync(source,
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(0).WithArguments(""),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(1).WithArguments("IsOSPlatformOrLater;Windows;1"),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(2).WithArguments(""));
}
[Fact]
public async Task PlatformSavedInLocal_NotYetSupported()
{
var source = @"
using System.Diagnostics;
using System.Runtime.InteropServices;
class Test
{
void M1()
{
{|#0:M2()|}; // Platform checks:''
var platform = OSPlatform.Windows;
if (RuntimeInformationHelper.IsOSPlatformOrLater(platform, 1))
{
{|#1:M2()|}; // Platform checks:''
}
{|#2:M2()|}; // Platform checks:''
}
void M2()
{
}
}" + PlatformCheckApiSource;
await VerifyCS.VerifyAnalyzerAsync(source,
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(0).WithArguments(""),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(1).WithArguments(""),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(2).WithArguments(""));
}
[Fact]
public async Task UnrelatedConditionCheckDoesNotInvalidateState()
{
var source = @"
using System.Diagnostics;
using System.Runtime.InteropServices;
class Test
{
void M1(bool flag1, bool flag2)
{
{|#0:M2()|}; // Platform checks:''
if (RuntimeInformationHelper.IsOSPlatformOrLater(OSPlatform.Windows, 1))
{
{|#1:M2()|}; // Platform checks:'IsOSPlatformOrLater;Windows;1'
if (flag1 || flag2)
{
{|#2:M2()|}; // Platform checks:'IsOSPlatformOrLater;Windows;1'
}
else
{
{|#3:M2()|}; // Platform checks:'IsOSPlatformOrLater;Windows;1'
}
{|#4:M2()|}; // Platform checks:'IsOSPlatformOrLater;Windows;1'
}
{|#5:M2()|}; // Platform checks:''
}
void M2()
{
}
}" + PlatformCheckApiSource;
await VerifyCS.VerifyAnalyzerAsync(source,
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(0).WithArguments(""),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(1).WithArguments("IsOSPlatformOrLater;Windows;1"),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(2).WithArguments("IsOSPlatformOrLater;Windows;1"),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(3).WithArguments("IsOSPlatformOrLater;Windows;1"),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(4).WithArguments("IsOSPlatformOrLater;Windows;1"),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(5).WithArguments(""));
}
[Theory]
[InlineData("")]
[InlineData("dotnet_code_quality.interprocedural_analysis_kind = ContextSensitive")]
public async Task InterproceduralAnalysisTest(string editorconfig)
{
var source = @"
using System.Runtime.InteropServices;
class Test
{
void M1()
{
{|#0:M2()|}; // Platform checks:''
if ({|#1:IsWindows3OrLater()|}) // Platform checks:''
{
{|#2:M2()|}; // Platform checks:'IsOSPlatformOrLater;Windows;3'
}
{|#3:M2()|}; // Platform checks:''
}
void M2()
{
}
bool IsWindows3OrLater()
{
return RuntimeInformationHelper.IsOSPlatformOrLater(OSPlatform.Windows, 3, 0, 0, 0);
}
}" + PlatformCheckApiSource;
var test = new VerifyCS.Test
{
TestState =
{
Sources = { source },
AdditionalFiles = { (".editorconfig", editorconfig) }
}
};
var argForInterprocDiagnostics = editorconfig.Length == 0 ? "" : "IsOSPlatformOrLater;Windows;3";
test.ExpectedDiagnostics.AddRange(new[]
{
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(0).WithArguments(""),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(1).WithArguments(argForInterprocDiagnostics),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(2).WithArguments(argForInterprocDiagnostics),
VerifyCS.Diagnostic(RuntimePlatformCheckAnalyzer.Rule).WithLocation(3).WithArguments("")
});
await test.RunAsync();
}
}
}
| |
using UnityEngine;
using System;
using System.Collections.Generic;
#if !UNITY_FLASH && !UNITY_METRO && !UNITY_WP8
using System.Text.RegularExpressions;
#endif
// Part of MegaShape?
public class MegaShapeSVG
{
public void LoadXML(string svgdata, MegaShape shape, bool clear, int start)
{
MegaXMLReader xml = new MegaXMLReader();
MegaXMLNode node = xml.read(svgdata);
if ( !clear )
shape.splines.Clear();
shape.selcurve = start;
splineindex = start;
ParseXML(node, shape);
}
int splineindex = 0;
public void ParseXML(MegaXMLNode node, MegaShape shape)
{
foreach ( MegaXMLNode n in node.children )
{
switch ( n.tagName )
{
case "circle": ParseCircle(n, shape); break;
case "path": ParsePath(n, shape); break;
case "ellipse": ParseEllipse(n, shape); break;
case "rect": ParseRect(n, shape); break;
case "polygon": ParsePolygon(n, shape); break;
default: break;
}
ParseXML(n, shape);
}
}
MegaSpline GetSpline(MegaShape shape)
{
MegaSpline spline;
if ( splineindex < shape.splines.Count )
spline = shape.splines[splineindex];
else
{
spline = new MegaSpline();
shape.splines.Add(spline);
}
splineindex++;
return spline;
}
Vector3 SwapAxis(Vector3 val, MegaAxis axis)
{
float v = 0.0f;
switch ( axis )
{
case MegaAxis.X:
v = val.x;
val.x = val.y;
val.y = v;
break;
case MegaAxis.Y:
break;
case MegaAxis.Z:
v = val.y;
val.y = val.z;
val.z = v;
break;
}
return val;
}
void AddKnot(MegaSpline spline, Vector3 p, Vector3 invec, Vector3 outvec, MegaAxis axis)
{
spline.AddKnot(SwapAxis(p, axis), SwapAxis(invec, axis), SwapAxis(outvec, axis));
}
void ParseCircle(MegaXMLNode node, MegaShape shape)
{
MegaSpline spline = GetSpline(shape);
float cx = 0.0f;
float cy = 0.0f;
float r = 0.0f;
for ( int i = 0; i < node.values.Count; i++ )
{
MegaXMLValue val = node.values[i];
switch ( val.name )
{
case "cx": cx = float.Parse(val.value); break;
case "cy": cy = float.Parse(val.value); break;
case "r": r = float.Parse(val.value); break;
}
}
float vector = CIRCLE_VECTOR_LENGTH * r;
spline.knots.Clear();
for ( int ix = 0; ix < 4; ++ix )
{
float angle = (Mathf.PI * 2.0f) * (float)ix / (float)4;
float sinfac = Mathf.Sin(angle);
float cosfac = Mathf.Cos(angle);
Vector3 p = new Vector3((cosfac * r) + cx, 0.0f, (sinfac * r) + cy);
Vector3 rotvec = new Vector3(sinfac * vector, 0.0f, -cosfac * vector);
//spline.AddKnot(p, p + rotvec, p - rotvec);
AddKnot(spline, p, p + rotvec, p - rotvec, shape.axis);
}
spline.closed = true;
}
void ParseEllipse(MegaXMLNode node, MegaShape shape)
{
MegaSpline spline = GetSpline(shape);
float cx = 0.0f;
float cy = 0.0f;
float rx = 0.0f;
float ry = 0.0f;
for ( int i = 0; i < node.values.Count; i++ )
{
MegaXMLValue val = node.values[i];
switch ( val.name )
{
case "cx": cx = float.Parse(val.value); break;
case "cy": cy = float.Parse(val.value); break;
case "rx": rx = float.Parse(val.value); break;
case "ry": ry = float.Parse(val.value); break;
}
}
ry = Mathf.Clamp(ry, 0.0f, float.MaxValue);
rx = Mathf.Clamp(rx, 0.0f, float.MaxValue);
float radius, xmult, ymult;
if ( ry < rx )
{
radius = rx;
xmult = 1.0f;
ymult = ry / rx;
}
else
{
if ( rx < ry )
{
radius = ry;
xmult = rx / ry;
ymult = 1.0f;
}
else
{
radius = ry;
xmult = ymult = 1.0f;
}
}
float vector = CIRCLE_VECTOR_LENGTH * radius;
Vector3 mult = new Vector3(xmult, ymult, 1.0f);
for ( int ix = 0; ix < 4; ++ix )
{
float angle = 6.2831853f * (float)ix / 4.0f;
float sinfac = Mathf.Sin(angle);
float cosfac = Mathf.Cos(angle);
Vector3 p = new Vector3(cosfac * radius + cx, 0.0f, sinfac * radius + cy);
Vector3 rotvec = new Vector3(sinfac * vector, 0.0f, -cosfac * vector);
//spline.AddKnot(Vector3.Scale(p, mult), Vector3.Scale((p + rotvec), mult), Vector3.Scale((p - rotvec), mult)); //, tm);
AddKnot(spline, Vector3.Scale(p, mult), Vector3.Scale((p + rotvec), mult), Vector3.Scale((p - rotvec), mult), shape.axis); //, tm);
}
spline.closed = true;
}
void ParseRect(MegaXMLNode node, MegaShape shape)
{
MegaSpline spline = GetSpline(shape);
Vector3[] ppoints = new Vector3[4];
float w = 0.0f;
float h = 0.0f;
float x = 0.0f;
float y = 0.0f;
for ( int i = 0; i < node.values.Count; i++ )
{
MegaXMLValue val = node.values[i];
switch ( val.name )
{
case "x": x = float.Parse(val.value); break;
case "y": y = float.Parse(val.value); break;
case "width": w = float.Parse(val.value); break;
case "height": h = float.Parse(val.value); break;
case "transform": Debug.Log("SVG Transform not implemented yet");
break;
}
}
ppoints[0] = new Vector3(x, 0.0f, y);
ppoints[1] = new Vector3(x, 0.0f, y + h);
ppoints[2] = new Vector3(x + w, 0.0f, y + h);
ppoints[3] = new Vector3(x + w, 0.0f, y);
spline.closed = true;
spline.knots.Clear();
//spline.AddKnot(ppoints[0], ppoints[0], ppoints[0]);
//spline.AddKnot(ppoints[1], ppoints[1], ppoints[1]);
//spline.AddKnot(ppoints[2], ppoints[2], ppoints[2]);
//spline.AddKnot(ppoints[3], ppoints[3], ppoints[3]);
AddKnot(spline, ppoints[0], ppoints[0], ppoints[0], shape.axis);
AddKnot(spline, ppoints[1], ppoints[1], ppoints[1], shape.axis);
AddKnot(spline, ppoints[2], ppoints[2], ppoints[2], shape.axis);
AddKnot(spline, ppoints[3], ppoints[3], ppoints[3], shape.axis);
}
void ParsePolygon(MegaXMLNode node, MegaShape shape)
{
MegaSpline spline = GetSpline(shape);
spline.knots.Clear();
spline.closed = true;
char[] charSeparators = new char[] { ' ' };
for ( int i = 0; i < node.values.Count; i++ )
{
MegaXMLValue val = node.values[i];
switch ( val.name )
{
case "points":
string[] coordinates = val.value.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
for ( int j = 0; j < coordinates.Length; j++ )
{
Vector3 p = ParseV2Split(coordinates[j], 0);
MegaKnot k = new MegaKnot();
k.p = SwapAxis(new Vector3(p.x, 0.0f, p.y), shape.axis);
k.invec = k.p;
k.outvec = k.p;
spline.knots.Add(k);
}
break;
}
}
if ( spline.closed )
{
Vector3 delta1 = spline.knots[0].outvec - spline.knots[0].p;
spline.knots[0].invec = spline.knots[0].p - delta1;
}
}
char[] commaspace = new char[] { ',', ' ' };
void ParsePath(MegaXMLNode node, MegaShape shape)
{
Vector3 cp = Vector3.zero;
Vector2 cP1;
Vector2 cP2;
char[] charSeparators = new char[] { ',', ' ' };
MegaSpline spline = null;
MegaKnot k;
string[] coord;
for ( int i = 0; i < node.values.Count; i++ )
{
MegaXMLValue val = node.values[i];
//Debug.Log("val name " + val.name);
switch ( val.name )
{
case "d":
#if UNITY_FLASH
string[] coordinates = null; //string.Split(val.value, @"(?=[MmLlCcSsZzHhVv])");
#else
string[] coordinates = Regex.Split(val.value, @"(?=[MmLlCcSsZzHhVv])");
#endif
for ( int j = 0; j < coordinates.Length; j++ )
{
if ( coordinates[j].Length > 0 )
{
string v = coordinates[j].Substring(1);
if ( v != null && v.Length > 0 )
{
v = v.Replace("-", ",-");
while ( v.Length > 0 && (v[0] == ',' || v[0] == ' ') )
v = v.Substring(1);
}
switch ( coordinates[j][0] )
{
case 'Z':
case 'z':
if ( spline != null )
{
spline.closed = true;
#if false
Vector3 delta1 = spline.knots[0].outvec - spline.knots[0].p;
spline.knots[0].invec = spline.knots[0].p - delta1;
if ( spline.knots[0].p == spline.knots[spline.knots.Count - 1].p )
spline.knots.Remove(spline.knots[spline.knots.Count - 1]);
#else
int kc = spline.knots.Count - 1;
spline.knots[0].invec = spline.knots[kc].invec;
spline.knots.Remove(spline.knots[kc]);
#endif
}
break;
case 'M':
spline = GetSpline(shape);
spline.knots.Clear();
cp = ParseV2Split(v, 0);
k = new MegaKnot();
k.p = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis);
k.invec = k.p;
k.outvec = k.p;
spline.knots.Add(k);
break;
case 'm':
spline = GetSpline(shape);
spline.knots.Clear();
//Debug.Log("v: " + v);
coord = v.Split(" "[0]);
//Debug.Log("m coords " + coord.Length);
//Debug.Log("v2 " + coord[0]);
for ( int k0 = 0; k0 < coord.Length - 1; k0 = k0 + 1 )
{
//Debug.Log("v2 " + coord[k0]);
Vector3 cp1 = ParseV2Split(coord[k0], 0);
//Debug.Log("cp1 " + cp1);
cp.x += cp1.x; //ParseV2Split(coord[k0], 0); // ParseV2(coord, k0);
cp.y += cp1.y;
k = new MegaKnot();
k.p = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis);
k.invec = k.p;
k.outvec = k.p;
spline.knots.Add(k);
}
#if false
Vector3 cp1 = ParseV2Split(v, 0);
cp.x += cp1.x;
cp.y += cp1.y;
k = new MegaKnot();
k.p = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis);
k.invec = k.p;
k.outvec = k.p;
spline.knots.Add(k);
#endif
break;
case 'l':
coord = v.Split(","[0]);
for ( int k0 = 0; k0 < coord.Length; k0 = k0 + 2 )
cp += ParseV2(coord, k0);
spline.knots[spline.knots.Count - 1].outvec = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis);
k = new MegaKnot();
k.p = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis);
k.invec = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis);
k.outvec = k.p - (k.invec - k.p);
spline.knots.Add(k);
break;
case 'c':
coord = v.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
for ( int k2 = 0; k2 < coord.Length; k2 += 6 )
{
cP1 = cp + ParseV2(coord, k2);
cP2 = cp + ParseV2(coord, k2 + 2);
cp += ParseV2(coord, k2 + 4);
spline.knots[spline.knots.Count - 1].outvec = SwapAxis(new Vector3(cP1.x, 0.0f, cP1.y), shape.axis);
k = new MegaKnot();
k.p = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis);
k.invec = SwapAxis(new Vector3(cP2.x, 0.0f, cP2.y), shape.axis);
k.outvec = k.p - (k.invec - k.p);
spline.knots.Add(k);
}
break;
case 'L':
coord = v.Split(","[0]);
for ( int k3 = 0; k3 < coord.Length; k3 = k3 + 2 )
cp = ParseV2(coord, k3);
spline.knots[spline.knots.Count - 1].outvec = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis);
k = new MegaKnot();
k.p = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis);
k.invec = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis);
k.outvec = k.p - (k.invec - k.p);
spline.knots.Add(k);
break;
case 'v':
//Debug.Log("v: " + v);
coord = v.Split(","[0]);
for ( int k4 = 0; k4 < coord.Length; k4++ )
cp.y += float.Parse(coord[k4]);
spline.knots[spline.knots.Count - 1].outvec = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis);
k = new MegaKnot();
k.p = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis);
k.invec = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis);
k.outvec = k.p - (k.invec - k.p);
spline.knots.Add(k);
break;
case 'V':
coord = v.Split(","[0]);
for ( int k9 = 0; k9 < coord.Length; k9++ )
cp.y = float.Parse(coord[k9]);
spline.knots[spline.knots.Count - 1].outvec = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis);
k = new MegaKnot();
k.p = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis);
k.invec = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis);
k.outvec = k.p - (k.invec - k.p);
spline.knots.Add(k);
break;
case 'h':
coord = v.Split(","[0]);
for ( int k5 = 0; k5 < coord.Length; k5++ )
cp.x += float.Parse(coord[k5]);
spline.knots[spline.knots.Count - 1].outvec = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis);
k = new MegaKnot();
k.p = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis);
k.invec = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis);
k.outvec = k.p - (k.invec - k.p);
spline.knots.Add(k);
break;
case 'H':
coord = v.Split(","[0]);
for ( int k6 = 0; k6 < coord.Length; k6++ )
cp.x = float.Parse(coord[k6]);
spline.knots[spline.knots.Count - 1].outvec = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis);
k = new MegaKnot();
k.p = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis);
k.invec = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis);
k.outvec = k.p - (k.invec - k.p);
spline.knots.Add(k);
break;
case 'S':
coord = v.Split(","[0]);
for ( int k7 = 0; k7 < coord.Length; k7 = k7 + 4 )
{
cp = ParseV2(coord, k7 + 2);
cP1 = ParseV2(coord, k7);
k = new MegaKnot();
k.p = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis);
k.invec = SwapAxis(new Vector3(cP1.x, 0.0f, cP1.y), shape.axis);
k.outvec = k.p - (k.invec - k.p);
spline.knots.Add(k);
}
break;
case 's':
coord = v.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
for ( int k7 = 0; k7 < coord.Length; k7 = k7 + 4 )
{
cP1 = cp + ParseV2(coord, k7);
cp += ParseV2(coord, k7 + 2);
k = new MegaKnot();
k.p = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis);
k.invec = SwapAxis(new Vector3(cP1.x, 0.0f, cP1.y), shape.axis);
k.outvec = k.p - (k.invec - k.p);
spline.knots.Add(k);
}
break;
case 'C':
coord = v.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
for ( int k2 = 0; k2 < coord.Length; k2 += 6 )
{
cP1 = ParseV2(coord, k2);
cP2 = ParseV2(coord, k2 + 2);
cp = ParseV2(coord, k2 + 4);
spline.knots[spline.knots.Count - 1].outvec = SwapAxis(new Vector3(cP1.x, 0.0f, cP1.y), shape.axis);
k = new MegaKnot();
k.p = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis);
k.invec = SwapAxis(new Vector3(cP2.x, 0.0f, cP2.y), shape.axis);
k.outvec = k.p - (k.invec - k.p);
spline.knots.Add(k);
}
break;
default:
break;
}
}
}
break;
}
}
}
public void importData(string svgdata, MegaShape shape, float scale, bool clear, int start)
{
LoadXML(svgdata, shape, clear, start);
for ( int i = start; i < splineindex; i++ )
{
float area = shape.splines[i].Area();
if ( area < 0.0f )
shape.splines[i].reverse = false;
else
shape.splines[i].reverse = true;
}
//shape.Centre(0.01f, new Vector3(-1.0f, 1.0f, 1.0f));
//shape.Centre(scale, new Vector3(-1.0f, 1.0f, 1.0f), start);
shape.CoordAdjust(scale, new Vector3(-1.0f, 1.0f, 1.0f), start);
shape.CalcLength(); //10);
}
const float CIRCLE_VECTOR_LENGTH = 0.5517861843f;
Vector2 ParseV2Split(string str, int i)
{
return ParseV2(str.Split(commaspace, StringSplitOptions.RemoveEmptyEntries), i);
}
Vector3 ParseV2(string[] str, int i)
{
Vector3 p = Vector2.zero;
p.x = float.Parse(str[i]);
p.y = float.Parse(str[i + 1]);
return p;
}
static public string Export(MegaShape shape, int x, int y, float strokewidth, Color col)
{
string file = "";
Color32 c = col;
file += "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
file += "<!-- MegaShapes SVG Exporter v1.0 -->\n";
file += "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n";
file += "<svg version=\"1.1\" id=\"" + shape.name + "\" x=\"0px\" y=\"0px\" width=\"640.0px\" height=\"480.0px\">\n";
for ( int i = 0; i < shape.splines.Count; i++ )
{
MegaSpline spline = shape.splines[i];
file += "<path d=\"";
MegaKnot k1;
MegaKnot k = spline.knots[0];
k1 = k;
file += "M" + k.p[x] + "," + -k.p[y];
//Vector3 cp = k.p;
for ( int j = 1; j < spline.knots.Count; j++ )
{
k = spline.knots[j];
Vector3 po = k1.outvec; // - cp; // - k1.p;
Vector3 pi = k.invec; // - cp; // - k.p;
Vector3 kp = k.p; // - cp;
kp[y] = -kp[y];
po[y] = -po[y];
pi[y] = -pi[y];
file += "C" + po[x] + "," + po[y];
file += " " + pi[x] + "," + pi[y];
file += " " + kp[x] + "," + kp[y];
k1 = k;
}
if ( spline.closed )
{
file += "z\"";
}
file += " fill=\"none\"";
file += " stroke=\"#" + c.r.ToString("x") + c.g.ToString("x") + c.b.ToString("x") + "\"";
file += " stroke-width=\"" + strokewidth + "\"";
file += "/>\n";
}
file += "</svg>\n";
return file;
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.ComponentModel;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.CoreServices.Progress;
using OpenLiveWriter.Localization;
namespace OpenLiveWriter.Controls
{
/// <summary>
/// Summary description for ProgressDialog.
/// </summary>
public class ProgressDialog : BaseForm
{
public ProgressDialog()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
this.cancelButton.Text = Res.Get(StringId.CancelButton);
// This will flip the direction of progress bar if we are RTL
progressBar.RightToLeftLayout = true;
}
protected override void OnLoad(EventArgs e)
{
if (m_progressProviderResult != DialogResult.None)
{
//the progress operation has already completed, so don't show the dialog.
this.DialogResult = m_progressProviderResult;
Close();
}
else
{
base.OnLoad(e);
DisplayHelper.AutoFitSystemButton(cancelButton, cancelButton.Width, int.MaxValue);
}
}
/// <summary>
/// The title displayed for this dialog
/// </summary>
public string Title
{
get
{
return Text;
}
set
{
AccessibleName = Text = value;
}
}
/// <summary>
/// Makes the capture button visible or invisible
/// </summary>
public bool CancelButtonVisible
{
get
{
return this.cancelButton.Visible;
}
set
{
this.cancelButton.Visible = value;
}
}
/// <summary>
/// The text displayed on the cancel button
/// </summary>
public StringId CancelButtonText
{
set
{
cancelButton.Text = Res.Get(value);
}
}
/// <summary>
/// The text displayed in the progress bar.
/// </summary>
public string ProgressText
{
get
{
return this.progressLabel.Text;
}
set
{
this.progressLabel.Text = value;
progressBar.AccessibleName = ControlHelper.ToAccessibleName(value);
}
}
/// <summary>
/// The AsyncOperation that this dialog is bound to.
/// Progress reported by this AsynOperation will be reflected in the progress bar.
/// </summary>
public IProgressProvider ProgressProvider
{
get
{
return m_progressProvider;
}
set
{
m_progressProvider = value;
ConfigureCategoryUI();
HookEvents();
}
}
public bool IgnoreProgressMessages = false;
/// <summary>
/// Invoked when the operation has made progress.
/// </summary>
/// <param name="sender"></param>
/// <param name="progressUpdatedEvt"></param>
private void OnProgressUpdated(object sender, ProgressUpdatedEventArgs progressUpdatedEvt)
{
if (!IgnoreProgressMessages)
this.progressLabel.Text = progressUpdatedEvt.ProgressMessage;
this.progressBar.Maximum = progressUpdatedEvt.Total;
this.progressBar.Value = progressUpdatedEvt.Completed;
}
/// <summary>
/// Handles user clicking the cancel button
/// </summary>
private void cancelButton_Click(object sender, EventArgs e)
{
progressLabel.Text = Res.Get(StringId.Canceling);
ProgressProvider.Cancel();
}
/// <summary>
/// Cleans up when the AsycOperation has been cancelled.
/// </summary>
private void asyncOp_Cancelled(object sender, EventArgs e)
{
// reset progress
progressBar.Value = 0;
progressLabel.Text = string.Empty;
UnHookEvents();
this.DialogResult = DialogResult.Cancel;
m_progressProviderResult = DialogResult.Cancel;
}
/// <summary>
/// Cleans up after the AsynOperation has completed its work.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void asyncOp_Completed(object sender, EventArgs e)
{
UnHookEvents();
this.DialogResult = DialogResult.OK;
m_progressProviderResult = DialogResult.OK;
}
/// <summary>
/// The operation has failed
/// </summary>
private void asyncOp_Failed(object sender, ThreadExceptionEventArgs e)
{
UnHookEvents();
this.DialogResult = DialogResult.Abort;
m_progressProviderResult = DialogResult.Abort;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
private void ConfigureCategoryUI()
{
// if this progress provider has categories then allow this UI to show
// on the form -- otherwise hide it and shrink the form as appropriate
m_progressCategoryProvider = m_progressProvider as IProgressCategoryProvider;
if (m_progressCategoryProvider != null && m_progressCategoryProvider.ShowCategories)
{
// Signup for the category changed event
m_progressCategoryProvider.ProgressCategoryChanged += new EventHandler(m_progressCategoryProvider_ProgressCategoryChanged);
}
else // hide the category ui
{
panelCategory.Visible = false;
ClientSize = new Size(ClientSize.Width, ClientSize.Height - panelCategory.Height);
}
}
/// <summary>
/// Synch the category ui w/ the category provider
/// </summary>
private void m_progressCategoryProvider_ProgressCategoryChanged(object sender, EventArgs e)
{
pictureBoxCategory.Image = m_progressCategoryProvider.CurrentCategory.Icon;
labelCategory.Text = m_progressCategoryProvider.CurrentCategory.Name;
}
private void HookEvents()
{
//Hook up this dialog's event handler's to the AsyncOperation events
m_progressProvider.ProgressUpdated += new ProgressUpdatedEventHandler(OnProgressUpdated);
m_progressProvider.Cancelled += new EventHandler(asyncOp_Cancelled);
m_progressProvider.Completed += new EventHandler(asyncOp_Completed);
m_progressProvider.Failed += new ThreadExceptionEventHandler(asyncOp_Failed);
}
private void UnHookEvents()
{
//Hook up this dialog's event handler's to the AsyncOperation events
m_progressProvider.ProgressUpdated -= new ProgressUpdatedEventHandler(OnProgressUpdated);
m_progressProvider.Cancelled -= new EventHandler(asyncOp_Cancelled);
m_progressProvider.Completed -= new EventHandler(asyncOp_Completed);
m_progressProvider.Failed -= new ThreadExceptionEventHandler(asyncOp_Failed);
}
#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.cancelButton = new System.Windows.Forms.Button();
this.progressBar = new ProgressBar();
this.progressLabel = new OpenLiveWriter.Controls.LabelControl();
this.panelCategory = new System.Windows.Forms.Panel();
this.labelCategory = new System.Windows.Forms.Label();
this.pictureBoxCategory = new System.Windows.Forms.PictureBox();
this.panelCategory.SuspendLayout();
this.SuspendLayout();
//
// cancelButton
//
this.cancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.cancelButton.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.cancelButton.Location = new System.Drawing.Point(237, 83);
this.cancelButton.Name = "cancelButton";
this.cancelButton.TabIndex = 1;
this.cancelButton.Text = "Cancel";
this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click);
//
// progressBar
//
this.progressBar.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.progressBar.Location = new System.Drawing.Point(10, 56);
this.progressBar.Name = "progressBar";
this.progressBar.Size = new System.Drawing.Size(304, 19);
this.progressBar.TabIndex = 0;
//
// progressLabel
//
this.progressLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.progressLabel.Location = new System.Drawing.Point(10, 38);
this.progressLabel.MultiLine = false;
this.progressLabel.Name = "progressLabel";
this.progressLabel.Size = new System.Drawing.Size(292, 16);
this.progressLabel.TabIndex = 2;
//
// panelCategory
//
this.panelCategory.Controls.Add(this.labelCategory);
this.panelCategory.Controls.Add(this.pictureBoxCategory);
this.panelCategory.Location = new System.Drawing.Point(10, 13);
this.panelCategory.Name = "panelCategory";
this.panelCategory.Size = new System.Drawing.Size(300, 24);
this.panelCategory.TabIndex = 3;
//
// labelCategory
//
this.labelCategory.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.labelCategory.Location = new System.Drawing.Point(22, 1);
this.labelCategory.Name = "labelCategory";
this.labelCategory.Size = new System.Drawing.Size(278, 16);
this.labelCategory.TabIndex = 1;
//
// pictureBoxCategory
//
this.pictureBoxCategory.Location = new System.Drawing.Point(1, 0);
this.pictureBoxCategory.Name = "pictureBoxCategory";
this.pictureBoxCategory.Size = new System.Drawing.Size(16, 16);
this.pictureBoxCategory.TabIndex = 0;
this.pictureBoxCategory.TabStop = false;
//
// ProgressDialog
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 14);
this.CancelButton = this.cancelButton;
this.ClientSize = new System.Drawing.Size(324, 113);
this.ControlBox = false;
this.Controls.Add(this.panelCategory);
this.Controls.Add(this.progressLabel);
this.Controls.Add(this.progressBar);
this.Controls.Add(this.cancelButton);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "ProgressDialog";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Progress Title";
this.panelCategory.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The progress provider for this progress dialog
/// </summary>
private IProgressProvider m_progressProvider;
private IProgressCategoryProvider m_progressCategoryProvider;
DialogResult m_progressProviderResult = DialogResult.None;
private Button cancelButton;
private ProgressBar progressBar;
private LabelControl progressLabel;
private Panel panelCategory;
private PictureBox pictureBoxCategory;
private Label labelCategory;
/// <summary>
/// Required designer variable.
/// </summary>
private Container components = null;
}
}
| |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
namespace MindTouch.Text.CharDet.Statistics {
internal class StatisticsEUCKR : AStatistics {
//--- Constructors ---
public StatisticsEUCKR() {
FirstByteFreq = new[] {
0.000000f, // FreqH[a1]
0.000000f, // FreqH[a2]
0.000000f, // FreqH[a3]
0.000000f, // FreqH[a4]
0.000000f, // FreqH[a5]
0.000000f, // FreqH[a6]
0.000000f, // FreqH[a7]
0.000412f, // FreqH[a8]
0.000000f, // FreqH[a9]
0.000000f, // FreqH[aa]
0.000000f, // FreqH[ab]
0.000000f, // FreqH[ac]
0.000000f, // FreqH[ad]
0.000000f, // FreqH[ae]
0.000000f, // FreqH[af]
0.057502f, // FreqH[b0]
0.033182f, // FreqH[b1]
0.002267f, // FreqH[b2]
0.016076f, // FreqH[b3]
0.014633f, // FreqH[b4]
0.032976f, // FreqH[b5]
0.004122f, // FreqH[b6]
0.011336f, // FreqH[b7]
0.058533f, // FreqH[b8]
0.024526f, // FreqH[b9]
0.025969f, // FreqH[ba]
0.054411f, // FreqH[bb]
0.019580f, // FreqH[bc]
0.063273f, // FreqH[bd]
0.113974f, // FreqH[be]
0.029885f, // FreqH[bf]
0.150041f, // FreqH[c0]
0.059151f, // FreqH[c1]
0.002679f, // FreqH[c2]
0.009893f, // FreqH[c3]
0.014839f, // FreqH[c4]
0.026381f, // FreqH[c5]
0.015045f, // FreqH[c6]
0.069456f, // FreqH[c7]
0.089860f, // FreqH[c8]
0.000000f, // FreqH[c9]
0.000000f, // FreqH[ca]
0.000000f, // FreqH[cb]
0.000000f, // FreqH[cc]
0.000000f, // FreqH[cd]
0.000000f, // FreqH[ce]
0.000000f, // FreqH[cf]
0.000000f, // FreqH[d0]
0.000000f, // FreqH[d1]
0.000000f, // FreqH[d2]
0.000000f, // FreqH[d3]
0.000000f, // FreqH[d4]
0.000000f, // FreqH[d5]
0.000000f, // FreqH[d6]
0.000000f, // FreqH[d7]
0.000000f, // FreqH[d8]
0.000000f, // FreqH[d9]
0.000000f, // FreqH[da]
0.000000f, // FreqH[db]
0.000000f, // FreqH[dc]
0.000000f, // FreqH[dd]
0.000000f, // FreqH[de]
0.000000f, // FreqH[df]
0.000000f, // FreqH[e0]
0.000000f, // FreqH[e1]
0.000000f, // FreqH[e2]
0.000000f, // FreqH[e3]
0.000000f, // FreqH[e4]
0.000000f, // FreqH[e5]
0.000000f, // FreqH[e6]
0.000000f, // FreqH[e7]
0.000000f, // FreqH[e8]
0.000000f, // FreqH[e9]
0.000000f, // FreqH[ea]
0.000000f, // FreqH[eb]
0.000000f, // FreqH[ec]
0.000000f, // FreqH[ed]
0.000000f, // FreqH[ee]
0.000000f, // FreqH[ef]
0.000000f, // FreqH[f0]
0.000000f, // FreqH[f1]
0.000000f, // FreqH[f2]
0.000000f, // FreqH[f3]
0.000000f, // FreqH[f4]
0.000000f, // FreqH[f5]
0.000000f, // FreqH[f6]
0.000000f, // FreqH[f7]
0.000000f, // FreqH[f8]
0.000000f, // FreqH[f9]
0.000000f, // FreqH[fa]
0.000000f, // FreqH[fb]
0.000000f, // FreqH[fc]
0.000000f, // FreqH[fd]
0.000000f // FreqH[fe]
};
FirstByteStdDev = 0.025593f; // Lead Byte StdDev
FirstByteMean = 0.010638f; // Lead Byte Mean
FirstByteWeight = 0.647437f; // Lead Byte Weight
SecondByteFreq = new[] {
0.016694f, // FreqL[a1]
0.000000f, // FreqL[a2]
0.012778f, // FreqL[a3]
0.030091f, // FreqL[a4]
0.002679f, // FreqL[a5]
0.006595f, // FreqL[a6]
0.001855f, // FreqL[a7]
0.000824f, // FreqL[a8]
0.005977f, // FreqL[a9]
0.004740f, // FreqL[aa]
0.003092f, // FreqL[ab]
0.000824f, // FreqL[ac]
0.019580f, // FreqL[ad]
0.037304f, // FreqL[ae]
0.008244f, // FreqL[af]
0.014633f, // FreqL[b0]
0.001031f, // FreqL[b1]
0.000000f, // FreqL[b2]
0.003298f, // FreqL[b3]
0.002061f, // FreqL[b4]
0.006183f, // FreqL[b5]
0.005977f, // FreqL[b6]
0.000824f, // FreqL[b7]
0.021847f, // FreqL[b8]
0.014839f, // FreqL[b9]
0.052968f, // FreqL[ba]
0.017312f, // FreqL[bb]
0.007626f, // FreqL[bc]
0.000412f, // FreqL[bd]
0.000824f, // FreqL[be]
0.011129f, // FreqL[bf]
0.000000f, // FreqL[c0]
0.000412f, // FreqL[c1]
0.001649f, // FreqL[c2]
0.005977f, // FreqL[c3]
0.065746f, // FreqL[c4]
0.020198f, // FreqL[c5]
0.021434f, // FreqL[c6]
0.014633f, // FreqL[c7]
0.004122f, // FreqL[c8]
0.001649f, // FreqL[c9]
0.000824f, // FreqL[ca]
0.000824f, // FreqL[cb]
0.051937f, // FreqL[cc]
0.019580f, // FreqL[cd]
0.023289f, // FreqL[ce]
0.026381f, // FreqL[cf]
0.040396f, // FreqL[d0]
0.009068f, // FreqL[d1]
0.001443f, // FreqL[d2]
0.003710f, // FreqL[d3]
0.007420f, // FreqL[d4]
0.001443f, // FreqL[d5]
0.013190f, // FreqL[d6]
0.002885f, // FreqL[d7]
0.000412f, // FreqL[d8]
0.003298f, // FreqL[d9]
0.025969f, // FreqL[da]
0.000412f, // FreqL[db]
0.000412f, // FreqL[dc]
0.006183f, // FreqL[dd]
0.003298f, // FreqL[de]
0.066983f, // FreqL[df]
0.002679f, // FreqL[e0]
0.002267f, // FreqL[e1]
0.011129f, // FreqL[e2]
0.000412f, // FreqL[e3]
0.010099f, // FreqL[e4]
0.015251f, // FreqL[e5]
0.007626f, // FreqL[e6]
0.043899f, // FreqL[e7]
0.003710f, // FreqL[e8]
0.002679f, // FreqL[e9]
0.001443f, // FreqL[ea]
0.010923f, // FreqL[eb]
0.002885f, // FreqL[ec]
0.009068f, // FreqL[ed]
0.019992f, // FreqL[ee]
0.000412f, // FreqL[ef]
0.008450f, // FreqL[f0]
0.005153f, // FreqL[f1]
0.000000f, // FreqL[f2]
0.010099f, // FreqL[f3]
0.000000f, // FreqL[f4]
0.001649f, // FreqL[f5]
0.012160f, // FreqL[f6]
0.011542f, // FreqL[f7]
0.006595f, // FreqL[f8]
0.001855f, // FreqL[f9]
0.010923f, // FreqL[fa]
0.000412f, // FreqL[fb]
0.023702f, // FreqL[fc]
0.003710f, // FreqL[fd]
0.001855f // FreqL[fe]
};
SecondByteStdDev = 0.013937f; // Trail Byte StdDev
SecondByteMean = 0.010638f; // Trail Byte Mean
SecondByteWeight = 0.352563f; // Trial Byte Weight
}
}
}
| |
// ***********************************************************************
// <copyright file="SimpleContainer.cs" company="ServiceStack, Inc.">
// Copyright (c) ServiceStack, Inc. All Rights Reserved.
// </copyright>
// <summary>Fork for YetAnotherForum.NET, Licensed under the Apache License, Version 2.0</summary>
// ***********************************************************************
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using ServiceStack.Configuration;
namespace ServiceStack
{
using ServiceStack.Text;
/// <summary>
/// Class SimpleContainer.
/// Implements the <see cref="ServiceStack.IContainer" />
/// Implements the <see cref="ServiceStack.Configuration.IResolver" />
/// </summary>
/// <seealso cref="ServiceStack.IContainer" />
/// <seealso cref="ServiceStack.Configuration.IResolver" />
public class SimpleContainer : IContainer, IResolver
{
/// <summary>
/// Gets the ignore types named.
/// </summary>
/// <value>The ignore types named.</value>
public HashSet<string> IgnoreTypesNamed { get; } = new();
/// <summary>
/// The instance cache
/// </summary>
protected readonly ConcurrentDictionary<Type, object> InstanceCache = new();
/// <summary>
/// The factory
/// </summary>
protected readonly ConcurrentDictionary<Type, Func<object>> Factory = new();
/// <summary>
/// Resolves the specified type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>object.</returns>
public object Resolve(Type type)
{
Factory.TryGetValue(type, out Func<object> fn);
return fn?.Invoke();
}
/// <summary>
/// Existses the specified type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>bool.</returns>
public bool Exists(Type type) => Factory.ContainsKey(type);
/// <summary>
/// Requireds the resolve.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="ownerType">Type of the owner.</param>
/// <returns>object.</returns>
/// <exception cref="Exception">$"Required Type of '{type.Name}' in '{ownerType.Name}' constructor was not registered in '{GetType().Name}'</exception>
public object RequiredResolve(Type type, Type ownerType)
{
var instance = Resolve(type);
if (instance == null)
throw new Exception($"Required Type of '{type.Name}' in '{ownerType.Name}' constructor was not registered in '{GetType().Name}'");
return instance;
}
/// <summary>
/// Adds the singleton.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="factory">The factory.</param>
/// <returns>ServiceStack.IContainer.</returns>
public IContainer AddSingleton(Type type, Func<object> factory)
{
Factory[type] = () => InstanceCache.GetOrAdd(type, factory());
return this;
}
/// <summary>
/// Adds the transient.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="factory">The factory.</param>
/// <returns>ServiceStack.IContainer.</returns>
public IContainer AddTransient(Type type, Func<object> factory)
{
Factory[type] = factory;
return this;
}
/// <summary>
/// Tries the resolve.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns>T.</returns>
public T TryResolve<T>() => (T)Resolve(typeof(T));
/// <summary>
/// Includes the property.
/// </summary>
/// <param name="pi">The pi.</param>
/// <returns>bool.</returns>
protected virtual bool IncludeProperty(PropertyInfo pi)
{
return pi.CanWrite
&& !pi.PropertyType.IsValueType
&& pi.PropertyType != typeof(string)
&& pi.PropertyType != typeof(object)
&& !IgnoreTypesNamed.Contains(pi.PropertyType.FullName);
}
/// <summary>
/// Resolves the best constructor.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>System.Reflection.ConstructorInfo.</returns>
protected virtual ConstructorInfo ResolveBestConstructor(Type type)
{
return type.GetConstructors()
.OrderByDescending(x => x.GetParameters().Length) //choose constructor with most params
.FirstOrDefault(ctor => !ctor.IsStatic);
}
/// <summary>
/// Creates the factory.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>System.Func<object>.</returns>
/// <exception cref="Exception">$"Constructor not found for Type '{type.Name}</exception>
public Func<object> CreateFactory(Type type)
{
var containerParam = Expression.Constant(this);
var memberBindings = type.GetPublicProperties()
.Where(IncludeProperty)
.Select(x =>
Expression.Bind
(
x,
Expression.TypeAs(Expression.Call(containerParam, GetType().GetMethod(nameof(Resolve)), Expression.Constant(x.PropertyType)), x.PropertyType)
)
).ToArray();
var ctorWithMostParameters = ResolveBestConstructor(type);
if (ctorWithMostParameters == null)
throw new Exception($"Constructor not found for Type '{type.Name}");
var constructorParameterInfos = ctorWithMostParameters.GetParameters();
var regParams = constructorParameterInfos
.Select(x =>
Expression.TypeAs(Expression.Call(containerParam, GetType().GetMethod(nameof(RequiredResolve)), Expression.Constant(x.ParameterType), Expression.Constant(type)), x.ParameterType)
);
return Expression.Lambda<Func<object>>
(
Expression.TypeAs(Expression.MemberInit
(
Expression.New(ctorWithMostParameters, regParams.ToArray()),
memberBindings
), typeof(object))
).Compile();
}
/// <summary>
/// Disposes this instance.
/// </summary>
public void Dispose()
{
var hold = InstanceCache;
InstanceCache.Clear();
foreach (var instance in hold)
{
try
{
using (instance.Value as IDisposable) { }
}
catch { /* ignored */ }
}
}
}
/// <summary>
/// Class ContainerExtensions.
/// </summary>
public static class ContainerExtensions
{
/// <summary>
/// Resolves the specified container.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="container">The container.</param>
/// <returns>T.</returns>
/// <exception cref="Exception">$"Error trying to resolve Service '{typeof(T).Name}' or one of its autowired dependencies.</exception>
public static T Resolve<T>(this IResolver container)
{
var ret = container.TryResolve<T>();
if (ret == null)
throw new Exception($"Error trying to resolve Service '{typeof(T).Name}' or one of its autowired dependencies.");
return ret;
}
/// <summary>
/// Resolves the specified container.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="container">The container.</param>
/// <returns>T.</returns>
public static T Resolve<T>(this IContainer container) =>
(T)container.Resolve(typeof(T));
/// <summary>
/// Existses the specified container.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="container">The container.</param>
/// <returns>bool.</returns>
public static bool Exists<T>(this IContainer container) => container.Exists(typeof(T));
/// <summary>
/// Adds the transient.
/// </summary>
/// <typeparam name="TService">The type of the t service.</typeparam>
/// <param name="container">The container.</param>
/// <returns>ServiceStack.IContainer.</returns>
public static IContainer AddTransient<TService>(this IContainer container) =>
container.AddTransient(typeof(TService), container.CreateFactory(typeof(TService)));
/// <summary>
/// Adds the transient.
/// </summary>
/// <typeparam name="TService">The type of the t service.</typeparam>
/// <param name="container">The container.</param>
/// <param name="factory">The factory.</param>
/// <returns>ServiceStack.IContainer.</returns>
public static IContainer AddTransient<TService>(this IContainer container, Func<TService> factory) =>
container.AddTransient(typeof(TService), () => factory());
/// <summary>
/// Adds the transient.
/// </summary>
/// <typeparam name="TService">The type of the t service.</typeparam>
/// <typeparam name="TImpl">The type of the t implementation.</typeparam>
/// <param name="container">The container.</param>
/// <returns>ServiceStack.IContainer.</returns>
public static IContainer AddTransient<TService, TImpl>(this IContainer container) where TImpl : TService =>
container.AddTransient(typeof(TService), container.CreateFactory(typeof(TImpl)));
/// <summary>
/// Adds the transient.
/// </summary>
/// <param name="container">The container.</param>
/// <param name="type">The type.</param>
/// <returns>ServiceStack.IContainer.</returns>
public static IContainer AddTransient(this IContainer container, Type type) =>
container.AddTransient(type, container.CreateFactory(type));
/// <summary>
/// Adds the singleton.
/// </summary>
/// <typeparam name="TService">The type of the t service.</typeparam>
/// <param name="container">The container.</param>
/// <returns>ServiceStack.IContainer.</returns>
public static IContainer AddSingleton<TService>(this IContainer container) =>
container.AddSingleton(typeof(TService), container.CreateFactory(typeof(TService)));
/// <summary>
/// Adds the singleton.
/// </summary>
/// <typeparam name="TService">The type of the t service.</typeparam>
/// <param name="container">The container.</param>
/// <param name="factory">The factory.</param>
/// <returns>ServiceStack.IContainer.</returns>
public static IContainer AddSingleton<TService>(this IContainer container, Func<TService> factory) =>
container.AddSingleton(typeof(TService), () => factory());
/// <summary>
/// Adds the singleton.
/// </summary>
/// <typeparam name="TService">The type of the t service.</typeparam>
/// <typeparam name="TImpl">The type of the t implementation.</typeparam>
/// <param name="container">The container.</param>
/// <returns>ServiceStack.IContainer.</returns>
public static IContainer AddSingleton<TService, TImpl>(this IContainer container) where TImpl : TService =>
container.AddSingleton(typeof(TService), container.CreateFactory(typeof(TImpl)));
/// <summary>
/// Adds the singleton.
/// </summary>
/// <param name="container">The container.</param>
/// <param name="type">The type.</param>
/// <returns>ServiceStack.IContainer.</returns>
public static IContainer AddSingleton(this IContainer container, Type type) =>
container.AddSingleton(type, container.CreateFactory(type));
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using CoreXml.Test.XLinq;
using Xunit;
namespace System.Xml.Linq.Tests
{
public class DeepEqualsTests
{
// equals => hashcode should be the same
// - all "simple" node types
// - text vs. CDATA
// XDocument:
// - Normal mode
// - Concatenated text (Whitespace) nodes
// - Diffs in XDecl
// XElement:
// - Normal mode
// - same nodes, different order
// - comments inside the texts
// - same nodes, same order (positive)
//
// - Concatenated text nodes
// - string content vs. text node/s
// - empty string vs. empty text node
// - Multiple text nodes but the same value
// - adjacent text & CData
//
// - IsEmpty
// - Attribute order
// - Namespace declarations
// - local vs. in-scope
// - default redef.
[InlineData("PI", "click", "PI", "click", true)] // normal
[InlineData("PI", "PI", "PI", "PI", true)] // target=data
[InlineData("PI", "", "PI", "", true)] // data = ''
[InlineData("PI", "click", "PI", "", false)] // data1!=data2
[InlineData("AAAAP", "click", "AAAAQ", "click", false)] // target1!=target2
[InlineData("AAAAP", "AAAAQ", "AAAAP", "AAAAQ", true)] // hashconflict I
[InlineData("PA", "PA", "PI", "PI", false)] // data=target
[InlineData("AAAAP", "AAAAQ", "AAAAQ", "AAAAP", false)] // hashconflict II
[Theory]
public void ProcessingInstruction(string target1, string data1, string target2, string data2, bool checkHashCode)
{
var p1 = new XProcessingInstruction(target1, data1);
var p2 = new XProcessingInstruction(target2, data2);
VerifyComparison(checkHashCode, p1, p2);
XDocument doc = new XDocument(p1);
XElement e2 = new XElement("p2p", p2);
VerifyComparison(checkHashCode, p1, p2);
}
[InlineData("AAAAP", "AAAAQ", false)] // not equals, hashconflict
[InlineData("AAAAP", "AAAAP", true)] // equals
[InlineData(" ", " ", false)] // Whitespaces (negative)
[InlineData(" ", " ", true)] // Whitespaces
[InlineData("", "", true)] // Empty
[Theory]
public void Comment(string value1, string value2, bool checkHashCode)
{
XComment c1 = new XComment(value1);
XComment c2 = new XComment(value2);
VerifyComparison(checkHashCode, c1, c2);
XDocument doc = new XDocument(c1);
XElement e2 = new XElement("p2p", c2);
VerifyComparison(checkHashCode, c1, c2);
}
[InlineData(new[] { "root", "a", "b", "c" }, new[] { "root", "a", "b", "c" }, true)] // all field
[InlineData(new[] { "root", null, null, null }, new[] { "root", null, null, null }, true)] // all nulls
[InlineData(new[] { "root", null, null, "data" }, new[] { "root", null, null, "data" }, true)] // internal subset only
[InlineData(new[] { "A", "", "", "" }, new[] { "B", "", "", "" }, false)] // (negative) : name diff
[InlineData(new[] { "A", null, null, "aa" }, new[] { "A", null, null, "bb" }, false)] // (negative) : subset diff
[InlineData(new[] { "A", "", "", "" }, new[] { "A", null, null, null }, false)] // (negative) : null vs. empty
[Theory]
public void DocumentType(string[] docType1, string[] docType2, bool checkHashCode)
{
var dtd1 = new XDocumentType(docType1[0], docType1[1], docType1[2], docType1[3]);
var dtd2 = new XDocumentType(docType2[0], docType2[1], docType2[2], docType2[3]);
VerifyComparison(checkHashCode, dtd1, dtd2);
}
[InlineData("same", "different", false)] // different
[InlineData("same", "same", true)] // same
[InlineData("", "", true)] // Empty
[InlineData(" ", " ", true)] // Whitespaces
[InlineData("\n", " ", false)] // Whitespaces (negative)
[Theory]
public void Text(string value1, string value2, bool checkHashCode)
{
XText t1 = new XText(value1);
XText t2 = new XText(value2);
VerifyComparison(checkHashCode, t1, t2);
XElement e2 = new XElement("p2p", t2);
e2.Add(t1);
VerifyComparison(checkHashCode, t1, t2);
}
[InlineData("same", "different", false)] // different
[InlineData("same", "same", true)] // same
[InlineData("", "", true)] // Empty
[InlineData(" ", " ", true)] // Whitespaces
[InlineData("\n", " ", false)] // Whitespaces (negative)
[Theory]
public void CData(string value1, string value2, bool checkHashCode)
{
XCData t1 = new XCData(value1);
XCData t2 = new XCData(value2);
VerifyComparison(checkHashCode, t1, t2);
XElement e2 = new XElement("p2p", t2);
e2.Add(t1);
VerifyComparison(checkHashCode, t1, t2);
}
[InlineData("same", "same", false)]
[InlineData("", "", false)]
[InlineData(" ", " ", false)]
[Theory]
public void TextVsCData(string value1, string value2, bool checkHashCode)
{
XText t1 = new XCData(value1);
XText t2 = new XText(value2);
VerifyComparison(checkHashCode, t1, t2);
XElement e2 = new XElement("p2p", t2);
e2.Add(t1);
VerifyComparison(checkHashCode, t1, t2);
}
// do not concatenate inside
[Fact]
public void TextWholeVsConcatenate()
{
XElement e = new XElement("A", new XText("_start_"), new XText("_end_"));
XNode[] pieces = new XNode[] { new XText("_start_"), new XText("_end_") };
XText together = new XText("_start__end_");
VerifyComparison(true, e.FirstNode, pieces[0]);
VerifyComparison(true, e.LastNode, pieces[1]);
VerifyComparison(false, e.FirstNode, together);
VerifyComparison(false, e.LastNode, together);
}
[InlineData("<A/>", "<A></A>", false)] // smoke
[InlineData("<A/>", "<A Id='a'/>", false)] // atribute missing
[InlineData("<A Id='a'/>", "<A Id='a'/>", true)] // atributes
[InlineData("<A at='1' Id='a'/>", "<A Id='a' at='1'/>", false)] // atributes (same, different order)
[InlineData("<A at='1' Id='a'/>", "<A at='1' Id='a'/>", true)] // atributes (same, same order)
[InlineData("<A at='1' Id='a'/>", "<A at='1' Id='ab'/>", false)] // atributes (same, same order, different value)
[InlineData("<A p:at='1' xmlns:p='nsp'/>", "<A p:at='1' xmlns:p='nsp'/>", true)] // atributes (same, same order, namespace decl)
[InlineData("<A p:at='1' xmlns:p='nsp'/>", "<A q:at='1' xmlns:q='nsp'/>", false)] // atributes (same, same order, namespace decl, different prefix)
[InlineData("<A>text</A>", "<A>text</A>", true)] // String content
[InlineData("<A>text<?PI click?></A>", "<A><?PI click?>text</A>", false)] // String + PI content (negative)
[InlineData("<A>text<?PI click?></A>", "<A>text<?PI click?></A>", true)] // String + PI content
[Theory]
public void Element(string text1, string text2, bool checkHashCode)
{
XElement e1 = XElement.Parse(text1);
XElement e2 = XElement.Parse(text2);
VerifyComparison(checkHashCode, e1, e2);
// Should always be the same ...
VerifyComparison(true, e1, e1);
VerifyComparison(true, e2, e2);
}
// String content vs. text node vs. CData
[Fact]
public void Element2()
{
XElement e1 = new XElement("A", "string_content");
XElement e2 = new XElement("A", new XText("string_content"));
XElement e3 = new XElement("A", new XCData("string_content"));
VerifyComparison(true, e1, e2);
VerifyComparison(false, e1, e3);
VerifyComparison(false, e2, e3);
}
// XElement - text node concatenations
[Fact]
public void Element3()
{
XElement e1 = new XElement("A", "string_content");
XElement e2 = new XElement("A", new XText("string"), new XText("_content"));
XElement e3 = new XElement("A", new XText("string"), new XComment("comm"), new XText("_content"));
XElement e4 = new XElement("A", new XText("string"), new XCData("_content"));
VerifyComparison(true, e1, e2);
VerifyComparison(false, e1, e3);
VerifyComparison(false, e2, e3);
VerifyComparison(false, e1, e4);
VerifyComparison(false, e2, e4);
VerifyComparison(false, e3, e4);
e3.Nodes().First(n => n is XComment).Remove();
VerifyComparison(true, e1, e3);
VerifyComparison(true, e2, e3);
}
[InlineData(1)] // XElement - text node incarnation - by touching
[InlineData(2)] // XElement - text node incarnation - by adding new node
[Theory]
public void Element6(int param)
{
XElement e1 = new XElement("A", "datata");
XElement e2 = new XElement("A", "datata");
switch (param)
{
case 1:
XComment c = new XComment("hele");
e2.Add(c);
c.Remove();
break;
case 2:
break;
}
VerifyComparison(true, e1, e2);
}
// XElement - text node concatenations (negative)
[Fact]
public void Element4()
{
XElement e1 = new XElement("A", new XCData("string_content"));
XElement e2 = new XElement("A", new XCData("string"), new XCData("_content"));
XElement e3 = new XElement("A", new XCData("string"), "_content");
VerifyComparison(false, e1, e2);
VerifyComparison(false, e1, e3);
VerifyComparison(false, e3, e2);
}
// XElement - namespace prefixes
[Fact]
public void Element5()
{
XElement e1 = XElement.Parse("<A xmlns='nsa'><B><!--comm--><C xmlns=''/></B></A>").Elements().First();
XElement e2 = XElement.Parse("<A xmlns:p='nsa'><p:B><!--comm--><C xmlns=''/></p:B></A>").Elements().First();
VerifyComparison(true, e1, e2);
// Should always be the same ...
VerifyComparison(true, e1, e1);
VerifyComparison(true, e2, e2);
}
[Fact]
public void ElementDynamic()
{
XElement helper = new XElement("helper", new XText("ko"), new XText("ho"));
object[] content = new object[]
{
"text1", new object[] { new string[] { "t1", null, "t2" }, "t1t2" }, new XProcessingInstruction("PI1", ""),
new XProcessingInstruction("PI1", ""), new XProcessingInstruction("PI2", "click"),
new object[] { new XElement("X", new XAttribute("id", "a1"), new XText("hula")), new XElement("X", new XText("hula"), new XAttribute("id", "a1")) },
new XElement("{nsp}X", new XAttribute("id", "a1"), "hula"),
new object[] { new XText("koho"), helper.Nodes() },
new object[] { new XText[] { new XText("hele"), new XText(""), new XCData("youuu") }, new XText[] { new XText("hele"), new XCData("youuu") } },
new XComment(""), new XComment("comment"),
new XAttribute("id1", "nono"), new XAttribute("id3", "nono2"), new XAttribute("{nsa}id3", "nono2"),
new XAttribute("{nsb}id3", "nono2"), new XAttribute("xmlns", "default"),
new XAttribute(XNamespace.Xmlns + "a", "nsa"), new XAttribute(XNamespace.Xmlns + "p", "nsp"),
new XElement("{nsa}X", new XAttribute("id", "a1"), "hula", new XAttribute("{nsb}aB", "hele"), new XElement("{nsc}C"))
};
foreach (object[] objs in content.NonRecursiveVariations(4))
{
XElement e1 = new XElement("E", ExpandAndProtectTextNodes(objs, 0));
XElement e2 = new XElement("E", ExpandAndProtectTextNodes(objs, 1));
VerifyComparison(true, e1, e2);
e1.RemoveAll();
e2.RemoveAll();
}
}
private IEnumerable<object> ExpandAndProtectTextNodes(IEnumerable<object> source, int position)
{
foreach (object o in source)
{
object t = (o is object[]) ? (o as object[])[position] : o;
if (t is XText && !(t is XCData))
{
yield return new XText(t as XText); // clone xtext node
continue;
}
if (t is XText[])
{
yield return (t as XText[]).Select(x => new XText(x)).ToArray(); // clone XText []
continue;
}
yield return t;
}
}
[Fact]
public void Document1()
{
object[] content = new object[]
{
new object[] { new string[] { " ", null, " " }, " " },
new object[] { new string[] { " ", " \t" }, new XText(" \t") },
new object[] { new XText[] { new XText(" "), new XText("\t") }, new XText(" \t") },
new XDocumentType("root", "", "", ""), new XProcessingInstruction("PI1", ""), new XText("\n"),
new XText("\t"), new XText(" "), new XProcessingInstruction("PI1", ""), new XElement("myroot"),
new XProcessingInstruction("PI2", "click"),
new object[]
{
new XElement("X", new XAttribute("id", "a1"), new XText("hula")),
new XElement("X", new XText("hula"), new XAttribute("id", "a1"))
},
new XComment(""),
new XComment("comment"),
};
foreach (object[] objs in content.NonRecursiveVariations(4))
{
XDocument doc1 = null;
XDocument doc2 = null;
try
{
object[] o1 = ExpandAndProtectTextNodes(objs, 0).ToArray();
object[] o2 = ExpandAndProtectTextNodes(objs, 1).ToArray();
if (o1.Select(x => new ExpectedValue(false, x)).IsXDocValid()
|| o2.Select(x => new ExpectedValue(false, x)).IsXDocValid()) continue;
doc1 = new XDocument(o1);
doc2 = new XDocument(o2);
VerifyComparison(true, doc1, doc2);
}
catch (InvalidOperationException)
{
// some combination produced from the array are invalid
continue;
}
finally
{
if (doc1 != null) doc1.RemoveNodes();
if (doc2 != null) doc2.RemoveNodes();
}
}
}
[InlineData(true)]
[InlineData(false)]
[Theory]
public void Document4(bool checkHashCode)
{
var doc1 = new XDocument(new object[] { (checkHashCode ? new XDocumentType("root", "", "", "") : null), new XElement("root") });
var doc2 = new XDocument(new object[] { new XDocumentType("root", "", "", ""), new XElement("root") });
VerifyComparison(checkHashCode, doc1, doc2);
}
private void VerifyComparison(bool expected, XNode n1, XNode n2)
{
Assert.Equal(XNode.EqualityComparer.Equals(n1, n2), XNode.EqualityComparer.Equals(n2, n1)); // commutative
Assert.Equal(((IEqualityComparer)XNode.EqualityComparer).Equals(n1, n2), ((IEqualityComparer)XNode.EqualityComparer).Equals(n2, n1)); // commutative - interface
Assert.Equal(expected, XNode.EqualityComparer.Equals(n1, n2));
Assert.Equal(expected, ((IEqualityComparer)XNode.EqualityComparer).Equals(n1, n2));
if (expected)
{
Assert.Equal(XNode.EqualityComparer.GetHashCode(n1), XNode.EqualityComparer.GetHashCode(n2));
Assert.Equal(((IEqualityComparer)XNode.EqualityComparer).GetHashCode(n1), ((IEqualityComparer)XNode.EqualityComparer).GetHashCode(n2));
}
}
[Fact]
public void Nulls()
{
XElement e = new XElement("A");
Assert.False(XNode.EqualityComparer.Equals(e, null), "left null");
Assert.False(XNode.EqualityComparer.Equals(null, e), "right null");
Assert.True(XNode.EqualityComparer.Equals(null, null), "both null");
Assert.Equal(0, XNode.EqualityComparer.GetHashCode(null));
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="RewritingValidator.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
namespace System.Data.Mapping.ViewGeneration.Validation
{
using System.Collections.Generic;
using System.Data.Common.Utils;
using System.Data.Common.Utils.Boolean;
using System.Data.Entity;
using System.Data.Mapping.ViewGeneration.QueryRewriting;
using System.Data.Mapping.ViewGeneration.Structures;
using System.Data.Mapping.ViewGeneration.Utils;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
/// <summary>
/// Validates each mapping fragment/cell (Qc = Qs)
/// by unfolding update views in Qs and checking query equivalence
/// </summary>
internal class RewritingValidator
{
private ViewgenContext _viewgenContext;
private MemberDomainMap _domainMap;
private CellTreeNode _basicView;
private IEnumerable<MemberPath> _keyAttributes;
private ErrorLog _errorLog;
internal RewritingValidator(ViewgenContext context, CellTreeNode basicView)
{
_viewgenContext = context;
_basicView = basicView;
_domainMap = _viewgenContext.MemberMaps.UpdateDomainMap;
_keyAttributes = MemberPath.GetKeyMembers(_viewgenContext.Extent, _domainMap);
_errorLog = new ErrorLog();
}
#region Main logic
internal void Validate()
{
// turn rewritings into cell trees
// plain: according to rewritings for case statements
Dictionary<MemberValueBinding, CellTreeNode> plainMemberValueTrees = CreateMemberValueTrees(false);
// complement: uses complement rewriting for the last WHEN ... THEN
// This is how the final case statement will be generated in update views
Dictionary<MemberValueBinding, CellTreeNode> complementMemberValueTrees = CreateMemberValueTrees(true);
WhereClauseVisitor plainWhereClauseVisitor = new WhereClauseVisitor(_basicView, plainMemberValueTrees);
WhereClauseVisitor complementWhereClauseVisitor = new WhereClauseVisitor(_basicView, complementMemberValueTrees);
// produce CellTree for each SQuery
foreach (LeftCellWrapper wrapper in _viewgenContext.AllWrappersForExtent)
{
Cell cell = wrapper.OnlyInputCell;
// construct cell tree for CQuery
CellTreeNode cQueryTree = new LeafCellTreeNode(_viewgenContext, wrapper);
// sQueryTree: unfolded update view inside S-side of the cell
CellTreeNode sQueryTree;
// construct cell tree for SQuery (will be used for domain constraint checking)
CellTreeNode complementSQueryTreeForCondition = complementWhereClauseVisitor.GetCellTreeNode(cell.SQuery.WhereClause);
Debug.Assert(complementSQueryTreeForCondition != null, "Rewriting for S-side query is unsatisfiable");
if (complementSQueryTreeForCondition == null)
{
continue; // situation should never happen
}
if (complementSQueryTreeForCondition != _basicView)
{
// intersect with basic expression
sQueryTree = new OpCellTreeNode(_viewgenContext, CellTreeOpType.IJ, complementSQueryTreeForCondition, _basicView);
}
else
{
sQueryTree = _basicView;
}
// Append in-set or in-end condition to both queries to produce more concise errors
// Otherwise, the errors are of the form "if there exists an entity in extent, then violation". We don't care about empty extents
BoolExpression inExtentCondition = BoolExpression.CreateLiteral(wrapper.CreateRoleBoolean(), _viewgenContext.MemberMaps.QueryDomainMap);
BoolExpression unsatisfiedConstraint;
if (!CheckEquivalence(cQueryTree.RightFragmentQuery, sQueryTree.RightFragmentQuery, inExtentCondition,
out unsatisfiedConstraint))
{
string extentName = StringUtil.FormatInvariant("{0}", _viewgenContext.Extent);
// Simplify to produce more readable error messages
cQueryTree.RightFragmentQuery.Condition.ExpensiveSimplify();
sQueryTree.RightFragmentQuery.Condition.ExpensiveSimplify();
String message = Strings.ViewGen_CQ_PartitionConstraint(extentName);
ReportConstraintViolation(message, unsatisfiedConstraint, ViewGenErrorCode.PartitionConstraintViolation,
cQueryTree.GetLeaves().Concat(sQueryTree.GetLeaves()));
}
CellTreeNode plainSQueryTreeForCondition = plainWhereClauseVisitor.GetCellTreeNode(cell.SQuery.WhereClause);
Debug.Assert(plainSQueryTreeForCondition != null, "Rewriting for S-side query is unsatisfiable");
if (plainSQueryTreeForCondition != null)
{
// Query is non-empty. Check domain constraints on:
// (a) swapped members
DomainConstraintVisitor.CheckConstraints(plainSQueryTreeForCondition, wrapper, _viewgenContext, _errorLog);
//If you have already found errors, just continue on to the next wrapper instead of //collecting more errors for the same
if (_errorLog.Count > 0)
{
continue;
}
// (b) projected members
CheckConstraintsOnProjectedConditionMembers(plainMemberValueTrees, wrapper, sQueryTree, inExtentCondition);
if (_errorLog.Count > 0)
{
continue;
}
}
CheckConstraintsOnNonNullableMembers(plainMemberValueTrees, wrapper, sQueryTree, inExtentCondition);
}
if (_errorLog.Count > 0)
{
ExceptionHelpers.ThrowMappingException(_errorLog, _viewgenContext.Config);
}
}
// Checks equivalence of two C-side queries
// inExtentConstraint holds a role variable that effectively denotes that some extent is non-empty
private bool CheckEquivalence(FragmentQuery cQuery, FragmentQuery sQuery, BoolExpression inExtentCondition,
out BoolExpression unsatisfiedConstraint)
{
FragmentQuery cMinusSx = _viewgenContext.RightFragmentQP.Difference(cQuery, sQuery);
FragmentQuery sMinusCx = _viewgenContext.RightFragmentQP.Difference(sQuery, cQuery);
// add in-extent condition
FragmentQuery cMinusS = FragmentQuery.Create(BoolExpression.CreateAnd(cMinusSx.Condition, inExtentCondition));
FragmentQuery sMinusC = FragmentQuery.Create(BoolExpression.CreateAnd(sMinusCx.Condition, inExtentCondition));
unsatisfiedConstraint = null;
bool forwardInclusion = true;
bool backwardInclusion = true;
if (_viewgenContext.RightFragmentQP.IsSatisfiable(cMinusS))
{
unsatisfiedConstraint = cMinusS.Condition;
forwardInclusion = false;
}
if (_viewgenContext.RightFragmentQP.IsSatisfiable(sMinusC))
{
unsatisfiedConstraint = sMinusC.Condition;
backwardInclusion = false;
}
if (forwardInclusion && backwardInclusion)
{
return true;
}
else
{
unsatisfiedConstraint.ExpensiveSimplify();
return false;
}
}
private void ReportConstraintViolation(string message, BoolExpression extraConstraint, ViewGenErrorCode errorCode, IEnumerable<LeftCellWrapper> relevantWrappers)
{
if (ErrorPatternMatcher.FindMappingErrors(_viewgenContext, _domainMap, _errorLog))
{
return;
}
extraConstraint.ExpensiveSimplify();
// gather all relevant cell wrappers and sort them in the original input order
HashSet<LeftCellWrapper> relevantCellWrappers = new HashSet<LeftCellWrapper>(relevantWrappers);
List<LeftCellWrapper> relevantWrapperList = new List<LeftCellWrapper>(relevantCellWrappers);
relevantWrapperList.Sort(LeftCellWrapper.OriginalCellIdComparer);
StringBuilder builder = new StringBuilder();
builder.AppendLine(message);
EntityConfigurationToUserString(extraConstraint, builder);
_errorLog.AddEntry(new ErrorLog.Record(true, errorCode, builder.ToString(), relevantCellWrappers, ""));
}
// according to case statements, where WHEN ... THEN was replaced by ELSE
private Dictionary<MemberValueBinding, CellTreeNode> CreateMemberValueTrees(bool complementElse)
{
Dictionary<MemberValueBinding, CellTreeNode> memberValueTrees = new Dictionary<MemberValueBinding, CellTreeNode>();
foreach (MemberPath column in _domainMap.ConditionMembers(_viewgenContext.Extent))
{
List<Constant> domain = new List<Constant>(_domainMap.GetDomain(column));
// all domain members but the last
OpCellTreeNode memberCover = new OpCellTreeNode(_viewgenContext, CellTreeOpType.Union);
for (int i = 0; i < domain.Count; i++)
{
Constant domainValue = domain[i];
MemberValueBinding memberValue = new MemberValueBinding(column, domainValue);
FragmentQuery memberConditionQuery = QueryRewriter.CreateMemberConditionQuery(column, domainValue, _keyAttributes, _domainMap);
Tile<FragmentQuery> rewriting;
if (_viewgenContext.TryGetCachedRewriting(memberConditionQuery, out rewriting))
{
// turn rewriting into a cell tree
CellTreeNode cellTreeNode = QueryRewriter.TileToCellTree(rewriting, _viewgenContext);
memberValueTrees[memberValue] = cellTreeNode;
// collect a union of all domain constants but the last
if (i < domain.Count - 1)
{
memberCover.Add(cellTreeNode);
}
}
else
{
Debug.Fail(String.Format(CultureInfo.InvariantCulture, "No cached rewriting for {0}={1}", column, domainValue));
}
}
if (complementElse && domain.Count > 1)
{
Constant lastDomainValue = domain[domain.Count - 1];
MemberValueBinding lastMemberValue = new MemberValueBinding(column, lastDomainValue);
memberValueTrees[lastMemberValue] = new OpCellTreeNode(_viewgenContext, CellTreeOpType.LASJ, _basicView, memberCover);
}
}
return memberValueTrees;
}
#endregion
#region Checking constraints on projected condition members
private void CheckConstraintsOnProjectedConditionMembers(Dictionary<MemberValueBinding, CellTreeNode> memberValueTrees, LeftCellWrapper wrapper, CellTreeNode sQueryTree, BoolExpression inExtentCondition)
{
// for S-side condition members that are projected,
// add condition <member=value> on both sides of the mapping constraint, and check key equivalence
// applies to columns that are (1) projected and (2) conditional
foreach (MemberPath column in _domainMap.ConditionMembers(_viewgenContext.Extent))
{
// Get the slot on the C side and see if it is projected
int index = _viewgenContext.MemberMaps.ProjectedSlotMap.IndexOf(column);
MemberProjectedSlot slot = wrapper.RightCellQuery.ProjectedSlotAt(index) as MemberProjectedSlot;
if (slot != null)
{
foreach (Constant domainValue in _domainMap.GetDomain(column))
{
CellTreeNode sQueryTreeForDomainValue;
if (memberValueTrees.TryGetValue(new MemberValueBinding(column, domainValue), out sQueryTreeForDomainValue))
{
BoolExpression cWhereClause = PropagateCellConstantsToWhereClause(wrapper, wrapper.RightCellQuery.WhereClause,
domainValue, column, _viewgenContext.MemberMaps);
FragmentQuery cCombinedQuery = FragmentQuery.Create(cWhereClause);
CellTreeNode sCombinedTree = (sQueryTree == _basicView) ?
sQueryTreeForDomainValue :
new OpCellTreeNode(_viewgenContext, CellTreeOpType.IJ, sQueryTreeForDomainValue, sQueryTree);
BoolExpression unsatisfiedConstraint;
if (!CheckEquivalence(cCombinedQuery, sCombinedTree.RightFragmentQuery, inExtentCondition,
out unsatisfiedConstraint))
{
string memberLossMessage = Strings.ViewGen_CQ_DomainConstraint(slot.ToUserString());
ReportConstraintViolation(memberLossMessage, unsatisfiedConstraint, ViewGenErrorCode.DomainConstraintViolation,
sCombinedTree.GetLeaves().Concat(new LeftCellWrapper[] { wrapper }));
}
}
}
}
}
}
// effects: Given a sequence of constants that need to be propagated
// to the C-side and the current boolean expression, generates a new
// expression of the form "expression AND C-side Member in constants"
// expression" and returns it. Each constant is propagated only if member
// is projected -- if member is not projected, returns "expression"
internal static BoolExpression PropagateCellConstantsToWhereClause(LeftCellWrapper wrapper, BoolExpression expression,
Constant constant, MemberPath member,
MemberMaps memberMaps)
{
MemberProjectedSlot joinSlot = wrapper.GetCSideMappedSlotForSMember(member);
if (joinSlot == null)
{
return expression;
}
// Look at the constants and determine if they correspond to
// typeConstants or scalarConstants
// This slot is being projected. We need to add a where clause element
Debug.Assert(constant is ScalarConstant || constant.IsNull() || constant is NegatedConstant, "Invalid type of constant");
// We want the possible values for joinSlot.MemberPath which is a
// C-side element -- so we use the queryDomainMap
IEnumerable<Constant> possibleValues = memberMaps.QueryDomainMap.GetDomain(joinSlot.MemberPath);
// Note: the values in constaints can be null or not null as
// well (i.e., just not scalarConstants)
Set<Constant> allowedValues = new Set<Constant>(Constant.EqualityComparer);
if (constant is NegatedConstant)
{
// select all values from the c-side domain that are not in the negated set
allowedValues.Unite(possibleValues);
allowedValues.Difference(((NegatedConstant)constant).Elements);
}
else
{
allowedValues.Add(constant);
}
MemberRestriction restriction = new ScalarRestriction(joinSlot.MemberPath, allowedValues, possibleValues);
BoolExpression result = BoolExpression.CreateAnd(expression, BoolExpression.CreateLiteral(restriction, memberMaps.QueryDomainMap));
return result;
}
#endregion
/// <summary>
/// Given a LeftCellWrapper for the S-side fragment and a non-nullable colum m, return a CQuery with nullability condition
/// appended to Cquery of c-side member that column m is mapped to
/// </summary>
private static FragmentQuery AddNullConditionOnCSideFragment(LeftCellWrapper wrapper, MemberPath member, MemberMaps memberMaps)
{
MemberProjectedSlot projectedSlot = wrapper.GetCSideMappedSlotForSMember(member);
if (projectedSlot == null || !projectedSlot.MemberPath.IsNullable) //don't bother checking further fore non nullable C-side member
{
return null;
}
BoolExpression expression = wrapper.RightCellQuery.WhereClause;
IEnumerable<Constant> possibleValues = memberMaps.QueryDomainMap.GetDomain(projectedSlot.MemberPath);
Set<Constant> allowedValues = new Set<Constant>(Constant.EqualityComparer);
allowedValues.Add(Constant.Null);
//Create a condition as conjunction of originalCondition and slot IS NULL
MemberRestriction restriction = new ScalarRestriction(projectedSlot.MemberPath, allowedValues, possibleValues);
BoolExpression resultingExpr = BoolExpression.CreateAnd(expression, BoolExpression.CreateLiteral(restriction, memberMaps.QueryDomainMap));
return FragmentQuery.Create(resultingExpr);
}
/// <summary>
/// Checks whether non nullable S-side members are mapped to nullable C-query.
/// It is possible that C-side attribute is nullable but the fragment's C-query is not
/// </summary>
private void CheckConstraintsOnNonNullableMembers(Dictionary<MemberValueBinding, CellTreeNode> memberValueTrees, LeftCellWrapper wrapper, CellTreeNode sQueryTree, BoolExpression inExtentCondition)
{
//For each non-condition member that has non-nullability constraint
foreach (MemberPath column in _domainMap.NonConditionMembers(_viewgenContext.Extent))
{
bool isColumnSimpleType = (column.EdmType as System.Data.Metadata.Edm.SimpleType) != null;
if (!column.IsNullable && isColumnSimpleType)
{
FragmentQuery cFragment = AddNullConditionOnCSideFragment(wrapper, column, _viewgenContext.MemberMaps);
if (cFragment != null && _viewgenContext.RightFragmentQP.IsSatisfiable(cFragment))
{
_errorLog.AddEntry(new ErrorLog.Record(true, ViewGenErrorCode.NullableMappingForNonNullableColumn, Strings.Viewgen_NullableMappingForNonNullableColumn(wrapper.LeftExtent.ToString(), column.ToFullString()), wrapper.Cells, ""));
}
}
}
}
#region Methods for turning a boolean condition into user string
internal static void EntityConfigurationToUserString(BoolExpression condition, StringBuilder builder)
{
//By default write the Round tripping message
EntityConfigurationToUserString(condition, builder, true);
}
internal static void EntityConfigurationToUserString(BoolExpression condition, StringBuilder builder, bool writeRoundTrippingMessage)
{
condition.AsUserString(builder, "PK", writeRoundTrippingMessage);
}
#endregion
#region WhereClauseVisitor: turns WHERE clause into CellTreeNode
private class WhereClauseVisitor : Visitor<DomainConstraint<BoolLiteral, Constant>, CellTreeNode>
{
ViewgenContext _viewgenContext;
CellTreeNode _topLevelTree;
Dictionary<MemberValueBinding, CellTreeNode> _memberValueTrees;
internal WhereClauseVisitor(CellTreeNode topLevelTree, Dictionary<MemberValueBinding, CellTreeNode> memberValueTrees)
{
_topLevelTree = topLevelTree;
_memberValueTrees = memberValueTrees;
_viewgenContext = topLevelTree.ViewgenContext;
}
// returns _topLevelTree when expression evaluates to True, null if it evaluates to False
internal CellTreeNode GetCellTreeNode(BoolExpression whereClause)
{
return whereClause.Tree.Accept(this);
}
internal override CellTreeNode VisitAnd(AndExpr<DomainConstraint<BoolLiteral, Constant>> expression)
{
IEnumerable<CellTreeNode> childrenTrees = AcceptChildren(expression.Children);
OpCellTreeNode node = new OpCellTreeNode(_viewgenContext, CellTreeOpType.IJ);
foreach (CellTreeNode childNode in childrenTrees)
{
if (childNode == null)
{
return null; // unsatisfiable
}
if (childNode != _topLevelTree)
{
node.Add(childNode);
}
}
return node.Children.Count == 0 ? _topLevelTree : node;
}
internal override CellTreeNode VisitTrue(TrueExpr<DomainConstraint<BoolLiteral, Constant>> expression)
{
return _topLevelTree;
}
internal override CellTreeNode VisitTerm(TermExpr<DomainConstraint<BoolLiteral, Constant>> expression)
{
MemberRestriction oneOf = (MemberRestriction)expression.Identifier.Variable.Identifier;
Set<Constant> range = expression.Identifier.Range;
// create a disjunction
OpCellTreeNode disjunctionNode = new OpCellTreeNode(_viewgenContext, CellTreeOpType.Union);
CellTreeNode singleNode = null;
foreach (Constant value in range)
{
if (TryGetCellTreeNode(oneOf.RestrictedMemberSlot.MemberPath, value, out singleNode))
{
disjunctionNode.Add(singleNode);
}
// else, there is no rewriting for this member value, i.e., it is empty
}
switch (disjunctionNode.Children.Count)
{
case 0:
return null; // empty rewriting
case 1: return singleNode;
default: return disjunctionNode;
}
}
internal override CellTreeNode VisitFalse(FalseExpr<DomainConstraint<BoolLiteral, Constant>> expression)
{
throw new NotImplementedException();
}
internal override CellTreeNode VisitNot(NotExpr<DomainConstraint<BoolLiteral, Constant>> expression)
{
throw new NotImplementedException();
}
internal override CellTreeNode VisitOr(OrExpr<DomainConstraint<BoolLiteral, Constant>> expression)
{
throw new NotImplementedException();
}
private bool TryGetCellTreeNode(MemberPath memberPath, Constant value, out CellTreeNode singleNode)
{
return (_memberValueTrees.TryGetValue(new MemberValueBinding(memberPath, value), out singleNode));
}
private IEnumerable<CellTreeNode> AcceptChildren(IEnumerable<BoolExpr<DomainConstraint<BoolLiteral, Constant>>> children)
{
foreach (BoolExpr<DomainConstraint<BoolLiteral, Constant>> child in children) { yield return child.Accept(this); }
}
}
#endregion
#region DomainConstraintVisitor: checks domain constraints
internal class DomainConstraintVisitor : CellTreeNode.SimpleCellTreeVisitor<bool, bool>
{
LeftCellWrapper m_wrapper;
ViewgenContext m_viewgenContext;
ErrorLog m_errorLog;
private DomainConstraintVisitor(LeftCellWrapper wrapper, ViewgenContext context, ErrorLog errorLog)
{
m_wrapper = wrapper;
m_viewgenContext = context;
m_errorLog = errorLog;
}
internal static void CheckConstraints(CellTreeNode node, LeftCellWrapper wrapper,
ViewgenContext context, ErrorLog errorLog)
{
DomainConstraintVisitor visitor = new DomainConstraintVisitor(wrapper, context, errorLog);
node.Accept<bool, bool>(visitor, true);
}
internal override bool VisitLeaf(LeafCellTreeNode node, bool dummy)
{
// make sure all projected attributes in wrapper correspond exactly to those in node
CellQuery thisQuery = m_wrapper.RightCellQuery;
CellQuery thatQuery = node.LeftCellWrapper.RightCellQuery;
List<MemberPath> collidingColumns = new List<MemberPath>();
if (thisQuery != thatQuery)
{
for (int i = 0; i < thisQuery.NumProjectedSlots; i++)
{
MemberProjectedSlot thisSlot = thisQuery.ProjectedSlotAt(i) as MemberProjectedSlot;
if (thisSlot != null)
{
MemberProjectedSlot thatSlot = thatQuery.ProjectedSlotAt(i) as MemberProjectedSlot;
if (thatSlot != null)
{
MemberPath tableMember = m_viewgenContext.MemberMaps.ProjectedSlotMap[i];
if (!tableMember.IsPartOfKey)
{
if (!MemberPath.EqualityComparer.Equals(thisSlot.MemberPath, thatSlot.MemberPath))
{
collidingColumns.Add(tableMember);
}
}
}
}
}
}
if (collidingColumns.Count > 0)
{
string columnsString = MemberPath.PropertiesToUserString(collidingColumns, false);
string message = Strings.ViewGen_NonKeyProjectedWithOverlappingPartitions(columnsString);
ErrorLog.Record record = new ErrorLog.Record(true, ViewGenErrorCode.NonKeyProjectedWithOverlappingPartitions, message,
new LeftCellWrapper[] { m_wrapper, node.LeftCellWrapper }, String.Empty);
m_errorLog.AddEntry(record);
}
return true;
}
internal override bool VisitOpNode(OpCellTreeNode node, bool dummy)
{
if (node.OpType == CellTreeOpType.LASJ)
{
// add conditions only on the positive node
node.Children[0].Accept<bool, bool>(this, dummy);
}
else
{
foreach (CellTreeNode child in node.Children)
{
child.Accept<bool, bool>(this, dummy);
}
}
return true;
}
}
#endregion
#region MemberValueBinding struct: (MemberPath, CellConstant) pair
private struct MemberValueBinding : IEquatable<MemberValueBinding>
{
internal readonly MemberPath Member;
internal readonly Constant Value;
public MemberValueBinding(MemberPath member, Constant value)
{
Member = member;
Value = value;
}
public override string ToString()
{
return String.Format(CultureInfo.InvariantCulture, "{0}={1}", Member, Value);
}
#region IEquatable<MemberValue> Members
public bool Equals(MemberValueBinding other)
{
return MemberPath.EqualityComparer.Equals(Member, other.Member) &&
Constant.EqualityComparer.Equals(Value, other.Value);
}
#endregion
}
#endregion
}
}
| |
/*
Copyright 2012 Michael Edwards
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.
*/
//-CRE-
using System;
using Glass.Mapper.Sc.Configuration;
using Glass.Mapper.Sc.DataMappers;
using Glass.Mapper.Sc.Fields;
using NSubstitute;
using NUnit.Framework;
using Sitecore.Data;
using Sitecore.FakeDb;
using Sitecore.Links;
namespace Glass.Mapper.Sc.FakeDb.DataMappers
{
[TestFixture]
public class SitecoreFieldLinkMapperFixture
{
#region Method - GetField
[Test]
public void GetField_FieldContainsAnchor_ReturnsAnchorLink()
{
//Assign
var templateId = ID.NewID;
var targetId = ID.NewID;
var fieldName = "Field";
using (Db database = new Db
{
new DbTemplate(templateId)
{
{fieldName, ""}
},
new Sitecore.FakeDb.DbItem("Target", targetId, templateId),
})
{
var mapper = new SitecoreFieldLinkMapper();
var fieldValue =
"<link text=\"Test description\" linktype=\"anchor\" url=\"testAnchor\" anchor=\"testAnchor\" title=\"test alternate\" class=\"testClass\" />";
var item = database.GetItem("/sitecore/content/Target");
var field = item.Fields[fieldName];
using (new ItemEditing(item, true))
{
field.Value = fieldValue;
}
//Act
var result = mapper.GetField(field, null, null) as Link;
//Assert
Assert.AreEqual("testAnchor", result.Anchor);
Assert.AreEqual("testClass", result.Class);
Assert.AreEqual("", result.Query);
Assert.AreEqual("", result.Target);
Assert.AreEqual(Guid.Empty, result.TargetId);
Assert.AreEqual("Test description", result.Text);
Assert.AreEqual("test alternate", result.Title);
Assert.AreEqual(LinkType.Anchor, result.Type);
Assert.AreEqual("testAnchor", result.Url);
}
}
[Test]
public void GetField_FieldContainsExternal_ReturnsExternalLink()
{
//Assign
var templateId = ID.NewID;
var targetId = ID.NewID;
var fieldName = "Field";
using (Db database = new Db
{
new DbTemplate(templateId)
{
{fieldName, ""}
},
new Sitecore.FakeDb.DbItem("Target", targetId, templateId),
})
{
var mapper = new SitecoreFieldLinkMapper();
var fieldValue =
"<link text=\"Test description\" linktype=\"external\" url=\"http://www.google.com\" anchor=\"\" title=\"test alternative\" class=\"testClass\" target=\"_blank\" />";
var item = database.GetItem("/sitecore/content/Target");
var field = item.Fields[fieldName];
using (new ItemEditing(item, true))
{
field.Value = fieldValue;
}
//Act
var result = mapper.GetField(field, null, null) as Link;
//Assert
Assert.AreEqual("", result.Anchor);
Assert.AreEqual("testClass", result.Class);
Assert.AreEqual("", result.Query);
Assert.AreEqual("_blank", result.Target);
Assert.AreEqual(Guid.Empty, result.TargetId);
Assert.AreEqual("Test description", result.Text);
Assert.AreEqual("test alternative", result.Title);
Assert.AreEqual(LinkType.External, result.Type);
Assert.AreEqual("http://www.google.com", result.Url);
}
}
[Test]
public void GetField_FieldContainsJavaScript_ReturnsJavascriptLink()
{
//Assign
var templateId = ID.NewID;
var targetId = ID.NewID;
var fieldName = "Field";
using (Db database = new Db
{
new DbTemplate(templateId)
{
{fieldName, ""}
},
new Sitecore.FakeDb.DbItem("Target", targetId, templateId),
})
{
var mapper = new SitecoreFieldLinkMapper();
var fieldValue =
"<link text=\"Test description\" linktype=\"javascript\" url=\"javascript:alert('hello world');\" anchor=\"\" title=\"test alternate\" class=\"testClass\" />";
var item = database.GetItem("/sitecore/content/Target");
var field = item.Fields[fieldName];
using (new ItemEditing(item, true))
{
field.Value = fieldValue;
}
//Act
var result = mapper.GetField(field, null, null) as Link;
//Assert
Assert.AreEqual("", result.Anchor);
Assert.AreEqual("testClass", result.Class);
Assert.AreEqual("", result.Query);
Assert.AreEqual("", result.Target);
Assert.AreEqual(Guid.Empty, result.TargetId);
Assert.AreEqual("Test description", result.Text);
Assert.AreEqual("test alternate", result.Title);
Assert.AreEqual(LinkType.JavaScript, result.Type);
Assert.AreEqual("javascript:alert('hello world');", result.Url);
}
}
[Test]
public void GetField_FieldContainsMailto_ReturnsMailtoLink()
{
//Assign
var templateId = ID.NewID;
var targetId = ID.NewID;
var fieldName = "Field";
using (Db database = new Db
{
new DbTemplate(templateId)
{
{fieldName, ""}
},
new Sitecore.FakeDb.DbItem("Target", targetId, templateId),
})
{
var mapper = new SitecoreFieldLinkMapper();
var fieldValue =
"<link text=\"Test description\" linktype=\"mailto\" url=\"mailto:test@test.com\" anchor=\"\" title=\"test alternate\" class=\"testClass\" />";
var item = database.GetItem("/sitecore/content/Target");
var field = item.Fields[fieldName];
using (new ItemEditing(item, true))
{
field.Value = fieldValue;
}
//Act
var result = mapper.GetField(field, new SitecoreFieldConfiguration(), null) as Link;
//Assert
Assert.AreEqual("", result.Anchor);
Assert.AreEqual("testClass", result.Class);
Assert.AreEqual("", result.Query);
Assert.AreEqual("", result.Target);
Assert.AreEqual(Guid.Empty, result.TargetId);
Assert.AreEqual("Test description", result.Text);
Assert.AreEqual("test alternate", result.Title);
Assert.AreEqual(LinkType.MailTo, result.Type);
Assert.AreEqual("mailto:test@test.com", result.Url);
}
}
[Test]
[Category("Exclude80")]
[Category("Exclude82")] //Requires fake db fix
public void GetField_FieldContainsInternal_ReturnsInternalLink()
{
//Assign
var templateId = ID.NewID;
var targetId = ID.NewID;
var fieldName = "Field";
using (Db database = new Db
{
new DbTemplate(templateId)
{
{fieldName, ""}
},
new Sitecore.FakeDb.DbItem("Target", targetId, templateId),
})
{
var mapper = new SitecoreFieldLinkMapper(new FakeUrlOptionsResolver());
var fieldValue =
"<link text=\"Test description\" linktype=\"internal\" url=\"/Target.aspx\" anchor=\"testAnchor\" querystring=\"q=s\" title=\"test alternative\" class=\"testClass\" target=\"testTarget\" id=\"{0}\" />"
.Formatted(targetId);
Sitecore.Context.Site = null;
var item = database.GetItem("/sitecore/content/Target");
var field = item.Fields[fieldName];
using (new ItemEditing(item, true))
{
field.Value = fieldValue;
}
Sitecore.Links.LinkProvider provider =
Substitute.For<Sitecore.Links.LinkProvider>();
provider
.GetItemUrl(item, Arg.Any<Sitecore.Links.UrlOptions>())
.Returns("/target.aspx");
using (new Sitecore.FakeDb.Links.LinkProviderSwitcher(provider))
{
//Act
var result = mapper.GetField(field, new SitecoreFieldConfiguration(), null) as Link;
//Assert
Assert.AreEqual("testAnchor", result.Anchor);
Assert.AreEqual("testClass", result.Class);
Assert.AreEqual("q=s", result.Query);
Assert.AreEqual("testTarget", result.Target);
Assert.AreEqual(targetId.Guid, result.TargetId);
Assert.AreEqual("Test description", result.Text);
Assert.AreEqual("test alternative", result.Title);
Assert.AreEqual(LinkType.Internal, result.Type);
Assert.AreEqual("/target.aspx", result.Url);
}
}
}
[Test]
[Category("Exclude80")]
[Category("Exclude82")] //Requires fake db fix
public void GetField_FieldContainsInternalWithSpecialCharacters_ReturnsInternalLink()
{
//Assign
var templateId = ID.NewID;
var targetId = ID.NewID;
var fieldName = "Field";
using (Db database = new Db
{
new DbTemplate(templateId)
{
{fieldName, ""}
},
new Sitecore.FakeDb.DbItem("Target", targetId, templateId),
})
{
var mapper = new SitecoreFieldLinkMapper(new FakeUrlOptionsResolver());
var fieldValue =
"<link text=\"Test description\" linktype=\"internal\" url=\"/Target.aspx\" anchor=\"testAnchor\" querystring=\"q%3ds%253d\" title=\"test alternative\" class=\"testClass\" target=\"testTarget\" id=\"{0}\" />"
.Formatted(targetId);
Sitecore.Context.Site = null;
var item = database.GetItem("/sitecore/content/Target");
var field = item.Fields[fieldName];
using (new ItemEditing(item, true))
{
field.Value = fieldValue;
}
Sitecore.Links.LinkProvider provider =
Substitute.For<Sitecore.Links.LinkProvider>();
provider
.GetItemUrl(item, Arg.Any<Sitecore.Links.UrlOptions>())
.Returns("/target.aspx");
using (new Sitecore.FakeDb.Links.LinkProviderSwitcher(provider))
{
//Act
var result = mapper.GetField(field, new SitecoreFieldConfiguration(), null) as Link;
//Assert
Assert.AreEqual("testAnchor", result.Anchor);
Assert.AreEqual("testClass", result.Class);
Assert.AreEqual("q=s%3d", result.Query);
Assert.AreEqual("testTarget", result.Target);
Assert.AreEqual(targetId.Guid, result.TargetId);
Assert.AreEqual("Test description", result.Text);
Assert.AreEqual("test alternative", result.Title);
Assert.AreEqual(LinkType.Internal, result.Type);
Assert.AreEqual("/target.aspx", result.Url);
}
}
}
[Test]
public void GetField_FieldContainsInternalButItemMissing_ReturnsEmptyUrl()
{
//Assign
var templateId = ID.NewID;
var targetId = ID.NewID;
var fieldName = "Field";
using (Db database = new Db
{
new DbTemplate(templateId)
{
{fieldName, ""}
},
new Sitecore.FakeDb.DbItem("Target", targetId, templateId),
})
{
//Assign
var mapper = new SitecoreFieldLinkMapper();
var fieldValue =
"<link text=\"Test description\" linktype=\"internal\" url=\"/Tests/DataMappers/SitecoreFieldLinkMapper/Target.aspx\" anchor=\"testAnchor\" querystring=\"q=s\" title=\"test alternative\" class=\"testClass\" target=\"testTarget\" id=\"{AAAAAAAA-3B6F-4F5F-A5C2-FD2B9D5A47A0}\" />";
Sitecore.Context.Site = null;
var item = database.GetItem("/sitecore/content/Target");
var field = item.Fields[fieldName];
using (new ItemEditing(item, true))
{
field.Value = fieldValue;
}
//Act
var result = mapper.GetField(field, new SitecoreFieldConfiguration(), null) as Link;
//Assert
Assert.AreEqual("testAnchor", result.Anchor);
Assert.AreEqual("testClass", result.Class);
Assert.AreEqual("q=s", result.Query);
Assert.AreEqual("testTarget", result.Target);
Assert.AreEqual(new Guid("{AAAAAAAA-3B6F-4F5F-A5C2-FD2B9D5A47A0}"), result.TargetId);
Assert.AreEqual("Test description", result.Text);
Assert.AreEqual("test alternative", result.Title);
Assert.AreEqual(LinkType.Internal, result.Type);
Assert.AreEqual(string.Empty, result.Url);
}
}
[Test]
[Category("Exclude80")]
[Category("Exclude82")] //Required FakeDB fix
public void GetField_FieldContainsInternalAbsoluteUrl_ReturnsInternalLink()
{
//Assign
var templateId = ID.NewID;
var targetId = ID.NewID;
var fieldName = "Field";
using (Db database = new Db
{
new DbTemplate(templateId)
{
{fieldName, ""}
},
new Sitecore.FakeDb.DbItem("Target", targetId, templateId),
})
{
var mapper = new SitecoreFieldLinkMapper(new FakeUrlOptionsResolver());
var fieldValue =
"<link text=\"Test description\" linktype=\"internal\" url=\"/Tests/DataMappers/SitecoreFieldLinkMapper/Target.aspx\" anchor=\"testAnchor\" querystring=\"q=s\" title=\"test alternative\" class=\"testClass\" target=\"testTarget\" id=\"{0}\" />"
.Formatted(targetId);
Sitecore.Context.Site = null;
var item = database.GetItem("/sitecore/content/Target");
var field = item.Fields[fieldName];
var config = new SitecoreFieldConfiguration();
config.UrlOptions = SitecoreInfoUrlOptions.LanguageEmbeddingNever;
using (new ItemEditing(item, true))
{
field.Value = fieldValue;
}
Sitecore.Links.LinkProvider provider =
Substitute.For<Sitecore.Links.LinkProvider>();
provider
.GetItemUrl(item, Arg.Is<Sitecore.Links.UrlOptions>(x=>x.LanguageEmbedding == LanguageEmbedding.Never))
.Returns("/target.aspx");
using (new Sitecore.FakeDb.Links.LinkProviderSwitcher(provider))
{
//Act
var result = mapper.GetField(field, config, null) as Link;
//Assert
Assert.AreEqual("testAnchor", result.Anchor);
Assert.AreEqual("testClass", result.Class);
Assert.AreEqual("q=s", result.Query);
Assert.AreEqual("testTarget", result.Target);
Assert.AreEqual(targetId.Guid, result.TargetId);
Assert.AreEqual("Test description", result.Text);
Assert.AreEqual("test alternative", result.Title);
Assert.AreEqual(LinkType.Internal, result.Type);
Assert.AreEqual("/target.aspx",
result.Url);
}
}
}
[Test]
public void GetField_FieldContainsInternalMissingItem_ReturnsNotSetLink()
{
//Assign
var templateId = ID.NewID;
var targetId = ID.NewID;
var fieldName = "Field";
using (Db database = new Db
{
new DbTemplate(templateId)
{
{fieldName, ""}
},
new Sitecore.FakeDb.DbItem("Target", targetId, templateId),
})
{
var mapper = new SitecoreFieldLinkMapper(new FakeUrlOptionsResolver());
var fieldValue =
"<link text=\"Test description\" linktype=\"internal\" url=\"/Target.aspx\" anchor=\"testAnchor\" querystring=\"q=s\" title=\"test alternative\" class=\"testClass\" target=\"testTarget\" id=\"{11111111-3B6F-4F5F-A5C2-FD2B9D5A47A0}\" />";
var item = database.GetItem("/sitecore/content/Target");
var field = item.Fields[fieldName];
using (new ItemEditing(item, true))
{
field.Value = fieldValue;
}
//Act
var result = mapper.GetField(field, new SitecoreFieldConfiguration(), null) as Link;
//Assert
Assert.AreEqual("testAnchor", result.Anchor);
Assert.AreEqual("testClass", result.Class);
Assert.AreEqual("q=s", result.Query);
Assert.AreEqual("testTarget", result.Target);
Assert.AreEqual(new Guid("{11111111-3B6F-4F5F-A5C2-FD2B9D5A47A0}"), result.TargetId);
Assert.AreEqual("Test description", result.Text);
Assert.AreEqual("test alternative", result.Title);
Assert.AreEqual(LinkType.Internal, result.Type);
Assert.AreEqual("", result.Url);
}
}
[Test]
public void GetField_FieldContainsMediaLink_ReturnsMediaLink()
{
//Assign
var templateId = ID.NewID;
var targetId = ID.NewID;
var fieldName = "Field";
using (Db database = new Db
{
new DbTemplate(templateId)
{
{fieldName, ""}
},
new Sitecore.FakeDb.DbItem("Target", targetId, templateId),
})
{
var mapper = new SitecoreFieldLinkMapper(new FakeUrlOptionsResolver());
var fieldValue =
"<link text=\"Test description\" linktype=\"media\" url=\"/Files/20121222_001405\" title=\"test alternative\" class=\"testClass\" target=\"_blank\" id=\"{0}\" />"
.Formatted(targetId);
var item = database.GetItem("/sitecore/content/Target");
var field = item.Fields[fieldName];
using (new ItemEditing(item, true))
{
field.Value = fieldValue;
}
Sitecore.Resources.Media.MediaProvider mediaProvider =
NSubstitute.Substitute.For<Sitecore.Resources.Media.MediaProvider>();
mediaProvider
.GetMediaUrl(Arg.Is<Sitecore.Data.Items.MediaItem>(i => i.ID == targetId))
.Returns("Media.Aspx");
// substitute the original provider with the mocked one
using (new Sitecore.FakeDb.Resources.Media.MediaProviderSwitcher(mediaProvider))
{
//Act
var result = mapper.GetField(field, null, null) as Link;
//Assert
Assert.AreEqual("", result.Anchor);
Assert.AreEqual("testClass", result.Class);
Assert.AreEqual("", result.Query);
Assert.AreEqual("_blank", result.Target);
Assert.AreEqual(targetId.Guid, result.TargetId);
Assert.AreEqual("Test description", result.Text);
Assert.AreEqual("test alternative", result.Title);
Assert.AreEqual(LinkType.Media, result.Type);
Assert.AreEqual("Media.Aspx", result.Url);
}
}
}
[Test]
public void GetField_FieldContainsMediaLinkMissingItem_ReturnsNotSetLink()
{
//Assign
var templateId = ID.NewID;
var targetId = ID.NewID;
var fieldName = "Field";
using (Db database = new Db
{
new DbTemplate(templateId)
{
{fieldName, ""}
},
new Sitecore.FakeDb.DbItem("Target", targetId, templateId),
})
{
var mapper = new SitecoreFieldLinkMapper(new FakeUrlOptionsResolver());
var fieldValue =
"<link text=\"Test description\" linktype=\"media\" url=\"/Files/20121222_001405\" title=\"test alternative\" class=\"testClass\" target=\"_blank\" id=\"{11111111-CF15-4067-A3F4-85148606F9CD}\" />";
var item = database.GetItem("/sitecore/content/Target");
var field = item.Fields[fieldName];
using (new ItemEditing(item, true))
{
field.Value = fieldValue;
}
//Act
var result = mapper.GetField(field, null, null) as Link;
//Assert
Assert.AreEqual("", result.Anchor);
Assert.AreEqual("testClass", result.Class);
Assert.AreEqual("", result.Query);
Assert.AreEqual("_blank", result.Target);
Assert.AreEqual(new Guid("{11111111-CF15-4067-A3F4-85148606F9CD}"), result.TargetId);
Assert.AreEqual("Test description", result.Text);
Assert.AreEqual("test alternative", result.Title);
Assert.AreEqual(LinkType.Media, result.Type);
Assert.AreEqual("", result.Url);
}
}
#endregion
//#region Method - SetField
[Test]
public void SetField_AnchorLink_AnchorLinkSetOnField()
{
//Assign
var templateId = ID.NewID;
var targetId = ID.NewID;
var fieldName = "Field";
using (Db database = new Db
{
new DbTemplate(templateId)
{
{fieldName, ""}
},
new Sitecore.FakeDb.DbItem("Target", targetId, templateId),
})
{
var mapper = new SitecoreFieldLinkMapper(new FakeUrlOptionsResolver());
var expected =
"<link title=\"test alternative\" linktype=\"anchor\" url=\"testAnchor\" anchor=\"testAnchor\" class=\"testClass\" text=\"Test description\" />";
var item = database.GetItem("/sitecore/content/Target");
var field = item.Fields[fieldName];
var value = new Link()
{
Anchor = "testAnchor",
Class = "testClass",
Query = "",
Target = "",
TargetId = Guid.Empty,
Text = "Test description",
Title = "test alternative",
Type = LinkType.Anchor,
Url = "testAnchor"
};
using (new ItemEditing(item, true))
{
field.Value = string.Empty;
}
//Act
using (new ItemEditing(item, true))
{
mapper.SetField(field, value, null, null);
}
//Assert
AssertHtml.AreHtmlElementsEqual(expected, field.Value, "link");
}
}
[Test]
public void SetField_ExternalLink_ExternalLinkSetOnField()
{
//Assign
var templateId = ID.NewID;
var targetId = ID.NewID;
var fieldName = "Field";
using (Db database = new Db
{
new DbTemplate(templateId)
{
{fieldName, ""}
},
new Sitecore.FakeDb.DbItem("Target", targetId, templateId),
})
{
var mapper = new SitecoreFieldLinkMapper(new FakeUrlOptionsResolver());
var expected =
"<link url=\"http://www.google.com\" text=\"Test description\" class=\"testClass\" title=\"test alternative\" linktype=\"external\" />";
var item = database.GetItem("/sitecore/content/Target");
var field = item.Fields[fieldName];
var value = new Link()
{
Anchor = "",
Class = "testClass",
Query = "",
Target = "",
TargetId = Guid.Empty,
Text = "Test description",
Title = "test alternative",
Type = LinkType.External,
Url = "http://www.google.com"
};
using (new ItemEditing(item, true))
{
field.Value = string.Empty;
}
//Act
using (new ItemEditing(item, true))
{
mapper.SetField(field, value, null, null);
}
//Assert
AssertHtml.AreHtmlElementsEqual(expected, field.Value,"link");
}
}
[Test]
public void SetField_JavaScriptLink_JavaScriptLinkSetOnField()
{
//Assign
var templateId = ID.NewID;
var targetId = ID.NewID;
var fieldName = "Field";
using (Db database = new Db
{
new DbTemplate(templateId)
{
{fieldName, ""}
},
new Sitecore.FakeDb.DbItem("Target", targetId, templateId),
})
{
var mapper = new SitecoreFieldLinkMapper(new FakeUrlOptionsResolver());
var expected =
"<link url=\"javascript:alert('hello world');\" text=\"Test description\" class=\"testClass\" title=\"test alternative\" linktype=\"javascript\" />";
var item =database.GetItem("/sitecore/content/Target");
var field = item.Fields[fieldName];
var value = new Link()
{
Anchor = "",
Class = "testClass",
Query = "",
Target = "",
TargetId = Guid.Empty,
Text = "Test description",
Title = "test alternative",
Type = LinkType.JavaScript,
Url = "javascript:alert('hello world');"
};
using (new ItemEditing(item, true))
{
field.Value = string.Empty;
}
//Act
using (new ItemEditing(item, true))
{
mapper.SetField(field, value, null, null);
}
//Assert
AssertHtml.AreHtmlElementsEqual(expected, field.Value, "link");
}
}
[Test]
public void SetField_MailToLink_MailToLinkSetOnField()
{
//Assign
var templateId = ID.NewID;
var targetId = ID.NewID;
var fieldName = "Field";
using (Db database = new Db
{
new DbTemplate(templateId)
{
{fieldName, ""}
},
new Sitecore.FakeDb.DbItem("Target", targetId, templateId),
})
{
var mapper = new SitecoreFieldLinkMapper(new FakeUrlOptionsResolver());
var expected =
"<link url=\"mailto:test@test.com\" text=\"Test description\" class=\"testClass\" title=\"test alternative\" linktype=\"mailto\" />";
var item = database.GetItem("/sitecore/content/Target");
var field = item.Fields[fieldName];
var value = new Link()
{
Anchor = "",
Class = "testClass",
Query = "",
Target = "",
TargetId = Guid.Empty,
Text = "Test description",
Title = "test alternative",
Type = LinkType.MailTo,
Url = "mailto:test@test.com"
};
using (new ItemEditing(item, true))
{
field.Value = string.Empty;
}
//Act
using (new ItemEditing(item, true))
{
mapper.SetField(field, value, null, null);
}
//Assert
AssertHtml.AreHtmlElementsEqual(expected, field.Value, "link");
}
}
[Test]
public void SetField_InternalLink_InternalLinkSetOnField()
{
//Assign
var templateId = ID.NewID;
var targetId = ID.NewID;
var fieldName = "Field";
using (Db database = new Db
{
new DbTemplate(templateId)
{
{fieldName, ""}
},
new Sitecore.FakeDb.DbItem("Target", targetId, templateId),
})
{
var mapper = new SitecoreFieldLinkMapper(new FakeUrlOptionsResolver());
var expected =
"<link target=\"testTarget\" title=\"test alternative\" querystring=\"q%3ds\" linktype=\"internal\" id=\"{0}\" anchor=\"testAnchor\" url=\"/en/sitecore/content/Target.aspx\" class=\"testClass\" text=\"Test description\" />"
.Formatted(targetId.Guid.ToString("B").ToUpperInvariant());
var item = database.GetItem("/sitecore/content/Target");
var field = item.Fields[fieldName];
var value = new Link()
{
Anchor = "testAnchor",
Class = "testClass",
Query = "q=s",
Target = "testTarget",
TargetId = targetId.Guid,
Text = "Test description",
Title = "test alternative",
Type = LinkType.Internal,
Url = ""
};
using (new ItemEditing(item, true))
{
field.Value = string.Empty;
}
//Act
using (new ItemEditing(item, true))
{
mapper.SetField(field, value, null, null);
}
//Assert
AssertHtml.AreHtmlElementsEqual(expected, field.Value, "link");
}
}
[Test]
public void SetField_InternalLinkWithSpecialCharacters_InternalLinkSetOnField()
{
//Assign
var templateId = ID.NewID;
var targetId = ID.NewID;
var fieldName = "Field";
using (Db database = new Db
{
new DbTemplate(templateId)
{
{fieldName, ""}
},
new Sitecore.FakeDb.DbItem("Target", targetId, templateId),
})
{
var mapper = new SitecoreFieldLinkMapper(new FakeUrlOptionsResolver());
var expected =
"<link target=\"testTarget\" title=\"test alternative\" querystring=\"q%3ds%253d\" linktype=\"internal\" id=\"{0}\" anchor=\"testAnchor\" url=\"/en/sitecore/content/Target.aspx\" class=\"testClass\" text=\"Test description\" />"
.Formatted(targetId.Guid.ToString("B").ToUpperInvariant());
var item = database.GetItem("/sitecore/content/Target");
var field = item.Fields[fieldName];
var value = new Link()
{
Anchor = "testAnchor",
Class = "testClass",
Query = "q=s%3d",
Target = "testTarget",
TargetId = targetId.Guid,
Text = "Test description",
Title = "test alternative",
Type = LinkType.Internal,
Url = ""
};
using (new ItemEditing(item, true))
{
field.Value = string.Empty;
}
//Act
using (new ItemEditing(item, true))
{
mapper.SetField(field, value, null, null);
}
//Assert
AssertHtml.AreHtmlElementsEqual(expected, field.Value, "link");
}
}
[Test]
public void SetField_InternalLinkMissingTarget_ThorwsException()
{
//Assign
var templateId = ID.NewID;
var targetId = ID.NewID;
var fieldName = "Field";
using (Db database = new Db
{
new DbTemplate(templateId)
{
{fieldName, ""}
},
new Sitecore.FakeDb.DbItem("Target", targetId, templateId),
})
{
var mapper = new SitecoreFieldLinkMapper(new FakeUrlOptionsResolver());
var item = database.GetItem("/sitecore/content/Target");
var field = item.Fields[fieldName];
var value = new Link()
{
Anchor = "testAnchor",
Class = "testClass",
Query = "q=s",
Target = "testTarget",
TargetId = new Guid("{11111111-3B6F-4F5F-A5C2-FD2B9D5A47A0}"),
Text = "Test description",
Title = "test alternative",
Type = LinkType.Internal,
Url = ""
};
using (new ItemEditing(item, true))
{
field.Value = string.Empty;
}
//Act
using (new ItemEditing(item, true))
{
Assert.Throws<MapperException>(() =>
{
mapper.SetField(field, value, null, null);
});
}
//Assert
}
}
[Test]
public void SetField_MedialLink_MediaLinkSetOnField()
{
//Assign
var templateId = ID.NewID;
var targetId = ID.NewID;
var fieldName = "Field";
using (Db database = new Db
{
new DbTemplate(templateId)
{
{fieldName, ""}
},
new Sitecore.FakeDb.DbItem("Target", targetId, templateId),
})
{
var mapper = new SitecoreFieldLinkMapper(new FakeUrlOptionsResolver());
var expected =
"<link target=\"_blank\" title=\"test alternative\" linktype=\"media\" id=\"{0}\" url=\"Media.Aspx\" class=\"testClass\" text=\"Test description\" />"
.Formatted(targetId.Guid.ToString("B").ToUpperInvariant());
var item = database.GetItem("/sitecore/content/Target");
var field = item.Fields[fieldName];
var value = new Link()
{
Anchor = "",
Class = "testClass",
Query = "",
Target = "_blank",
TargetId = targetId.Guid,
Text = "Test description",
Title = "test alternative",
Type = LinkType.Media,
Url = ""
};
using (new ItemEditing(item, true))
{
field.Value = string.Empty;
}
Sitecore.Resources.Media.MediaProvider mediaProvider =
NSubstitute.Substitute.For<Sitecore.Resources.Media.MediaProvider>();
mediaProvider
.GetMediaUrl(Arg.Is<Sitecore.Data.Items.MediaItem>(i => i.ID == targetId))
.Returns("Media.Aspx");
// substitute the original provider with the mocked one
using (new Sitecore.FakeDb.Resources.Media.MediaProviderSwitcher(mediaProvider))
{
//Act
using (new ItemEditing(item, true))
{
mapper.SetField(field, value, null, null);
}
//Assert
AssertHtml.AreHtmlElementsEqual(expected, field.Value, "link");
}
}
}
[Test]
public void SetField_MedialLinkMissingItem_ThrowsException()
{
//Assign
var templateId = ID.NewID;
var targetId = ID.NewID;
var fieldName = "Field";
using (Db database = new Db
{
new DbTemplate(templateId)
{
{fieldName, ""}
},
new Sitecore.FakeDb.DbItem("Target", targetId, templateId),
})
{
var mapper = new SitecoreFieldLinkMapper(new FakeUrlOptionsResolver());
var item = database.GetItem("/sitecore/content/Target");
var field = item.Fields[fieldName];
var value = new Link()
{
Anchor = "",
Class = "testClass",
Query = "",
Target = "_blank",
TargetId = new Guid("{11111111-CF15-4067-A3F4-85148606F9CD}"),
Text = "Test description",
Title = "test alternative",
Type = LinkType.Media,
Url = ""
};
using (new ItemEditing(item, true))
{
field.Value = string.Empty;
}
//Act
using (new ItemEditing(item, true))
{
Assert.Throws<MapperException>(() => {
mapper.SetField(field, value, null, null);
});
}
//Assert
}
}
//#endregion
public class FakeUrlOptionsResolver : UrlOptionsResolver
{
public override UrlOptions CreateUrlOptions(SitecoreInfoUrlOptions urlOptions)
{
return base.CreateUrlOptions(urlOptions, new UrlOptions());
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace GitHub.Unity
{
[Serializable]
public class PopupWindow : BaseWindow
{
public enum PopupViewType
{
None,
PublishView,
AuthenticationView,
}
[SerializeField] private PopupViewType activeViewType;
[SerializeField] private AuthenticationView authenticationView;
[SerializeField] private LoadingView loadingView;
[SerializeField] private PublishView publishView;
[SerializeField] private bool shouldCloseOnFinish;
public event Action<bool> OnClose;
public static PopupWindow OpenWindow(PopupViewType popupViewType, Action<bool> onClose = null)
{
var popupWindow = GetWindow<PopupWindow>(true);
popupWindow.Open(popupViewType, onClose);
return popupWindow;
}
public override void Initialize(IApplicationManager applicationManager)
{
base.Initialize(applicationManager);
publishView = publishView ?? new PublishView();
authenticationView = authenticationView ?? new AuthenticationView();
loadingView = loadingView ?? new LoadingView();
publishView.InitializeView(this);
authenticationView.InitializeView(this);
loadingView.InitializeView(this);
titleContent = new GUIContent(ActiveView.Title, Styles.SmallLogo);
}
public override void OnEnable()
{
base.OnEnable();
minSize = maxSize = ActiveView.Size;
ActiveView.OnEnable();
}
public override void OnDisable()
{
base.OnDisable();
ActiveView.OnDisable();
}
public override void OnDataUpdate()
{
base.OnDataUpdate();
if (titleContent.image == null)
titleContent = new GUIContent(ActiveView.Title, Styles.SmallLogo);
ActiveView.OnDataUpdate();
}
public override void OnUI()
{
base.OnUI();
ActiveView.OnGUI();
}
public override void Refresh()
{
base.Refresh();
ActiveView.Refresh();
}
public override void OnSelectionChange()
{
base.OnSelectionChange();
ActiveView.OnSelectionChange();
}
public override void Finish(bool result)
{
OnClose.SafeInvoke(result);
OnClose = null;
if (shouldCloseOnFinish)
{
shouldCloseOnFinish = false;
Close();
}
base.Finish(result);
}
public override void OnDestroy()
{
base.OnDestroy();
OnClose.SafeInvoke(false);
OnClose = null;
}
private void Open(PopupViewType popupViewType, Action<bool> onClose)
{
OnClose.SafeInvoke(false);
OnClose = null;
var viewNeedsAuthentication = popupViewType == PopupViewType.PublishView;
if (viewNeedsAuthentication)
{
var userHasAuthentication = false;
foreach (var keychainConnection in Platform.Keychain.Connections.OrderByDescending(HostAddress.IsGitHubDotCom))
{
var apiClient = new ApiClient(Platform.Keychain, Platform.ProcessManager, TaskManager,
Environment, keychainConnection.Host);
try
{
apiClient.EnsureValidCredentials();
userHasAuthentication = true;
break;
}
catch (Exception ex)
{
Logger.Trace(ex, "Exception validating host {0}", keychainConnection.Host);
}
}
if (userHasAuthentication)
{
OpenInternal(popupViewType, onClose);
shouldCloseOnFinish = true;
}
else
{
authenticationView.Initialize(null);
OpenInternal(PopupViewType.AuthenticationView, completedAuthentication =>
{
if (completedAuthentication)
{
Open(popupViewType, onClose);
}
});
shouldCloseOnFinish = false;
}
}
else
{
OpenInternal(popupViewType, onClose);
shouldCloseOnFinish = true;
}
}
private void OpenInternal(PopupViewType popupViewType, Action<bool> onClose)
{
if (onClose != null)
{
OnClose += onClose;
}
var fromView = ActiveView;
ActiveViewType = popupViewType;
SwitchView(fromView, ActiveView);
Show();
}
private void SwitchView(Subview fromView, Subview toView)
{
GUI.FocusControl(null);
if (fromView != null)
fromView.OnDisable();
toView.OnEnable();
titleContent = new GUIContent(ActiveView.Title, Styles.SmallLogo);
// this triggers a repaint
Repaint();
}
private Subview ActiveView
{
get
{
switch (activeViewType)
{
case PopupViewType.PublishView:
return publishView;
case PopupViewType.AuthenticationView:
return authenticationView;
default:
return loadingView;
}
}
}
private PopupViewType ActiveViewType
{
get { return activeViewType; }
set
{
if (activeViewType != value)
{
ActiveView.OnDisable();
activeViewType = value;
}
}
}
public override bool IsBusy
{
get { return ActiveView.IsBusy; }
}
}
}
| |
namespace Boxed.AspNetCore.Test
{
using System;
using System.Collections.Generic;
using Xunit;
public class CursorTest
{
public static IEnumerable<object[]> DateTimeOffsetToCursor
{
get
{
// If no-store is set, then location is ignored.
yield return new object[]
{
null,
string.Empty,
};
yield return new object[]
{
new DateTimeOffset(2000, 1, 1, 0, 0, 0, TimeSpan.Zero),
"MDEvMDEvMjAwMCAwMDowMDowMCArMDA6MDA=",
};
}
}
[Theory]
[InlineData("MA=", 0)]
[InlineData("MA==", 0)]
[InlineData("NQ==", 5)]
[InlineData("LTU=", -5)]
public void FromCursor_IntValue_ReturnsPrefixedBase64Cursor(string cursor, int expectedValue)
{
var value = Cursor.FromCursor<int>(cursor);
Assert.Equal(expectedValue, value);
}
[Theory]
[InlineData("MA=", null)]
[InlineData("MA==", 0)]
[InlineData("NQ==", 5)]
[InlineData("LTU=", -5)]
public void FromCursor_NullableIntValue_ReturnsPrefixedBase64Cursor(string cursor, int? expectedValue)
{
var value = Cursor.FromCursor<int?>(cursor);
Assert.Equal(expectedValue, value);
}
[Theory]
[InlineData("Rg==", "F")]
[InlineData("Rm9v", "Foo")]
public void FromCursor_StringValue_ReturnsPrefixedBase64Cursor(string cursor, string expectedValue)
{
var value = Cursor.FromCursor<string>(cursor);
Assert.Equal(expectedValue, value);
}
[Fact]
public void FromCursor_DateTimeOffsetValue_ReturnsPrefixedBase64Cursor()
{
var value = Cursor.FromCursor<DateTimeOffset>("MjAwMC0wMS0wMVQwMDowMDowMC4wMDAwMDAwKzAwOjAw");
Assert.Equal(new DateTimeOffset(2000, 1, 1, 0, 0, 0, TimeSpan.Zero), value);
}
[Fact]
public void FromCursor_NullableDateTimeOffsetValue_ReturnsPrefixedBase64Cursor()
{
var value = Cursor.FromCursor<DateTimeOffset?>("MjAwMC0wMS0wMVQwMDowMDowMC4wMDAwMDAwKzAwOjAw");
Assert.Equal(new DateTimeOffset(2000, 1, 1, 0, 0, 0, TimeSpan.Zero), value);
}
[Fact]
public void FromCursor_NullStringValue_ReturnsNull()
{
var value = Cursor.FromCursor<string>(null);
Assert.Null(value);
}
[Fact]
public void FromCursor_EmptyStringValue_ReturnsNull()
{
var value = Cursor.FromCursor<string>(string.Empty);
Assert.Null(value);
}
[Fact]
public void FromCursor_InvalidBase64String_ReturnsNull()
{
var value = Cursor.FromCursor<string>("This is not base 64");
Assert.Null(value);
}
[Fact]
public void FromCursor_InvalidBase64StringValue_ReturnsNull()
{
var value = Cursor.FromCursor<string>("This is not base64");
Assert.Null(value);
}
[Fact]
public void GetFirstAndLastCursor_NullCollection_ReturnsNullFirstAndLast()
{
var (first, last) = Cursor.GetFirstAndLastCursor<Item, int>(null, x => x.Integer);
Assert.Null(first);
Assert.Null(last);
}
[Fact]
public void GetFirstAndLastCursor_NullGetCursorDelegate_ThrowsArgumentNullException() =>
Assert.Throws<ArgumentNullException>(() => Cursor.GetFirstAndLastCursor<Item, int>(null, null));
[Fact]
public void GetFirstAndLastCursor_EmptyCollection_ReturnsNullFirstAndLast()
{
var items = new List<Item>();
var (first, last) = Cursor.GetFirstAndLastCursor(items, x => x.Integer);
Assert.Null(first);
Assert.Null(last);
}
[Fact]
public void GetFirstAndLastCursor_OneItem_ReturnsSameCursor()
{
var items = new List<Item>()
{
new Item() { Integer = 1 },
};
var (first, last) = Cursor.GetFirstAndLastCursor(items, x => x.Integer);
Assert.Equal("MQ==", first);
Assert.Equal("MQ==", last);
}
[Fact]
public void GetFirstAndLastCursor_TwoItems_ReturnsFirstAndLastCursor()
{
var items = new List<Item>()
{
new Item() { Integer = 1 },
new Item() { Integer = 2 },
};
var (first, last) = Cursor.GetFirstAndLastCursor(items, x => x.Integer);
Assert.Equal("MQ==", first);
Assert.Equal("Mg==", last);
}
[Fact]
public void ToCursor_Null_ThrowsArgumentNullException() =>
Assert.Throws<ArgumentNullException>(() => Cursor.ToCursor<string>(null));
[Theory]
[InlineData(0, "MA==")]
[InlineData(5, "NQ==")]
[InlineData(-5, "LTU=")]
public void ToCursor_IntValue_ReturnsPrefixedBase64Cursor(int value, string expectedCursor)
{
var cursor = Cursor.ToCursor(value);
Assert.Equal(expectedCursor, cursor);
}
[Theory]
[InlineData(0, "MA==")]
[InlineData(5, "NQ==")]
[InlineData(-5, "LTU=")]
public void ToCursor_NullableIntValue_ReturnsPrefixedBase64Cursor(int? value, string expectedCursor)
{
var cursor = Cursor.ToCursor(value);
Assert.Equal(expectedCursor, cursor);
}
[Theory]
[InlineData("", "")]
[InlineData("Foo", "Rm9v")]
public void ToCursor_StringValue_ReturnsPrefixedBase64Cursor(string value, string expectedCursor)
{
var cursor = Cursor.ToCursor(value);
Assert.Equal(expectedCursor, cursor);
}
[Fact]
public void ToCursor_DateTimeOffsetValue_ReturnsPrefixedBase64Cursor()
{
var cursor = Cursor.ToCursor(new DateTimeOffset(2000, 1, 1, 0, 0, 0, TimeSpan.Zero));
Assert.Equal("MjAwMC0wMS0wMVQwMDowMDowMC4wMDAwMDAwKzAwOjAw", cursor);
}
[Fact]
public void ToCursor_NullableDateTimeOffsetValue_ReturnsPrefixedBase64Cursor()
{
var cursor = Cursor.ToCursor(new DateTimeOffset?(new DateTimeOffset(2000, 1, 1, 0, 0, 0, TimeSpan.Zero)));
Assert.Equal("MjAwMC0wMS0wMVQwMDowMDowMC4wMDAwMDAwKzAwOjAw", cursor);
}
private class Item
{
public int Integer { get; set; }
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Bolt.Client;
using Bolt.Client.Proxy;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Features;
using Microsoft.AspNet.Session;
using Microsoft.Framework.Caching.Distributed;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.Logging;
using Moq;
using Xunit;
namespace Bolt.Server.IntegrationTest
{
public class DistributedSessionTest : IntegrationTestBase, ITestContext
{
public DistributedSessionTest()
{
ClientConfiguration.UseDynamicProxy();
}
[Fact]
public void Execute_EnsureHasSession()
{
Callback = new Mock<IDummyContract>();
DistributedCache.Setup(c => c.RefreshAsync(It.IsAny<string>())).Returns(Task.FromResult(true)).Verifiable();
Callback.Setup(c => c.OnExecute(It.IsAny<object>())).Callback<object>(
v =>
{
Assert.NotNull(((DummyContract)v).HttpSessionProvider.Session);
Assert.NotNull(((DummyContract)v).HttpSessionProvider.SessionId);
}).Verifiable();
CreateChannel().OnExecute(null);
Callback.Verify();
DistributedCache.Verify();
}
[Fact]
public void Execute_MutltipleTimes_EnsureSameSession()
{
Callback = new Mock<IDummyContract>();
string sessionId = null;
DistributedCache.Setup(c => c.RefreshAsync(It.IsAny<string>())).Returns(Task.FromResult(true)).Verifiable();
Callback.Setup(c => c.OnExecute(It.IsAny<object>())).Callback<object>(
v =>
{
if (sessionId == null)
{
sessionId = ((DummyContract)v).HttpSessionProvider.SessionId;
}
else
{
Assert.Equal(sessionId, ((DummyContract)v).HttpSessionProvider.SessionId);
}
}).Verifiable();
var channel = CreateChannel();
channel.OnExecute(null);
channel.OnExecute(null);
Callback.Verify();
DistributedCache.Verify();
}
[Fact]
public void MultipleClients_EnsureUniqueSessions()
{
Callback = new Mock<IDummyContract>();
List<string> sessions = new List<string>();
DistributedCache.Setup(c => c.RefreshAsync(It.IsAny<string>())).Returns(Task.FromResult(true)).Verifiable();
Callback.Setup(c => c.OnExecute(It.IsAny<object>())).Callback<object>(
v =>
{
sessions.Add(((DummyContract)v).HttpSessionProvider.SessionId);
}).Verifiable();
for (int i = 0; i < 10; i++)
{
CreateChannel().OnExecute(null);
}
Assert.True(sessions.Distinct().Count() == 10, "Unique sessions were not created");
}
[Fact]
public void AccessSession_NotNull()
{
Callback = new Mock<IDummyContract>();
DistributedCache.Setup(c => c.RefreshAsync(It.IsAny<string>())).Returns(Task.FromResult(true)).Verifiable();
Callback.Setup(c => c.OnExecute(It.IsAny<object>())).Callback<object>(
v =>
{
ISession session = ((DummyContract)v).HttpSessionProvider.Session;
Assert.NotNull(session);
}).Verifiable();
CreateChannel().OnExecute(null);
}
[Fact]
public void LoadSession_Ok()
{
Callback = new Mock<IDummyContract>();
DistributedCache.Setup(c => c.RefreshAsync(It.IsAny<string>())).Returns(Task.FromResult(true)).Verifiable();
DistributedCache.Setup(c => c.GetAsync(It.IsAny<string>())).Returns(Task.FromResult((byte[])null)).Verifiable();
Callback.Setup(c => c.OnExecute(It.IsAny<object>())).Callback<object>(
v =>
{
ISession session = ((DummyContract)v).HttpSessionProvider.Session;
session.LoadAsync().GetAwaiter().GetResult();
}).Verifiable();
CreateChannel().OnExecute(null);
}
[Fact]
public void LoadSession_GetValue_Ok()
{
Callback = new Mock<IDummyContract>();
DistributedCache.Setup(c => c.RefreshAsync(It.IsAny<string>())).Returns(Task.FromResult(true)).Verifiable();
DistributedCache.Setup(c => c.GetAsync(It.IsAny<string>())).Returns(Task.FromResult((byte[])null)).Verifiable();
Callback.Setup(c => c.OnExecute(It.IsAny<object>())).Callback<object>(
v =>
{
ISession session = ((DummyContract)v).HttpSessionProvider.Session;
session.Get("temp");
}).Verifiable();
CreateChannel().OnExecute(null);
}
[Fact]
public void LoadSession_SetValue_Ok()
{
Callback = new Mock<IDummyContract>();
DistributedCache.Setup(c => c.SetAsync(It.IsAny<string>(), It.IsAny<byte[]>(), It.IsAny<DistributedCacheEntryOptions>()))
.Returns(Task.FromResult(true))
.Verifiable();
DistributedCache.Setup(c => c.GetAsync(It.IsAny<string>())).Returns(Task.FromResult((byte[])null)).Verifiable();
Callback.Setup(c => c.OnExecute(It.IsAny<object>())).Callback<object>(
v =>
{
ISession session = ((DummyContract)v).HttpSessionProvider.Session;
session.Set("temp", new byte[10]);
}).Verifiable();
CreateChannel().OnExecute(null);
DistributedCache.Verify();
}
[Fact]
public void GetSession_EnsureSameDistributedSession()
{
List<string> sessions = new List<string>();
Callback = new Mock<IDummyContract>();
DistributedCache.Setup(c => c.RefreshAsync(It.IsAny<string>())).Returns(Task.FromResult(true)).Callback<string>(
v =>
{
sessions.Add(v);
}).Verifiable();
Callback.Setup(c => c.OnExecute(It.IsAny<object>())).Callback<object>(
v =>
{
sessions.Add(((DummyContract)v).HttpSessionProvider.SessionId);
}).Verifiable();
IDummyContract channel = CreateChannel();
channel.OnExecute(null);
channel.OnExecute(null);
channel.OnExecute(null);
Assert.True(sessions.Distinct().Count()== 1, "Multiple sessions were created.");
DistributedCache.Verify();
}
protected override void ConfigureServices(IServiceCollection services)
{
services.AddLogging();
services.AddSingleton<ITestContext>(c => this);
base.ConfigureServices(services);
}
protected override void Configure(IApplicationBuilder appBuilder)
{
DistributedCache = new Mock<IDistributedCache>(MockBehavior.Strict);
DistributedSessionStore store = new DistributedSessionStore(
DistributedCache.Object,
appBuilder.ApplicationServices.GetRequiredService<ILoggerFactory>());
appBuilder.UseBolt(
h =>
{
h.UseDistributedSession<IDummyContract, DummyContract>(store);
});
}
protected internal Mock<IDummyContract> Callback { get; set; }
protected internal Mock<IDistributedCache> DistributedCache { get; set; }
protected virtual IDummyContract CreateChannel()
{
return ClientConfiguration.CreateSessionProxy<IDummyContract>(ServerUrl);
}
public class DummyContract : IDummyContract
{
public DummyContract(ITestContext context, IHttpSessionProvider httpSessionProvider)
{
HttpSessionProvider = httpSessionProvider;
_context = context;
}
private readonly ITestContext _context;
public IHttpSessionProvider HttpSessionProvider { get; }
public void OnExecute(object context)
{
((DistributedSessionTest)_context.Instance).Callback?.Object.OnExecute(this);
}
}
public object Instance => this;
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using FileHelpers.FileTransformEngine;
using FileHelpers.Streams;
namespace FileHelpers
{
/// <summary>
/// This class allow you to convert the records of a file to a different record format.
/// </summary>
/// <typeparam name="TSource">The source record type.</typeparam>
/// <typeparam name="TDestination">The destination record type.</typeparam>
[DebuggerDisplay(
"FileTransformanEngine for types: {SourceType.Name} --> {DestinationType.Name}. Source Encoding: {SourceEncoding.EncodingName}. Destination Encoding: {DestinationEncoding.EncodingName}"
)]
public sealed class FileTransformEngine<TSource, TDestination>
where TSource : class, ITransformable<TDestination>
where TDestination : class
{
#region " Constructor "
/// <summary>Create a new FileTransformEngine.</summary>
public FileTransformEngine() {}
#endregion
#region " Private Fields "
// [DebuggerBrowsable(DebuggerBrowsableState.Never)]
// private static object[] mEmptyArray = new object[] {};
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private Encoding mSourceEncoding = Encoding.GetEncoding(0);
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private Encoding mDestinationEncoding = Encoding.GetEncoding(0);
private ErrorMode mErrorMode;
/// <summary>Indicates the behavior of the engine when an error is found.</summary>
public ErrorMode ErrorMode
{
get { return mErrorMode; }
set
{
mErrorMode = value;
mSourceErrorManager = new ErrorManager(value);
mDestinationErrorManager = new ErrorManager(value);
}
}
private ErrorManager mSourceErrorManager = new ErrorManager();
/// <summary>
/// Allow access the <see cref="ErrorManager"/> of the engine used to
/// read the source file, is null before any file is transformed
/// </summary>
public ErrorManager SourceErrorManager
{
get { return mSourceErrorManager; }
}
private ErrorManager mDestinationErrorManager = new ErrorManager();
/// <summary>
/// Allow access the <see cref="ErrorManager"/> of the engine used to
/// write the destination file, is null before any file is transformed
/// </summary>
public ErrorManager DestinationErrorManager
{
get { return mDestinationErrorManager; }
}
#endregion
#region " TransformFile "
/// <summary>
/// Transform the contents of the sourceFile and write them to the
/// destFile.(use only if you need the array of the transformed
/// records, TransformFileFast is faster)
/// </summary>
/// <param name="sourceFile">The source file.</param>
/// <param name="destFile">The destination file.</param>
/// <returns>The transformed records.</returns>
public TDestination[] TransformFile(string sourceFile, string destFile)
{
ExHelper.CheckNullParam(sourceFile, "sourceFile");
ExHelper.CheckNullParam(destFile, "destFile");
ExHelper.CheckDifferentsParams(sourceFile, "sourceFile", destFile, "destFile");
return CoreTransformFile(sourceFile, destFile);
}
/// <summary>
/// Transform the contents of the sourceFile and write them to the
/// destFile. (faster and uses less memory, best choice for big
/// files)
/// </summary>
/// <param name="sourceFile">The source file.</param>
/// <param name="destFile">The destination file.</param>
/// <returns>The number of transformed records.</returns>
public int TransformFileFast(string sourceFile, string destFile)
{
ExHelper.CheckNullParam(sourceFile, "sourceFile");
ExHelper.CheckNullParam(destFile, "destFile");
ExHelper.CheckDifferentsParams(sourceFile, "sourceFile", destFile, "destFile");
return
CoreTransformAsync(
new InternalStreamReader(sourceFile, SourceEncoding, true, EngineBase.DefaultReadBufferSize*5),
new StreamWriter(destFile, false, DestinationEncoding, EngineBase.DefaultWriteBufferSize*5));
}
/// <summary>
/// Transform the contents of the sourceFile and write them to the
/// destFile. (faster and uses less memory, best choice for big
/// files)
/// </summary>
/// <param name="sourceStream">The source stream.</param>
/// <param name="destFile">The destination file.</param>
/// <returns>The number of transformed records.</returns>
public int TransformFileFast(TextReader sourceStream, string destFile)
{
ExHelper.CheckNullParam(sourceStream, "sourceStream");
ExHelper.CheckNullParam(destFile, "destFile");
return CoreTransformAsync(sourceStream,
new StreamWriter(destFile, false, DestinationEncoding, EngineBase.DefaultWriteBufferSize*5));
}
/// <summary>
/// Transform the contents of the sourceFile and write them to the
/// destFile. (faster and uses less memory, best choice for big
/// files)
/// </summary>
/// <param name="sourceStream">The source stream.</param>
/// <param name="destStream">The destination stream.</param>
/// <returns>The number of transformed records.</returns>
public int TransformFileFast(TextReader sourceStream, StreamWriter destStream)
{
ExHelper.CheckNullParam(sourceStream, "sourceStream");
ExHelper.CheckNullParam(destStream, "destStream");
return CoreTransformAsync(sourceStream, destStream);
}
/// <summary>
/// Transform the contents of the sourceFile and write them to the
/// destFile. (faster and uses less memory, best choice for big
/// files)
/// </summary>
/// <param name="sourceFile">The source file.</param>
/// <param name="destStream">The destination stream.</param>
/// <returns>The number of transformed records.</returns>
public int TransformFileFast(string sourceFile, StreamWriter destStream)
{
ExHelper.CheckNullParam(sourceFile, "sourceFile");
ExHelper.CheckNullParam(destStream, "destStream");
return
CoreTransformAsync(
new InternalStreamReader(sourceFile, SourceEncoding, true, EngineBase.DefaultReadBufferSize*5),
destStream);
}
#endregion
/// <summary>
/// Transforms an array of records from the source type to the destination type
/// </summary>
/// <param name="sourceRecords">An array of the source records.</param>
/// <returns>The transformed records.</returns>
public TDestination[] TransformRecords(TSource[] sourceRecords)
{
return CoreTransformRecords(sourceRecords);
//return CoreTransformAsync(sourceFile, destFile, mSourceType, mDestinationType, mConvert1to2);
}
/// <summary>
/// Transform a file that contains source records to an array of the destination type
/// </summary>
/// <param name="sourceFile">A file containing the source records.</param>
/// <returns>The transformed records.</returns>
public TDestination[] ReadAndTransformRecords(string sourceFile)
{
var engine = new FileHelperAsyncEngine<TSource>(mSourceEncoding) {
ErrorMode = ErrorMode
};
mSourceErrorManager = engine.ErrorManager;
mDestinationErrorManager = new ErrorManager(ErrorMode);
var res = new List<TDestination>();
engine.BeginReadFile(sourceFile);
foreach (var record in engine)
res.Add(record.TransformTo());
engine.Close();
return res.ToArray();
}
#region " Transform Internal Methods "
private TDestination[] CoreTransform(InternalStreamReader sourceFile, StreamWriter destFile)
{
var sourceEngine = new FileHelperEngine<TSource>(mSourceEncoding);
var destEngine = new FileHelperEngine<TDestination>(mDestinationEncoding);
sourceEngine.ErrorMode = ErrorMode;
destEngine.ErrorManager.ErrorMode = ErrorMode;
mSourceErrorManager = sourceEngine.ErrorManager;
mDestinationErrorManager = destEngine.ErrorManager;
TSource[] source = sourceEngine.ReadStream(sourceFile);
TDestination[] transformed = CoreTransformRecords(source);
destEngine.WriteStream(destFile, transformed);
return transformed;
}
private TDestination[] CoreTransformRecords(TSource[] sourceRecords)
{
var res = new List<TDestination>(sourceRecords.Length);
for (int i = 0; i < sourceRecords.Length; i++)
res.Add(sourceRecords[i].TransformTo());
return res.ToArray();
}
private TDestination[] CoreTransformFile(string sourceFile, string destFile)
{
TDestination[] tempRes;
using (
var fs = new InternalStreamReader(sourceFile, mSourceEncoding, true, EngineBase.DefaultReadBufferSize*10)
) {
using (
var ds = new StreamWriter(destFile,
false,
mDestinationEncoding,
EngineBase.DefaultWriteBufferSize*10)) {
tempRes = CoreTransform(fs, ds);
ds.Close();
}
fs.Close();
}
return tempRes;
}
private int CoreTransformAsync(TextReader sourceFile, StreamWriter destFile)
{
var sourceEngine = new FileHelperAsyncEngine<TSource>();
var destEngine = new FileHelperAsyncEngine<TDestination>();
sourceEngine.ErrorMode = ErrorMode;
destEngine.ErrorMode = ErrorMode;
mSourceErrorManager = sourceEngine.ErrorManager;
mDestinationErrorManager = destEngine.ErrorManager;
sourceEngine.Encoding = mSourceEncoding;
destEngine.Encoding = mDestinationEncoding;
sourceEngine.BeginReadStream(sourceFile);
destEngine.BeginWriteStream(destFile);
foreach (var record in sourceEngine)
destEngine.WriteNext(record.TransformTo());
sourceEngine.Close();
destEngine.Close();
return sourceEngine.TotalRecords;
}
#endregion
#region " Properties "
/// <summary>The source record Type.</summary>
public Type SourceType
{
get { return typeof (TSource); }
}
/// <summary>The destination record Type.</summary>
public Type DestinationType
{
get { return typeof (TDestination); }
}
/// <summary>The Encoding of the Source File.</summary>
public Encoding SourceEncoding
{
get { return mSourceEncoding; }
set { mSourceEncoding = value; }
}
/// <summary>The Encoding of the Destination File.</summary>
public Encoding DestinationEncoding
{
get { return mDestinationEncoding; }
set { mDestinationEncoding = value; }
}
#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.Runtime.Serialization;
using System.Text;
using System;
using System.Diagnostics.Contracts;
namespace System.Text
{
// An Encoder is used to encode a sequence of blocks of characters into
// a sequence of blocks of bytes. Following instantiation of an encoder,
// sequential blocks of characters are converted into blocks of bytes through
// calls to the GetBytes method. The encoder maintains state between the
// conversions, allowing it to correctly encode character sequences that span
// adjacent blocks.
//
// Instances of specific implementations of the Encoder abstract base
// class are typically obtained through calls to the GetEncoder method
// of Encoding objects.
//
internal class EncoderNLS : Encoder, ISerializable
{
// Need a place for the last left over character, most of our encodings use this
internal char charLeftOver;
protected Encoding m_encoding;
[NonSerialized] protected bool m_mustFlush;
[NonSerialized] internal bool m_throwOnOverflow;
[NonSerialized] internal int m_charsUsed;
#region Serialization
// ISerializable implementation.
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
#endregion Serialization
internal EncoderNLS(Encoding encoding)
{
this.m_encoding = encoding;
this.m_fallback = this.m_encoding.EncoderFallback;
this.Reset();
}
// This one is used when deserializing (like UTF7Encoding.Encoder)
internal EncoderNLS()
{
this.m_encoding = null;
this.Reset();
}
public override void Reset()
{
this.charLeftOver = (char)0;
if (m_fallbackBuffer != null)
m_fallbackBuffer.Reset();
}
public override unsafe int GetByteCount(char[] chars, int index, int count, bool flush)
{
// Validate input parameters
if (chars == null)
throw new ArgumentNullException(nameof(chars),
SR.ArgumentNull_Array);
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)),
SR.ArgumentOutOfRange_NeedNonNegNum);
if (chars.Length - index < count)
throw new ArgumentOutOfRangeException(nameof(chars),
SR.ArgumentOutOfRange_IndexCountBuffer);
Contract.EndContractBlock();
// Avoid empty input problem
if (chars.Length == 0)
chars = new char[1];
// Just call the pointer version
int result = -1;
fixed (char* pChars = &chars[0])
{
result = GetByteCount(pChars + index, count, flush);
}
return result;
}
public unsafe override int GetByteCount(char* chars, int count, bool flush)
{
// Validate input parameters
if (chars == null)
throw new ArgumentNullException(nameof(chars),
SR.ArgumentNull_Array);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count),
SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
this.m_mustFlush = flush;
this.m_throwOnOverflow = true;
return m_encoding.GetByteCount(chars, count, this);
}
public override unsafe int GetBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex, bool flush)
{
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)),
SR.ArgumentNull_Array);
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)),
SR.ArgumentOutOfRange_NeedNonNegNum);
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException(nameof(chars),
SR.ArgumentOutOfRange_IndexCountBuffer);
if (byteIndex < 0 || byteIndex > bytes.Length)
throw new ArgumentOutOfRangeException(nameof(byteIndex),
SR.ArgumentOutOfRange_Index);
Contract.EndContractBlock();
if (chars.Length == 0)
chars = new char[1];
int byteCount = bytes.Length - byteIndex;
if (bytes.Length == 0)
bytes = new byte[1];
// Just call pointer version
fixed (char* pChars = &chars[0])
fixed (byte* pBytes = &bytes[0])
// Remember that charCount is # to decode, not size of array.
return GetBytes(pChars + charIndex, charCount,
pBytes + byteIndex, byteCount, flush);
}
public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush)
{
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)),
SR.ArgumentNull_Array);
if (byteCount < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)),
SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
this.m_mustFlush = flush;
this.m_throwOnOverflow = true;
return m_encoding.GetBytes(chars, charCount, bytes, byteCount, this);
}
// This method is used when your output buffer might not be large enough for the entire result.
// Just call the pointer version. (This gets bytes)
public override unsafe void Convert(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex, int byteCount, bool flush,
out int charsUsed, out int bytesUsed, out bool completed)
{
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)),
SR.ArgumentNull_Array);
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)),
SR.ArgumentOutOfRange_NeedNonNegNum);
if (byteIndex < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)),
SR.ArgumentOutOfRange_NeedNonNegNum);
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException(nameof(chars),
SR.ArgumentOutOfRange_IndexCountBuffer);
if (bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException(nameof(bytes),
SR.ArgumentOutOfRange_IndexCountBuffer);
Contract.EndContractBlock();
// Avoid empty input problem
if (chars.Length == 0)
chars = new char[1];
if (bytes.Length == 0)
bytes = new byte[1];
// Just call the pointer version (can't do this for non-msft encoders)
fixed (char* pChars = &chars[0])
{
fixed (byte* pBytes = &bytes[0])
{
Convert(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, flush,
out charsUsed, out bytesUsed, out completed);
}
}
}
// This is the version that uses pointers. We call the base encoding worker function
// after setting our appropriate internal variables. This is getting bytes
public override unsafe void Convert(char* chars, int charCount,
byte* bytes, int byteCount, bool flush,
out int charsUsed, out int bytesUsed, out bool completed)
{
// Validate input parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars),
SR.ArgumentNull_Array);
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)),
SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// We don't want to throw
this.m_mustFlush = flush;
this.m_throwOnOverflow = false;
this.m_charsUsed = 0;
// Do conversion
bytesUsed = this.m_encoding.GetBytes(chars, charCount, bytes, byteCount, this);
charsUsed = this.m_charsUsed;
// Its completed if they've used what they wanted AND if they didn't want flush or if we are flushed
completed = (charsUsed == charCount) && (!flush || !this.HasState) &&
(m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0);
// Our data thingys are now full, we can return
}
public Encoding Encoding
{
get
{
return m_encoding;
}
}
public bool MustFlush
{
get
{
return m_mustFlush;
}
}
// Anything left in our encoder?
internal virtual bool HasState
{
get
{
return (this.charLeftOver != (char)0);
}
}
// Allow encoding to clear our must flush instead of throwing (in ThrowBytesOverflow)
internal void ClearMustFlush()
{
m_mustFlush = false;
}
}
}
| |
//Copyright (C) 2006 Richard J. Northedge
//
// 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 program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//This file is based on the ProperNounResolver.java source file found in the
//original java implementation of OpenNLP. That source file contains the following header:
//Copyright (C) 2003 Thomas Morton
//
//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 program; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
using System;
//UPGRADE_TODO: The type 'java.util.regex.Pattern' could not be found. If it was not included in the conversion, there may be compiler issues. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1262'"
using System.Collections;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using MentionContext = OpenNLP.Tools.Coreference.Mention.MentionContext;
using System.Collections.Generic;
namespace OpenNLP.Tools.Coreference.Resolver
{
/// <summary> Resolves coreference between proper nouns.</summary>
public class ProperNounResolver:MaximumEntropyResolver
{
//UPGRADE_NOTE: Final was removed from the declaration of 'initialCaps '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
private static readonly Regex InitialCaps = new Regex("^[A-Z]", RegexOptions.Compiled);
private static IDictionary _acroMap;
private static bool _acroMapLoaded = false;
public ProperNounResolver(string projectName, ResolverMode mode):base(projectName, "pnmodel", mode, 500)
{
if (!_acroMapLoaded)
{
initAcronyms(projectName + "/acronyms");
_acroMapLoaded = true;
}
ShowExclusions = false;
}
public ProperNounResolver(string projectName, ResolverMode mode, INonReferentialResolver nonReferentialResolver):base(projectName, "pnmodel", mode, 500, nonReferentialResolver)
{
if (!_acroMapLoaded)
{
initAcronyms(projectName + "/acronyms");
_acroMapLoaded = true;
}
ShowExclusions = false;
}
public override bool CanResolve(MentionContext mention)
{
return (PartsOfSpeech.IsProperNoun(mention.HeadTokenTag) || mention.HeadTokenTag.StartsWith(PartsOfSpeech.CardinalNumber));
}
private void initAcronyms(string name)
{
//UPGRADE_TODO: Class 'java.util.HashMap' was converted to 'System.Collections.Hashtable' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMap'"
_acroMap = new Hashtable(15000);
try
{
StreamReader str;
//if (MaxentResolver.loadAsResource())
//{
//UPGRADE_TODO: The differences in the expected value of parameters for constructor 'java.io.BufferedReader.BufferedReader' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'"
//UPGRADE_WARNING: At least one expression was used more than once in the target code. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1181'"
//UPGRADE_ISSUE: Method 'java.lang.Class.getResourceAsStream' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javalangClassgetResourceAsStream_javalangString'"
//str = new System.IO.StreamReader(new System.IO.StreamReader(this.GetType().getResourceAsStream(name), System.Text.Encoding.Default).BaseStream, new System.IO.StreamReader(this.GetType().getResourceAsStream(name), System.Text.Encoding.Default).CurrentEncoding);
//}
//else
//{
//UPGRADE_TODO: The differences in the expected value of parameters for constructor 'java.io.BufferedReader.BufferedReader' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'"
//UPGRADE_WARNING: At least one expression was used more than once in the target code. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1181'"
//UPGRADE_TODO: Constructor 'java.io.FileReader.FileReader' was converted to 'System.IO.StreamReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'"
str = new StreamReader(new StreamReader(name, Encoding.Default).BaseStream, new StreamReader(name, Encoding.Default).CurrentEncoding);
//}
string line;
while (null != (line = str.ReadLine()))
{
var st = new Util.StringTokenizer(line, "\t");
string acro = st.NextToken();
string full = st.NextToken();
var exSet = (Util.Set<string>) _acroMap[acro];
if (exSet == null)
{
//UPGRADE_TODO: Class 'java.util.HashSet' was converted to 'SupportClass.HashSetSupport' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashSet'"
exSet = new Util.HashSet<string>();
_acroMap[acro] = exSet;
}
exSet.Add(full);
exSet = (Util.Set<string>) _acroMap[full];
if (exSet == null)
{
//UPGRADE_TODO: Class 'java.util.HashSet' was converted to 'SupportClass.HashSetSupport' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashSet'"
exSet = new Util.HashSet<string>();
_acroMap[full] = exSet;
}
exSet.Add(acro);
}
}
catch (IOException e)
{
//UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.ToString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
Console.Error.WriteLine("ProperNounResolver.initAcronyms: Acronym Database not found: " + e);
}
}
private MentionContext getProperNounExtent(DiscourseEntity de)
{
foreach (MentionContext xec in de.Mentions)
{
//use first extent which is propername
string xecHeadTag = xec.HeadTokenTag;
if (PartsOfSpeech.IsProperNoun(xecHeadTag) || InitialCaps.IsMatch(xec.HeadTokenText))
{
return xec;
}
}
return null;
}
private bool isAcronym(string ecStrip, string xecStrip)
{
var exSet = (Util.Set<string>) _acroMap[ecStrip];
if (exSet != null && exSet.Contains(xecStrip))
{
return true;
}
return false;
}
protected internal virtual List<string> getAcronymFeatures(MentionContext mention, DiscourseEntity entity)
{
MentionContext xec = getProperNounExtent(entity);
string ecStrip = StripNounPhrase(mention);
string xecStrip = StripNounPhrase(xec);
if (ecStrip != null && xecStrip != null)
{
if (isAcronym(ecStrip, xecStrip))
{
var features = new List<string>(1) {"knownAcronym"};
return features;
}
}
return new List<string>();
}
protected internal override List<string> GetFeatures(MentionContext mention, DiscourseEntity entity)
{
List<string> features = base.GetFeatures(mention, entity);
if (entity != null)
{
features.AddRange(GetStringMatchFeatures(mention, entity));
features.AddRange(getAcronymFeatures(mention, entity));
}
return features;
}
protected internal override bool IsExcluded(MentionContext mention, DiscourseEntity entity)
{
if (base.IsExcluded(mention, entity))
{
return true;
}
foreach (MentionContext xec in entity.Mentions)
{
if (PartsOfSpeech.IsProperNoun(xec.HeadTokenTag))
{
// || initialCaps.matcher(xec.headToken.ToString()).find()) {
return false;
}
}
return true;
}
}
}
| |
using J2N.Text;
using YAF.Lucene.Net.Index;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using JCG = J2N.Collections.Generic;
using Console = YAF.Lucene.Net.Util.SystemConsole;
namespace YAF.Lucene.Net.Codecs.Lucene3x
{
/*
* 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 IBits = YAF.Lucene.Net.Util.IBits;
using BytesRef = YAF.Lucene.Net.Util.BytesRef;
using Directory = YAF.Lucene.Net.Store.Directory;
using DocsAndPositionsEnum = YAF.Lucene.Net.Index.DocsAndPositionsEnum;
using DocsEnum = YAF.Lucene.Net.Index.DocsEnum;
using FieldInfo = YAF.Lucene.Net.Index.FieldInfo;
using FieldInfos = YAF.Lucene.Net.Index.FieldInfos;
using IndexFileNames = YAF.Lucene.Net.Index.IndexFileNames;
using IndexInput = YAF.Lucene.Net.Store.IndexInput;
using IndexOptions = YAF.Lucene.Net.Index.IndexOptions;
using IOContext = YAF.Lucene.Net.Store.IOContext;
using IOUtils = YAF.Lucene.Net.Util.IOUtils;
using SegmentInfo = YAF.Lucene.Net.Index.SegmentInfo;
using StringHelper = YAF.Lucene.Net.Util.StringHelper;
using Term = YAF.Lucene.Net.Index.Term;
using Terms = YAF.Lucene.Net.Index.Terms;
using TermsEnum = YAF.Lucene.Net.Index.TermsEnum;
using UnicodeUtil = YAF.Lucene.Net.Util.UnicodeUtil;
/// <summary>
/// Exposes flex API on a pre-flex index, as a codec.
/// <para/>
/// @lucene.experimental
/// </summary>
[Obsolete("(4.0)")]
internal class Lucene3xFields : FieldsProducer
{
private static bool DEBUG_SURROGATES = false;
public TermInfosReader Tis { get; set; }
public TermInfosReader TisNoIndex { get; private set; }
public IndexInput FreqStream { get; private set; }
public IndexInput ProxStream { get; private set; }
private readonly FieldInfos fieldInfos;
private readonly SegmentInfo si;
// LUCENENET specific: Use StringComparer.Ordinal to get the same ordering as Java
internal readonly IDictionary<string, FieldInfo> fields = new JCG.SortedDictionary<string, FieldInfo>(StringComparer.Ordinal);
internal readonly IDictionary<string, Terms> preTerms = new Dictionary<string, Terms>();
private readonly Directory dir;
private readonly IOContext context;
//private Directory cfsReader; // LUCENENET NOTE: cfsReader not used
public Lucene3xFields(Directory dir, FieldInfos fieldInfos, SegmentInfo info, IOContext context, int indexDivisor)
{
si = info;
// NOTE: we must always load terms index, even for
// "sequential" scan during merging, because what is
// sequential to merger may not be to TermInfosReader
// since we do the surrogates dance:
if (indexDivisor < 0)
{
indexDivisor = -indexDivisor;
}
bool success = false;
try
{
var r = new TermInfosReader(dir, info.Name, fieldInfos, context, indexDivisor);
if (indexDivisor == -1)
{
TisNoIndex = r;
}
else
{
TisNoIndex = null;
Tis = r;
}
this.context = context;
this.fieldInfos = fieldInfos;
// make sure that all index files have been read or are kept open
// so that if an index update removes them we'll still have them
FreqStream = dir.OpenInput(IndexFileNames.SegmentFileName(info.Name, "", Lucene3xPostingsFormat.FREQ_EXTENSION), context);
bool anyProx = false;
foreach (FieldInfo fi in fieldInfos)
{
if (fi.IsIndexed)
{
fields[fi.Name] = fi;
preTerms[fi.Name] = new PreTerms(this, fi);
if (fi.IndexOptions == IndexOptions.DOCS_AND_FREQS_AND_POSITIONS)
{
anyProx = true;
}
}
}
if (anyProx)
{
ProxStream = dir.OpenInput(IndexFileNames.SegmentFileName(info.Name, "", Lucene3xPostingsFormat.PROX_EXTENSION), context);
}
else
{
ProxStream = null;
}
success = true;
}
finally
{
// With lock-less commits, it's entirely possible (and
// fine) to hit a FileNotFound exception above. In
// this case, we want to explicitly close any subset
// of things that were opened so that we don't have to
// wait for a GC to do so.
if (!success)
{
Dispose();
}
}
this.dir = dir;
}
// If this returns, we do the surrogates dance so that the
// terms are sorted by unicode sort order. this should be
// true when segments are used for "normal" searching;
// it's only false during testing, to create a pre-flex
// index, using the test-only PreFlexRW.
protected virtual bool SortTermsByUnicode
{
get { return true; }
}
public override IEnumerator<string> GetEnumerator()
{
return fields.Keys.GetEnumerator();
}
public override Terms GetTerms(string field)
{
Terms result;
preTerms.TryGetValue(field, out result);
return result;
}
public override int Count
{
get
{
Debug.Assert(preTerms.Count == fields.Count);
return fields.Count;
}
}
[Obsolete("iterate fields and add their Count instead.")]
public override long UniqueTermCount
{
get
{
return TermsDict.Count;
}
}
private TermInfosReader TermsDict
{
get
{
lock (this)
{
if (Tis != null)
{
return Tis;
}
else
{
return TisNoIndex;
}
}
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
IOUtils.Dispose(Tis, TisNoIndex, /*cfsReader,*/ FreqStream, ProxStream); // LUCENENET NOTE: cfsReader not used
}
}
private class PreTerms : Terms
{
private readonly Lucene3xFields outerInstance;
internal readonly FieldInfo fieldInfo;
internal PreTerms(Lucene3xFields outerInstance, FieldInfo fieldInfo)
{
this.outerInstance = outerInstance;
this.fieldInfo = fieldInfo;
}
public override TermsEnum GetIterator(TermsEnum reuse)
{
var termsEnum = new PreTermsEnum(outerInstance);
termsEnum.Reset(fieldInfo);
return termsEnum;
}
public override IComparer<BytesRef> Comparer
{
get
{
// Pre-flex indexes always sorted in UTF16 order, but
// we remap on-the-fly to unicode order
if (outerInstance.SortTermsByUnicode)
{
return BytesRef.UTF8SortedAsUnicodeComparer;
}
else
{
return BytesRef.UTF8SortedAsUTF16Comparer;
}
}
}
public override long Count
{
get { return -1; }
}
public override long SumTotalTermFreq
{
get
{
return -1;
}
}
public override long SumDocFreq
{
get
{
return -1;
}
}
public override int DocCount
{
get
{
return -1;
}
}
public override bool HasFreqs
{
get { return fieldInfo.IndexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS) >= 0; }
}
public override bool HasOffsets
{
get
{
// preflex doesn't support this
Debug.Assert(fieldInfo.IndexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) < 0);
return false;
}
}
public override bool HasPositions
{
get { return fieldInfo.IndexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0; }
}
public override bool HasPayloads
{
get { return fieldInfo.HasPayloads; }
}
}
private class PreTermsEnum : TermsEnum
{
private readonly Lucene3xFields outerInstance;
public PreTermsEnum(Lucene3xFields outerInstance)
{
this.outerInstance = outerInstance;
}
private SegmentTermEnum termEnum;
private FieldInfo fieldInfo;
private string internedFieldName;
private bool skipNext;
private BytesRef current;
private SegmentTermEnum seekTermEnum;
private static readonly sbyte UTF8_NON_BMP_LEAD = unchecked((sbyte) 0xf0);
private static readonly sbyte UTF8_HIGH_BMP_LEAD = unchecked((sbyte) 0xee);
// Returns true if the unicode char is "after" the
// surrogates in UTF16, ie >= U+E000 and <= U+FFFF:
private static bool IsHighBMPChar(byte[] b, int idx)
{
return (((sbyte)b[idx]) & UTF8_HIGH_BMP_LEAD) == UTF8_HIGH_BMP_LEAD;
}
// Returns true if the unicode char in the UTF8 byte
// sequence starting at idx encodes a char outside of
// BMP (ie what would be a surrogate pair in UTF16):
private static bool IsNonBMPChar(byte[] b, int idx)
{
return (((sbyte)b[idx]) & UTF8_NON_BMP_LEAD) == UTF8_NON_BMP_LEAD;
}
private readonly sbyte[] scratch = new sbyte[4];
private readonly BytesRef prevTerm = new BytesRef();
private readonly BytesRef scratchTerm = new BytesRef();
private int newSuffixStart;
// Swap in S, in place of E:
private bool SeekToNonBMP(SegmentTermEnum te, BytesRef term, int pos)
{
int savLength = term.Length;
Debug.Assert(term.Offset == 0);
// The 3 bytes starting at downTo make up 1
// unicode character:
Debug.Assert(IsHighBMPChar(term.Bytes, pos));
// NOTE: we cannot make this assert, because
// AutomatonQuery legitimately sends us malformed UTF8
// (eg the UTF8 bytes with just 0xee)
// assert term.length >= pos + 3: "term.length=" + term.length + " pos+3=" + (pos+3) + " byte=" + Integer.toHexString(term.bytes[pos]) + " term=" + term.toString();
// Save the bytes && length, since we need to
// restore this if seek "back" finds no matching
// terms
if (term.Bytes.Length < 4 + pos)
{
term.Grow(4 + pos);
}
scratch[0] = (sbyte)term.Bytes[pos];
scratch[1] = (sbyte)term.Bytes[pos + 1];
scratch[2] = (sbyte)term.Bytes[pos + 2];
term.Bytes[pos] = 0xf0;
term.Bytes[pos + 1] = 0x90;
term.Bytes[pos + 2] = 0x80;
term.Bytes[pos + 3] = 0x80;
term.Length = 4 + pos;
if (DEBUG_SURROGATES)
{
Console.WriteLine(" try seek term=" + UnicodeUtil.ToHexString(term.Utf8ToString()));
}
// Seek "back":
outerInstance.TermsDict.SeekEnum(te, new Term(fieldInfo.Name, term), true);
// Test if the term we seek'd to in fact found a
// surrogate pair at the same position as the E:
Term t2 = te.Term();
// Cannot be null (or move to next field) because at
// "worst" it'd seek to the same term we are on now,
// unless we are being called from seek
if (t2 == null || t2.Field != internedFieldName)
{
return false;
}
if (DEBUG_SURROGATES)
{
Console.WriteLine(" got term=" + UnicodeUtil.ToHexString(t2.Text()));
}
// Now test if prefix is identical and we found
// a non-BMP char at the same position:
BytesRef b2 = t2.Bytes;
Debug.Assert(b2.Offset == 0);
bool matches;
if (b2.Length >= term.Length && IsNonBMPChar(b2.Bytes, pos))
{
matches = true;
for (int i = 0; i < pos; i++)
{
if (term.Bytes[i] != b2.Bytes[i])
{
matches = false;
break;
}
}
}
else
{
matches = false;
}
// Restore term:
term.Length = savLength;
term.Bytes[pos] = (byte)scratch[0];
term.Bytes[pos + 1] = (byte)scratch[1];
term.Bytes[pos + 2] = (byte)scratch[2];
return matches;
}
// Seek type 2 "continue" (back to the start of the
// surrogates): scan the stripped suffix from the
// prior term, backwards. If there was an E in that
// part, then we try to seek back to S. If that
// seek finds a matching term, we go there.
private bool DoContinue()
{
if (DEBUG_SURROGATES)
{
Console.WriteLine(" try cont");
}
int downTo = prevTerm.Length - 1;
bool didSeek = false;
int limit = Math.Min(newSuffixStart, scratchTerm.Length - 1);
while (downTo > limit)
{
if (IsHighBMPChar(prevTerm.Bytes, downTo))
{
if (DEBUG_SURROGATES)
{
Console.WriteLine(" found E pos=" + downTo + " vs len=" + prevTerm.Length);
}
if (SeekToNonBMP(seekTermEnum, prevTerm, downTo))
{
// TODO: more efficient seek?
outerInstance.TermsDict.SeekEnum(termEnum, seekTermEnum.Term(), true);
//newSuffixStart = downTo+4;
newSuffixStart = downTo;
scratchTerm.CopyBytes(termEnum.Term().Bytes);
didSeek = true;
if (DEBUG_SURROGATES)
{
Console.WriteLine(" seek!");
}
break;
}
else
{
if (DEBUG_SURROGATES)
{
Console.WriteLine(" no seek");
}
}
}
// Shorten prevTerm in place so that we don't redo
// this loop if we come back here:
if ((prevTerm.Bytes[downTo] & 0xc0) == 0xc0 || (prevTerm.Bytes[downTo] & 0x80) == 0)
{
prevTerm.Length = downTo;
}
downTo--;
}
return didSeek;
}
// Look for seek type 3 ("pop"): if the delta from
// prev -> current was replacing an S with an E,
// we must now seek to beyond that E. this seek
// "finishes" the dance at this character
// position.
private bool DoPop()
{
if (DEBUG_SURROGATES)
{
Console.WriteLine(" try pop");
}
Debug.Assert(newSuffixStart <= prevTerm.Length);
Debug.Assert(newSuffixStart < scratchTerm.Length || newSuffixStart == 0);
if (prevTerm.Length > newSuffixStart && IsNonBMPChar(prevTerm.Bytes, newSuffixStart) && IsHighBMPChar(scratchTerm.Bytes, newSuffixStart))
{
// Seek type 2 -- put 0xFF at this position:
scratchTerm.Bytes[newSuffixStart] = 0xff;
scratchTerm.Length = newSuffixStart + 1;
if (DEBUG_SURROGATES)
{
Console.WriteLine(" seek to term=" + UnicodeUtil.ToHexString(scratchTerm.Utf8ToString()) + " " + scratchTerm.ToString());
}
// TODO: more efficient seek? can we simply swap
// the enums?
outerInstance.TermsDict.SeekEnum(termEnum, new Term(fieldInfo.Name, scratchTerm), true);
Term t2 = termEnum.Term();
// We could hit EOF or different field since this
// was a seek "forward":
if (t2 != null && t2.Field == internedFieldName)
{
if (DEBUG_SURROGATES)
{
Console.WriteLine(" got term=" + UnicodeUtil.ToHexString(t2.Text()) + " " + t2.Bytes);
}
BytesRef b2 = t2.Bytes;
Debug.Assert(b2.Offset == 0);
// Set newSuffixStart -- we can't use
// termEnum's since the above seek may have
// done no scanning (eg, term was precisely
// and index term, or, was in the term seek
// cache):
scratchTerm.CopyBytes(b2);
SetNewSuffixStart(prevTerm, scratchTerm);
return true;
}
else if (newSuffixStart != 0 || scratchTerm.Length != 0)
{
if (DEBUG_SURROGATES)
{
Console.WriteLine(" got term=null (or next field)");
}
newSuffixStart = 0;
scratchTerm.Length = 0;
return true;
}
}
return false;
}
// Pre-flex indices store terms in UTF16 sort order, but
// certain queries require Unicode codepoint order; this
// method carefully seeks around surrogates to handle
// this impedance mismatch
private void SurrogateDance()
{
if (!unicodeSortOrder)
{
return;
}
// We are invoked after TIS.next() (by UTF16 order) to
// possibly seek to a different "next" (by unicode
// order) term.
// We scan only the "delta" from the last term to the
// current term, in UTF8 bytes. We look at 1) the bytes
// stripped from the prior term, and then 2) the bytes
// appended to that prior term's prefix.
// We don't care about specific UTF8 sequences, just
// the "category" of the UTF16 character. Category S
// is a high/low surrogate pair (it non-BMP).
// Category E is any BMP char > UNI_SUR_LOW_END (and <
// U+FFFF). Category A is the rest (any unicode char
// <= UNI_SUR_HIGH_START).
// The core issue is that pre-flex indices sort the
// characters as ASE, while flex must sort as AES. So
// when scanning, when we hit S, we must 1) seek
// forward to E and enum the terms there, then 2) seek
// back to S and enum all terms there, then 3) seek to
// after E. Three different seek points (1, 2, 3).
// We can easily detect S in UTF8: if a byte has
// prefix 11110 (0xf0), then that byte and the
// following 3 bytes encode a single unicode codepoint
// in S. Similarly, we can detect E: if a byte has
// prefix 1110111 (0xee), then that byte and the
// following 2 bytes encode a single unicode codepoint
// in E.
// Note that this is really a recursive process --
// maybe the char at pos 2 needs to dance, but any
// point in its dance, suddenly pos 4 needs to dance
// so you must finish pos 4 before returning to pos
// 2. But then during pos 4's dance maybe pos 7 needs
// to dance, etc. However, despite being recursive,
// we don't need to hold any state because the state
// can always be derived by looking at prior term &
// current term.
// TODO: can we avoid this copy?
if (termEnum.Term() == null || termEnum.Term().Field != internedFieldName)
{
scratchTerm.Length = 0;
}
else
{
scratchTerm.CopyBytes(termEnum.Term().Bytes);
}
if (DEBUG_SURROGATES)
{
Console.WriteLine(" dance");
Console.WriteLine(" prev=" + UnicodeUtil.ToHexString(prevTerm.Utf8ToString()));
Console.WriteLine(" " + prevTerm.ToString());
Console.WriteLine(" term=" + UnicodeUtil.ToHexString(scratchTerm.Utf8ToString()));
Console.WriteLine(" " + scratchTerm.ToString());
}
// this code assumes TermInfosReader/SegmentTermEnum
// always use BytesRef.offset == 0
Debug.Assert(prevTerm.Offset == 0);
Debug.Assert(scratchTerm.Offset == 0);
// Need to loop here because we may need to do multiple
// pops, and possibly a continue in the end, ie:
//
// cont
// pop, cont
// pop, pop, cont
// <nothing>
//
while (true)
{
if (DoContinue())
{
break;
}
else
{
if (!DoPop())
{
break;
}
}
}
if (DEBUG_SURROGATES)
{
Console.WriteLine(" finish bmp ends");
}
DoPushes();
}
// Look for seek type 1 ("push"): if the newly added
// suffix contains any S, we must try to seek to the
// corresponding E. If we find a match, we go there;
// else we keep looking for additional S's in the new
// suffix. this "starts" the dance, at this character
// position:
private void DoPushes()
{
int upTo = newSuffixStart;
if (DEBUG_SURROGATES)
{
Console.WriteLine(" try push newSuffixStart=" + newSuffixStart + " scratchLen=" + scratchTerm.Length);
}
while (upTo < scratchTerm.Length)
{
if (IsNonBMPChar(scratchTerm.Bytes, upTo) && (upTo > newSuffixStart || (upTo >= prevTerm.Length || (!IsNonBMPChar(prevTerm.Bytes, upTo) && !IsHighBMPChar(prevTerm.Bytes, upTo)))))
{
// A non-BMP char (4 bytes UTF8) starts here:
Debug.Assert(scratchTerm.Length >= upTo + 4);
int savLength = scratchTerm.Length;
scratch[0] = (sbyte)scratchTerm.Bytes[upTo];
scratch[1] = (sbyte)scratchTerm.Bytes[upTo + 1];
scratch[2] = (sbyte)scratchTerm.Bytes[upTo + 2];
scratchTerm.Bytes[upTo] = (byte)UTF8_HIGH_BMP_LEAD;
scratchTerm.Bytes[upTo + 1] = 0x80;
scratchTerm.Bytes[upTo + 2] = 0x80;
scratchTerm.Length = upTo + 3;
if (DEBUG_SURROGATES)
{
Console.WriteLine(" try seek 1 pos=" + upTo + " term=" + UnicodeUtil.ToHexString(scratchTerm.Utf8ToString()) + " " + scratchTerm.ToString() + " len=" + scratchTerm.Length);
}
// Seek "forward":
// TODO: more efficient seek?
outerInstance.TermsDict.SeekEnum(seekTermEnum, new Term(fieldInfo.Name, scratchTerm), true);
scratchTerm.Bytes[upTo] = (byte)scratch[0];
scratchTerm.Bytes[upTo + 1] = (byte)scratch[1];
scratchTerm.Bytes[upTo + 2] = (byte)scratch[2];
scratchTerm.Length = savLength;
// Did we find a match?
Term t2 = seekTermEnum.Term();
if (DEBUG_SURROGATES)
{
if (t2 == null)
{
Console.WriteLine(" hit term=null");
}
else
{
Console.WriteLine(" hit term=" + UnicodeUtil.ToHexString(t2.Text()) + " " + (t2 == null ? null : t2.Bytes));
}
}
// Since this was a seek "forward", we could hit
// EOF or a different field:
bool matches;
if (t2 != null && t2.Field == internedFieldName)
{
BytesRef b2 = t2.Bytes;
Debug.Assert(b2.Offset == 0);
if (b2.Length >= upTo + 3 && IsHighBMPChar(b2.Bytes, upTo))
{
matches = true;
for (int i = 0; i < upTo; i++)
{
if (scratchTerm.Bytes[i] != b2.Bytes[i])
{
matches = false;
break;
}
}
}
else
{
matches = false;
}
}
else
{
matches = false;
}
if (matches)
{
if (DEBUG_SURROGATES)
{
Console.WriteLine(" matches!");
}
// OK seek "back"
// TODO: more efficient seek?
outerInstance.TermsDict.SeekEnum(termEnum, seekTermEnum.Term(), true);
scratchTerm.CopyBytes(seekTermEnum.Term().Bytes);
// +3 because we don't need to check the char
// at upTo: we know it's > BMP
upTo += 3;
// NOTE: we keep iterating, now, since this
// can easily "recurse". Ie, after seeking
// forward at a certain char position, we may
// find another surrogate in our [new] suffix
// and must then do another seek (recurse)
}
else
{
upTo++;
}
}
else
{
upTo++;
}
}
}
private bool unicodeSortOrder;
internal virtual void Reset(FieldInfo fieldInfo)
{
//System.out.println("pff.reset te=" + termEnum);
this.fieldInfo = fieldInfo;
internedFieldName = fieldInfo.Name.Intern();
Term term = new Term(internedFieldName);
if (termEnum == null)
{
termEnum = outerInstance.TermsDict.Terms(term);
seekTermEnum = outerInstance.TermsDict.Terms(term);
//System.out.println(" term=" + termEnum.term());
}
else
{
outerInstance.TermsDict.SeekEnum(termEnum, term, true);
}
skipNext = true;
unicodeSortOrder = outerInstance.SortTermsByUnicode;
Term t = termEnum.Term();
if (t != null && t.Field == internedFieldName)
{
newSuffixStart = 0;
prevTerm.Length = 0;
SurrogateDance();
}
}
public override IComparer<BytesRef> Comparer
{
get
{
// Pre-flex indexes always sorted in UTF16 order, but
// we remap on-the-fly to unicode order
if (unicodeSortOrder)
{
return BytesRef.UTF8SortedAsUnicodeComparer;
}
else
{
return BytesRef.UTF8SortedAsUTF16Comparer;
}
}
}
public override void SeekExact(long ord)
{
throw new System.NotSupportedException();
}
public override long Ord
{
get { throw new System.NotSupportedException(); }
}
public override SeekStatus SeekCeil(BytesRef term)
{
if (DEBUG_SURROGATES)
{
Console.WriteLine("TE.seek target=" + UnicodeUtil.ToHexString(term.Utf8ToString()));
}
skipNext = false;
TermInfosReader tis = outerInstance.TermsDict;
Term t0 = new Term(fieldInfo.Name, term);
Debug.Assert(termEnum != null);
tis.SeekEnum(termEnum, t0, false);
Term t = termEnum.Term();
if (t != null && t.Field == internedFieldName && term.BytesEquals(t.Bytes))
{
// If we found an exact match, no need to do the
// surrogate dance
if (DEBUG_SURROGATES)
{
Console.WriteLine(" seek exact match");
}
current = t.Bytes;
return SeekStatus.FOUND;
}
else if (t == null || t.Field != internedFieldName)
{
// TODO: maybe we can handle this like the next()
// into null? set term as prevTerm then dance?
if (DEBUG_SURROGATES)
{
Console.WriteLine(" seek hit EOF");
}
// We hit EOF; try end-case surrogate dance: if we
// find an E, try swapping in S, backwards:
scratchTerm.CopyBytes(term);
Debug.Assert(scratchTerm.Offset == 0);
for (int i = scratchTerm.Length - 1; i >= 0; i--)
{
if (IsHighBMPChar(scratchTerm.Bytes, i))
{
if (DEBUG_SURROGATES)
{
Console.WriteLine(" found E pos=" + i + "; try seek");
}
if (SeekToNonBMP(seekTermEnum, scratchTerm, i))
{
scratchTerm.CopyBytes(seekTermEnum.Term().Bytes);
outerInstance.TermsDict.SeekEnum(termEnum, seekTermEnum.Term(), false);
newSuffixStart = 1 + i;
DoPushes();
// Found a match
// TODO: faster seek?
current = termEnum.Term().Bytes;
return SeekStatus.NOT_FOUND;
}
}
}
if (DEBUG_SURROGATES)
{
Console.WriteLine(" seek END");
}
current = null;
return SeekStatus.END;
}
else
{
// We found a non-exact but non-null term; this one
// is fun -- just treat it like next, by pretending
// requested term was prev:
prevTerm.CopyBytes(term);
if (DEBUG_SURROGATES)
{
Console.WriteLine(" seek hit non-exact term=" + UnicodeUtil.ToHexString(t.Text()));
}
BytesRef br = t.Bytes;
Debug.Assert(br.Offset == 0);
SetNewSuffixStart(term, br);
SurrogateDance();
Term t2 = termEnum.Term();
if (t2 == null || t2.Field != internedFieldName)
{
// PreFlex codec interns field names; verify:
Debug.Assert(t2 == null || !t2.Field.Equals(internedFieldName, StringComparison.Ordinal));
current = null;
return SeekStatus.END;
}
else
{
current = t2.Bytes;
Debug.Assert(!unicodeSortOrder || term.CompareTo(current) < 0, "term=" + UnicodeUtil.ToHexString(term.Utf8ToString()) + " vs current=" + UnicodeUtil.ToHexString(current.Utf8ToString()));
return SeekStatus.NOT_FOUND;
}
}
}
private void SetNewSuffixStart(BytesRef br1, BytesRef br2)
{
int limit = Math.Min(br1.Length, br2.Length);
int lastStart = 0;
for (int i = 0; i < limit; i++)
{
if ((br1.Bytes[br1.Offset + i] & 0xc0) == 0xc0 || (br1.Bytes[br1.Offset + i] & 0x80) == 0)
{
lastStart = i;
}
if (br1.Bytes[br1.Offset + i] != br2.Bytes[br2.Offset + i])
{
newSuffixStart = lastStart;
if (DEBUG_SURROGATES)
{
Console.WriteLine(" set newSuffixStart=" + newSuffixStart);
}
return;
}
}
newSuffixStart = limit;
if (DEBUG_SURROGATES)
{
Console.WriteLine(" set newSuffixStart=" + newSuffixStart);
}
}
public override BytesRef Next()
{
if (DEBUG_SURROGATES)
{
Console.WriteLine("TE.next()");
}
if (skipNext)
{
if (DEBUG_SURROGATES)
{
Console.WriteLine(" skipNext=true");
}
skipNext = false;
if (termEnum.Term() == null)
{
return null;
// PreFlex codec interns field names:
}
else if (termEnum.Term().Field != internedFieldName)
{
return null;
}
else
{
return current = termEnum.Term().Bytes;
}
}
// TODO: can we use STE's prevBuffer here?
prevTerm.CopyBytes(termEnum.Term().Bytes);
if (termEnum.Next() && termEnum.Term().Field == internedFieldName)
{
newSuffixStart = termEnum.newSuffixStart;
if (DEBUG_SURROGATES)
{
Console.WriteLine(" newSuffixStart=" + newSuffixStart);
}
SurrogateDance();
Term t = termEnum.Term();
if (t == null || t.Field != internedFieldName)
{
// PreFlex codec interns field names; verify:
Debug.Assert(t == null || !t.Field.Equals(internedFieldName, StringComparison.Ordinal));
current = null;
}
else
{
current = t.Bytes;
}
return current;
}
else
{
// this field is exhausted, but we have to give
// surrogateDance a chance to seek back:
if (DEBUG_SURROGATES)
{
Console.WriteLine(" force cont");
}
//newSuffixStart = prevTerm.length;
newSuffixStart = 0;
SurrogateDance();
Term t = termEnum.Term();
if (t == null || t.Field != internedFieldName)
{
// PreFlex codec interns field names; verify:
Debug.Assert(t == null || !t.Field.Equals(internedFieldName, StringComparison.Ordinal));
return null;
}
else
{
current = t.Bytes;
return current;
}
}
}
public override BytesRef Term
{
get { return current; }
}
public override int DocFreq
{
get { return termEnum.DocFreq; }
}
public override long TotalTermFreq
{
get { return -1; }
}
public override DocsEnum Docs(IBits liveDocs, DocsEnum reuse, DocsFlags flags)
{
PreDocsEnum docsEnum;
if (reuse == null || !(reuse is PreDocsEnum))
{
docsEnum = new PreDocsEnum(outerInstance);
}
else
{
docsEnum = (PreDocsEnum)reuse;
if (docsEnum.FreqStream != outerInstance.FreqStream)
{
docsEnum = new PreDocsEnum(outerInstance);
}
}
return docsEnum.Reset(termEnum, liveDocs);
}
public override DocsAndPositionsEnum DocsAndPositions(IBits liveDocs, DocsAndPositionsEnum reuse, DocsAndPositionsFlags flags)
{
PreDocsAndPositionsEnum docsPosEnum;
if (fieldInfo.IndexOptions != IndexOptions.DOCS_AND_FREQS_AND_POSITIONS)
{
return null;
}
else if (reuse == null || !(reuse is PreDocsAndPositionsEnum))
{
docsPosEnum = new PreDocsAndPositionsEnum(outerInstance);
}
else
{
docsPosEnum = (PreDocsAndPositionsEnum)reuse;
if (docsPosEnum.FreqStream != outerInstance.FreqStream)
{
docsPosEnum = new PreDocsAndPositionsEnum(outerInstance);
}
}
return docsPosEnum.Reset(termEnum, liveDocs);
}
}
private sealed class PreDocsEnum : DocsEnum
{
private readonly Lucene3xFields outerInstance;
internal readonly SegmentTermDocs docs;
private int docID = -1;
internal PreDocsEnum(Lucene3xFields outerInstance)
{
this.outerInstance = outerInstance;
docs = new SegmentTermDocs(outerInstance.FreqStream, outerInstance.TermsDict, outerInstance.fieldInfos);
}
internal IndexInput FreqStream
{
get
{
return outerInstance.FreqStream;
}
}
public PreDocsEnum Reset(SegmentTermEnum termEnum, IBits liveDocs)
{
docs.LiveDocs = liveDocs;
docs.Seek(termEnum);
docs.freq = 1;
docID = -1;
return this;
}
public override int NextDoc()
{
if (docs.Next())
{
return docID = docs.Doc;
}
else
{
return docID = NO_MORE_DOCS;
}
}
public override int Advance(int target)
{
if (docs.SkipTo(target))
{
return docID = docs.Doc;
}
else
{
return docID = NO_MORE_DOCS;
}
}
public override int Freq
{
get { return docs.Freq; }
}
public override int DocID
{
get { return docID; }
}
public override long GetCost()
{
return docs.m_df;
}
}
private sealed class PreDocsAndPositionsEnum : DocsAndPositionsEnum
{
private readonly Lucene3xFields outerInstance;
private readonly SegmentTermPositions pos;
private int docID = -1;
internal PreDocsAndPositionsEnum(Lucene3xFields outerInstance)
{
this.outerInstance = outerInstance;
pos = new SegmentTermPositions(outerInstance.FreqStream, outerInstance.ProxStream, outerInstance.TermsDict, outerInstance.fieldInfos);
}
internal IndexInput FreqStream
{
get
{
return outerInstance.FreqStream;
}
}
public DocsAndPositionsEnum Reset(SegmentTermEnum termEnum, IBits liveDocs)
{
pos.LiveDocs = liveDocs;
pos.Seek(termEnum);
docID = -1;
return this;
}
public override int NextDoc()
{
if (pos.Next())
{
return docID = pos.Doc;
}
else
{
return docID = NO_MORE_DOCS;
}
}
public override int Advance(int target)
{
if (pos.SkipTo(target))
{
return docID = pos.Doc;
}
else
{
return docID = NO_MORE_DOCS;
}
}
public override int Freq
{
get { return pos.Freq; }
}
public override int DocID
{
get { return docID; }
}
public override int NextPosition()
{
Debug.Assert(docID != NO_MORE_DOCS);
return pos.NextPosition();
}
public override int StartOffset
{
get { return -1; }
}
public override int EndOffset
{
get { return -1; }
}
public override BytesRef GetPayload()
{
return pos.GetPayload();
}
public override long GetCost()
{
return pos.m_df;
}
}
public override long RamBytesUsed()
{
if (Tis != null)
{
return Tis.RamBytesUsed();
}
else
{
// when there is no index, there is almost nothing loaded into RAM
return 0L;
}
}
public override void CheckIntegrity()
{
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void SubtractUInt16()
{
var test = new SimpleBinaryOpTest__SubtractUInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__SubtractUInt16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(UInt16[] inArray1, UInt16[] inArray2, UInt16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt16, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<UInt16> _fld1;
public Vector256<UInt16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__SubtractUInt16 testClass)
{
var result = Avx2.Subtract(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__SubtractUInt16 testClass)
{
fixed (Vector256<UInt16>* pFld1 = &_fld1)
fixed (Vector256<UInt16>* pFld2 = &_fld2)
{
var result = Avx2.Subtract(
Avx.LoadVector256((UInt16*)(pFld1)),
Avx.LoadVector256((UInt16*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16);
private static UInt16[] _data1 = new UInt16[Op1ElementCount];
private static UInt16[] _data2 = new UInt16[Op2ElementCount];
private static Vector256<UInt16> _clsVar1;
private static Vector256<UInt16> _clsVar2;
private Vector256<UInt16> _fld1;
private Vector256<UInt16> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__SubtractUInt16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
}
public SimpleBinaryOpTest__SubtractUInt16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
_dataTable = new DataTable(_data1, _data2, new UInt16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.Subtract(
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.Subtract(
Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.Subtract(
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Subtract), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Subtract), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Subtract), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.Subtract(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<UInt16>* pClsVar1 = &_clsVar1)
fixed (Vector256<UInt16>* pClsVar2 = &_clsVar2)
{
var result = Avx2.Subtract(
Avx.LoadVector256((UInt16*)(pClsVar1)),
Avx.LoadVector256((UInt16*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr);
var result = Avx2.Subtract(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr));
var result = Avx2.Subtract(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr));
var result = Avx2.Subtract(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__SubtractUInt16();
var result = Avx2.Subtract(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__SubtractUInt16();
fixed (Vector256<UInt16>* pFld1 = &test._fld1)
fixed (Vector256<UInt16>* pFld2 = &test._fld2)
{
var result = Avx2.Subtract(
Avx.LoadVector256((UInt16*)(pFld1)),
Avx.LoadVector256((UInt16*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.Subtract(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<UInt16>* pFld1 = &_fld1)
fixed (Vector256<UInt16>* pFld2 = &_fld2)
{
var result = Avx2.Subtract(
Avx.LoadVector256((UInt16*)(pFld1)),
Avx.LoadVector256((UInt16*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.Subtract(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx2.Subtract(
Avx.LoadVector256((UInt16*)(&test._fld1)),
Avx.LoadVector256((UInt16*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<UInt16> op1, Vector256<UInt16> op2, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt16[] inArray2 = new UInt16[Op2ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt16[] inArray2 = new UInt16[Op2ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt16[] left, UInt16[] right, UInt16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((ushort)(left[0] - right[0]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((ushort)(left[i] - right[i]) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Subtract)}<UInt16>(Vector256<UInt16>, Vector256<UInt16>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="JournalTemplateService.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.JournalTemplate
{
public class JournalTemplateService : ServiceBase
{
public JournalTemplateService(ISession session)
: base(session)
{
}
public async Task<dynamic> AddTemplateAsync(long groupId, string templateId, bool autoTemplateId, string structureId, IDictionary<string, string> nameMap, IDictionary<string, string> descriptionMap, string xsl, bool formatXsl, string langType, bool cacheable, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("templateId", templateId);
_parameters.Add("autoTemplateId", autoTemplateId);
_parameters.Add("structureId", structureId);
_parameters.Add("nameMap", nameMap);
_parameters.Add("descriptionMap", descriptionMap);
_parameters.Add("xsl", xsl);
_parameters.Add("formatXsl", formatXsl);
_parameters.Add("langType", langType);
_parameters.Add("cacheable", cacheable);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/journaltemplate/add-template", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> AddTemplateAsync(long groupId, string templateId, bool autoTemplateId, string structureId, IDictionary<string, string> nameMap, IDictionary<string, string> descriptionMap, string xsl, bool formatXsl, string langType, bool cacheable, bool smallImage, string smallImageURL, Stream smallFile, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("templateId", templateId);
_parameters.Add("autoTemplateId", autoTemplateId);
_parameters.Add("structureId", structureId);
_parameters.Add("nameMap", nameMap);
_parameters.Add("descriptionMap", descriptionMap);
_parameters.Add("xsl", xsl);
_parameters.Add("formatXsl", formatXsl);
_parameters.Add("langType", langType);
_parameters.Add("cacheable", cacheable);
_parameters.Add("smallImage", smallImage);
_parameters.Add("smallImageURL", smallImageURL);
_parameters.Add("smallFile", smallFile);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/journaltemplate/add-template", _parameters }
};
var _obj = await this.Session.UploadAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> CopyTemplateAsync(long groupId, string oldTemplateId, string newTemplateId, bool autoTemplateId)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("oldTemplateId", oldTemplateId);
_parameters.Add("newTemplateId", newTemplateId);
_parameters.Add("autoTemplateId", autoTemplateId);
var _command = new JsonObject()
{
{ "/journaltemplate/copy-template", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task DeleteTemplateAsync(long groupId, string templateId)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("templateId", templateId);
var _command = new JsonObject()
{
{ "/journaltemplate/delete-template", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task<IEnumerable<dynamic>> GetStructureTemplatesAsync(long groupId, string structureId)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("structureId", structureId);
var _command = new JsonObject()
{
{ "/journaltemplate/get-structure-templates", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<dynamic> GetTemplateAsync(long groupId, string templateId)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("templateId", templateId);
var _command = new JsonObject()
{
{ "/journaltemplate/get-template", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> GetTemplateAsync(long groupId, string templateId, bool includeGlobalTemplates)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("templateId", templateId);
_parameters.Add("includeGlobalTemplates", includeGlobalTemplates);
var _command = new JsonObject()
{
{ "/journaltemplate/get-template", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<IEnumerable<dynamic>> SearchAsync(long companyId, IEnumerable<long> groupIds, string templateId, string structureId, string structureIdComparator, string name, string description, bool andOperator, int start, int end, JsonObjectWrapper obc)
{
var _parameters = new JsonObject();
_parameters.Add("companyId", companyId);
_parameters.Add("groupIds", groupIds);
_parameters.Add("templateId", templateId);
_parameters.Add("structureId", structureId);
_parameters.Add("structureIdComparator", structureIdComparator);
_parameters.Add("name", name);
_parameters.Add("description", description);
_parameters.Add("andOperator", andOperator);
_parameters.Add("start", start);
_parameters.Add("end", end);
this.MangleWrapper(_parameters, "obc", "com.liferay.portal.kernel.util.OrderByComparator", obc);
var _command = new JsonObject()
{
{ "/journaltemplate/search", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<IEnumerable<dynamic>> SearchAsync(long companyId, IEnumerable<long> groupIds, string keywords, string structureId, string structureIdComparator, int start, int end, JsonObjectWrapper obc)
{
var _parameters = new JsonObject();
_parameters.Add("companyId", companyId);
_parameters.Add("groupIds", groupIds);
_parameters.Add("keywords", keywords);
_parameters.Add("structureId", structureId);
_parameters.Add("structureIdComparator", structureIdComparator);
_parameters.Add("start", start);
_parameters.Add("end", end);
this.MangleWrapper(_parameters, "obc", "com.liferay.portal.kernel.util.OrderByComparator", obc);
var _command = new JsonObject()
{
{ "/journaltemplate/search", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<long> SearchCountAsync(long companyId, IEnumerable<long> groupIds, string keywords, string structureId, string structureIdComparator)
{
var _parameters = new JsonObject();
_parameters.Add("companyId", companyId);
_parameters.Add("groupIds", groupIds);
_parameters.Add("keywords", keywords);
_parameters.Add("structureId", structureId);
_parameters.Add("structureIdComparator", structureIdComparator);
var _command = new JsonObject()
{
{ "/journaltemplate/search-count", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (long)_obj;
}
public async Task<long> SearchCountAsync(long companyId, IEnumerable<long> groupIds, string templateId, string structureId, string structureIdComparator, string name, string description, bool andOperator)
{
var _parameters = new JsonObject();
_parameters.Add("companyId", companyId);
_parameters.Add("groupIds", groupIds);
_parameters.Add("templateId", templateId);
_parameters.Add("structureId", structureId);
_parameters.Add("structureIdComparator", structureIdComparator);
_parameters.Add("name", name);
_parameters.Add("description", description);
_parameters.Add("andOperator", andOperator);
var _command = new JsonObject()
{
{ "/journaltemplate/search-count", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (long)_obj;
}
public async Task<dynamic> UpdateTemplateAsync(long groupId, string templateId, string structureId, IDictionary<string, string> nameMap, IDictionary<string, string> descriptionMap, string xsl, bool formatXsl, string langType, bool cacheable, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("templateId", templateId);
_parameters.Add("structureId", structureId);
_parameters.Add("nameMap", nameMap);
_parameters.Add("descriptionMap", descriptionMap);
_parameters.Add("xsl", xsl);
_parameters.Add("formatXsl", formatXsl);
_parameters.Add("langType", langType);
_parameters.Add("cacheable", cacheable);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/journaltemplate/update-template", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> UpdateTemplateAsync(long groupId, string templateId, string structureId, IDictionary<string, string> nameMap, IDictionary<string, string> descriptionMap, string xsl, bool formatXsl, string langType, bool cacheable, bool smallImage, string smallImageURL, Stream smallFile, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("templateId", templateId);
_parameters.Add("structureId", structureId);
_parameters.Add("nameMap", nameMap);
_parameters.Add("descriptionMap", descriptionMap);
_parameters.Add("xsl", xsl);
_parameters.Add("formatXsl", formatXsl);
_parameters.Add("langType", langType);
_parameters.Add("cacheable", cacheable);
_parameters.Add("smallImage", smallImage);
_parameters.Add("smallImageURL", smallImageURL);
_parameters.Add("smallFile", smallFile);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/journaltemplate/update-template", _parameters }
};
var _obj = await this.Session.UploadAsync(_command);
return (dynamic)_obj;
}
}
}
| |
/*
* 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.Text;
using System.Xml;
using System.Collections.Generic;
using System.IO;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Server.Handlers.Base;
using log4net;
using OpenMetaverse;
namespace OpenSim.Server.Handlers.Asset
{
public class XInventoryInConnector : ServiceConnector
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IInventoryService m_InventoryService;
private string m_ConfigName = "InventoryService";
public XInventoryInConnector(IConfigSource config, IHttpServer server, string configName) :
base(config, server, configName)
{
if (configName != String.Empty)
m_ConfigName = configName;
m_log.DebugFormat("[XInventoryInConnector]: Starting with config name {0}", m_ConfigName);
IConfig serverConfig = config.Configs[m_ConfigName];
if (serverConfig == null)
throw new Exception(String.Format("No section '{0}' in config file", m_ConfigName));
string inventoryService = serverConfig.GetString("LocalServiceModule",
String.Empty);
if (inventoryService == String.Empty)
throw new Exception("No InventoryService in config file");
Object[] args = new Object[] { config };
m_InventoryService =
ServerUtils.LoadPlugin<IInventoryService>(inventoryService, args);
server.AddStreamHandler(new XInventoryConnectorPostHandler(m_InventoryService));
}
}
public class XInventoryConnectorPostHandler : BaseStreamHandler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IInventoryService m_InventoryService;
public XInventoryConnectorPostHandler(IInventoryService service) :
base("POST", "/xinventory")
{
m_InventoryService = service;
}
public override byte[] Handle(string path, Stream requestData,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
StreamReader sr = new StreamReader(requestData);
string body = sr.ReadToEnd();
sr.Close();
body = body.Trim();
//m_log.DebugFormat("[XXX]: query String: {0}", body);
try
{
Dictionary<string, object> request =
ServerUtils.ParseQueryString(body);
if (!request.ContainsKey("METHOD"))
return FailureResult();
string method = request["METHOD"].ToString();
request.Remove("METHOD");
switch (method)
{
case "CREATEUSERINVENTORY":
return HandleCreateUserInventory(request);
case "GETINVENTORYSKELETON":
return HandleGetInventorySkeleton(request);
case "GETROOTFOLDER":
return HandleGetRootFolder(request);
case "GETFOLDERFORTYPE":
return HandleGetFolderForType(request);
case "GETFOLDERCONTENT":
return HandleGetFolderContent(request);
case "GETFOLDERITEMS":
return HandleGetFolderItems(request);
case "ADDFOLDER":
return HandleAddFolder(request);
case "UPDATEFOLDER":
return HandleUpdateFolder(request);
case "MOVEFOLDER":
return HandleMoveFolder(request);
case "DELETEFOLDERS":
return HandleDeleteFolders(request);
case "PURGEFOLDER":
return HandlePurgeFolder(request);
case "ADDITEM":
return HandleAddItem(request);
case "UPDATEITEM":
return HandleUpdateItem(request);
case "MOVEITEMS":
return HandleMoveItems(request);
case "DELETEITEMS":
return HandleDeleteItems(request);
case "GETITEM":
return HandleGetItem(request);
case "GETFOLDER":
return HandleGetFolder(request);
case "GETACTIVEGESTURES":
return HandleGetActiveGestures(request);
case "GETASSETPERMISSIONS":
return HandleGetAssetPermissions(request);
}
m_log.DebugFormat("[XINVENTORY HANDLER]: unknown method request: {0}", method);
}
catch (Exception e)
{
m_log.Debug("[XINVENTORY HANDLER]: Exception {0}", e);
}
return FailureResult();
}
private byte[] FailureResult()
{
return BoolResult(false);
}
private byte[] SuccessResult()
{
return BoolResult(true);
}
private byte[] BoolResult(bool value)
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "RESULT", "");
result.AppendChild(doc.CreateTextNode(value.ToString()));
rootElement.AppendChild(result);
return DocToBytes(doc);
}
private byte[] DocToBytes(XmlDocument doc)
{
MemoryStream ms = new MemoryStream();
XmlTextWriter xw = new XmlTextWriter(ms, null);
xw.Formatting = Formatting.Indented;
doc.WriteTo(xw);
xw.Flush();
return ms.ToArray();
}
byte[] HandleCreateUserInventory(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
if (!request.ContainsKey("PRINCIPAL"))
return FailureResult();
if (m_InventoryService.CreateUserInventory(new UUID(request["PRINCIPAL"].ToString())))
result["RESULT"] = "True";
else
result["RESULT"] = "False";
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
byte[] HandleGetInventorySkeleton(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
if (!request.ContainsKey("PRINCIPAL"))
return FailureResult();
List<InventoryFolderBase> folders = m_InventoryService.GetInventorySkeleton(new UUID(request["PRINCIPAL"].ToString()));
Dictionary<string, object> sfolders = new Dictionary<string, object>();
if (folders != null)
{
int i = 0;
foreach (InventoryFolderBase f in folders)
{
sfolders["folder_" + i.ToString()] = EncodeFolder(f);
i++;
}
}
result["FOLDERS"] = sfolders;
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
byte[] HandleGetRootFolder(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
InventoryFolderBase rfolder = m_InventoryService.GetRootFolder(principal);
if (rfolder != null)
result["folder"] = EncodeFolder(rfolder);
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
byte[] HandleGetFolderForType(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
int type = 0;
Int32.TryParse(request["TYPE"].ToString(), out type);
InventoryFolderBase folder = m_InventoryService.GetFolderForType(principal, (AssetType)type);
if (folder != null)
result["folder"] = EncodeFolder(folder);
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
byte[] HandleGetFolderContent(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
UUID folderID = UUID.Zero;
UUID.TryParse(request["FOLDER"].ToString(), out folderID);
InventoryCollection icoll = m_InventoryService.GetFolderContent(principal, folderID);
if (icoll != null)
{
Dictionary<string, object> folders = new Dictionary<string, object>();
int i = 0;
foreach (InventoryFolderBase f in icoll.Folders)
{
folders["folder_" + i.ToString()] = EncodeFolder(f);
i++;
}
result["FOLDERS"] = folders;
i = 0;
Dictionary<string, object> items = new Dictionary<string, object>();
foreach (InventoryItemBase it in icoll.Items)
{
items["item_" + i.ToString()] = EncodeItem(it);
i++;
}
result["ITEMS"] = items;
}
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
byte[] HandleGetFolderItems(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
UUID folderID = UUID.Zero;
UUID.TryParse(request["FOLDER"].ToString(), out folderID);
List<InventoryItemBase> items = m_InventoryService.GetFolderItems(principal, folderID);
Dictionary<string, object> sitems = new Dictionary<string, object>();
if (items != null)
{
int i = 0;
foreach (InventoryItemBase item in items)
{
sitems["item_" + i.ToString()] = EncodeItem(item);
i++;
}
}
result["ITEMS"] = sitems;
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
byte[] HandleAddFolder(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
InventoryFolderBase folder = BuildFolder(request);
if (m_InventoryService.AddFolder(folder))
return SuccessResult();
else
return FailureResult();
}
byte[] HandleUpdateFolder(Dictionary<string,object> request)
{
Dictionary<string, object> result = new Dictionary<string, object>();
InventoryFolderBase folder = BuildFolder(request);
if (m_InventoryService.UpdateFolder(folder))
return SuccessResult();
else
return FailureResult();
}
byte[] HandleMoveFolder(Dictionary<string,object> request)
{
Dictionary<string, object> result = new Dictionary<string, object>();
UUID parentID = UUID.Zero;
UUID.TryParse(request["ParentID"].ToString(), out parentID);
UUID folderID = UUID.Zero;
UUID.TryParse(request["ID"].ToString(), out folderID);
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
InventoryFolderBase folder = new InventoryFolderBase(folderID, "", principal, parentID);
if (m_InventoryService.MoveFolder(folder))
return SuccessResult();
else
return FailureResult();
}
byte[] HandleDeleteFolders(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
List<string> slist = (List<string>)request["FOLDERS"];
List<UUID> uuids = new List<UUID>();
foreach (string s in slist)
{
UUID u = UUID.Zero;
if (UUID.TryParse(s, out u))
uuids.Add(u);
}
if (m_InventoryService.DeleteFolders(principal, uuids))
return SuccessResult();
else
return
FailureResult();
}
byte[] HandlePurgeFolder(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
UUID folderID = UUID.Zero;
UUID.TryParse(request["ID"].ToString(), out folderID);
InventoryFolderBase folder = new InventoryFolderBase(folderID);
if (m_InventoryService.PurgeFolder(folder))
return SuccessResult();
else
return FailureResult();
}
byte[] HandleAddItem(Dictionary<string,object> request)
{
Dictionary<string, object> result = new Dictionary<string, object>();
InventoryItemBase item = BuildItem(request);
if (m_InventoryService.AddItem(item))
return SuccessResult();
else
return FailureResult();
}
byte[] HandleUpdateItem(Dictionary<string,object> request)
{
Dictionary<string, object> result = new Dictionary<string, object>();
InventoryItemBase item = BuildItem(request);
if (m_InventoryService.UpdateItem(item))
return SuccessResult();
else
return FailureResult();
}
byte[] HandleMoveItems(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
List<string> idlist = (List<string>)request["IDLIST"];
List<string> destlist = (List<string>)request["DESTLIST"];
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
List<InventoryItemBase> items = new List<InventoryItemBase>();
int n = 0;
try
{
foreach (string s in idlist)
{
UUID u = UUID.Zero;
if (UUID.TryParse(s, out u))
{
UUID fid = UUID.Zero;
if (UUID.TryParse(destlist[n++], out fid))
{
InventoryItemBase item = new InventoryItemBase(u, principal);
item.Folder = fid;
items.Add(item);
}
}
}
}
catch (Exception e)
{
m_log.DebugFormat("[XINVENTORY IN CONNECTOR]: Exception in HandleMoveItems: {0}", e.Message);
return FailureResult();
}
if (m_InventoryService.MoveItems(principal, items))
return SuccessResult();
else
return FailureResult();
}
byte[] HandleDeleteItems(Dictionary<string,object> request)
{
Dictionary<string, object> result = new Dictionary<string, object>();
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
List<string> slist = (List<string>)request["ITEMS"];
List<UUID> uuids = new List<UUID>();
foreach (string s in slist)
{
UUID u = UUID.Zero;
if (UUID.TryParse(s, out u))
uuids.Add(u);
}
if (m_InventoryService.DeleteItems(principal, uuids))
return SuccessResult();
else
return
FailureResult();
}
byte[] HandleGetItem(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
UUID id = UUID.Zero;
UUID.TryParse(request["ID"].ToString(), out id);
InventoryItemBase item = new InventoryItemBase(id);
item = m_InventoryService.GetItem(item);
if (item != null)
result["item"] = EncodeItem(item);
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
byte[] HandleGetFolder(Dictionary<string,object> request)
{
Dictionary<string, object> result = new Dictionary<string, object>();
UUID id = UUID.Zero;
UUID.TryParse(request["ID"].ToString(), out id);
InventoryFolderBase folder = new InventoryFolderBase(id);
folder = m_InventoryService.GetFolder(folder);
if (folder != null)
result["folder"] = EncodeFolder(folder);
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
byte[] HandleGetActiveGestures(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
List<InventoryItemBase> gestures = m_InventoryService.GetActiveGestures(principal);
Dictionary<string, object> items = new Dictionary<string, object>();
if (gestures != null)
{
int i = 0;
foreach (InventoryItemBase item in gestures)
{
items["item_" + i.ToString()] = EncodeItem(item);
i++;
}
}
result["ITEMS"] = items;
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
byte[] HandleGetAssetPermissions(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
UUID assetID = UUID.Zero;
UUID.TryParse(request["ASSET"].ToString(), out assetID);
int perms = m_InventoryService.GetAssetPermissions(principal, assetID);
result["RESULT"] = perms.ToString();
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
private Dictionary<string, object> EncodeFolder(InventoryFolderBase f)
{
Dictionary<string, object> ret = new Dictionary<string, object>();
ret["ParentID"] = f.ParentID.ToString();
ret["Type"] = f.Type.ToString();
ret["Version"] = f.Version.ToString();
ret["Name"] = f.Name;
ret["Owner"] = f.Owner.ToString();
ret["ID"] = f.ID.ToString();
return ret;
}
private Dictionary<string, object> EncodeItem(InventoryItemBase item)
{
Dictionary<string, object> ret = new Dictionary<string, object>();
ret["AssetID"] = item.AssetID.ToString();
ret["AssetType"] = item.AssetType.ToString();
ret["BasePermissions"] = item.BasePermissions.ToString();
ret["CreationDate"] = item.CreationDate.ToString();
ret["CreatorId"] = item.CreatorId.ToString();
ret["CurrentPermissions"] = item.CurrentPermissions.ToString();
ret["Description"] = item.Description.ToString();
ret["EveryOnePermissions"] = item.EveryOnePermissions.ToString();
ret["Flags"] = item.Flags.ToString();
ret["Folder"] = item.Folder.ToString();
ret["GroupID"] = item.GroupID.ToString();
ret["GroupOwned"] = item.GroupOwned.ToString();
ret["GroupPermissions"] = item.GroupPermissions.ToString();
ret["ID"] = item.ID.ToString();
ret["InvType"] = item.InvType.ToString();
ret["Name"] = item.Name.ToString();
ret["NextPermissions"] = item.NextPermissions.ToString();
ret["Owner"] = item.Owner.ToString();
ret["SalePrice"] = item.SalePrice.ToString();
ret["SaleType"] = item.SaleType.ToString();
return ret;
}
private InventoryFolderBase BuildFolder(Dictionary<string,object> data)
{
InventoryFolderBase folder = new InventoryFolderBase();
folder.ParentID = new UUID(data["ParentID"].ToString());
folder.Type = short.Parse(data["Type"].ToString());
folder.Version = ushort.Parse(data["Version"].ToString());
folder.Name = data["Name"].ToString();
folder.Owner = new UUID(data["Owner"].ToString());
folder.ID = new UUID(data["ID"].ToString());
return folder;
}
private InventoryItemBase BuildItem(Dictionary<string,object> data)
{
InventoryItemBase item = new InventoryItemBase();
item.AssetID = new UUID(data["AssetID"].ToString());
item.AssetType = int.Parse(data["AssetType"].ToString());
item.Name = data["Name"].ToString();
item.Owner = new UUID(data["Owner"].ToString());
item.ID = new UUID(data["ID"].ToString());
item.InvType = int.Parse(data["InvType"].ToString());
item.Folder = new UUID(data["Folder"].ToString());
item.CreatorId = data["CreatorId"].ToString();
item.Description = data["Description"].ToString();
item.NextPermissions = uint.Parse(data["NextPermissions"].ToString());
item.CurrentPermissions = uint.Parse(data["CurrentPermissions"].ToString());
item.BasePermissions = uint.Parse(data["BasePermissions"].ToString());
item.EveryOnePermissions = uint.Parse(data["EveryOnePermissions"].ToString());
item.GroupPermissions = uint.Parse(data["GroupPermissions"].ToString());
item.GroupID = new UUID(data["GroupID"].ToString());
item.GroupOwned = bool.Parse(data["GroupOwned"].ToString());
item.SalePrice = int.Parse(data["SalePrice"].ToString());
item.SaleType = byte.Parse(data["SaleType"].ToString());
item.Flags = uint.Parse(data["Flags"].ToString());
item.CreationDate = int.Parse(data["CreationDate"].ToString());
return item;
}
}
}
| |
#region License
//
// Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.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
using System;
using System.Collections.Generic;
using System.Reflection;
using FluentMigrator.Expressions;
using FluentMigrator.Infrastructure;
using FluentMigrator.Runner;
using FluentMigrator.Runner.Initialization;
using FluentMigrator.Runner.Processors;
using FluentMigrator.Tests.Integration.Migrations;
using Moq;
using NUnit.Framework;
using NUnit.Should;
namespace FluentMigrator.Tests.Unit
{
[TestFixture]
public class MigrationRunnerTests
{
private MigrationRunner _runner;
private Mock<IAnnouncer> _announcer;
private Mock<IStopWatch> _stopWatch;
private Mock<IMigrationProcessor> _processorMock;
private Mock<IMigrationLoader> _migrationLoaderMock;
private Mock<IProfileLoader> _profileLoaderMock;
private Mock<IRunnerContext> _runnerContextMock;
private SortedList<long, IMigration> _migrationList;
private TestVersionLoader _fakeVersionLoader;
private int _applicationContext;
[SetUp]
public void SetUp()
{
_applicationContext = new Random().Next();
_migrationList = new SortedList<long, IMigration>();
_runnerContextMock = new Mock<IRunnerContext>(MockBehavior.Loose);
_processorMock = new Mock<IMigrationProcessor>(MockBehavior.Loose);
_migrationLoaderMock = new Mock<IMigrationLoader>(MockBehavior.Loose);
_profileLoaderMock = new Mock<IProfileLoader>(MockBehavior.Loose);
_announcer = new Mock<IAnnouncer>();
_stopWatch = new Mock<IStopWatch>();
var options = new ProcessorOptions
{
PreviewOnly = false
};
_processorMock.SetupGet(x => x.Options).Returns(options);
_runnerContextMock.SetupGet(x => x.Namespace).Returns("FluentMigrator.Tests.Integration.Migrations");
_runnerContextMock.SetupGet(x => x.Announcer).Returns(_announcer.Object);
_runnerContextMock.SetupGet(x => x.StopWatch).Returns(_stopWatch.Object);
_runnerContextMock.SetupGet(x => x.Target).Returns(Assembly.GetExecutingAssembly().ToString());
_runnerContextMock.SetupGet(x => x.Connection).Returns(IntegrationTestOptions.SqlServer2008.ConnectionString);
_runnerContextMock.SetupGet(x => x.Database).Returns("sqlserver");
_runnerContextMock.SetupGet(x => x.ApplicationContext).Returns(_applicationContext);
_migrationLoaderMock.SetupGet(x => x.Migrations).Returns(_migrationList);
_runner = new MigrationRunner(Assembly.GetAssembly(typeof(MigrationRunnerTests)), _runnerContextMock.Object, _processorMock.Object)
{
MigrationLoader = _migrationLoaderMock.Object,
ProfileLoader = _profileLoaderMock.Object,
};
_fakeVersionLoader = new TestVersionLoader(_runner, _runner.VersionLoader.VersionTableMetaData);
_runner.VersionLoader = _fakeVersionLoader;
_processorMock.Setup(x => x.SchemaExists(It.Is<string>(s => s == _runner.VersionLoader.VersionTableMetaData.SchemaName)))
.Returns(true);
_processorMock.Setup(x => x.TableExists(It.Is<string>(s => s == _runner.VersionLoader.VersionTableMetaData.SchemaName),
It.Is<string>(t => t == _runner.VersionLoader.VersionTableMetaData.TableName)))
.Returns(true);
}
private void LoadVersionData(params long[] fakeVersions)
{
_fakeVersionLoader.Versions.Clear();
_runner.MigrationLoader.Migrations.Clear();
foreach (var version in fakeVersions)
{
_fakeVersionLoader.Versions.Add(version);
_runner.MigrationLoader.Migrations.Add(version, new TestMigration());
}
_fakeVersionLoader.LoadVersionInfo();
}
/// <summary>Unit test which ensures that the application context is correctly propagated down to each migration class.</summary>
[Test(Description = "Ensure that the application context is correctly propagated down to each migration class.")]
public void CanPassApplicationContext()
{
IMigration migration = new TestEmptyMigration();
_runner.Up(migration);
Assert.AreEqual(_applicationContext, _runnerContextMock.Object.ApplicationContext, "The runner context does not have the expected application context.");
Assert.AreEqual(_applicationContext, _runner.ApplicationContext, "The MigrationRunner does not have the expected application context.");
Assert.AreEqual(_applicationContext, migration.ApplicationContext, "The migration does not have the expected application context.");
_announcer.VerifyAll();
}
[Test]
public void CanAnnounceUp()
{
_announcer.Setup(x => x.Heading(It.IsRegex(containsAll("Test", "migrating"))));
_runner.Up(new TestMigration());
_announcer.VerifyAll();
}
[Test]
public void CanAnnounceUpFinish()
{
_announcer.Setup(x => x.Say(It.IsRegex(containsAll("Test", "migrated"))));
_runner.Up(new TestMigration());
_announcer.VerifyAll();
}
[Test]
public void CanAnnounceDown()
{
_announcer.Setup(x => x.Heading(It.IsRegex(containsAll("Test", "reverting"))));
_runner.Down(new TestMigration());
_announcer.VerifyAll();
}
[Test]
public void CanAnnounceDownFinish()
{
_announcer.Setup(x => x.Say(It.IsRegex(containsAll("Test", "reverted"))));
_runner.Down(new TestMigration());
_announcer.VerifyAll();
}
[Test]
public void CanAnnounceUpElapsedTime()
{
var ts = new TimeSpan(0, 0, 0, 1, 3);
_announcer.Setup(x => x.ElapsedTime(It.Is<TimeSpan>(y => y == ts)));
_stopWatch.Setup(x => x.ElapsedTime()).Returns(ts);
_runner.Up(new TestMigration());
_announcer.VerifyAll();
}
[Test]
public void CanAnnounceDownElapsedTime()
{
var ts = new TimeSpan(0, 0, 0, 1, 3);
_announcer.Setup(x => x.ElapsedTime(It.Is<TimeSpan>(y => y == ts)));
_stopWatch.Setup(x => x.ElapsedTime()).Returns(ts);
_runner.Down(new TestMigration());
_announcer.VerifyAll();
}
[Test]
public void CanReportExceptions()
{
_processorMock.Setup(x => x.Process(It.IsAny<CreateTableExpression>())).Throws(new Exception("Oops"));
_announcer.Setup(x => x.Error(It.IsRegex(containsAll("Oops"))));
try
{
_runner.Up(new TestMigration());
}
catch (Exception)
{
}
_announcer.VerifyAll();
}
[Test]
public void CanSayExpression()
{
_announcer.Setup(x => x.Say(It.IsRegex(containsAll("CreateTable"))));
_stopWatch.Setup(x => x.ElapsedTime()).Returns(new TimeSpan(0, 0, 0, 1, 3));
_runner.Up(new TestMigration());
_announcer.VerifyAll();
}
[Test]
public void CanTimeExpression()
{
var ts = new TimeSpan(0, 0, 0, 1, 3);
_announcer.Setup(x => x.ElapsedTime(It.Is<TimeSpan>(y => y == ts)));
_stopWatch.Setup(x => x.ElapsedTime()).Returns(ts);
_runner.Up(new TestMigration());
_announcer.VerifyAll();
}
private string containsAll(params string[] words)
{
return ".*?" + string.Join(".*?", words) + ".*?";
}
[Test]
public void LoadsCorrectCallingAssembly()
{
_runner.MigrationAssembly.ShouldBe(Assembly.GetAssembly(typeof(MigrationRunnerTests)));
}
[Test]
public void RollbackOnlyOneStepsOfTwoShouldNotDeleteVersionInfoTable()
{
long fakeMigrationVersion = 2009010101;
long fakeMigrationVersion2 = 2009010102;
var versionInfoTableName = _runner.VersionLoader.VersionTableMetaData.TableName;
LoadVersionData(fakeMigrationVersion, fakeMigrationVersion2);
_runner.VersionLoader.LoadVersionInfo();
_runner.Rollback(1);
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse();
}
[Test]
public void RollbackLastVersionShouldDeleteVersionInfoTable()
{
long fakeMigrationVersion = 2009010101;
LoadVersionData(fakeMigrationVersion);
var versionInfoTableName = _runner.VersionLoader.VersionTableMetaData.TableName;
_runner.Rollback(1);
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeTrue();
}
[Test]
public void RollbackToVersionZeroShouldDeleteVersionInfoTable()
{
var versionInfoTableName = _runner.VersionLoader.VersionTableMetaData.TableName;
_runner.RollbackToVersion(0);
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeTrue();
}
[Test]
public void RollbackToVersionZeroShouldNotCreateVersionInfoTableAfterRemoval()
{
var versionInfoTableName = _runner.VersionLoader.VersionTableMetaData.TableName;
_runner.RollbackToVersion(0);
//Should only be called once in setup
_processorMock.Verify(
pm => pm.Process(It.Is<CreateTableExpression>(
dte => dte.TableName == versionInfoTableName)
),
Times.Once()
);
}
[Test]
public void RollbackToVersionShouldShouldLimitMigrationsToNamespace()
{
const long fakeMigration1 = 2011010101;
const long fakeMigration2 = 2011010102;
const long fakeMigration3 = 2011010103;
LoadVersionData(fakeMigration1,fakeMigration3);
_fakeVersionLoader.Versions.Add(fakeMigration2);
_fakeVersionLoader.LoadVersionInfo();
_runner.RollbackToVersion(2011010101);
_fakeVersionLoader.Versions.ShouldContain(fakeMigration1);
_fakeVersionLoader.Versions.ShouldContain(fakeMigration2);
_fakeVersionLoader.Versions.ShouldNotContain(fakeMigration3);
}
[Test]
public void RollbackToVersionZeroShouldShouldLimitMigrationsToNamespace()
{
const long fakeMigration1 = 2011010101;
const long fakeMigration2 = 2011010102;
const long fakeMigration3 = 2011010103;
LoadVersionData(fakeMigration1, fakeMigration2, fakeMigration3);
_runner.MigrationLoader.Migrations.Remove(fakeMigration1);
_runner.MigrationLoader.Migrations.Remove(fakeMigration2);
_fakeVersionLoader.LoadVersionInfo();
_runner.RollbackToVersion(0);
_fakeVersionLoader.Versions.ShouldContain(fakeMigration1);
_fakeVersionLoader.Versions.ShouldContain(fakeMigration2);
_fakeVersionLoader.Versions.ShouldNotContain(fakeMigration3);
}
[Test]
public void RollbackShouldLimitMigrationsToNamespace()
{
const long fakeMigration1 = 2011010101;
const long fakeMigration2 = 2011010102;
const long fakeMigration3 = 2011010103;
LoadVersionData(fakeMigration1, fakeMigration3);
_fakeVersionLoader.Versions.Add(fakeMigration2);
_fakeVersionLoader.LoadVersionInfo();
_runner.Rollback(2);
_fakeVersionLoader.Versions.ShouldNotContain(fakeMigration1);
_fakeVersionLoader.Versions.ShouldContain(fakeMigration2);
_fakeVersionLoader.Versions.ShouldNotContain(fakeMigration3);
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse();
}
[Test]
public void RollbackToVersionShouldLoadVersionInfoIfVersionGreaterThanZero()
{
var versionInfoTableName = _runner.VersionLoader.VersionTableMetaData.TableName;
_runner.RollbackToVersion(1);
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse();
//Once in setup
_processorMock.Verify(
pm => pm.Process(It.Is<CreateTableExpression>(
dte => dte.TableName == versionInfoTableName)
),
Times.Exactly(1)
);
//After setup is done, fake version loader owns the proccess
_fakeVersionLoader.DidLoadVersionInfoGetCalled.ShouldBe(true);
}
[Test, Ignore("Move to MigrationLoader tests")]
public void HandlesNullMigrationList()
{
//set migrations to return empty list
// var asm = Assembly.GetAssembly(typeof(MigrationVersionRunnerUnitTests));
// _migrationLoaderMock.Setup(x => x.FindMigrations(asm, null)).Returns<IEnumerable<Migration>>(null);
//
// _runner.Migrations.Count.ShouldBe(0);
//
// _vrunner.MigrateUp();
//
// _migrationLoaderMock.VerifyAll();
}
[Test, ExpectedException(typeof(Exception))]
[Ignore("Move to migrationloader tests")]
public void ShouldThrowExceptionIfDuplicateVersionNumbersAreLoaded()
{
// _migrationLoaderMock.Setup(x => x.FindMigrationsIn(It.IsAny<Assembly>(), null)).Returns(new List<MigrationMetadata>
// {
// new MigrationMetadata {Version = 1, Type = typeof(UserToRole)},
// new MigrationMetadata {Version = 2, Type = typeof(FluentMigrator.Tests.Integration.Migrations.Interleaved.Pass2.UserToRole)},
// new MigrationMetadata {Version = 2, Type = typeof(FluentMigrator.Tests.Integration.Migrations.Interleaved.Pass2.UserToRole)}
// });
//
// _vrunner.MigrateUp();
}
[Test]
[Ignore("Move to migrationloader tests")]
public void HandlesMigrationThatDoesNotInheritFromMigrationBaseClass()
{
// _migrationLoaderMock.Setup(x => x.FindMigrationsIn(It.IsAny<Assembly>(), null)).Returns(new List<MigrationMetadata>
// {
// new MigrationMetadata {Version = 1, Type = typeof(MigrationThatDoesNotInheritFromMigrationBaseClass)},
// });
//
// _vrunner.Migrations[1].ShouldNotBeNull();
// _vrunner.Migrations[1].ShouldBeOfType<MigrationThatDoesNotInheritFromMigrationBaseClass>();
}
private class MigrationThatDoesNotInheritFromMigrationBaseClass : IMigration
{
/// <summary>The arbitrary application context passed to the task runner.</summary>
public object ApplicationContext
{
get { throw new NotImplementedException(); }
}
public void GetUpExpressions(IMigrationContext context)
{
throw new NotImplementedException();
}
public void GetDownExpressions(IMigrationContext context)
{
throw new NotImplementedException();
}
}
}
}
| |
using System;
using System.Data;
using Csla;
using Csla.Data;
using ParentLoadSoftDelete.DataAccess;
using ParentLoadSoftDelete.DataAccess.ERLevel;
namespace ParentLoadSoftDelete.Business.ERLevel
{
/// <summary>
/// E09_Region_ReChild (editable child object).<br/>
/// This is a generated base class of <see cref="E09_Region_ReChild"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="E08_Region"/> collection.
/// </remarks>
[Serializable]
public partial class E09_Region_ReChild : BusinessBase<E09_Region_ReChild>
{
#region State Fields
[NotUndoable]
[NonSerialized]
internal int region_ID2 = 0;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Region_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Region_Child_NameProperty = RegisterProperty<string>(p => p.Region_Child_Name, "Cities Child Name");
/// <summary>
/// Gets or sets the Cities Child Name.
/// </summary>
/// <value>The Cities Child Name.</value>
public string Region_Child_Name
{
get { return GetProperty(Region_Child_NameProperty); }
set { SetProperty(Region_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="E09_Region_ReChild"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="E09_Region_ReChild"/> object.</returns>
internal static E09_Region_ReChild NewE09_Region_ReChild()
{
return DataPortal.CreateChild<E09_Region_ReChild>();
}
/// <summary>
/// Factory method. Loads a <see cref="E09_Region_ReChild"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="E09_Region_ReChild"/> object.</returns>
internal static E09_Region_ReChild GetE09_Region_ReChild(SafeDataReader dr)
{
E09_Region_ReChild obj = new E09_Region_ReChild();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.MarkOld();
// check all object rules and property rules
obj.BusinessRules.CheckRules();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="E09_Region_ReChild"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public E09_Region_ReChild()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="E09_Region_ReChild"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="E09_Region_ReChild"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Region_Child_NameProperty, dr.GetString("Region_Child_Name"));
// parent properties
region_ID2 = dr.GetInt32("Region_ID2");
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="E09_Region_ReChild"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(E08_Region parent)
{
using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnInsertPre(args);
var dal = dalManager.GetProvider<IE09_Region_ReChildDal>();
using (BypassPropertyChecks)
{
dal.Insert(
parent.Region_ID,
Region_Child_Name
);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="E09_Region_ReChild"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(E08_Region parent)
{
if (!IsDirty)
return;
using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnUpdatePre(args);
var dal = dalManager.GetProvider<IE09_Region_ReChildDal>();
using (BypassPropertyChecks)
{
dal.Update(
parent.Region_ID,
Region_Child_Name
);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="E09_Region_ReChild"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(E08_Region parent)
{
using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<IE09_Region_ReChildDal>();
using (BypassPropertyChecks)
{
dal.Delete(parent.Region_ID);
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
using System;
using System.Diagnostics.Contracts;
namespace System.Security.Cryptography {
/// <summary>
/// Utility class to strongly type algorithms used with CNG. Since all CNG APIs which require an
/// algorithm name take the name as a string, we use this string wrapper class to specifically mark
/// which parameters are expected to be algorithms. We also provide a list of well known algorithm
/// names, which helps Intellisense users find a set of good algorithm names to use.
/// </summary>
[Serializable]
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public sealed class CngAlgorithm : IEquatable<CngAlgorithm> {
private static volatile CngAlgorithm s_ecdhp256;
private static volatile CngAlgorithm s_ecdhp384;
private static volatile CngAlgorithm s_ecdhp521;
private static volatile CngAlgorithm s_ecdsap256;
private static volatile CngAlgorithm s_ecdsap384;
private static volatile CngAlgorithm s_ecdsap521;
private static volatile CngAlgorithm s_md5;
private static volatile CngAlgorithm s_sha1;
private static volatile CngAlgorithm s_sha256;
private static volatile CngAlgorithm s_sha384;
private static volatile CngAlgorithm s_sha512;
private string m_algorithm;
public CngAlgorithm(string algorithm) {
Contract.Ensures(!String.IsNullOrEmpty(m_algorithm));
if (algorithm == null) {
throw new ArgumentNullException("algorithm");
}
if (algorithm.Length == 0) {
throw new ArgumentException(SR.GetString(SR.Cryptography_InvalidAlgorithmName, algorithm), "algorithm");
}
m_algorithm = algorithm;
}
/// <summary>
/// Name of the algorithm
/// </summary>
public string Algorithm {
get {
Contract.Ensures(!String.IsNullOrEmpty(Contract.Result<string>()));
return m_algorithm;
}
}
public static bool operator==(CngAlgorithm left, CngAlgorithm right) {
if (Object.ReferenceEquals(left, null)) {
return Object.ReferenceEquals(right, null);
}
return left.Equals(right);
}
[Pure]
public static bool operator !=(CngAlgorithm left, CngAlgorithm right) {
if (Object.ReferenceEquals(left, null)) {
return !Object.ReferenceEquals(right, null);
}
return !left.Equals(right);
}
public override bool Equals(object obj) {
Contract.Assert(m_algorithm != null);
return Equals(obj as CngAlgorithm);
}
public bool Equals(CngAlgorithm other) {
if (Object.ReferenceEquals(other, null)) {
return false;
}
return m_algorithm.Equals(other.Algorithm);
}
public override int GetHashCode() {
Contract.Assert(m_algorithm != null);
return m_algorithm.GetHashCode();
}
public override string ToString() {
Contract.Assert(m_algorithm != null);
return m_algorithm;
}
//
// Well known algorithms
//
public static CngAlgorithm ECDiffieHellmanP256 {
get {
Contract.Ensures(Contract.Result<CngAlgorithm>() != null);
if (s_ecdhp256 == null) {
s_ecdhp256 = new CngAlgorithm(BCryptNative.AlgorithmName.ECDHP256);
}
return s_ecdhp256;
}
}
public static CngAlgorithm ECDiffieHellmanP384 {
get {
Contract.Ensures(Contract.Result<CngAlgorithm>() != null);
if (s_ecdhp384 == null) {
s_ecdhp384 = new CngAlgorithm(BCryptNative.AlgorithmName.ECDHP384);
}
return s_ecdhp384;
}
}
public static CngAlgorithm ECDiffieHellmanP521 {
get {
Contract.Ensures(Contract.Result<CngAlgorithm>() != null);
if (s_ecdhp521 == null) {
s_ecdhp521 = new CngAlgorithm(BCryptNative.AlgorithmName.ECDHP521);
}
return s_ecdhp521;
}
}
public static CngAlgorithm ECDsaP256 {
get {
Contract.Ensures(Contract.Result<CngAlgorithm>() != null);
if (s_ecdsap256 == null) {
s_ecdsap256 = new CngAlgorithm(BCryptNative.AlgorithmName.ECDsaP256);
}
return s_ecdsap256;
}
}
public static CngAlgorithm ECDsaP384 {
get {
Contract.Ensures(Contract.Result<CngAlgorithm>() != null);
if (s_ecdsap384 == null) {
s_ecdsap384 = new CngAlgorithm(BCryptNative.AlgorithmName.ECDsaP384);
}
return s_ecdsap384;
}
}
public static CngAlgorithm ECDsaP521 {
get {
Contract.Ensures(Contract.Result<CngAlgorithm>() != null);
if (s_ecdsap521 == null) {
s_ecdsap521 = new CngAlgorithm(BCryptNative.AlgorithmName.ECDsaP521);
}
return s_ecdsap521;
}
}
public static CngAlgorithm MD5 {
get {
Contract.Ensures(Contract.Result<CngAlgorithm>() != null);
if (s_md5 == null) {
s_md5 = new CngAlgorithm(BCryptNative.AlgorithmName.MD5);
}
return s_md5;
}
}
public static CngAlgorithm Sha1 {
get {
Contract.Ensures(Contract.Result<CngAlgorithm>() != null);
if (s_sha1 == null) {
s_sha1 = new CngAlgorithm(BCryptNative.AlgorithmName.Sha1);
}
return s_sha1;
}
}
public static CngAlgorithm Sha256 {
get {
Contract.Ensures(Contract.Result<CngAlgorithm>() != null);
if (s_sha256 == null) {
s_sha256 = new CngAlgorithm(BCryptNative.AlgorithmName.Sha256);
}
return s_sha256;
}
}
public static CngAlgorithm Sha384 {
get {
Contract.Ensures(Contract.Result<CngAlgorithm>() != null);
if (s_sha384 == null) {
s_sha384 = new CngAlgorithm(BCryptNative.AlgorithmName.Sha384);
}
return s_sha384;
}
}
public static CngAlgorithm Sha512 {
get {
Contract.Ensures(Contract.Result<CngAlgorithm>() != null);
if (s_sha512 == null) {
s_sha512 = new CngAlgorithm(BCryptNative.AlgorithmName.Sha512);
}
return s_sha512;
}
}
}
}
| |
using System;
using System.IO;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
public class SceneValidator
{
private const string MasterPathStopper = "#";
private static string GetGameObjectPath(GameObject gameObject)
{
if (gameObject == null)
return null;
string fullName = "";
while(gameObject != null)
{
fullName = gameObject.name + ((fullName.Length > 0) ? "." : "") + fullName;
gameObject = (gameObject.transform.parent == null) ? null : gameObject.transform.parent.gameObject;
}
return fullName;
}
private static System.Type GetCollectionValueType(System.Type type)
{
if (type == null)
return null;
var genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 0)
return null;
return genericArguments[0];
}
private static System.Type GetBindingValueType(string path, System.Type type, GameObject gameObject, bool command, ref string tail)
{
tail = string.Empty;
if (string.IsNullOrEmpty(path))
{
Debug.Log("Binding is empty for object " + GetGameObjectPath(gameObject), gameObject);
return null;
}
var parts = path.Split('.');
var pathMessage = "";
for (var i = 0; i < parts.Length; ++i)
{
var part = parts[i];
pathMessage += part;
if (i < parts.Length - 1)
{
int index;
if (int.TryParse(part, out index))
{
for (var j = i + 1; j < parts.Length; ++j)
tail += parts[j] + ".";
if (tail.Length > 0)
tail = tail.Substring(0, tail.Length - 1);
return type;
}
else
{
var nodeProperty = type.GetProperty(part);
if (nodeProperty == null)
{
Debug.LogError("Failed to resolve node in binding " + path + " in object " + GetGameObjectPath(gameObject) +
"\n[context type is " + type + "], error at " + pathMessage, gameObject);
return null;
}
pathMessage += ".";
type = nodeProperty.PropertyType;
}
}
else
{
if (command)
{
var leafCommand = type.GetMethod(part);
if (leafCommand == null)
{
Debug.LogError("Failed to resolve leaf command in binding " + path + " in object " + GetGameObjectPath(gameObject) +
"\n[context type is " + type + "], error at " + pathMessage, gameObject);
return null;
}
}
else
{
var leafProperty = type.GetProperty(part);
if (leafProperty == null)
{
Debug.LogError("Failed to resolve leaf property in binding " + path + " in object " + GetGameObjectPath(gameObject) +
"\n[context type is " + type + "], error at " + pathMessage, gameObject);
return null;
}
type = leafProperty.PropertyType;
}
}
}
return type;
}
private static System.Type GetBindingValueType(string path, System.Type type, GameObject gameObject, bool command)
{
var tail = path;
while(tail.Length > 0)
{
type = GetBindingValueType(tail, type, gameObject, command, ref tail);
if (tail.Length == 0)
break;
type = GetCollectionValueType(type);
}
return type;
}
private static System.Type GetCleanType(Stack<System.Type> type, int depth)
{
var array = type.ToArray();
if (array.Length == 0)
return null;
if (depth >= array.Length)
depth = array.Length - 1;
return array[depth];
}
private static string GetFullCleanPath(Stack<string> masterPaths, string path, int depthToGo)
{
var masterPath = string.Empty;
foreach(var p in masterPaths)
{
if (string.IsNullOrEmpty(p))
continue;
if (p == MasterPathStopper)
{
if (depthToGo == 0)
break;
depthToGo--;
continue;
}
if (string.IsNullOrEmpty(masterPath))
masterPath = p;
else
masterPath = p + "." + masterPath;
}
return string.IsNullOrEmpty(masterPath) ?
path : (masterPath + "." + NguiUtils.GetCleanPath(path));
}
private static void ValidateRootObjectBindings(GameObject gameObject, Stack<System.Type> type, Stack<GameObject> templatesPath, Stack<string> masterPaths)
{
if (gameObject == null || type.Count == 0 || type.Peek() == null)
return;
if (gameObject.GetComponents<NguiMasterPath>().Length > 1)
Debug.LogWarning("More than one NguiMasterPath detected in object " + GetGameObjectPath(gameObject), gameObject);
var masterPath = gameObject.GetComponent<NguiMasterPath>();
masterPaths.Push(masterPath == null ? string.Empty : masterPath.MasterPath);
var childrenValidated = false;
foreach(var c in gameObject.GetComponents<NguiBaseBinding>())
{
if (!c.enabled)
{
Debug.LogWarning("Binding in object " + GetGameObjectPath(gameObject) + " is disabled", gameObject);
}
var paths = c.ReferencedPaths;
var types = new List<System.Type>();
foreach(var p in paths)
{
var cleanPath = GetFullCleanPath(masterPaths, NguiUtils.GetCleanPath(p), NguiUtils.GetPathDepth(p));
var cleanType = GetCleanType(type, NguiUtils.GetPathDepth(p));
types.Add(GetBindingValueType(cleanPath, cleanType, gameObject, c is NguiCommandBinding));
}
var templates = c.gameObject.GetComponents<NguiListItemTemplate>();
if (templates.Length == 0 &&
types.Count > 0 &&
c is NguiItemsSourceBinding)
{
type.Push(GetCollectionValueType(types[0]));
masterPaths.Push(MasterPathStopper);
for (var i = 0; i < c.transform.childCount; ++i)
ValidateRootObjectBindings(c.transform.GetChild(i).gameObject, type, templatesPath, masterPaths);
masterPaths.Pop();
type.Pop();
childrenValidated = true;
}
foreach(var l in templates)
{
if (l.Template == null)
{
Debug.LogError("List in object " + GetGameObjectPath(gameObject) + " doesn't have item template", gameObject);
}
if (types.Count > 0 && c is NguiItemsSourceBinding)
{
if (templatesPath.Contains(l.Template))
{
Debug.Log("Skipping recursive template reference: " + l.Template);
continue;
}
templatesPath.Push(l.Template);
type.Push(GetCollectionValueType(types[0]));
masterPaths.Push(MasterPathStopper);
ValidateRootObjectBindings(l.Template, type, templatesPath, masterPaths);
masterPaths.Pop();
type.Pop();
templatesPath.Pop();
}
}
foreach(var p in c.gameObject.GetComponents<NguiPopupListSourceBinding>())
{
var cleanPath = GetFullCleanPath(masterPaths, NguiUtils.GetCleanPath(p.DisplayValuePath), NguiUtils.GetPathDepth(p.DisplayValuePath));
var cleanType = GetCleanType(type, NguiUtils.GetPathDepth(p.DisplayValuePath));
GetBindingValueType(cleanPath, cleanType, gameObject, false);
}
}
if (!childrenValidated)
{
for (var i = 0; i < gameObject.transform.childCount; ++i)
{
ValidateRootObjectBindings(gameObject.transform.GetChild(i).gameObject, type, templatesPath, masterPaths);
}
childrenValidated = true;
}
masterPaths.Pop();
}
[MenuItem("Tools/NData/Clear Console &c")]
public static void ClearConsole()
{
Assembly assembly = Assembly.GetAssembly(typeof(PrefabType));
Type type = assembly.GetType("UnityEditorInternal.LogEntries");
MethodInfo method = type.GetMethod ("Clear");
method.Invoke (new object (), null);
}
[MenuItem("Tools/NData/Validate Bindings &v")]
public static void ValidateBindings()
{
foreach (var s in UnityEditor.Selection.gameObjects)
{
if (PrefabUtility.GetPrefabType(s) != PrefabType.None)
continue;
var type = new Stack<System.Type>();
var templatesPath = new Stack<GameObject>();
var masterPaths = new Stack<string>();
//type.Push(typeof(Ui.Game)); // Use your root data context class type here to speed up validation
if (type.Count == 0)
{
var rootContext = NguiUtils.GetComponentInParents<NguiDataContext>(s) as NguiRootContext;
if (rootContext != null && rootContext.defaultContext != null)
type.Push(rootContext.defaultContext.GetType());
}
if (type.Count == 0)
{
System.Type bestType = null;
var types = typeof(NguiRootContext).Assembly.GetTypes();
foreach(var t in types)
{
var hasRootContextProperty = false;
var hasContext = false;
Type contextType = null;
foreach(var f in t.GetFields())
{
if (f.FieldType == typeof(NguiRootContext))
hasRootContextProperty = true;
if (typeof(EZData.Context).IsAssignableFrom(f.FieldType))
{
hasContext = true;
contextType = f.FieldType;
}
}
foreach(var p in t.GetProperties())
{
if (p.PropertyType == typeof(NguiRootContext))
hasRootContextProperty = true;
if (typeof(EZData.Context).IsAssignableFrom(p.PropertyType))
{
hasContext = true;
contextType = p.PropertyType;
}
}
var presentInScene = false;
if (typeof(Component).IsAssignableFrom(t))
presentInScene = GameObject.FindObjectsOfType(t).Length > 0;
if (hasRootContextProperty && hasContext && presentInScene)
{
Debug.Log(string.Format("Root data context class detected: {0}", contextType));
bestType = contextType;
}
}
type.Push(bestType);
}
ValidateRootObjectBindings(s, type, templatesPath, masterPaths);
}
}
}
| |
// 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.
/*============================================================
**
** Classes: Common Object Security class
**
**
===========================================================*/
using Microsoft.Win32;
using System;
using System.Collections;
using System.Security.Principal;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
namespace System.Security.AccessControl
{
public abstract class CommonObjectSecurity : ObjectSecurity
{
#region Constructors
protected CommonObjectSecurity(bool isContainer)
: base(isContainer, false)
{
}
internal CommonObjectSecurity(CommonSecurityDescriptor securityDescriptor)
: base(securityDescriptor)
{
}
#endregion
#region Private Methods
// Ported from NDP\clr\src\BCL\System\Security\Principal\SID.cs since we can't access System.Security.Principal.IdentityReference's internals
private static bool IsValidTargetTypeStatic(Type targetType)
{
if (targetType == typeof(NTAccount))
{
return true;
}
else if (targetType == typeof(SecurityIdentifier))
{
return true;
}
else
{
return false;
}
}
private AuthorizationRuleCollection GetRules(bool access, bool includeExplicit, bool includeInherited, System.Type targetType)
{
ReadLock();
try
{
AuthorizationRuleCollection result = new AuthorizationRuleCollection();
if (!IsValidTargetTypeStatic(targetType))
{
throw new ArgumentException(
SR.Arg_MustBeIdentityReferenceType,
"targetType");
}
CommonAcl acl = null;
if (access)
{
if ((_securityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclPresent) != 0)
{
acl = _securityDescriptor.DiscretionaryAcl;
}
}
else // !access == audit
{
if ((_securityDescriptor.ControlFlags & ControlFlags.SystemAclPresent) != 0)
{
acl = _securityDescriptor.SystemAcl;
}
}
if (acl == null)
{
//
// The required ACL was not present; return an empty collection.
//
return result;
}
IdentityReferenceCollection irTarget = null;
if (targetType != typeof(SecurityIdentifier))
{
IdentityReferenceCollection irSource = new IdentityReferenceCollection(acl.Count);
for (int i = 0; i < acl.Count; i++)
{
//
// Calling the indexer on a common ACL results in cloning,
// (which would not be the case if we were to use the internal RawAcl property)
// but also ensures that the resulting order of ACEs is proper
// However, this is a big price to pay - cloning all the ACEs just so that
// the canonical order could be ascertained just once.
// A better way would be to have an internal method that would canonicalize the ACL
// and call it once, then use the RawAcl.
//
CommonAce ace = acl[i] as CommonAce;
if (AceNeedsTranslation(ace, access, includeExplicit, includeInherited))
{
irSource.Add(ace.SecurityIdentifier);
}
}
irTarget = irSource.Translate(targetType);
}
int targetIndex = 0;
for (int i = 0; i < acl.Count; i++)
{
//
// Calling the indexer on a common ACL results in cloning,
// (which would not be the case if we were to use the internal RawAcl property)
// but also ensures that the resulting order of ACEs is proper
// However, this is a big price to pay - cloning all the ACEs just so that
// the canonical order could be ascertained just once.
// A better way would be to have an internal method that would canonicalize the ACL
// and call it once, then use the RawAcl.
//
CommonAce ace = acl[i] as CommonAce;
if (AceNeedsTranslation(ace, access, includeExplicit, includeInherited))
{
IdentityReference iref = (targetType == typeof(SecurityIdentifier)) ? ace.SecurityIdentifier : irTarget[targetIndex++];
if (access)
{
AccessControlType type;
if (ace.AceQualifier == AceQualifier.AccessAllowed)
{
type = AccessControlType.Allow;
}
else
{
type = AccessControlType.Deny;
}
result.AddRule(
AccessRuleFactory(
iref,
ace.AccessMask,
ace.IsInherited,
ace.InheritanceFlags,
ace.PropagationFlags,
type));
}
else
{
result.AddRule(
AuditRuleFactory(
iref,
ace.AccessMask,
ace.IsInherited,
ace.InheritanceFlags,
ace.PropagationFlags,
ace.AuditFlags));
}
}
}
return result;
}
finally
{
ReadUnlock();
}
}
private bool AceNeedsTranslation(CommonAce ace, bool isAccessAce, bool includeExplicit, bool includeInherited)
{
if (ace == null)
{
//
// Only consider common ACEs
//
return false;
}
if (isAccessAce)
{
if (ace.AceQualifier != AceQualifier.AccessAllowed &&
ace.AceQualifier != AceQualifier.AccessDenied)
{
return false;
}
}
else
{
if (ace.AceQualifier != AceQualifier.SystemAudit)
{
return false;
}
}
if ((includeExplicit &&
((ace.AceFlags & AceFlags.Inherited) == 0)) ||
(includeInherited &&
((ace.AceFlags & AceFlags.Inherited) != 0)))
{
return true;
}
return false;
}
//
// Modifies the DACL
//
protected override bool ModifyAccess(AccessControlModification modification, AccessRule rule, out bool modified)
{
if (rule == null)
{
throw new ArgumentNullException("rule");
}
Contract.EndContractBlock();
WriteLock();
try
{
bool result = true;
if (_securityDescriptor.DiscretionaryAcl == null)
{
if (modification == AccessControlModification.Remove ||
modification == AccessControlModification.RemoveAll ||
modification == AccessControlModification.RemoveSpecific)
{
modified = false;
return result;
}
_securityDescriptor.DiscretionaryAcl = new DiscretionaryAcl(IsContainer, IsDS, GenericAcl.AclRevision, 1);
_securityDescriptor.AddControlFlags(ControlFlags.DiscretionaryAclPresent);
}
SecurityIdentifier sid = rule.IdentityReference.Translate(typeof(SecurityIdentifier)) as SecurityIdentifier;
if (rule.AccessControlType == AccessControlType.Allow)
{
switch (modification)
{
case AccessControlModification.Add:
_securityDescriptor.DiscretionaryAcl.AddAccess(AccessControlType.Allow, sid, rule.AccessMask, rule.InheritanceFlags, rule.PropagationFlags);
break;
case AccessControlModification.Set:
_securityDescriptor.DiscretionaryAcl.SetAccess(AccessControlType.Allow, sid, rule.AccessMask, rule.InheritanceFlags, rule.PropagationFlags);
break;
case AccessControlModification.Reset:
_securityDescriptor.DiscretionaryAcl.RemoveAccess(AccessControlType.Deny, sid, -1, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, 0);
_securityDescriptor.DiscretionaryAcl.SetAccess(AccessControlType.Allow, sid, rule.AccessMask, rule.InheritanceFlags, rule.PropagationFlags);
break;
case AccessControlModification.Remove:
result = _securityDescriptor.DiscretionaryAcl.RemoveAccess(AccessControlType.Allow, sid, rule.AccessMask, rule.InheritanceFlags, rule.PropagationFlags);
break;
case AccessControlModification.RemoveAll:
result = _securityDescriptor.DiscretionaryAcl.RemoveAccess(AccessControlType.Allow, sid, -1, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, 0);
if (result == false)
{
Contract.Assert(false, "Invalid operation");
throw new InvalidOperationException();
}
break;
case AccessControlModification.RemoveSpecific:
_securityDescriptor.DiscretionaryAcl.RemoveAccessSpecific(AccessControlType.Allow, sid, rule.AccessMask, rule.InheritanceFlags, rule.PropagationFlags);
break;
default:
throw new ArgumentOutOfRangeException(
"modification",
SR.ArgumentOutOfRange_Enum);
}
}
else if (rule.AccessControlType == AccessControlType.Deny)
{
switch (modification)
{
case AccessControlModification.Add:
_securityDescriptor.DiscretionaryAcl.AddAccess(AccessControlType.Deny, sid, rule.AccessMask, rule.InheritanceFlags, rule.PropagationFlags);
break;
case AccessControlModification.Set:
_securityDescriptor.DiscretionaryAcl.SetAccess(AccessControlType.Deny, sid, rule.AccessMask, rule.InheritanceFlags, rule.PropagationFlags);
break;
case AccessControlModification.Reset:
_securityDescriptor.DiscretionaryAcl.RemoveAccess(AccessControlType.Allow, sid, -1, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, 0);
_securityDescriptor.DiscretionaryAcl.SetAccess(AccessControlType.Deny, sid, rule.AccessMask, rule.InheritanceFlags, rule.PropagationFlags);
break;
case AccessControlModification.Remove:
result = _securityDescriptor.DiscretionaryAcl.RemoveAccess(AccessControlType.Deny, sid, rule.AccessMask, rule.InheritanceFlags, rule.PropagationFlags);
break;
case AccessControlModification.RemoveAll:
result = _securityDescriptor.DiscretionaryAcl.RemoveAccess(AccessControlType.Deny, sid, -1, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, 0);
if (result == false)
{
Contract.Assert(false, "Invalid operation");
throw new InvalidOperationException();
}
break;
case AccessControlModification.RemoveSpecific:
_securityDescriptor.DiscretionaryAcl.RemoveAccessSpecific(AccessControlType.Deny, sid, rule.AccessMask, rule.InheritanceFlags, rule.PropagationFlags);
break;
default:
throw new ArgumentOutOfRangeException(
"modification",
SR.ArgumentOutOfRange_Enum);
}
}
else
{
Contract.Assert(false, "rule.AccessControlType unrecognized");
throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)rule.AccessControlType), "rule.AccessControlType");
}
modified = result;
AccessRulesModified |= modified;
return result;
}
finally
{
WriteUnlock();
}
}
//
// Modifies the SACL
//
protected override bool ModifyAudit(AccessControlModification modification, AuditRule rule, out bool modified)
{
if (rule == null)
{
throw new ArgumentNullException("rule");
}
Contract.EndContractBlock();
WriteLock();
try
{
bool result = true;
if (_securityDescriptor.SystemAcl == null)
{
if (modification == AccessControlModification.Remove ||
modification == AccessControlModification.RemoveAll ||
modification == AccessControlModification.RemoveSpecific)
{
modified = false;
return result;
}
_securityDescriptor.SystemAcl = new SystemAcl(IsContainer, IsDS, GenericAcl.AclRevision, 1);
_securityDescriptor.AddControlFlags(ControlFlags.SystemAclPresent);
}
SecurityIdentifier sid = rule.IdentityReference.Translate(typeof(SecurityIdentifier)) as SecurityIdentifier;
switch (modification)
{
case AccessControlModification.Add:
_securityDescriptor.SystemAcl.AddAudit(rule.AuditFlags, sid, rule.AccessMask, rule.InheritanceFlags, rule.PropagationFlags);
break;
case AccessControlModification.Set:
_securityDescriptor.SystemAcl.SetAudit(rule.AuditFlags, sid, rule.AccessMask, rule.InheritanceFlags, rule.PropagationFlags);
break;
case AccessControlModification.Reset:
_securityDescriptor.SystemAcl.SetAudit(rule.AuditFlags, sid, rule.AccessMask, rule.InheritanceFlags, rule.PropagationFlags);
break;
case AccessControlModification.Remove:
result = _securityDescriptor.SystemAcl.RemoveAudit(rule.AuditFlags, sid, rule.AccessMask, rule.InheritanceFlags, rule.PropagationFlags);
break;
case AccessControlModification.RemoveAll:
result = _securityDescriptor.SystemAcl.RemoveAudit(AuditFlags.Failure | AuditFlags.Success, sid, -1, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, 0);
if (result == false)
{
throw new InvalidOperationException();
}
break;
case AccessControlModification.RemoveSpecific:
_securityDescriptor.SystemAcl.RemoveAuditSpecific(rule.AuditFlags, sid, rule.AccessMask, rule.InheritanceFlags, rule.PropagationFlags);
break;
default:
throw new ArgumentOutOfRangeException(
"modification",
SR.ArgumentOutOfRange_Enum);
}
modified = result;
AuditRulesModified |= modified;
return result;
}
finally
{
WriteUnlock();
}
}
#endregion
#region Protected Methods
#endregion
#region Public Methods
protected void AddAccessRule(AccessRule rule)
{
if (rule == null)
{
throw new ArgumentNullException("rule");
}
Contract.EndContractBlock();
WriteLock();
try
{
bool modified;
ModifyAccess(AccessControlModification.Add, rule, out modified);
}
finally
{
WriteUnlock();
}
}
protected void SetAccessRule(AccessRule rule)
{
if (rule == null)
{
throw new ArgumentNullException("rule");
}
Contract.EndContractBlock();
WriteLock();
try
{
bool modified;
ModifyAccess(AccessControlModification.Set, rule, out modified);
}
finally
{
WriteUnlock();
}
}
protected void ResetAccessRule(AccessRule rule)
{
if (rule == null)
{
throw new ArgumentNullException("rule");
}
Contract.EndContractBlock();
WriteLock();
try
{
bool modified;
ModifyAccess(AccessControlModification.Reset, rule, out modified);
}
finally
{
WriteUnlock();
}
return;
}
protected bool RemoveAccessRule(AccessRule rule)
{
if (rule == null)
{
throw new ArgumentNullException("rule");
}
Contract.EndContractBlock();
WriteLock();
try
{
if (_securityDescriptor == null)
{
return true;
}
bool modified;
return ModifyAccess(AccessControlModification.Remove, rule, out modified);
}
finally
{
WriteUnlock();
}
}
protected void RemoveAccessRuleAll(AccessRule rule)
{
if (rule == null)
{
throw new ArgumentNullException("rule");
}
Contract.EndContractBlock();
WriteLock();
try
{
if (_securityDescriptor == null)
{
return;
}
bool modified;
ModifyAccess(AccessControlModification.RemoveAll, rule, out modified);
}
finally
{
WriteUnlock();
}
return;
}
protected void RemoveAccessRuleSpecific(AccessRule rule)
{
if (rule == null)
{
throw new ArgumentNullException("rule");
}
Contract.EndContractBlock();
WriteLock();
try
{
if (_securityDescriptor == null)
{
return;
}
bool modified;
ModifyAccess(AccessControlModification.RemoveSpecific, rule, out modified);
}
finally
{
WriteUnlock();
}
}
protected void AddAuditRule(AuditRule rule)
{
if (rule == null)
{
throw new ArgumentNullException("rule");
}
Contract.EndContractBlock();
WriteLock();
try
{
bool modified;
ModifyAudit(AccessControlModification.Add, rule, out modified);
}
finally
{
WriteUnlock();
}
}
protected void SetAuditRule(AuditRule rule)
{
if (rule == null)
{
throw new ArgumentNullException("rule");
}
Contract.EndContractBlock();
WriteLock();
try
{
bool modified;
ModifyAudit(AccessControlModification.Set, rule, out modified);
}
finally
{
WriteUnlock();
}
}
protected bool RemoveAuditRule(AuditRule rule)
{
if (rule == null)
{
throw new ArgumentNullException("rule");
}
Contract.EndContractBlock();
WriteLock();
try
{
bool modified;
return ModifyAudit(AccessControlModification.Remove, rule, out modified);
}
finally
{
WriteUnlock();
}
}
protected void RemoveAuditRuleAll(AuditRule rule)
{
if (rule == null)
{
throw new ArgumentNullException("rule");
}
Contract.EndContractBlock();
WriteLock();
try
{
bool modified;
ModifyAudit(AccessControlModification.RemoveAll, rule, out modified);
}
finally
{
WriteUnlock();
}
}
protected void RemoveAuditRuleSpecific(AuditRule rule)
{
if (rule == null)
{
throw new ArgumentNullException("rule");
}
Contract.EndContractBlock();
WriteLock();
try
{
bool modified;
ModifyAudit(AccessControlModification.RemoveSpecific, rule, out modified);
}
finally
{
WriteUnlock();
}
}
public AuthorizationRuleCollection GetAccessRules(bool includeExplicit, bool includeInherited, System.Type targetType)
{
return GetRules(true, includeExplicit, includeInherited, targetType);
}
public AuthorizationRuleCollection GetAuditRules(bool includeExplicit, bool includeInherited, System.Type targetType)
{
return GetRules(false, includeExplicit, includeInherited, targetType);
}
#endregion
}
}
| |
// "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Text;
using System.Windows.Forms;
using Scientia.HtmlRenderer.Core;
using Scientia.HtmlRenderer.Core.Entities;
using Scientia.HtmlRenderer.Core.Utils;
using Scientia.HtmlRenderer.WinForms.Utilities;
namespace Scientia.HtmlRenderer.WinForms
{
/// <summary>
/// Provides HTML rendering using the text property.<br/>
/// WinForms control that will render html content in it's client rectangle.<br/>
/// If <see cref="AutoScroll"/> is true and the layout of the html resulted in its content beyond the client bounds
/// of the panel it will show scrollbars (horizontal/vertical) allowing to scroll the content.<br/>
/// If <see cref="AutoScroll"/> is false html content outside the client bounds will be clipped.<br/>
/// The control will handle mouse and keyboard events on it to support html text selection, copy-paste and mouse clicks.<br/>
/// <para>
/// The major differential to use HtmlPanel or HtmlLabel is size and scrollbars.<br/>
/// If the size of the control depends on the html content the HtmlLabel should be used.<br/>
/// If the size is set by some kind of layout then HtmlPanel is more suitable, also shows scrollbars if the html contents is larger than the control client rectangle.<br/>
/// </para>
/// <para>
/// <h4>AutoScroll:</h4>
/// Allows showing scrollbars if html content is placed outside the visible boundaries of the panel.
/// </para>
/// <para>
/// <h4>LinkClicked event:</h4>
/// Raised when the user clicks on a link in the html.<br/>
/// Allows canceling the execution of the link.
/// </para>
/// <para>
/// <h4>StylesheetLoad event:</h4>
/// Raised when a stylesheet is about to be loaded by file path or URI by link element.<br/>
/// This event allows to provide the stylesheet manually or provide new source (file or uri) to load from.<br/>
/// If no alternative data is provided the original source will be used.<br/>
/// </para>
/// <para>
/// <h4>ImageLoad event:</h4>
/// Raised when an image is about to be loaded by file path or URI.<br/>
/// This event allows to provide the image manually, if not handled the image will be loaded from file or download from URI.
/// </para>
/// <para>
/// <h4>RenderError event:</h4>
/// Raised when an error occurred during html rendering.<br/>
/// </para>
/// </summary>
public class HtmlPanel : ScrollableControl
{
#region Fields and Consts
/// <summary>
/// Underline html container instance.
/// </summary>
protected HtmlContainer HtmlContainer;
/// <summary>
/// The current border style of the control
/// </summary>
protected BorderStyle _BorderStyle;
/// <summary>
/// the raw base stylesheet data used in the control
/// </summary>
protected string BaseRawCssData;
/// <summary>
/// the base stylesheet data used in the control
/// </summary>
protected CssData BaseCssData;
/// <summary>
/// the current html text set in the control
/// </summary>
protected string _Text;
/// <summary>
/// If to use cursors defined by the operating system or .NET cursors
/// </summary>
protected bool _UseSystemCursors;
/// <summary>
/// The text rendering hint to be used for text rendering.
/// </summary>
protected TextRenderingHint _TextRenderingHint = TextRenderingHint.SystemDefault;
/// <summary>
/// The last position of the scrollbars to know if it has changed to update mouse
/// </summary>
protected Point LastScrollOffset;
#endregion
/// <summary>
/// Creates a new HtmlPanel and sets a basic css for it's styling.
/// </summary>
public HtmlPanel()
{
this.AutoScroll = true;
this.BackColor = SystemColors.Window;
this.DoubleBuffered = true;
this.SetStyle(ControlStyles.ResizeRedraw, true);
this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
this.HtmlContainer = new HtmlContainer();
this.HtmlContainer.LoadComplete += this.OnLoadComplete;
this.HtmlContainer.LinkClicked += this.OnLinkClicked;
this.HtmlContainer.RenderError += this.OnRenderError;
this.HtmlContainer.Refresh += this.OnRefresh;
this.HtmlContainer.ScrollChange += this.OnScrollChange;
this.HtmlContainer.StylesheetLoad += this.OnStylesheetLoad;
this.HtmlContainer.ImageLoad += this.OnImageLoad;
}
/// <summary>
/// Raised when the BorderStyle property value changes.
/// </summary>
[Category("Property Changed")]
public event EventHandler BorderStyleChanged;
/// <summary>
/// Raised when the set html document has been fully loaded.<br/>
/// Allows manipulation of the html dom, scroll position, etc.
/// </summary>
public event EventHandler LoadComplete;
/// <summary>
/// Raised when the user clicks on a link in the html.<br/>
/// Allows canceling the execution of the link.
/// </summary>
public event EventHandler<HtmlLinkClickedEventArgs> LinkClicked;
/// <summary>
/// Raised when an error occurred during html rendering.<br/>
/// </summary>
public event EventHandler<HtmlRenderErrorEventArgs> RenderError;
/// <summary>
/// Raised when a stylesheet is about to be loaded by file path or URI by link element.<br/>
/// This event allows to provide the stylesheet manually or provide new source (file or uri) to load from.<br/>
/// If no alternative data is provided the original source will be used.<br/>
/// </summary>
public event EventHandler<HtmlStylesheetLoadEventArgs> StylesheetLoad;
/// <summary>
/// Raised when an image is about to be loaded by file path or URI.<br/>
/// This event allows to provide the image manually, if not handled the image will be loaded from file or download from URI.
/// </summary>
public event EventHandler<HtmlImageLoadEventArgs> ImageLoad;
/// <summary>
/// Gets or sets a value indicating if anti-aliasing should be avoided for geometry like backgrounds and borders (default - false).
/// </summary>
[Category("Behavior")]
[DefaultValue(false)]
[Description("If anti-aliasing should be avoided for geometry like backgrounds and borders")]
public virtual bool AvoidGeometryAntialias
{
get { return this.HtmlContainer.AvoidGeometryAntialias; }
set { this.HtmlContainer.AvoidGeometryAntialias = value; }
}
/// <summary>
/// Gets or sets a value indicating if image loading only when visible should be avoided (default - false).<br/>
/// True - images are loaded as soon as the html is parsed.<br/>
/// False - images that are not visible because of scroll location are not loaded until they are scrolled to.
/// </summary>
/// <remarks>
/// Images late loading improve performance if the page contains image outside the visible scroll area, especially if there is large
/// amount of images, as all image loading is delayed (downloading and loading into memory).<br/>
/// Late image loading may effect the layout and actual size as image without set size will not have actual size until they are loaded
/// resulting in layout change during user scroll.<br/>
/// Early image loading may also effect the layout if image without known size above the current scroll location are loaded as they
/// will push the html elements down.
/// </remarks>
[Category("Behavior")]
[DefaultValue(false)]
[Description("If image loading only when visible should be avoided")]
public virtual bool AvoidImagesLateLoading
{
get { return this.HtmlContainer.AvoidImagesLateLoading; }
set { this.HtmlContainer.AvoidImagesLateLoading = value; }
}
/// <summary>
/// Use GDI+ text rendering to measure/draw text.<br/>
/// </summary>
/// <remarks>
/// <para>
/// GDI+ text rendering is less smooth than GDI text rendering but it natively supports alpha channel
/// thus allows creating transparent images.
/// </para>
/// <para>
/// While using GDI+ text rendering you can control the text rendering using <see cref="Graphics.TextRenderingHint"/>, note that
/// using <see cref="System.Drawing.Text.TextRenderingHint.ClearTypeGridFit"/> doesn't work well with transparent background.
/// </para>
/// </remarks>
[Category("Behavior")]
[DefaultValue(false)]
[EditorBrowsable(EditorBrowsableState.Always)]
[Description("If to use GDI+ text rendering to measure/draw text, false - use GDI")]
public bool UseGdiPlusTextRendering
{
get { return this.HtmlContainer.UseGdiPlusTextRendering; }
set { this.HtmlContainer.UseGdiPlusTextRendering = value; }
}
/// <summary>
/// The text rendering hint to be used for text rendering.
/// </summary>
[Category("Behavior")]
[EditorBrowsable(EditorBrowsableState.Always)]
[DefaultValue(TextRenderingHint.SystemDefault)]
[Description("The text rendering hint to be used for text rendering.")]
public TextRenderingHint TextRenderingHint
{
get { return this._TextRenderingHint; }
set { this._TextRenderingHint = value; }
}
/// <summary>
/// If to use cursors defined by the operating system or .NET cursors
/// </summary>
[Category("Behavior")]
[EditorBrowsable(EditorBrowsableState.Always)]
[DefaultValue(false)]
[Description("If to use cursors defined by the operating system or .NET cursors")]
public bool UseSystemCursors
{
get { return this._UseSystemCursors; }
set { this._UseSystemCursors = value; }
}
/// <summary>
/// Gets or sets the border style.
/// </summary>
/// <value>The border style.</value>
[Category("Appearance")]
[DefaultValue(typeof(BorderStyle), "None")]
public virtual BorderStyle BorderStyle
{
get
{
return this._BorderStyle;
}
set
{
if (this.BorderStyle != value)
{
this._BorderStyle = value;
this.OnBorderStyleChanged(EventArgs.Empty);
}
}
}
/// <summary>
/// Is content selection is enabled for the rendered html (default - true).<br/>
/// If set to 'false' the rendered html will be static only with ability to click on links.
/// </summary>
[Browsable(true)]
[DefaultValue(true)]
[Category("Behavior")]
[EditorBrowsable(EditorBrowsableState.Always)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Description("Is content selection is enabled for the rendered html.")]
public virtual bool IsSelectionEnabled
{
get { return this.HtmlContainer.IsSelectionEnabled; }
set { this.HtmlContainer.IsSelectionEnabled = value; }
}
/// <summary>
/// Is the build-in context menu enabled and will be shown on mouse right click (default - true)
/// </summary>
[Browsable(true)]
[DefaultValue(true)]
[Category("Behavior")]
[EditorBrowsable(EditorBrowsableState.Always)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Description("Is the build-in context menu enabled and will be shown on mouse right click.")]
public virtual bool IsContextMenuEnabled
{
get { return this.HtmlContainer.IsContextMenuEnabled; }
set { this.HtmlContainer.IsContextMenuEnabled = value; }
}
/// <summary>
/// Set base stylesheet to be used by html rendered in the panel.
/// </summary>
[Browsable(true)]
[Category("Appearance")]
[Description("Set base stylesheet to be used by html rendered in the control.")]
[Editor("System.ComponentModel.Design.MultilineStringEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
public virtual string BaseStylesheet
{
get
{
return this.BaseRawCssData;
}
set
{
this.BaseRawCssData = value;
this.BaseCssData = HtmlRender.ParseStyleSheet(value);
this.HtmlContainer.SetHtml(this._Text, this.BaseCssData);
}
}
/// <summary>
/// Gets or sets a value indicating whether the container enables the user to scroll to any controls placed outside of its visible boundaries.
/// </summary>
[Browsable(true)]
[Description("Sets a value indicating whether the container enables the user to scroll to any controls placed outside of its visible boundaries.")]
public override bool AutoScroll
{
get { return base.AutoScroll; }
set { base.AutoScroll = value; }
}
/// <summary>
/// Gets or sets the text of this panel
/// </summary>
[Browsable(true)]
[Description("Sets the html of this control.")]
public override string Text
{
get
{
return this._Text;
}
set
{
this._Text = value;
base.Text = value;
if (!this.IsDisposed)
{
this.VerticalScroll.Value = this.VerticalScroll.Minimum;
this.HtmlContainer.SetHtml(this._Text, this.BaseCssData);
this.PerformLayout();
this.Invalidate();
this.InvokeMouseMove();
}
}
}
/// <summary>
/// Get the currently selected text segment in the html.
/// </summary>
[Browsable(false)]
public virtual string SelectedText
{
get { return this.HtmlContainer.SelectedText; }
}
/// <summary>
/// Copy the currently selected html segment with style.
/// </summary>
[Browsable(false)]
public virtual string SelectedHtml
{
get { return this.HtmlContainer.SelectedHtml; }
}
/// <summary>
/// Get html from the current DOM tree with inline style.
/// </summary>
/// <returns>generated html</returns>
public virtual string GetHtml()
{
return this.HtmlContainer != null ? this.HtmlContainer.GetHtml() : null;
}
/// <summary>
/// Get the rectangle of html element as calculated by html layout.<br/>
/// Element if found by id (id attribute on the html element).<br/>
/// Note: to get the screen rectangle you need to adjust by the hosting control.<br/>
/// </summary>
/// <param name="elementId">the id of the element to get its rectangle</param>
/// <returns>the rectangle of the element or null if not found</returns>
public virtual RectangleF? GetElementRectangle(string elementId)
{
return this.HtmlContainer != null ? this.HtmlContainer.GetElementRectangle(elementId) : null;
}
/// <summary>
/// Adjust the scrollbar of the panel on html element by the given id.<br/>
/// The top of the html element rectangle will be at the top of the panel, if there
/// is not enough height to scroll to the top the scroll will be at maximum.<br/>
/// </summary>
/// <param name="elementId">the id of the element to scroll to</param>
public virtual void ScrollToElement(string elementId)
{
ArgChecker.AssertArgNotNullOrEmpty(elementId, "elementId");
if (this.HtmlContainer != null)
{
var rect = this.HtmlContainer.GetElementRectangle(elementId);
if (rect.HasValue)
{
this.UpdateScroll(Point.Round(rect.Value.Location));
this.HtmlContainer.HandleMouseMove(this, new MouseEventArgs(MouseButtons, 0, MousePosition.X, MousePosition.Y, 0));
}
}
}
/// <summary>
/// Clear the current selection.
/// </summary>
public void ClearSelection()
{
if (this.HtmlContainer != null)
{
this.HtmlContainer.ClearSelection();
}
}
#region Private methods
#if !MONO
/// <summary>
/// Override to support border for the control.
/// </summary>
protected override CreateParams CreateParams
{
get
{
CreateParams createParams = base.CreateParams;
switch (this._BorderStyle)
{
case BorderStyle.FixedSingle:
createParams.Style |= Win32Utils.WsBorder;
break;
case BorderStyle.Fixed3D:
createParams.ExStyle |= Win32Utils.WsExClientEdge;
break;
}
return createParams;
}
}
#endif
/// <summary>
/// Perform the layout of the html in the control.
/// </summary>
protected override void OnLayout(LayoutEventArgs levent)
{
this.PerformHtmlLayout();
base.OnLayout(levent);
// to handle if vertical scrollbar is appearing or disappearing
if (this.HtmlContainer != null && Math.Abs(this.HtmlContainer.MaxSize.Width - this.ClientSize.Width) > 0.1)
{
this.PerformHtmlLayout();
base.OnLayout(levent);
}
}
/// <summary>
/// Perform html container layout by the current panel client size.
/// </summary>
protected void PerformHtmlLayout()
{
if (this.HtmlContainer != null)
{
this.HtmlContainer.MaxSize = new SizeF(this.ClientSize.Width - this.Padding.Horizontal, 0);
Graphics g = Utils.CreateGraphics(this);
if (g != null)
{
using (g)
{
this.HtmlContainer.PerformLayout(g);
}
}
this.AutoScrollMinSize = Size.Round(new SizeF(this.HtmlContainer.ActualSize.Width + this.Padding.Horizontal, this.HtmlContainer.ActualSize.Height));
}
}
/// <summary>
/// Perform paint of the html in the control.
/// </summary>
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if (this.HtmlContainer != null)
{
e.Graphics.TextRenderingHint = this._TextRenderingHint;
e.Graphics.SetClip(this.ClientRectangle);
this.HtmlContainer.Location = new PointF(this.Padding.Left, this.Padding.Top);
this.HtmlContainer.ScrollOffset = this.AutoScrollPosition;
this.HtmlContainer.PerformPaint(e.Graphics);
if (!this.LastScrollOffset.Equals(this.HtmlContainer.ScrollOffset))
{
this.LastScrollOffset = this.HtmlContainer.ScrollOffset;
this.InvokeMouseMove();
}
}
}
/// <summary>
/// Set focus on the control for keyboard scrollbars handling.
/// </summary>
protected override void OnClick(EventArgs e)
{
base.OnClick(e);
this.Focus();
}
/// <summary>
/// Handle mouse move to handle hover cursor and text selection.
/// </summary>
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
if (this.HtmlContainer != null)
{
this.HtmlContainer.HandleMouseMove(this, e);
}
}
/// <summary>
/// Handle mouse leave to handle cursor change.
/// </summary>
protected override void OnMouseLeave(EventArgs e)
{
base.OnMouseLeave(e);
if (this.HtmlContainer != null)
{
this.HtmlContainer.HandleMouseLeave(this);
}
}
/// <summary>
/// Handle mouse down to handle selection.
/// </summary>
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
if (this.HtmlContainer != null)
{
this.HtmlContainer.HandleMouseDown(this, e);
}
}
/// <summary>
/// Handle mouse up to handle selection and link click.
/// </summary>
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
if (this.HtmlContainer != null)
{
this.HtmlContainer.HandleMouseUp(this, e);
}
}
/// <summary>
/// Handle mouse double click to select word under the mouse.
/// </summary>
protected override void OnMouseDoubleClick(MouseEventArgs e)
{
base.OnMouseDoubleClick(e);
if (this.HtmlContainer != null)
{
this.HtmlContainer.HandleMouseDoubleClick(this, e);
}
}
/// <summary>
/// Handle key down event for selection, copy and scrollbars handling.
/// </summary>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (this.HtmlContainer != null)
{
this.HtmlContainer.HandleKeyDown(this, e);
}
if (e.KeyCode == Keys.Up)
{
this.VerticalScroll.Value = Math.Max(this.VerticalScroll.Value - 70, this.VerticalScroll.Minimum);
this.PerformLayout();
}
else if (e.KeyCode == Keys.Down)
{
this.VerticalScroll.Value = Math.Min(this.VerticalScroll.Value + 70, this.VerticalScroll.Maximum);
this.PerformLayout();
}
else if (e.KeyCode == Keys.PageDown)
{
this.VerticalScroll.Value = Math.Min(this.VerticalScroll.Value + 400, this.VerticalScroll.Maximum);
this.PerformLayout();
}
else if (e.KeyCode == Keys.PageUp)
{
this.VerticalScroll.Value = Math.Max(this.VerticalScroll.Value - 400, this.VerticalScroll.Minimum);
this.PerformLayout();
}
else if (e.KeyCode == Keys.End)
{
this.VerticalScroll.Value = this.VerticalScroll.Maximum;
this.PerformLayout();
}
else if (e.KeyCode == Keys.Home)
{
this.VerticalScroll.Value = this.VerticalScroll.Minimum;
this.PerformLayout();
}
}
/// <summary>
/// Raises the <see cref="BorderStyleChanged" /> event.
/// </summary>
protected virtual void OnBorderStyleChanged(EventArgs e)
{
this.UpdateStyles();
var handler = this.BorderStyleChanged;
if (handler != null)
{
handler(this, e);
}
}
/// <summary>
/// Propagate the LoadComplete event from root container.
/// </summary>
protected virtual void OnLoadComplete(EventArgs e)
{
var handler = this.LoadComplete;
if (handler != null)
{
handler(this, e);
}
}
/// <summary>
/// Propagate the LinkClicked event from root container.
/// </summary>
protected virtual void OnLinkClicked(HtmlLinkClickedEventArgs e)
{
var handler = this.LinkClicked;
if (handler != null)
{
handler(this, e);
}
}
/// <summary>
/// Propagate the Render Error event from root container.
/// </summary>
protected virtual void OnRenderError(HtmlRenderErrorEventArgs e)
{
var handler = this.RenderError;
if (handler != null)
{
handler(this, e);
}
}
/// <summary>
/// Propagate the stylesheet load event from root container.
/// </summary>
protected virtual void OnStylesheetLoad(HtmlStylesheetLoadEventArgs e)
{
var handler = this.StylesheetLoad;
if (handler != null)
{
handler(this, e);
}
}
/// <summary>
/// Propagate the image load event from root container.
/// </summary>
protected virtual void OnImageLoad(HtmlImageLoadEventArgs e)
{
var handler = this.ImageLoad;
if (handler != null)
{
handler(this, e);
}
}
/// <summary>
/// Handle html renderer invalidate and re-layout as requested.
/// </summary>
protected virtual void OnRefresh(HtmlRefreshEventArgs e)
{
if (e.Layout)
{
this.PerformLayout();
}
this.Invalidate();
}
/// <summary>
/// On html renderer scroll request adjust the scrolling of the panel to the requested location.
/// </summary>
protected virtual void OnScrollChange(HtmlScrollEventArgs e)
{
this.UpdateScroll(new Point((int)e.X, (int)e.Y));
}
/// <summary>
/// Adjust the scrolling of the panel to the requested location.
/// </summary>
/// <param name="location">the location to adjust the scroll to</param>
protected virtual void UpdateScroll(Point location)
{
this.AutoScrollPosition = location;
this.HtmlContainer.ScrollOffset = this.AutoScrollPosition;
}
/// <summary>
/// call mouse move to handle paint after scroll or html change affecting mouse cursor.
/// </summary>
protected virtual void InvokeMouseMove()
{
try
{
// mono has issue throwing exception for no reason
var mp = this.PointToClient(MousePosition);
this.HtmlContainer.HandleMouseMove(this, new MouseEventArgs(MouseButtons.None, 0, mp.X, mp.Y, 0));
}
catch
{
#if !MONO
throw;
#endif
}
}
/// <summary>
/// Used to add arrow keys to the handled keys in <see cref="OnKeyDown"/>.
/// </summary>
protected override bool IsInputKey(Keys keyData)
{
switch (keyData)
{
case Keys.Right:
case Keys.Left:
case Keys.Up:
case Keys.Down:
return true;
case Keys.Shift | Keys.Right:
case Keys.Shift | Keys.Left:
case Keys.Shift | Keys.Up:
case Keys.Shift | Keys.Down:
return true;
}
return base.IsInputKey(keyData);
}
#if !MONO
/// <summary>
/// Override the proc processing method to set OS specific hand cursor.
/// </summary>
/// <param name="m">The Windows <see cref="T:System.Windows.Forms.Message"/> to process. </param>
[DebuggerStepThrough]
protected override void WndProc(ref Message m)
{
if (this._UseSystemCursors && m.Msg == Win32Utils.WmSetCursor && this.Cursor == Cursors.Hand)
{
try
{
// Replace .NET's hand cursor with the OS cursor
Win32Utils.SetCursor(Win32Utils.LoadCursor(0, Win32Utils.IdcHand));
m.Result = IntPtr.Zero;
return;
}
catch (Exception ex)
{
this.OnRenderError(this, new HtmlRenderErrorEventArgs(HtmlRenderErrorType.General, "Failed to set OS hand cursor", ex));
}
}
base.WndProc(ref m);
}
#endif
/// <summary>
/// Release the html container resources.
/// </summary>
protected override void Dispose(bool disposing)
{
if (this.HtmlContainer != null)
{
this.HtmlContainer.LoadComplete -= this.OnLoadComplete;
this.HtmlContainer.LinkClicked -= this.OnLinkClicked;
this.HtmlContainer.RenderError -= this.OnRenderError;
this.HtmlContainer.Refresh -= this.OnRefresh;
this.HtmlContainer.ScrollChange -= this.OnScrollChange;
this.HtmlContainer.StylesheetLoad -= this.OnStylesheetLoad;
this.HtmlContainer.ImageLoad -= this.OnImageLoad;
this.HtmlContainer.Dispose();
this.HtmlContainer = null;
}
base.Dispose(disposing);
}
#region Private event handlers
private void OnLoadComplete(object sender, EventArgs e)
{
this.OnLoadComplete(e);
}
private void OnLinkClicked(object sender, HtmlLinkClickedEventArgs e)
{
this.OnLinkClicked(e);
}
private void OnRenderError(object sender, HtmlRenderErrorEventArgs e)
{
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker(() => this.OnRenderError(e)));
}
else
{
this.OnRenderError(e);
}
}
private void OnStylesheetLoad(object sender, HtmlStylesheetLoadEventArgs e)
{
this.OnStylesheetLoad(e);
}
private void OnImageLoad(object sender, HtmlImageLoadEventArgs e)
{
this.OnImageLoad(e);
}
private void OnRefresh(object sender, HtmlRefreshEventArgs e)
{
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker(() => this.OnRefresh(e)));
}
else
{
this.OnRefresh(e);
}
}
private void OnScrollChange(object sender, HtmlScrollEventArgs e)
{
this.OnScrollChange(e);
}
#endregion
#region Hide not relevant properties from designer
/// <summary>
/// Not applicable.
/// </summary>
[Browsable(false)]
public override Font Font
{
get { return base.Font; }
set { base.Font = value; }
}
/// <summary>
/// Not applicable.
/// </summary>
[Browsable(false)]
public override Color ForeColor
{
get { return base.ForeColor; }
set { base.ForeColor = value; }
}
/// <summary>
/// Not applicable.
/// </summary>
[Browsable(false)]
public override bool AllowDrop
{
get { return base.AllowDrop; }
set { base.AllowDrop = value; }
}
/// <summary>
/// Not applicable.
/// </summary>
[Browsable(false)]
public override RightToLeft RightToLeft
{
get { return base.RightToLeft; }
set { base.RightToLeft = value; }
}
/// <summary>
/// Not applicable.
/// </summary>
[Browsable(false)]
public override Cursor Cursor
{
get { return base.Cursor; }
set { base.Cursor = value; }
}
/// <summary>
/// Not applicable.
/// </summary>
[Browsable(false)]
public new bool UseWaitCursor
{
get { return base.UseWaitCursor; }
set { base.UseWaitCursor = value; }
}
#endregion
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.ComponentModel.Design;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Versions;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.LanguageServices.Implementation;
using Microsoft.VisualStudio.LanguageServices.Implementation.Library.FindResults;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.RuleSets;
using Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource;
using Microsoft.VisualStudio.LanguageServices.Utilities;
using Microsoft.VisualStudio.PlatformUI;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Task = System.Threading.Tasks.Task;
namespace Microsoft.VisualStudio.LanguageServices.Setup
{
[Guid(Guids.RoslynPackageIdString)]
[PackageRegistration(UseManagedResourcesOnly = true)]
[ProvideMenuResource("Menus.ctmenu", version: 12)]
internal class RoslynPackage : Package
{
private LibraryManager _libraryManager;
private uint _libraryManagerCookie;
private VisualStudioWorkspace _workspace;
private WorkspaceFailureOutputPane _outputPane;
private IComponentModel _componentModel;
private RuleSetEventHandler _ruleSetEventHandler;
private IDisposable _solutionEventMonitor;
protected override void Initialize()
{
base.Initialize();
ForegroundThreadAffinitizedObject.Initialize();
FatalError.Handler = FailFast.OnFatalException;
FatalError.NonFatalHandler = WatsonReporter.Report;
// We also must set the FailFast handler for the compiler layer as well
var compilerAssembly = typeof(Compilation).Assembly;
var compilerFatalError = compilerAssembly.GetType("Microsoft.CodeAnalysis.FatalError", throwOnError: true);
var property = compilerFatalError.GetProperty(nameof(FatalError.Handler), BindingFlags.Static | BindingFlags.Public);
var compilerFailFast = compilerAssembly.GetType(typeof(FailFast).FullName, throwOnError: true);
var method = compilerFailFast.GetMethod(nameof(FailFast.OnFatalException), BindingFlags.Static | BindingFlags.NonPublic);
property.SetValue(null, Delegate.CreateDelegate(property.PropertyType, method));
InitializePortableShim(compilerAssembly);
RegisterFindResultsLibraryManager();
var componentModel = (IComponentModel)this.GetService(typeof(SComponentModel));
_workspace = componentModel.GetService<VisualStudioWorkspace>();
var telemetrySetupExtensions = componentModel.GetExtensions<IRoslynTelemetrySetup>();
foreach (var telemetrySetup in telemetrySetupExtensions)
{
telemetrySetup.Initialize(this);
}
// set workspace output pane
_outputPane = new WorkspaceFailureOutputPane(this, _workspace);
InitializeColors();
// load some services that have to be loaded in UI thread
LoadComponentsInUIContext();
_solutionEventMonitor = new SolutionEventMonitor(_workspace);
}
private static void InitializePortableShim(Assembly compilerAssembly)
{
// We eagerly force all of the types to be loaded within the PortableShim because there are scenarios
// in which loading types can trigger the current AppDomain's AssemblyResolve or TypeResolve events.
// If handlers of those events do anything that would cause PortableShim to be accessed recursively,
// bad things can happen. In particular, this fixes the scenario described in TFS bug #1185842.
//
// Note that the fix below is written to be as defensive as possible to do no harm if it impacts other
// scenarios.
// Initialize the PortableShim linked into the Workspaces layer.
Roslyn.Utilities.PortableShim.Initialize();
// Initialize the PortableShim linked into the Compilers layer via reflection.
var compilerPortableShim = compilerAssembly.GetType("Roslyn.Utilities.PortableShim", throwOnError: false);
var initializeMethod = compilerPortableShim?.GetMethod(nameof(Roslyn.Utilities.PortableShim.Initialize), BindingFlags.Static | BindingFlags.NonPublic);
initializeMethod?.Invoke(null, null);
}
private void InitializeColors()
{
// Use VS color keys in order to support theming.
CodeAnalysisColors.SystemCaptionTextColorKey = EnvironmentColors.SystemWindowTextColorKey;
CodeAnalysisColors.SystemCaptionTextBrushKey = EnvironmentColors.SystemWindowTextBrushKey;
CodeAnalysisColors.CheckBoxTextBrushKey = EnvironmentColors.SystemWindowTextBrushKey;
CodeAnalysisColors.RenameErrorTextBrushKey = VSCodeAnalysisColors.RenameErrorTextBrushKey;
CodeAnalysisColors.RenameResolvableConflictTextBrushKey = VSCodeAnalysisColors.RenameResolvableConflictTextBrushKey;
CodeAnalysisColors.BackgroundBrushKey = VsBrushes.CommandBarGradientBeginKey;
CodeAnalysisColors.ButtonStyleKey = VsResourceKeys.ButtonStyleKey;
CodeAnalysisColors.AccentBarColorKey = EnvironmentColors.FileTabInactiveDocumentBorderEdgeBrushKey;
}
private void LoadComponentsInUIContext()
{
if (KnownUIContexts.SolutionExistsAndFullyLoadedContext.IsActive)
{
// if we are already in the right UI context, load it right away
LoadComponents();
}
else
{
// load them when it is a right context.
KnownUIContexts.SolutionExistsAndFullyLoadedContext.UIContextChanged += OnSolutionExistsAndFullyLoadedContext;
}
}
private void OnSolutionExistsAndFullyLoadedContext(object sender, UIContextChangedEventArgs e)
{
if (e.Activated)
{
// unsubscribe from it
KnownUIContexts.SolutionExistsAndFullyLoadedContext.UIContextChanged -= OnSolutionExistsAndFullyLoadedContext;
// load components
LoadComponents();
}
}
private void LoadComponents()
{
// we need to load it as early as possible since we can have errors from
// package from each language very early
this.ComponentModel.GetService<VisualStudioDiagnosticListTable>();
this.ComponentModel.GetService<VisualStudioTodoListTable>();
this.ComponentModel.GetService<VisualStudioDiagnosticListTableCommandHandler>().Initialize(this);
this.ComponentModel.GetService<HACK_ThemeColorFixer>();
this.ComponentModel.GetExtensions<IReferencedSymbolsPresenter>();
this.ComponentModel.GetExtensions<INavigableItemsPresenter>();
this.ComponentModel.GetService<VisualStudioMetadataAsSourceFileSupportService>();
this.ComponentModel.GetService<VirtualMemoryNotificationListener>();
LoadAnalyzerNodeComponents();
Task.Run(() => LoadComponentsBackground());
}
private void LoadComponentsBackground()
{
// Perf: Initialize the command handlers.
var commandHandlerServiceFactory = this.ComponentModel.GetService<ICommandHandlerServiceFactory>();
commandHandlerServiceFactory.Initialize(ContentTypeNames.RoslynContentType);
this.ComponentModel.GetService<MiscellaneousTodoListTable>();
this.ComponentModel.GetService<MiscellaneousDiagnosticListTable>();
}
internal IComponentModel ComponentModel
{
get
{
if (_componentModel == null)
{
_componentModel = (IComponentModel)GetService(typeof(SComponentModel));
}
return _componentModel;
}
}
protected override void Dispose(bool disposing)
{
UnregisterFindResultsLibraryManager();
DisposeVisualStudioDocumentTrackingService();
UnregisterAnalyzerTracker();
UnregisterRuleSetEventHandler();
ReportSessionWideTelemetry();
if (_solutionEventMonitor != null)
{
_solutionEventMonitor.Dispose();
_solutionEventMonitor = null;
}
base.Dispose(disposing);
}
private void ReportSessionWideTelemetry()
{
PersistedVersionStampLogger.LogSummary();
}
private void RegisterFindResultsLibraryManager()
{
var objectManager = this.GetService(typeof(SVsObjectManager)) as IVsObjectManager2;
if (objectManager != null)
{
_libraryManager = new LibraryManager(this);
if (ErrorHandler.Failed(objectManager.RegisterSimpleLibrary(_libraryManager, out _libraryManagerCookie)))
{
_libraryManagerCookie = 0;
}
((IServiceContainer)this).AddService(typeof(LibraryManager), _libraryManager, promote: true);
}
}
private void UnregisterFindResultsLibraryManager()
{
if (_libraryManagerCookie != 0)
{
var objectManager = this.GetService(typeof(SVsObjectManager)) as IVsObjectManager2;
if (objectManager != null)
{
objectManager.UnregisterLibrary(_libraryManagerCookie);
_libraryManagerCookie = 0;
}
((IServiceContainer)this).RemoveService(typeof(LibraryManager), promote: true);
_libraryManager = null;
}
}
private void DisposeVisualStudioDocumentTrackingService()
{
if (_workspace != null)
{
var documentTrackingService = _workspace.Services.GetService<IDocumentTrackingService>() as VisualStudioDocumentTrackingService;
documentTrackingService.Dispose();
}
}
private void LoadAnalyzerNodeComponents()
{
this.ComponentModel.GetService<IAnalyzerNodeSetup>().Initialize(this);
_ruleSetEventHandler = this.ComponentModel.GetService<RuleSetEventHandler>();
if (_ruleSetEventHandler != null)
{
_ruleSetEventHandler.Register();
}
}
private void UnregisterAnalyzerTracker()
{
this.ComponentModel.GetService<IAnalyzerNodeSetup>().Unregister();
}
private void UnregisterRuleSetEventHandler()
{
if (_ruleSetEventHandler != null)
{
_ruleSetEventHandler.Unregister();
_ruleSetEventHandler = null;
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.