context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Text;
using System.Threading;
namespace WindowsDebugLauncher
{
internal class Program
{
private static int Main(string[] argv)
{
DebugLauncher.LaunchParameters parameters = new DebugLauncher.LaunchParameters();
parameters.PipeServer = "."; // Currently only supporting local pipe connections
// Avoid sending the BOM on Windows if the Beta Unicode feature is enabled in Windows 10
Console.OutputEncoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
Console.InputEncoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
foreach (var a in argv)
{
if (String.IsNullOrEmpty(a))
{
continue;
}
switch (a)
{
case "-h":
case "-?":
case "/?":
case "--help":
HelpMessage();
return 1;
case "--pauseForDebugger":
{
while (!Debugger.IsAttached)
{
Thread.Sleep(500);
}
}
break;
default:
if (a.StartsWith("--stdin=", StringComparison.OrdinalIgnoreCase))
{
string stdin = a.Substring("--stdin=".Length);
if (string.IsNullOrWhiteSpace(stdin))
{
GenerateError("--stdin");
return -1;
}
parameters.StdInPipeName = stdin;
}
else if (a.StartsWith("--stdout=", StringComparison.OrdinalIgnoreCase))
{
string stdout = a.Substring("--stdout=".Length);
if (string.IsNullOrWhiteSpace(stdout))
{
GenerateError("--stdout");
return -1;
}
parameters.StdOutPipeName = stdout;
}
else if (a.StartsWith("--stderr=", StringComparison.OrdinalIgnoreCase))
{
string stderr = a.Substring("--stderr=".Length);
if (string.IsNullOrWhiteSpace(stderr))
{
GenerateError("--stderr");
return -1;
}
parameters.StdErrPipeName = stderr;
}
else if (a.StartsWith("--pid=", StringComparison.OrdinalIgnoreCase))
{
string pid = a.Substring("--pid=".Length);
if (string.IsNullOrWhiteSpace(pid))
{
GenerateError("--pid");
return -1;
}
parameters.PidPipeName = pid;
}
else if (a.StartsWith("--dbgExe=", StringComparison.OrdinalIgnoreCase))
{
string dbgExe = a.Substring("--dbgExe=".Length);
if (String.IsNullOrEmpty(dbgExe) || !File.Exists(dbgExe))
{
GenerateError("--dbgExe");
return -1;
}
parameters.DbgExe = dbgExe;
}
else
{
parameters.DbgExeArgs.AddRange(ParseDebugExeArgs(a));
}
break;
}
}
if (!parameters.ValidateParameters())
{
Console.Error.WriteLine("One or more required values are missing.");
HelpMessage();
return -1;
}
DebugLauncher launcher = new DebugLauncher(parameters);
launcher.StartPipeConnection();
return 0;
}
private static void GenerateError(string flag)
{
Console.Error.WriteLine(FormattableString.Invariant($"Value for flag:'{flag}' is missing or incorrect."));
HelpMessage();
}
/// <summary>
/// Parse dbgargs for spaces and quoted strings
/// </summary>
private static List<string> ParseDebugExeArgs(string line)
{
List<string> args = new List<string>();
bool inQuotedString = false;
bool isEscape = false;
StringBuilder builder = new StringBuilder();
foreach (char c in line)
{
if (isEscape)
{
switch (c)
{
case 'n':
builder.Append("\n");
break;
case 'r':
builder.Append("\r");
break;
case '\\':
builder.Append("\\");
break;
case '"':
builder.Append("\"");
break;
case ' ':
builder.Append(" ");
break;
default:
throw new ArgumentException(FormattableString.Invariant($"Invalid escape sequence: \\{c}"));
}
isEscape = false;
continue;
}
if (c == '\\')
{
isEscape = true;
continue;
}
if (!inQuotedString && c == '"')
{
inQuotedString = true;
continue;
}
if (inQuotedString && c == '"')
{
inQuotedString = false;
continue;
}
if (!inQuotedString && c == ' ')
{
if (builder.Length > 0)
{
args.Add(builder.ToString());
builder.Clear();
}
continue;
}
builder.Append(c);
}
if (builder.Length > 0)
{
args.Add(builder.ToString());
}
return args;
}
private static void HelpMessage()
{
Console.WriteLine("WindowsDebugLauncher: Launching debuggers for use with MIEngine in a separate process.");
Console.WriteLine("--stdin=<value> '<value>' is NamedPipeName for debugger stdin");
Console.WriteLine("--stdout=<value> '<value>' is NamedPipeName for debugger stdout");
Console.WriteLine("--stderr=<value> '<value>' is NamedPipeName for debugger stderr");
Console.WriteLine("--pid=<value> '<value>' is NamedPipeName for debugger pid");
Console.WriteLine("--dbgExe=<value> '<value>' is the path to the debugger");
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Immutable;
using System.Diagnostics;
using System.Reflection.Metadata.Ecma335;
namespace System.Reflection.Metadata
{
struct TypeDefinition
{
private readonly MetadataReader reader;
// Workaround: JIT doesn't generate good code for nested structures, so use RowId.
private readonly uint treatmentAndRowId;
internal TypeDefinition(MetadataReader reader, uint treatmentAndRowId)
{
DebugCorlib.Assert(reader != null);
DebugCorlib.Assert(treatmentAndRowId != 0);
this.reader = reader;
this.treatmentAndRowId = treatmentAndRowId;
}
private uint RowId
{
get { return treatmentAndRowId & TokenTypeIds.RIDMask; }
}
private TypeDefTreatment Treatment
{
get { return (TypeDefTreatment)(treatmentAndRowId >> TokenTypeIds.RowIdBitCount); }
}
private TypeDefinitionHandle Handle
{
get { return TypeDefinitionHandle.FromRowId(RowId); }
}
public TypeAttributes Attributes
{
get
{
if (Treatment == 0)
{
return reader.TypeDefTable.GetFlags(Handle);
}
return GetProjectedFlags();
}
}
/// <summary>
/// Name of the type.
/// </summary>
public StringHandle Name
{
get
{
if (Treatment == 0)
{
return reader.TypeDefTable.GetName(Handle);
}
return GetProjectedName();
}
}
/// <summary>
/// Namespace of the type, or nil if the type is nested or defined in a root namespace.
/// </summary>
public NamespaceDefinitionHandle Namespace
{
get
{
if (Treatment == 0)
{
return reader.TypeDefTable.GetNamespace(Handle);
}
return GetProjectedNamespace();
}
}
/// <summary>
/// The base type of the type definition: either
/// <see cref="TypeSpecificationHandle"/>, <see cref="TypeReferenceHandle"/> or <see cref="TypeDefinitionHandle"/>.
/// </summary>
public Handle BaseType
{
get
{
if (Treatment == 0)
{
return reader.TypeDefTable.GetExtends(Handle);
}
return GetProjectedBaseType();
}
}
public TypeLayout GetLayout()
{
uint classLayoutRowId = reader.ClassLayoutTable.FindRow(Handle);
if (classLayoutRowId == 0)
{
// NOTE: We don't need a bool/TryGetLayout because zero also means use default:
//
// Spec:
// ClassSize of zero does not mean the class has zero size. It means that no .size directive was specified
// at definition time, in which case, the actual size is calculated from the field types, taking account of
// packing size (default or specified) and natural alignment on the target, runtime platform.
//
// PackingSize shall be one of {0, 1, 2, 4, 8, 16, 32, 64, 128}. (0 means use
// the default pack size for the platform on which the application is
// running.)
return default(TypeLayout);
}
int size = (int)reader.ClassLayoutTable.GetClassSize(classLayoutRowId);
int packingSize = reader.ClassLayoutTable.GetPackingSize(classLayoutRowId);
return new TypeLayout(size, packingSize);
}
/// <summary>
/// Returns the enclosing type of a specified nested type or nil handle if the type is not nested.
/// </summary>
public TypeDefinitionHandle GetDeclaringType()
{
return reader.NestedClassTable.FindEnclosingType(Handle);
}
public GenericParameterHandleCollection GetGenericParameters()
{
return reader.GenericParamTable.FindGenericParametersForType(Handle);
}
public MethodDefinitionHandleCollection GetMethods()
{
return new MethodDefinitionHandleCollection(reader, Handle);
}
public FieldDefinitionHandleCollection GetFields()
{
return new FieldDefinitionHandleCollection(reader, Handle);
}
public PropertyDefinitionHandleCollection GetProperties()
{
return new PropertyDefinitionHandleCollection(reader, Handle);
}
public EventDefinitionHandleCollection GetEvents()
{
return new EventDefinitionHandleCollection(reader, Handle);
}
/// <summary>
/// Returns an array of types nested in the specified type.
/// </summary>
public ImmutableArray<TypeDefinitionHandle> GetNestedTypes()
{
return reader.GetNestedTypes(Handle);
}
public MethodImplementationHandleCollection GetMethodImplementations()
{
return new MethodImplementationHandleCollection(reader, Handle);
}
public InterfaceImplementationHandleCollection GetInterfaceImplementations()
{
return new InterfaceImplementationHandleCollection(reader, Handle);
}
public CustomAttributeHandleCollection GetCustomAttributes()
{
return new CustomAttributeHandleCollection(reader, Handle);
}
public DeclarativeSecurityAttributeHandleCollection GetDeclarativeSecurityAttributes()
{
return new DeclarativeSecurityAttributeHandleCollection(reader, Handle);
}
#region Projections
private TypeAttributes GetProjectedFlags()
{
var flags = reader.TypeDefTable.GetFlags(Handle);
var treatment = Treatment;
switch (treatment & TypeDefTreatment.KindMask)
{
case TypeDefTreatment.NormalNonAttribute:
flags |= TypeAttributes.WindowsRuntime | TypeAttributes.Import;
break;
case TypeDefTreatment.NormalAttribute:
flags |= TypeAttributes.WindowsRuntime | TypeAttributes.Sealed;
break;
case TypeDefTreatment.UnmangleWinRTName:
flags = flags & ~TypeAttributes.SpecialName | TypeAttributes.Public;
break;
case TypeDefTreatment.PrefixWinRTName:
flags = flags & ~TypeAttributes.Public | TypeAttributes.Import;
break;
case TypeDefTreatment.RedirectedToClrType:
flags = flags & ~TypeAttributes.Public | TypeAttributes.Import;
break;
case TypeDefTreatment.RedirectedToClrAttribute:
flags &= ~TypeAttributes.Public;
break;
}
if ((treatment & TypeDefTreatment.MarkAbstractFlag) != 0)
{
flags |= TypeAttributes.Abstract;
}
if ((treatment & TypeDefTreatment.MarkInternalFlag) != 0)
{
flags &= ~TypeAttributes.Public;
}
return flags;
}
private StringHandle GetProjectedName()
{
var name = reader.TypeDefTable.GetName(Handle);
switch (Treatment & TypeDefTreatment.KindMask)
{
case TypeDefTreatment.UnmangleWinRTName:
return name.SuffixRaw(MetadataReader.ClrPrefix.Length);
case TypeDefTreatment.PrefixWinRTName:
return name.WithWinRTPrefix();
}
return name;
}
private NamespaceDefinitionHandle GetProjectedNamespace()
{
// NOTE: NamespaceDefinitionHandle currently relies on never having virtual values. If this ever gets projected
// to a virtual namespace name, then that assumption will need to be removed.
// no change:
return reader.TypeDefTable.GetNamespace(Handle);
}
private Handle GetProjectedBaseType()
{
// no change:
return reader.TypeDefTable.GetExtends(Handle);
}
#endregion
}
}
| |
using SemanticReleaseNotesParser.Core.Formatter;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using Xunit;
namespace SemanticReleaseNotesParser.Core.Tests
{
public class SemanticReleaseNotesFormatterTest
{
[Fact]
public void Format_Null_Exception()
{
// act & assert
var exception = Assert.Throws<ArgumentNullException>(() => SemanticReleaseNotesFormatter.Format(null));
Assert.Equal("releaseNotes", exception.ParamName);
}
[Fact]
public void Format_TextWriter_Null_Exception()
{
// act & assert
var exception = Assert.Throws<ArgumentNullException>(() => SemanticReleaseNotesFormatter.Format(null, new ReleaseNotes()));
Assert.Equal("writer", exception.ParamName);
}
[Fact]
public void Format_ExampleA_Default()
{
// act
var resultHtml = SemanticReleaseNotesFormatter.Format(GetExampleAReleaseNotes());
// assert
Assert.Equal(ExampleAHtml, resultHtml.Trim());
}
[Fact]
public void Format_TextWriter_ExampleA_Default()
{
// arrange
var resultHtml = new StringBuilder();
// act
SemanticReleaseNotesFormatter.Format(new StringWriter(resultHtml), GetExampleAReleaseNotes());
// assert
Assert.Equal(ExampleAHtml, resultHtml.ToString().Trim());
}
[Fact]
public void Format_ExampleA_Output_Html()
{
// act
var resultHtml = SemanticReleaseNotesFormatter.Format(GetExampleAReleaseNotes(), new SemanticReleaseNotesConverterSettings { OutputFormat = OutputFormat.Html });
// assert
Assert.Equal(ExampleAHtml, resultHtml.Trim());
}
[Fact]
public void Format_ExampleA_Output_Markdown()
{
// act
var resultMarkdown = SemanticReleaseNotesFormatter.Format(GetExampleAReleaseNotes(), new SemanticReleaseNotesConverterSettings { OutputFormat = OutputFormat.Markdown });
// assert
Assert.Equal(ExampleAMarkdown, resultMarkdown.Trim());
}
[Fact]
public void Format_ExampleA_Output_Markdown_TextWriter()
{
// arrange
var resultMarkdown = new StringBuilder();
// act
SemanticReleaseNotesFormatter.Format(new StringWriter(resultMarkdown), GetExampleAReleaseNotes(), new SemanticReleaseNotesConverterSettings { OutputFormat = OutputFormat.Markdown });
// assert
Assert.Equal(ExampleAMarkdown, resultMarkdown.ToString().Trim());
}
[Fact]
public void Format_ExampleA_Output_Html_GroupBy_Categories()
{
// act
var resultHtml = SemanticReleaseNotesFormatter.Format(GetExampleAReleaseNotes(), new SemanticReleaseNotesConverterSettings { OutputFormat = OutputFormat.Html, GroupBy = GroupBy.Categories });
// assert
Assert.Equal(ExampleAHtmlCategories, resultHtml.Trim());
}
[Fact]
public void Format_ExampleA_Output_Markdown_GroupBy_Categories()
{
// act
var resultMarkdown = SemanticReleaseNotesFormatter.Format(GetExampleAReleaseNotes(), new SemanticReleaseNotesConverterSettings { OutputFormat = OutputFormat.Markdown, GroupBy = GroupBy.Categories });
// assert
Assert.Equal(ExampleAMarkdownCategories, resultMarkdown.Trim());
}
[Fact]
public void Format_ExampleB_Output_Html()
{
// act
var resultHtml = SemanticReleaseNotesFormatter.Format(GetExampleBReleaseNotes(), new SemanticReleaseNotesConverterSettings { OutputFormat = OutputFormat.Html });
// assert
Assert.Equal(ExampleBHtml, resultHtml.Trim());
}
[Fact]
public void Format_ExampleB_Output_Markdown()
{
// act
var resultMarkdown = SemanticReleaseNotesFormatter.Format(GetExampleBReleaseNotes(), new SemanticReleaseNotesConverterSettings { OutputFormat = OutputFormat.Markdown });
// assert
Assert.Equal(ExampleBMarkdown, resultMarkdown.Trim());
}
[Fact]
public void Format_ExampleA_Output_Html_Custom_LiquidTemplate()
{
// act
var resultHtml = SemanticReleaseNotesFormatter.Format(GetExampleAReleaseNotes(), new SemanticReleaseNotesConverterSettings { OutputFormat = OutputFormat.Html, LiquidTemplate = CustomLiquidTemplate });
// assert
Assert.Equal(CustomLiquidTemplateHtml, resultHtml.Trim());
}
[Fact]
public void Format_ExampleA_Output_Markdown_Custom_LiquidTemplate()
{
// act
var resultMarkdown = SemanticReleaseNotesFormatter.Format(GetExampleAReleaseNotes(), new SemanticReleaseNotesConverterSettings { OutputFormat = OutputFormat.Markdown, LiquidTemplate = CustomLiquidTemplate });
// assert
Assert.Equal(CustomLiquidTemplateMarkdown, resultMarkdown.Trim());
}
[Fact]
public void Format_ExampleC_Output_Html()
{
// act
var resultHtml = SemanticReleaseNotesFormatter.Format(GetExampleCReleaseNotes(), new SemanticReleaseNotesConverterSettings { OutputFormat = OutputFormat.Html });
// assert
Assert.Equal(ExampleCHtml, resultHtml.Trim());
}
[Fact]
public void Format_ExampleC_Output_Markdown()
{
// act
var resultMarkdown = SemanticReleaseNotesFormatter.Format(GetExampleCReleaseNotes(), new SemanticReleaseNotesConverterSettings { OutputFormat = OutputFormat.Markdown });
// assert
Assert.Equal(ExampleCMarkdown, resultMarkdown.Trim());
}
[Fact]
public void Format_ExampleC_Output_Html_GroupBy_Categories()
{
// act
var resultHtml = SemanticReleaseNotesFormatter.Format(GetExampleCReleaseNotes(), new SemanticReleaseNotesConverterSettings { OutputFormat = OutputFormat.Html, GroupBy = GroupBy.Categories });
// assert
Assert.Equal(ExampleCHtmlCategories, resultHtml.Trim());
}
[Fact]
public void Format_ExampleC_Output_Markdown_GroupBy_Categories()
{
// act
var resultMarkdown = SemanticReleaseNotesFormatter.Format(GetExampleCReleaseNotes(), new SemanticReleaseNotesConverterSettings { OutputFormat = OutputFormat.Markdown, GroupBy = GroupBy.Categories });
// assert
Assert.Equal(ExampleCMarkdownCategories, resultMarkdown.Trim());
}
[Fact]
public void Format_ExampleD_Output_Html()
{
// act
var resultHtml = SemanticReleaseNotesFormatter.Format(GetExampleDReleaseNotes(), new SemanticReleaseNotesConverterSettings { OutputFormat = OutputFormat.Html });
// assert
Assert.Equal(ExampleDHtml, resultHtml.Trim());
}
[Fact]
public void Format_ExampleD_Output_Markdown()
{
// act
var resultMarkdown = SemanticReleaseNotesFormatter.Format(GetExampleDReleaseNotes(), new SemanticReleaseNotesConverterSettings { OutputFormat = OutputFormat.Markdown });
// assert
Assert.Equal(ExampleDMarkdown, resultMarkdown.Trim());
}
[Fact]
public void Format_ExampleA_Output_Html_PluralizeCategoriesTitle()
{
// act
var resultHtml = SemanticReleaseNotesFormatter.Format(GetExampleABisReleaseNotes(), new SemanticReleaseNotesConverterSettings { OutputFormat = OutputFormat.Html, GroupBy = GroupBy.Categories, PluralizeCategoriesTitle = true });
// assert
Assert.Equal(ExampleABisHtmlCategories, resultHtml.Trim());
}
[Fact]
public void Format_ExampleA_Output_Markdown_PluralizeCategoriesTitle()
{
// act
var resultMarkdown = SemanticReleaseNotesFormatter.Format(GetExampleABisReleaseNotes(), new SemanticReleaseNotesConverterSettings { OutputFormat = OutputFormat.Markdown, GroupBy = GroupBy.Categories, PluralizeCategoriesTitle = true });
// assert
Assert.Equal(ExampleABisMarkdownCategories, resultMarkdown.Trim());
}
[Fact]
public void Format_SyntaxMetadataCommits_Output_Html()
{
// act
var resultHtml = SemanticReleaseNotesFormatter.Format(GetSyntaxMetadataCommitsReleaseNotes(), new SemanticReleaseNotesConverterSettings { OutputFormat = OutputFormat.Html, GroupBy = GroupBy.Categories, PluralizeCategoriesTitle = true });
// assert
Assert.Equal(SyntaxMetadataCommitsHtml, resultHtml.Trim());
}
[Fact]
public void Format_SyntaxMetadataCommits_Output_Markdown()
{
// act
var resultMarkdown = SemanticReleaseNotesFormatter.Format(GetSyntaxMetadataCommitsReleaseNotes(), new SemanticReleaseNotesConverterSettings { OutputFormat = OutputFormat.Markdown, GroupBy = GroupBy.Categories, PluralizeCategoriesTitle = true });
// assert
Assert.Equal(SyntaxMetadataCommitsMarkdown, resultMarkdown.Trim());
}
[Fact]
public void Format_ExampleA_Output_Html_With_DefaultStyle()
{
// act
var resultHtml = SemanticReleaseNotesFormatter.Format(GetExampleAReleaseNotes(), new SemanticReleaseNotesConverterSettings { OutputFormat = OutputFormat.Html, IncludeStyle = true });
// assert
Assert.Equal(GetExampleAHtmlWithStyle(), resultHtml.Trim());
}
[Fact]
public void Format_ExampleA_Output_Html_WithCustomStyle()
{
// arrange
var customStyle = "body { color:black; width:500px; }";
// act
var resultHtml = SemanticReleaseNotesFormatter.Format(GetExampleAReleaseNotes(), new SemanticReleaseNotesConverterSettings { OutputFormat = OutputFormat.Html, IncludeStyle = true, CustomStyle = customStyle });
// assert
Assert.Equal(GetExampleAHtmlWithStyle(customStyle), resultHtml.Trim());
}
private ReleaseNotes GetExampleAReleaseNotes()
{
return new ReleaseNotes
{
Summary = "Incremental release designed to provide an update to some of the core plugins.",
Items = new List<Item>
{
new Item { Categories = { { "New" } }, Summary = "Release Checker: Now gives you a breakdown of exactly what you are missing." },
new Item { Categories = { { "New" } }, Summary = "Structured Layout: An alternative layout engine that allows developers to control layout." },
new Item { Categories = { { "Changed" } }, Summary = "Timeline: Comes with an additional grid view to show the same data." },
new Item { Categories = { { "Fix" } }, Summary = "Ajax: Fix that crashed poll in Chrome and IE due to log/trace statement." }
}
};
}
private ReleaseNotes GetExampleBReleaseNotes()
{
return new ReleaseNotes
{
Summary = "Incremental release designed to provide an update to some of the core plugins.",
Sections = new List<Section>
{
new Section { Name = "System", Items = new List<Item>
{
new Item { Categories = { { "New" } }, Summary = "*Release Checker*: Now gives you a breakdown of exactly what you are missing." },
new Item { Categories = { { "New" } }, Summary = "*Structured Layout*: An alternative layout engine that allows developers to control layout." }
} },
new Section { Name = "Plugin", Items = new List<Item>
{
new Item { Categories = { { "Changed" } }, Summary = "*Timeline*: Comes with an additional grid view to show the same data." },
new Item { Categories = { { "Fix" } }, Summary = "*Ajax*: Fix that crashed poll in Chrome and IE due to log/trace statement." }
} }
}
};
}
private ReleaseNotes GetExampleCReleaseNotes()
{
return new ReleaseNotes
{
Summary = "Incremental release designed to provide an update to some of the core plugins.",
Items = new List<Item> { new Item { Summary = "*Example*: You can have global issues that aren't grouped to a section" } },
Sections = new List<Section>
{
new Section { Name = "System", Summary = "This description is specific to system section.", Items = new List<Item>
{
new Item { Categories = { { "New" } }, Summary = "*Release Checker*: Now gives you a breakdown of exactly what you are missing." },
new Item { Categories = { { "New" } }, Summary = "*Structured Layout*: An alternative layout engine that allows developers to control layout." }
} },
new Section { Name = "Plugin", Summary = "This description is specific to plugin section.", Items = new List<Item>
{
new Item { Categories = { { "Changed" } }, Summary = "*Timeline*: Comes with an additional grid view to show the same data." },
new Item { Categories = { { "Fix" } }, Summary = "*Ajax*: Fix that crashed poll in Chrome and IE due to log/trace statement.", TaskId = "i1234", TaskLink = "http://getglimpse.com" }
} }
}
};
}
private ReleaseNotes GetExampleDReleaseNotes()
{
return new ReleaseNotes
{
Summary = "Incremental release designed to provide an update to some of the core plugins.",
Items = new List<Item> { new Item { Priority = 1, Summary = "*Example*: You can have global issues that aren't grouped to a section" } },
Sections = new List<Section>
{
new Section { Name = "System", Summary = "This description is specific to system section.", Icon = "http://getglimpse.com/release/icon/core.png", Items = new List<Item>
{
new Item { Priority = 3, Categories = { { "New" } }, Summary = "*Release Checker*: Now gives you a breakdown of exactly what you are missing." },
new Item { Priority = 2, Categories = { { "New" } }, Summary = "*Structured Layout*: An alternative layout engine that allows developers to control layout." }
} },
new Section { Name = "Plugin", Summary = "This description is specific to plugin section.", Icon= "http://getglimpse.com/release/icon/mvc.png", Items = new List<Item>
{
new Item { Priority = 1, Categories = { { "Changed" } }, Summary = "*Timeline*: Comes with an additional grid view to show the same data." },
new Item { Priority = 1, Categories = { { "Fix" } }, Summary = "*Ajax*: Fix that crashed poll in Chrome and IE due to log/trace statement.", TaskId = "i1234", TaskLink = "http://getglimpse.com" }
} }
}
};
}
private ReleaseNotes GetExampleABisReleaseNotes()
{
return new ReleaseNotes
{
Summary = "Incremental release designed to provide an update to some of the core plugins.",
Items = new List<Item>
{
new Item { Categories = { { "Enhancement" } }, Summary = "Release Checker: Now gives you a breakdown of exactly what you are missing." },
new Item { Categories = { { "Enhancement" } }, Summary = "Structured Layout: An alternative layout engine that allows developers to control layout." },
new Item { Categories = { { "Breaking Change" } }, Summary = "Timeline: Comes with an additional grid view to show the same data." },
new Item { Categories = { { "Fix" } }, Summary = "Ajax: Fix that crashed poll in Chrome and IE due to log/trace statement." }
}
};
}
private ReleaseNotes GetSyntaxMetadataCommitsReleaseNotes()
{
return new ReleaseNotes
{
Metadata = new List<Metadata>
{
new Metadata { Name = "Commits", Value = "56af25a...d3fead4" },
new Metadata { Name = "Commits", Value = "[56af25a...d3fead4](https://github.com/Glimpse/Semantic-Release-Notes/compare/56af25a...d3fead4)" }
}
};
}
private string GetExampleAHtmlWithStyle(string style = null)
{
if (style == null)
{
using (var reader = new StreamReader(Assembly.GetAssembly(typeof(SemanticReleaseNotesFormatter)).GetManifestResourceStream("SemanticReleaseNotesParser.Core.Resources.DefaultStyle.css")))
{
style = reader.ReadToEnd();
}
}
return string.Format(ExampleAHtmlWithHead, style);
}
private const string ExampleAHtml = @"<html>
<body>
<p>Incremental release designed to provide an update to some of the core plugins.</p>
<ul>
<li>{New} Release Checker: Now gives you a breakdown of exactly what you are missing.</li>
<li>{New} Structured Layout: An alternative layout engine that allows developers to control layout.</li>
<li>{Changed} Timeline: Comes with an additional grid view to show the same data.</li>
<li>{Fix} Ajax: Fix that crashed poll in Chrome and IE due to log/trace statement.</li>
</ul>
</body>
</html>";
private const string ExampleAMarkdown = @"Incremental release designed to provide an update to some of the core plugins.
- {New} Release Checker: Now gives you a breakdown of exactly what you are missing.
- {New} Structured Layout: An alternative layout engine that allows developers to control layout.
- {Changed} Timeline: Comes with an additional grid view to show the same data.
- {Fix} Ajax: Fix that crashed poll in Chrome and IE due to log/trace statement.";
private const string ExampleAHtmlCategories = @"<html>
<body>
<p>Incremental release designed to provide an update to some of the core plugins.</p>
<h1>New</h1>
<ul>
<li>Release Checker: Now gives you a breakdown of exactly what you are missing.</li>
<li>Structured Layout: An alternative layout engine that allows developers to control layout.</li>
</ul>
<h1>Changed</h1>
<ul>
<li>Timeline: Comes with an additional grid view to show the same data.</li>
</ul>
<h1>Fix</h1>
<ul>
<li>Ajax: Fix that crashed poll in Chrome and IE due to log/trace statement.</li>
</ul>
</body>
</html>";
private const string ExampleAMarkdownCategories = @"Incremental release designed to provide an update to some of the core plugins.
# New
- Release Checker: Now gives you a breakdown of exactly what you are missing.
- Structured Layout: An alternative layout engine that allows developers to control layout.
# Changed
- Timeline: Comes with an additional grid view to show the same data.
# Fix
- Ajax: Fix that crashed poll in Chrome and IE due to log/trace statement.";
private const string ExampleABisHtmlCategories = @"<html>
<body>
<p>Incremental release designed to provide an update to some of the core plugins.</p>
<h1>Enhancements</h1>
<ul>
<li>Release Checker: Now gives you a breakdown of exactly what you are missing.</li>
<li>Structured Layout: An alternative layout engine that allows developers to control layout.</li>
</ul>
<h1>Breaking Changes</h1>
<ul>
<li>Timeline: Comes with an additional grid view to show the same data.</li>
</ul>
<h1>Fixes</h1>
<ul>
<li>Ajax: Fix that crashed poll in Chrome and IE due to log/trace statement.</li>
</ul>
</body>
</html>";
private const string ExampleABisMarkdownCategories = @"Incremental release designed to provide an update to some of the core plugins.
# Enhancements
- Release Checker: Now gives you a breakdown of exactly what you are missing.
- Structured Layout: An alternative layout engine that allows developers to control layout.
# Breaking Changes
- Timeline: Comes with an additional grid view to show the same data.
# Fixes
- Ajax: Fix that crashed poll in Chrome and IE due to log/trace statement.";
private const string ExampleBHtml = @"<html>
<body>
<p>Incremental release designed to provide an update to some of the core plugins.</p>
<h1>System</h1>
<ul>
<li>{New} <em>Release Checker</em>: Now gives you a breakdown of exactly what you are missing.</li>
<li>{New} <em>Structured Layout</em>: An alternative layout engine that allows developers to control layout.</li>
</ul>
<h1>Plugin</h1>
<ul>
<li>{Changed} <em>Timeline</em>: Comes with an additional grid view to show the same data.</li>
<li>{Fix} <em>Ajax</em>: Fix that crashed poll in Chrome and IE due to log/trace statement.</li>
</ul>
</body>
</html>";
private const string ExampleBMarkdown = @"Incremental release designed to provide an update to some of the core plugins.
# System
- {New} *Release Checker*: Now gives you a breakdown of exactly what you are missing.
- {New} *Structured Layout*: An alternative layout engine that allows developers to control layout.
# Plugin
- {Changed} *Timeline*: Comes with an additional grid view to show the same data.
- {Fix} *Ajax*: Fix that crashed poll in Chrome and IE due to log/trace statement.";
private const string CustomLiquidTemplate = @"
{%- for category in categories -%}
# {{ category.name }}
{%- for item in category.items -%}
- {{ item.summary }}
{%- endfor -%}
{%- endfor -%}
{{ release_notes.summary }}";
private const string CustomLiquidTemplateHtml = @"<html>
<body>
<h1>New</h1>
<ul>
<li>Release Checker: Now gives you a breakdown of exactly what you are missing.</li>
<li>Structured Layout: An alternative layout engine that allows developers to control layout.</li>
</ul>
<h1>Changed</h1>
<ul>
<li>Timeline: Comes with an additional grid view to show the same data.</li>
</ul>
<h1>Fix</h1>
<ul>
<li>Ajax: Fix that crashed poll in Chrome and IE due to log/trace statement.</li>
</ul>
<p>Incremental release designed to provide an update to some of the core plugins.</p>
</body>
</html>";
private const string CustomLiquidTemplateMarkdown = @"# New
- Release Checker: Now gives you a breakdown of exactly what you are missing.
- Structured Layout: An alternative layout engine that allows developers to control layout.
# Changed
- Timeline: Comes with an additional grid view to show the same data.
# Fix
- Ajax: Fix that crashed poll in Chrome and IE due to log/trace statement.
Incremental release designed to provide an update to some of the core plugins.";
private const string ExampleCHtml = @"<html>
<body>
<p>Incremental release designed to provide an update to some of the core plugins.</p>
<ul>
<li><em>Example</em>: You can have global issues that aren't grouped to a section</li>
</ul>
<h1>System</h1>
<ul>
<li>{New} <em>Release Checker</em>: Now gives you a breakdown of exactly what you are missing.</li>
<li>{New} <em>Structured Layout</em>: An alternative layout engine that allows developers to control layout.</li>
</ul>
<h1>Plugin</h1>
<ul>
<li>{Changed} <em>Timeline</em>: Comes with an additional grid view to show the same data.</li>
<li>{Fix} <em>Ajax</em>: Fix that crashed poll in Chrome and IE due to log/trace statement. <a href=""http://getglimpse.com"">i1234</a></li>
</ul>
</body>
</html>";
private const string ExampleCMarkdown = @"Incremental release designed to provide an update to some of the core plugins.
- *Example*: You can have global issues that aren't grouped to a section
# System
- {New} *Release Checker*: Now gives you a breakdown of exactly what you are missing.
- {New} *Structured Layout*: An alternative layout engine that allows developers to control layout.
# Plugin
- {Changed} *Timeline*: Comes with an additional grid view to show the same data.
- {Fix} *Ajax*: Fix that crashed poll in Chrome and IE due to log/trace statement. [i1234](http://getglimpse.com)";
private const string ExampleCHtmlCategories = @"<html>
<body>
<p>Incremental release designed to provide an update to some of the core plugins.</p>
<ul>
<li><em>Example</em>: You can have global issues that aren't grouped to a section</li>
</ul>
<h1>New</h1>
<ul>
<li><em>Release Checker</em>: Now gives you a breakdown of exactly what you are missing.</li>
<li><em>Structured Layout</em>: An alternative layout engine that allows developers to control layout.</li>
</ul>
<h1>Changed</h1>
<ul>
<li><em>Timeline</em>: Comes with an additional grid view to show the same data.</li>
</ul>
<h1>Fix</h1>
<ul>
<li><em>Ajax</em>: Fix that crashed poll in Chrome and IE due to log/trace statement. <a href=""http://getglimpse.com"">i1234</a></li>
</ul>
</body>
</html>";
private const string ExampleCMarkdownCategories = @"Incremental release designed to provide an update to some of the core plugins.
- *Example*: You can have global issues that aren't grouped to a section
# New
- *Release Checker*: Now gives you a breakdown of exactly what you are missing.
- *Structured Layout*: An alternative layout engine that allows developers to control layout.
# Changed
- *Timeline*: Comes with an additional grid view to show the same data.
# Fix
- *Ajax*: Fix that crashed poll in Chrome and IE due to log/trace statement. [i1234](http://getglimpse.com)";
private const string ExampleDHtml = @"<html>
<body>
<p>Incremental release designed to provide an update to some of the core plugins.</p>
<ul class=""srn-priorities"">
<li srn-priority=""1""><em>Example</em>: You can have global issues that aren't grouped to a section</li>
</ul>
<h1>System</h1>
<ul class=""srn-priorities"">
<li srn-priority=""3"">{New} <em>Release Checker</em>: Now gives you a breakdown of exactly what you are missing.</li>
<li srn-priority=""2"">{New} <em>Structured Layout</em>: An alternative layout engine that allows developers to control layout.</li>
</ul>
<h1>Plugin</h1>
<ul class=""srn-priorities"">
<li srn-priority=""1"">{Changed} <em>Timeline</em>: Comes with an additional grid view to show the same data.</li>
<li srn-priority=""1"">{Fix} <em>Ajax</em>: Fix that crashed poll in Chrome and IE due to log/trace statement. <a href=""http://getglimpse.com"">i1234</a></li>
</ul>
</body>
</html>";
private const string ExampleDMarkdown = @"Incremental release designed to provide an update to some of the core plugins.
1. *Example*: You can have global issues that aren't grouped to a section
# System
3. {New} *Release Checker*: Now gives you a breakdown of exactly what you are missing.
2. {New} *Structured Layout*: An alternative layout engine that allows developers to control layout.
# Plugin
1. {Changed} *Timeline*: Comes with an additional grid view to show the same data.
1. {Fix} *Ajax*: Fix that crashed poll in Chrome and IE due to log/trace statement. [i1234](http://getglimpse.com)";
private const string SyntaxMetadataCommitsMarkdown = @"Commits: 56af25a...d3fead4
Commits: [56af25a...d3fead4](https://github.com/Glimpse/Semantic-Release-Notes/compare/56af25a...d3fead4)";
private const string SyntaxMetadataCommitsHtml = @"<html>
<body>
<p>Commits: 56af25a...d3fead4</p>
<p>Commits: <a href=""https://github.com/Glimpse/Semantic-Release-Notes/compare/56af25a...d3fead4"">56af25a...d3fead4</a></p>
</body>
</html>";
private const string ExampleAHtmlWithHead = @"<html>
<head>
<style>
{0}
</style>
</head>
<body>
<p>Incremental release designed to provide an update to some of the core plugins.</p>
<ul>
<li>{{New}} Release Checker: Now gives you a breakdown of exactly what you are missing.</li>
<li>{{New}} Structured Layout: An alternative layout engine that allows developers to control layout.</li>
<li>{{Changed}} Timeline: Comes with an additional grid view to show the same data.</li>
<li>{{Fix}} Ajax: Fix that crashed poll in Chrome and IE due to log/trace statement.</li>
</ul>
</body>
</html>";
}
}
| |
/*
* DeflateStream.cs - Implementation of the
* "System.IO.Compression.DeflateStream" class.
*
* Copyright (C) 2004 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.IO.Compression
{
#if CONFIG_COMPRESSION
using System;
using System.IO;
using ICSharpCode.SharpZipLib.Zip.Compression;
public class DeflateStream : Stream
{
// Internal state.
private Stream stream;
private CompressionMode mode;
private bool leaveOpen;
private Inflater inflater;
private Deflater deflater;
private byte[] buf;
// Constructors.
public DeflateStream(Stream stream, CompressionMode mode)
: this(stream, mode, false) {}
public DeflateStream(Stream stream, CompressionMode mode, bool leaveOpen)
{
if(stream == null)
{
throw new ArgumentNullException("stream");
}
if(mode == CompressionMode.Decompress)
{
if(!stream.CanRead)
{
throw new ArgumentException
(S._("IO_NotReadable"), "stream");
}
}
else if(mode == CompressionMode.Compress)
{
if(!stream.CanWrite)
{
throw new ArgumentException
(S._("IO_NotWritable"), "stream");
}
}
else
{
throw new ArgumentException
(S._("IO_CompressionMode"), "mode");
}
this.stream = stream;
this.mode = mode;
this.leaveOpen = leaveOpen;
this.buf = new byte [4096];
if(mode == CompressionMode.Decompress)
{
inflater = new Inflater();
}
else
{
deflater = new Deflater();
}
}
// Get the base stream that underlies this one.
public Stream BaseStream
{
get
{
return stream;
}
}
// Determine if the stream supports reading, writing, or seeking.
public override bool CanRead
{
get
{
return (stream != null &&
mode == CompressionMode.Decompress);
}
}
public override bool CanWrite
{
get
{
return (stream != null &&
mode == CompressionMode.Compress);
}
}
public override bool CanSeek
{
get
{
return false;
}
}
// Get the length of the stream.
public override long Length
{
get
{
throw new NotSupportedException(S._("IO_NotSupp_Seek"));
}
}
// Get or set the current seek position within this stream.
public override long Position
{
get
{
throw new NotSupportedException(S._("IO_NotSupp_Seek"));
}
set
{
throw new NotSupportedException(S._("IO_NotSupp_Seek"));
}
}
// Begin an asynchronous read operation.
public override IAsyncResult BeginRead
(byte[] buffer, int offset, int count,
AsyncCallback callback, Object state)
{
if(stream == null)
{
throw new ObjectDisposedException
(S._("Exception_Disposed"));
}
if(mode != CompressionMode.Decompress)
{
throw new NotSupportedException(S._("IO_NotSupp_Read"));
}
return base.BeginRead(buffer, offset, count, callback, state);
}
// Wait for an asynchronous read operation to end.
public override int EndRead(IAsyncResult asyncResult)
{
return base.EndRead(asyncResult);
}
// Begin an asychronous write operation.
public override IAsyncResult BeginWrite
(byte[] buffer, int offset, int count,
AsyncCallback callback, Object state)
{
if(stream == null)
{
throw new ObjectDisposedException
(S._("Exception_Disposed"));
}
if(mode != CompressionMode.Compress)
{
throw new NotSupportedException(S._("IO_NotSupp_Write"));
}
return base.BeginWrite(buffer, offset, count, callback, state);
}
// Wait for an asynchronous write operation to end.
public override void EndWrite(IAsyncResult asyncResult)
{
base.EndWrite(asyncResult);
}
// Close this stream.
public override void Close()
{
if(stream != null)
{
if(deflater != null)
{
int temp;
deflater.Finish();
while(!deflater.IsFinished)
{
temp = deflater.Deflate(buf, 0, buf.Length);
if(temp <= 0)
{
if(!deflater.IsFinished)
{
throw new IOException
(S._("IO_Compress_Input"));
}
break;
}
stream.Write(buf, 0, temp);
}
}
if(!leaveOpen)
{
stream.Close();
}
stream = null;
inflater = null;
deflater = null;
buf = null;
}
}
// Flush this stream.
public override void Flush()
{
if(stream == null)
{
throw new ObjectDisposedException
(S._("Exception_Disposed"));
}
}
// Read data from this stream.
public override int Read(byte[] buffer, int offset, int count)
{
int temp;
if(stream == null)
{
throw new ObjectDisposedException
(S._("Exception_Disposed"));
}
if(mode != CompressionMode.Decompress)
{
throw new NotSupportedException(S._("IO_NotSupp_Read"));
}
ValidateBuffer(buffer, offset, count);
for(;;)
{
temp = inflater.Inflate(buffer, offset, count);
if(temp > 0)
{
return temp;
}
if(inflater.IsNeedingDictionary)
{
throw new IOException
(S._("IO_Decompress_NeedDict"));
}
else if(inflater.IsFinished)
{
return 0;
}
else if(inflater.IsNeedingInput)
{
temp = stream.Read(buf, 0, buf.Length);
if(temp <= 0)
{
throw new IOException
(S._("IO_Decompress_Truncated"));
}
inflater.SetInput(buf, 0, temp);
}
else
{
throw new IOException
(S._("IO_Decompress_Invalid"));
}
}
}
// Seek to a new position within this stream.
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException(S._("IO_NotSupp_Seek"));
}
// Set the length of this stream.
public override void SetLength(long value)
{
throw new NotSupportedException(S._("IO_NotSupp_SetLength"));
}
// Write data to this stream.
public override void Write(byte[] buffer, int offset, int count)
{
int temp;
if(stream == null)
{
throw new ObjectDisposedException
(S._("Exception_Disposed"));
}
if(mode != CompressionMode.Compress)
{
throw new NotSupportedException(S._("IO_NotSupp_Write"));
}
ValidateBuffer(buffer, offset, count);
deflater.SetInput(buffer, offset, count);
while(!deflater.IsNeedingInput)
{
temp = deflater.Deflate(buf, 0, buf.Length);
if(temp <= 0)
{
if(!deflater.IsNeedingInput)
{
throw new IOException(S._("IO_Compress_Input"));
}
break;
}
stream.Write(buf, 0, temp);
}
}
// Helper function for validating buffer arguments.
internal static void ValidateBuffer
(byte[] buffer, int offset, int count)
{
if(buffer == null)
{
throw new ArgumentNullException("buffer");
}
else if(offset < 0 || offset > buffer.Length)
{
throw new ArgumentOutOfRangeException
("offset", S._("ArgRange_Array"));
}
else if(count < 0)
{
throw new ArgumentOutOfRangeException
("count", S._("ArgRange_Array"));
}
else if((buffer.Length - offset) < count)
{
throw new ArgumentException(S._("Arg_InvalidArrayRange"));
}
}
}; // class DeflateStream
#endif // CONFIG_COMPRESSION
}; // namespace System.IO.Compression
| |
/*
* AssemblyInstaller.cs - Implementation of the
* "System.Configuration.Install.AssemblyInstaller" class.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Configuration.Install
{
#if !ECMA_COMPAT
using System.Reflection;
using System.Collections;
using System.ComponentModel;
using System.IO;
public class AssemblyInstaller : Installer
{
// Internal state.
private Assembly assembly;
private String assemblyPath;
private String[] commandLine;
private bool useNewContext;
private AssemblyInfo info;
private static AssemblyInfo[] assemblies;
internal class AssemblyInfo
{
public String filename;
public Assembly assembly;
public AssemblyInstaller installer;
public Exception loadException;
}; // class AssemblyInfo
// Constructors.
public AssemblyInstaller()
{
this.useNewContext = true;
}
public AssemblyInstaller(Assembly assembly, String[] commandLine)
{
this.assembly = assembly;
this.commandLine = commandLine;
this.useNewContext = true;
}
public AssemblyInstaller(String filename, String[] commandLine)
{
this.assemblyPath = filename;
this.commandLine = commandLine;
this.useNewContext = true;
}
// Get or set this object's properties.
public Assembly Assembly
{
get
{
return assembly;
}
set
{
assembly = value;
}
}
public String[] CommandLine
{
get
{
return commandLine;
}
set
{
commandLine = value;
}
}
public override String HelpText
{
get
{
Initialize();
String text = String.Empty;
foreach(Installer inst in Installers)
{
text += inst.HelpText + Environment.NewLine;
}
return text;
}
}
public String Path
{
get
{
return assemblyPath;
}
set
{
assemblyPath = value;
}
}
public bool UseNewContext
{
get
{
return useNewContext;
}
set
{
useNewContext = value;
}
}
// Load all installers from a particular assembly.
private static void LoadInstallers(AssemblyInfo info)
{
Type[] types = info.assembly.GetTypes();
ConstructorInfo ctor;
foreach(Type type in types)
{
// Type must not be abstract and must
// inherit from the "Installer" class.
if(!type.IsAbstract &&
type.IsSubclassOf(typeof(Installer)))
{
// Check for a zero-argument public ctor.
ctor = type.GetConstructor(Type.EmptyTypes);
if(ctor == null)
{
continue;
}
#if !ECMA_COMPAT
// Check for the "RunInstaller" attribute.
Object[] attrs =
type.GetCustomAttributes
(typeof(RunInstallerAttribute), false);
if(attrs != null && attrs.Length > 0)
{
if(((RunInstallerAttribute)(attrs[0]))
.RunInstaller)
{
// This is a valid installer.
info.installer.Installers.Add
(ctor.Invoke(new Object [0])
as Installer);
}
}
#endif
}
}
}
// Initialize this object if necessary.
private void Initialize()
{
if(info == null)
{
if(Context == null)
{
Context = new InstallContext(null, commandLine);
}
if(assembly != null)
{
info = new AssemblyInfo();
info.assembly = assembly;
info.installer = this;
LoadInstallers(info);
}
else
{
LoadInstallerAssembly(assemblyPath, Context);
}
}
}
// Check to see if a particular assembly is installable.
public static void CheckIfInstallable(String assemblyName)
{
AssemblyInfo info = LoadInstallerAssembly
(assemblyName, new InstallContext());
if(info.installer.Installers.Count == 0)
{
throw new InvalidOperationException
(S._("Installer_NoInstallersFound"));
}
}
// Commit the installation transaction.
public override void Commit(IDictionary savedState)
{
Initialize();
base.Commit(savedState);
}
// Perform the installation process, saving the previous
// state in the "stateSaver" object.
public override void Install(IDictionary stateSaver)
{
Initialize();
base.Install(stateSaver);
}
// Roll back the current installation to "savedState".
public override void Rollback(IDictionary savedState)
{
Initialize();
base.Rollback(savedState);
}
// Uninstall and return to a previously saved state.
public override void Uninstall(IDictionary savedState)
{
Initialize();
base.Uninstall(savedState);
}
// Load an assembly by name and get the information object for it.
internal static AssemblyInfo LoadInstallerAssembly
(String filename, InstallContext logContext)
{
String fullName;
AssemblyInfo info;
AssemblyInfo[] newAssemblies;
int index;
lock(typeof(AssemblyInstaller))
{
try
{
// See if we have a cached information block,
// from when we loaded the assembly previously.
fullName = IO.Path.GetFullPath(filename);
if(assemblies != null)
{
for(index = 0; index < assemblies.Length; ++index)
{
info = assemblies[index];
if(info.filename == fullName)
{
if(info.loadException == null)
{
return info;
}
throw info.loadException;
}
}
newAssemblies = new AssemblyInfo
[assemblies.Length + 1];
Array.Copy(assemblies, 0, newAssemblies, 0,
assemblies.Length);
info = new AssemblyInfo();
newAssemblies[assemblies.Length] = info;
assemblies = newAssemblies;
}
else
{
info = new AssemblyInfo();
assemblies = new AssemblyInfo [] {info};
}
// Try to load the assembly into memory.
info.filename = fullName;
try
{
info.assembly = Assembly.LoadFrom(fullName);
}
catch(SystemException e)
{
info.loadException = e;
throw;
}
// Wrap the assembly in an installer.
info.installer = new AssemblyInstaller();
info.installer.assemblyPath = filename;
info.installer.info = info;
// Search for all public installer types.
LoadInstallers(info);
// The assembly is ready to go.
return info;
}
catch(SystemException e)
{
if(logContext != null)
{
if(logContext.IsParameterTrue("ShowCallStack"))
{
logContext.LogLine
("LoadAssembly: " + e.ToString());
}
else
{
logContext.LogLine
("LoadAssembly: " + e.Message);
}
}
throw new InvalidOperationException
(String.Format
(S._("Installer_CouldNotLoadAssembly"),
filename), e);
}
}
}
}; // class AssemblyInstaller
#endif // !ECMA_COMPAT
}; // namespace System.Configuration.Install
| |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityModel;
using IdentityServer4.Configuration;
using IdentityServer4.Extensions;
using IdentityServer4.Models;
using IdentityServer4.Services;
using IdentityServer4.Stores;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Specialized;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Threading.Tasks;
using IdentityServer4.Logging.Models;
namespace IdentityServer4.Validation
{
internal class AuthorizeRequestValidator : IAuthorizeRequestValidator
{
private readonly IdentityServerOptions _options;
private readonly IClientStore _clients;
private readonly ICustomAuthorizeRequestValidator _customValidator;
private readonly IRedirectUriValidator _uriValidator;
private readonly ScopeValidator _scopeValidator;
private readonly IUserSession _userSession;
private readonly JwtRequestValidator _jwtRequestValidator;
private readonly JwtRequestUriHttpClient _jwtRequestUriHttpClient;
private readonly ILogger _logger;
private readonly ResponseTypeEqualityComparer
_responseTypeEqualityComparer = new ResponseTypeEqualityComparer();
public AuthorizeRequestValidator(
IdentityServerOptions options,
IClientStore clients,
ICustomAuthorizeRequestValidator customValidator,
IRedirectUriValidator uriValidator,
ScopeValidator scopeValidator,
IUserSession userSession,
JwtRequestValidator jwtRequestValidator,
JwtRequestUriHttpClient jwtRequestUriHttpClient,
ILogger<AuthorizeRequestValidator> logger)
{
_options = options;
_clients = clients;
_customValidator = customValidator;
_uriValidator = uriValidator;
_scopeValidator = scopeValidator;
_jwtRequestValidator = jwtRequestValidator;
_userSession = userSession;
_jwtRequestUriHttpClient = jwtRequestUriHttpClient;
_logger = logger;
}
public async Task<AuthorizeRequestValidationResult> ValidateAsync(NameValueCollection parameters, ClaimsPrincipal subject = null)
{
_logger.LogDebug("Start authorize request protocol validation");
var request = new ValidatedAuthorizeRequest
{
Options = _options,
Subject = subject ?? Principal.Anonymous,
Raw = parameters ?? throw new ArgumentNullException(nameof(parameters))
};
// load client_id
var loadClientResult = await LoadClientAsync(request);
if (loadClientResult.IsError)
{
return loadClientResult;
}
// look for JWT in request
var jwtRequestResult = await ReadJwtRequestAsync(request);
if (jwtRequestResult.IsError)
{
return jwtRequestResult;
}
// validate client_id and redirect_uri
var clientResult = await ValidateClientAsync(request);
if (clientResult.IsError)
{
return clientResult;
}
// state, response_type, response_mode
var mandatoryResult = ValidateCoreParameters(request);
if (mandatoryResult.IsError)
{
return mandatoryResult;
}
// scope, scope restrictions and plausability
var scopeResult = await ValidateScopeAsync(request);
if (scopeResult.IsError)
{
return scopeResult;
}
// nonce, prompt, acr_values, login_hint etc.
var optionalResult = await ValidateOptionalParametersAsync(request);
if (optionalResult.IsError)
{
return optionalResult;
}
// custom validator
_logger.LogDebug("Calling into custom validator: {type}", _customValidator.GetType().FullName);
var context = new CustomAuthorizeRequestValidationContext
{
Result = new AuthorizeRequestValidationResult(request)
};
await _customValidator.ValidateAsync(context);
var customResult = context.Result;
if (customResult.IsError)
{
LogError("Error in custom validation", customResult.Error, request);
return Invalid(request, customResult.Error, customResult.ErrorDescription);
}
_logger.LogTrace("Authorize request protocol validation successful");
return Valid(request);
}
private async Task<AuthorizeRequestValidationResult> LoadClientAsync(ValidatedAuthorizeRequest request)
{
//////////////////////////////////////////////////////////
// client_id must be present
/////////////////////////////////////////////////////////
var clientId = request.Raw.Get(OidcConstants.AuthorizeRequest.ClientId);
if (clientId.IsMissingOrTooLong(_options.InputLengthRestrictions.ClientId))
{
LogError("client_id is missing or too long", request);
return Invalid(request, description: "Invalid client_id");
}
request.ClientId = clientId;
//////////////////////////////////////////////////////////
// check for valid client
//////////////////////////////////////////////////////////
var client = await _clients.FindEnabledClientByIdAsync(request.ClientId);
if (client == null)
{
LogError("Unknown client or not enabled", request.ClientId, request);
return Invalid(request, OidcConstants.AuthorizeErrors.UnauthorizedClient, "Unknown client or client not enabled");
}
request.SetClient(client);
return Valid(request);
}
private async Task<AuthorizeRequestValidationResult> ReadJwtRequestAsync(ValidatedAuthorizeRequest request)
{
//////////////////////////////////////////////////////////
// look for optional request params
/////////////////////////////////////////////////////////
var jwtRequest = request.Raw.Get(OidcConstants.AuthorizeRequest.Request);
var jwtRequestUri = request.Raw.Get(OidcConstants.AuthorizeRequest.RequestUri);
if (request.Client.RequireRequestObject)
{
if (jwtRequest.IsMissing() && jwtRequestUri.IsMissing())
{
return Invalid(request, description: "Client must use request object, but no request or request_uri parameter present");
}
}
if (_options.Endpoints.EnableJwtRequestUri)
{
if (jwtRequest.IsPresent() && jwtRequestUri.IsPresent())
{
LogError("Both request and request_uri are present", request);
return Invalid(request, description: "Only one request parameter is allowed");
}
if (jwtRequestUri.IsPresent())
{
// 512 is from the spec
if (jwtRequestUri.Length > 512)
{
LogError("request_uri is too long", request);
return Invalid(request, description: "request_uri is too long");
}
var jwt = await _jwtRequestUriHttpClient.GetJwtAsync(jwtRequestUri, request.Client);
if (jwt.IsMissing())
{
LogError("no value returned from request_uri", request);
return Invalid(request, description: "no value returned from request_uri");
}
jwtRequest = jwt;
}
}
//////////////////////////////////////////////////////////
// validate request JWT
/////////////////////////////////////////////////////////
if (jwtRequest.IsPresent())
{
// check length restrictions
if (jwtRequest.Length >= _options.InputLengthRestrictions.Jwt)
{
LogError("request value is too long", request);
return Invalid(request, description: "Invalid request value");
}
// validate the request JWT for this client
var jwtRequestValidationResult = await _jwtRequestValidator.ValidateAsync(request.Client, jwtRequest);
if (jwtRequestValidationResult.IsError)
{
LogError("request JWT validation failure", request);
return Invalid(request, description: "Invalid JWT request");
}
// validate client_id match
if (jwtRequestValidationResult.Payload.TryGetValue(OidcConstants.AuthorizeRequest.ClientId, out var payloadClientId))
{
if (payloadClientId != request.Client.ClientId)
{
LogError("client_id in JWT payload does not match client_id in request", request);
return Invalid(request, description: "Invalid JWT request");
}
}
// validate response_type match
var responseType = request.Raw.Get(OidcConstants.AuthorizeRequest.ResponseType);
if (responseType != null)
{
if (jwtRequestValidationResult.Payload.TryGetValue(OidcConstants.AuthorizeRequest.ResponseType, out var payloadResponseType))
{
if (payloadResponseType != responseType)
{
LogError("response_type in JWT payload does not match response_type in request", request);
return Invalid(request, description: "Invalid JWT request");
}
}
}
// merge jwt payload values into original request parameters
foreach (var key in jwtRequestValidationResult.Payload.Keys)
{
var value = jwtRequestValidationResult.Payload[key];
request.Raw.Set(key, value);
}
request.RequestObjectValues = jwtRequestValidationResult.Payload;
}
return Valid(request);
}
private async Task<AuthorizeRequestValidationResult> ValidateClientAsync(ValidatedAuthorizeRequest request)
{
//////////////////////////////////////////////////////////
// redirect_uri must be present, and a valid uri
//////////////////////////////////////////////////////////
var redirectUri = request.Raw.Get(OidcConstants.AuthorizeRequest.RedirectUri);
if (redirectUri.IsMissingOrTooLong(_options.InputLengthRestrictions.RedirectUri))
{
LogError("redirect_uri is missing or too long", request);
return Invalid(request, description:"Invalid redirect_uri");
}
if (!Uri.TryCreate(redirectUri, UriKind.Absolute, out var _))
{
LogError("malformed redirect_uri", redirectUri, request);
return Invalid(request, description: "Invalid redirect_uri");
}
//////////////////////////////////////////////////////////
// check if client protocol type is oidc
//////////////////////////////////////////////////////////
if (request.Client.ProtocolType != IdentityServerConstants.ProtocolTypes.OpenIdConnect)
{
LogError("Invalid protocol type for OIDC authorize endpoint", request.Client.ProtocolType, request);
return Invalid(request, OidcConstants.AuthorizeErrors.UnauthorizedClient, description: "Invalid protocol");
}
//////////////////////////////////////////////////////////
// check if redirect_uri is valid
//////////////////////////////////////////////////////////
if (await _uriValidator.IsRedirectUriValidAsync(redirectUri, request.Client) == false)
{
LogError("Invalid redirect_uri", redirectUri, request);
return Invalid(request, OidcConstants.AuthorizeErrors.UnauthorizedClient, "Invalid redirect_uri");
}
request.RedirectUri = redirectUri;
return Valid(request);
}
private AuthorizeRequestValidationResult ValidateCoreParameters(ValidatedAuthorizeRequest request)
{
//////////////////////////////////////////////////////////
// check state
//////////////////////////////////////////////////////////
var state = request.Raw.Get(OidcConstants.AuthorizeRequest.State);
if (state.IsPresent())
{
request.State = state;
}
//////////////////////////////////////////////////////////
// response_type must be present and supported
//////////////////////////////////////////////////////////
var responseType = request.Raw.Get(OidcConstants.AuthorizeRequest.ResponseType);
if (responseType.IsMissing())
{
LogError("Missing response_type", request);
return Invalid(request, OidcConstants.AuthorizeErrors.UnsupportedResponseType, "Missing response_type");
}
// The responseType may come in in an unconventional order.
// Use an IEqualityComparer that doesn't care about the order of multiple values.
// Per https://tools.ietf.org/html/rfc6749#section-3.1.1 -
// 'Extension response types MAY contain a space-delimited (%x20) list of
// values, where the order of values does not matter (e.g., response
// type "a b" is the same as "b a").'
// http://openid.net/specs/oauth-v2-multiple-response-types-1_0-03.html#terminology -
// 'If a response type contains one of more space characters (%20), it is compared
// as a space-delimited list of values in which the order of values does not matter.'
if (!Constants.SupportedResponseTypes.Contains(responseType, _responseTypeEqualityComparer))
{
LogError("Response type not supported", responseType, request);
return Invalid(request, OidcConstants.AuthorizeErrors.UnsupportedResponseType, "Response type not supported");
}
// Even though the responseType may have come in in an unconventional order,
// we still need the request's ResponseType property to be set to the
// conventional, supported response type.
request.ResponseType = Constants.SupportedResponseTypes.First(
supportedResponseType => _responseTypeEqualityComparer.Equals(supportedResponseType, responseType));
//////////////////////////////////////////////////////////
// match response_type to grant type
//////////////////////////////////////////////////////////
request.GrantType = Constants.ResponseTypeToGrantTypeMapping[request.ResponseType];
// set default response mode for flow; this is needed for any client error processing below
request.ResponseMode = Constants.AllowedResponseModesForGrantType[request.GrantType].First();
//////////////////////////////////////////////////////////
// check if flow is allowed at authorize endpoint
//////////////////////////////////////////////////////////
if (!Constants.AllowedGrantTypesForAuthorizeEndpoint.Contains(request.GrantType))
{
LogError("Invalid grant type", request.GrantType, request);
return Invalid(request, description: "Invalid response_type");
}
//////////////////////////////////////////////////////////
// check if PKCE is required and validate parameters
//////////////////////////////////////////////////////////
if (request.GrantType == GrantType.AuthorizationCode || request.GrantType == GrantType.Hybrid)
{
_logger.LogDebug("Checking for PKCE parameters");
/////////////////////////////////////////////////////////////////////////////
// validate code_challenge and code_challenge_method
/////////////////////////////////////////////////////////////////////////////
var proofKeyResult = ValidatePkceParameters(request);
if (proofKeyResult.IsError)
{
return proofKeyResult;
}
}
//////////////////////////////////////////////////////////
// check response_mode parameter and set response_mode
//////////////////////////////////////////////////////////
// check if response_mode parameter is present and valid
var responseMode = request.Raw.Get(OidcConstants.AuthorizeRequest.ResponseMode);
if (responseMode.IsPresent())
{
if (Constants.SupportedResponseModes.Contains(responseMode))
{
if (Constants.AllowedResponseModesForGrantType[request.GrantType].Contains(responseMode))
{
request.ResponseMode = responseMode;
}
else
{
LogError("Invalid response_mode for flow", responseMode, request);
return Invalid(request, OidcConstants.AuthorizeErrors.UnsupportedResponseType, description: "Invalid response_mode");
}
}
else
{
LogError("Unsupported response_mode", responseMode, request);
return Invalid(request, OidcConstants.AuthorizeErrors.UnsupportedResponseType, description: "Invalid response_mode");
}
}
//////////////////////////////////////////////////////////
// check if grant type is allowed for client
//////////////////////////////////////////////////////////
if (!request.Client.AllowedGrantTypes.Contains(request.GrantType))
{
LogError("Invalid grant type for client", request.GrantType, request);
return Invalid(request, OidcConstants.AuthorizeErrors.UnauthorizedClient, "Invalid grant type for client");
}
//////////////////////////////////////////////////////////
// check if response type contains an access token,
// and if client is allowed to request access token via browser
//////////////////////////////////////////////////////////
var responseTypes = responseType.FromSpaceSeparatedString();
if (responseTypes.Contains(OidcConstants.ResponseTypes.Token))
{
if (!request.Client.AllowAccessTokensViaBrowser)
{
LogError("Client requested access token - but client is not configured to receive access tokens via browser", request);
return Invalid(request, description: "Client not configured to receive access tokens via browser");
}
}
return Valid(request);
}
private AuthorizeRequestValidationResult ValidatePkceParameters(ValidatedAuthorizeRequest request)
{
var fail = Invalid(request);
var codeChallenge = request.Raw.Get(OidcConstants.AuthorizeRequest.CodeChallenge);
if (codeChallenge.IsMissing())
{
if (request.Client.RequirePkce)
{
LogError("code_challenge is missing", request);
fail.ErrorDescription = "code challenge required";
}
else
{
_logger.LogDebug("No PKCE used.");
return Valid(request);
}
return fail;
}
if (codeChallenge.Length < _options.InputLengthRestrictions.CodeChallengeMinLength ||
codeChallenge.Length > _options.InputLengthRestrictions.CodeChallengeMaxLength)
{
LogError("code_challenge is either too short or too long", request);
fail.ErrorDescription = "Invalid code_challenge";
return fail;
}
request.CodeChallenge = codeChallenge;
var codeChallengeMethod = request.Raw.Get(OidcConstants.AuthorizeRequest.CodeChallengeMethod);
if (codeChallengeMethod.IsMissing())
{
_logger.LogDebug("Missing code_challenge_method, defaulting to plain");
codeChallengeMethod = OidcConstants.CodeChallengeMethods.Plain;
}
if (!Constants.SupportedCodeChallengeMethods.Contains(codeChallengeMethod))
{
LogError("Unsupported code_challenge_method", codeChallengeMethod, request);
fail.ErrorDescription = "Transform algorithm not supported";
return fail;
}
// check if plain method is allowed
if (codeChallengeMethod == OidcConstants.CodeChallengeMethods.Plain)
{
if (!request.Client.AllowPlainTextPkce)
{
LogError("code_challenge_method of plain is not allowed", request);
fail.ErrorDescription = "Transform algorithm not supported";
return fail;
}
}
request.CodeChallengeMethod = codeChallengeMethod;
return Valid(request);
}
private async Task<AuthorizeRequestValidationResult> ValidateScopeAsync(ValidatedAuthorizeRequest request)
{
//////////////////////////////////////////////////////////
// scope must be present
//////////////////////////////////////////////////////////
var scope = request.Raw.Get(OidcConstants.AuthorizeRequest.Scope);
if (scope.IsMissing())
{
LogError("scope is missing", request);
return Invalid(request, description: "Invalid scope");
}
if (scope.Length > _options.InputLengthRestrictions.Scope)
{
LogError("scopes too long.", request);
return Invalid(request, description: "Invalid scope");
}
request.RequestedScopes = scope.FromSpaceSeparatedString().Distinct().ToList();
if (request.RequestedScopes.Contains(IdentityServerConstants.StandardScopes.OpenId))
{
request.IsOpenIdRequest = true;
}
//////////////////////////////////////////////////////////
// check scope vs response_type plausability
//////////////////////////////////////////////////////////
var requirement = Constants.ResponseTypeToScopeRequirement[request.ResponseType];
if (requirement == Constants.ScopeRequirement.Identity ||
requirement == Constants.ScopeRequirement.IdentityOnly)
{
if (request.IsOpenIdRequest == false)
{
LogError("response_type requires the openid scope", request);
return Invalid(request, description: "Missing openid scope");
}
}
//////////////////////////////////////////////////////////
// check if scopes are valid/supported and check for resource scopes
//////////////////////////////////////////////////////////
if (await _scopeValidator.AreScopesValidAsync(request.RequestedScopes) == false)
{
return Invalid(request, OidcConstants.AuthorizeErrors.InvalidScope, "Invalid scope");
}
if (_scopeValidator.ContainsOpenIdScopes && !request.IsOpenIdRequest)
{
LogError("Identity related scope requests, but no openid scope", request);
return Invalid(request, OidcConstants.AuthorizeErrors.InvalidScope, "Identity scopes requested, but openid scope is missing");
}
if (_scopeValidator.ContainsApiResourceScopes)
{
request.IsApiResourceRequest = true;
}
//////////////////////////////////////////////////////////
// check scopes and scope restrictions
//////////////////////////////////////////////////////////
if (await _scopeValidator.AreScopesAllowedAsync(request.Client, request.RequestedScopes) == false)
{
return Invalid(request, OidcConstants.AuthorizeErrors.UnauthorizedClient, description: "Invalid scope for client");
}
request.ValidatedScopes = _scopeValidator;
//////////////////////////////////////////////////////////
// check id vs resource scopes and response types plausability
//////////////////////////////////////////////////////////
if (!_scopeValidator.IsResponseTypeValid(request.ResponseType))
{
return Invalid(request, OidcConstants.AuthorizeErrors.InvalidScope, "Invalid scope for response type");
}
return Valid(request);
}
private async Task<AuthorizeRequestValidationResult> ValidateOptionalParametersAsync(ValidatedAuthorizeRequest request)
{
//////////////////////////////////////////////////////////
// check nonce
//////////////////////////////////////////////////////////
var nonce = request.Raw.Get(OidcConstants.AuthorizeRequest.Nonce);
if (nonce.IsPresent())
{
if (nonce.Length > _options.InputLengthRestrictions.Nonce)
{
LogError("Nonce too long", request);
return Invalid(request, description: "Invalid nonce");
}
request.Nonce = nonce;
}
else
{
if (request.GrantType == GrantType.Implicit ||
request.GrantType == GrantType.Hybrid)
{
// only openid requests require nonce
if (request.IsOpenIdRequest)
{
LogError("Nonce required for implicit and hybrid flow with openid scope", request);
return Invalid(request, description: "Invalid nonce");
}
}
}
//////////////////////////////////////////////////////////
// check prompt
//////////////////////////////////////////////////////////
var prompt = request.Raw.Get(OidcConstants.AuthorizeRequest.Prompt);
if (prompt.IsPresent())
{
if (Constants.SupportedPromptModes.Contains(prompt))
{
request.PromptMode = prompt;
}
else
{
_logger.LogDebug("Unsupported prompt mode - ignored: " + prompt);
}
}
//////////////////////////////////////////////////////////
// check ui locales
//////////////////////////////////////////////////////////
var uilocales = request.Raw.Get(OidcConstants.AuthorizeRequest.UiLocales);
if (uilocales.IsPresent())
{
if (uilocales.Length > _options.InputLengthRestrictions.UiLocale)
{
LogError("UI locale too long", request);
return Invalid(request, description: "Invalid ui_locales");
}
request.UiLocales = uilocales;
}
//////////////////////////////////////////////////////////
// check display
//////////////////////////////////////////////////////////
var display = request.Raw.Get(OidcConstants.AuthorizeRequest.Display);
if (display.IsPresent())
{
if (Constants.SupportedDisplayModes.Contains(display))
{
request.DisplayMode = display;
}
_logger.LogDebug("Unsupported display mode - ignored: " + display);
}
//////////////////////////////////////////////////////////
// check max_age
//////////////////////////////////////////////////////////
var maxAge = request.Raw.Get(OidcConstants.AuthorizeRequest.MaxAge);
if (maxAge.IsPresent())
{
if (int.TryParse(maxAge, out var seconds))
{
if (seconds >= 0)
{
request.MaxAge = seconds;
}
else
{
LogError("Invalid max_age.", request);
return Invalid(request, description: "Invalid max_age");
}
}
else
{
LogError("Invalid max_age.", request);
return Invalid(request, description: "Invalid max_age");
}
}
//////////////////////////////////////////////////////////
// check login_hint
//////////////////////////////////////////////////////////
var loginHint = request.Raw.Get(OidcConstants.AuthorizeRequest.LoginHint);
if (loginHint.IsPresent())
{
if (loginHint.Length > _options.InputLengthRestrictions.LoginHint)
{
LogError("Login hint too long", request);
return Invalid(request, description:"Invalid login_hint");
}
request.LoginHint = loginHint;
}
//////////////////////////////////////////////////////////
// check acr_values
//////////////////////////////////////////////////////////
var acrValues = request.Raw.Get(OidcConstants.AuthorizeRequest.AcrValues);
if (acrValues.IsPresent())
{
if (acrValues.Length > _options.InputLengthRestrictions.AcrValues)
{
LogError("Acr values too long", request);
return Invalid(request, description: "Invalid acr_values");
}
request.AuthenticationContextReferenceClasses = acrValues.FromSpaceSeparatedString().Distinct().ToList();
}
//////////////////////////////////////////////////////////
// check custom acr_values: idp
//////////////////////////////////////////////////////////
var idp = request.GetIdP();
if (idp.IsPresent())
{
// if idp is present but client does not allow it, strip it from the request message
if (request.Client.IdentityProviderRestrictions != null && request.Client.IdentityProviderRestrictions.Any())
{
if (!request.Client.IdentityProviderRestrictions.Contains(idp))
{
_logger.LogWarning("idp requested ({idp}) is not in client restriction list.", idp);
request.RemoveIdP();
}
}
}
//////////////////////////////////////////////////////////
// check session cookie
//////////////////////////////////////////////////////////
if (_options.Endpoints.EnableCheckSessionEndpoint)
{
if (request.Subject.IsAuthenticated())
{
var sessionId = await _userSession.GetSessionIdAsync();
if (sessionId.IsPresent())
{
request.SessionId = sessionId;
}
else
{
LogError("Check session endpoint enabled, but SessionId is missing", request);
}
}
else
{
request.SessionId = ""; // empty string for anonymous users
}
}
return Valid(request);
}
private AuthorizeRequestValidationResult Invalid(ValidatedAuthorizeRequest request, string error = OidcConstants.AuthorizeErrors.InvalidRequest, string description = null)
{
return new AuthorizeRequestValidationResult(request, error, description);
}
private AuthorizeRequestValidationResult Valid(ValidatedAuthorizeRequest request)
{
return new AuthorizeRequestValidationResult(request);
}
private void LogError(string message, ValidatedAuthorizeRequest request)
{
var requestDetails = new AuthorizeRequestValidationLog(request);
_logger.LogError(message + "\n{@requestDetails}", requestDetails);
}
private void LogError(string message, string detail, ValidatedAuthorizeRequest request)
{
var requestDetails = new AuthorizeRequestValidationLog(request);
_logger.LogError(message + ": {detail}\n{@requestDetails}", detail, requestDetails);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Cache
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cache.Expiry;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.Core.Cache.Query.Continuous;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Cache.Expiry;
using Apache.Ignite.Core.Impl.Cache.Query;
using Apache.Ignite.Core.Impl.Cache.Query.Continuous;
using Apache.Ignite.Core.Impl.Cluster;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Transactions;
using Apache.Ignite.Core.Impl.Unmanaged;
/// <summary>
/// Native cache wrapper.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")]
internal class CacheImpl<TK, TV> : PlatformTarget, ICache<TK, TV>, ICacheInternal, ICacheLockInternal
{
/** Ignite instance. */
private readonly Ignite _ignite;
/** Flag: skip store. */
private readonly bool _flagSkipStore;
/** Flag: keep binary. */
private readonly bool _flagKeepBinary;
/** Flag: no-retries.*/
private readonly bool _flagNoRetries;
/** Transaction manager. */
private readonly CacheTransactionManager _txManager;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="grid">Grid.</param>
/// <param name="target">Target.</param>
/// <param name="marsh">Marshaller.</param>
/// <param name="flagSkipStore">Skip store flag.</param>
/// <param name="flagKeepBinary">Keep binary flag.</param>
/// <param name="flagNoRetries">No-retries mode flag.</param>
public CacheImpl(Ignite grid, IUnmanagedTarget target, Marshaller marsh,
bool flagSkipStore, bool flagKeepBinary, bool flagNoRetries) : base(target, marsh)
{
Debug.Assert(grid != null);
_ignite = grid;
_flagSkipStore = flagSkipStore;
_flagKeepBinary = flagKeepBinary;
_flagNoRetries = flagNoRetries;
// TransactionScope feature disabled: IGNITE-3430.
_txManager = null;
//_txManager = GetConfiguration().AtomicityMode == CacheAtomicityMode.Transactional
// ? new CacheTransactionManager(grid.GetTransactions())
// : null;
}
/** <inheritDoc /> */
public IIgnite Ignite
{
get { return _ignite; }
}
/// <summary>
/// Performs async operation.
/// </summary>
private Task DoOutOpAsync<T1>(CacheOp op, T1 val1)
{
return DoOutOpAsync<object, T1>((int) op, val1);
}
/// <summary>
/// Performs async operation.
/// </summary>
private Task<TR> DoOutOpAsync<T1, TR>(CacheOp op, T1 val1)
{
return DoOutOpAsync<T1, TR>((int) op, val1);
}
/// <summary>
/// Performs async operation.
/// </summary>
private Task DoOutOpAsync<T1, T2>(CacheOp op, T1 val1, T2 val2)
{
return DoOutOpAsync<T1, T2, object>((int) op, val1, val2);
}
/// <summary>
/// Performs async operation.
/// </summary>
private Task<TR> DoOutOpAsync<T1, T2, TR>(CacheOp op, T1 val1, T2 val2)
{
return DoOutOpAsync<T1, T2, TR>((int) op, val1, val2);
}
/// <summary>
/// Performs async operation.
/// </summary>
private Task DoOutOpAsync(CacheOp op, Action<BinaryWriter> writeAction = null)
{
return DoOutOpAsync<object>(op, writeAction);
}
/// <summary>
/// Performs async operation.
/// </summary>
private Task<T> DoOutOpAsync<T>(CacheOp op, Action<BinaryWriter> writeAction = null,
Func<BinaryReader, T> convertFunc = null)
{
return DoOutOpAsync((int)op, writeAction, IsKeepBinary, convertFunc);
}
/** <inheritDoc /> */
public string Name
{
get { return DoInOp<string>((int)CacheOp.GetName); }
}
/** <inheritDoc /> */
public CacheConfiguration GetConfiguration()
{
return DoInOp((int) CacheOp.GetConfig, stream => new CacheConfiguration(Marshaller.StartUnmarshal(stream)));
}
/** <inheritDoc /> */
public bool IsEmpty()
{
return GetSize() == 0;
}
/** <inheritDoc /> */
public ICache<TK, TV> WithSkipStore()
{
if (_flagSkipStore)
return this;
return new CacheImpl<TK, TV>(_ignite, DoOutOpObject((int) CacheOp.WithSkipStore), Marshaller,
true, _flagKeepBinary, true);
}
/// <summary>
/// Skip store flag getter.
/// </summary>
internal bool IsSkipStore { get { return _flagSkipStore; } }
/** <inheritDoc /> */
public ICache<TK1, TV1> WithKeepBinary<TK1, TV1>()
{
if (_flagKeepBinary)
{
var result = this as ICache<TK1, TV1>;
if (result == null)
throw new InvalidOperationException(
"Can't change type of binary cache. WithKeepBinary has been called on an instance of " +
"binary cache with incompatible generic arguments.");
return result;
}
return new CacheImpl<TK1, TV1>(_ignite, DoOutOpObject((int) CacheOp.WithKeepBinary), Marshaller,
_flagSkipStore, true, _flagNoRetries);
}
/** <inheritDoc /> */
public ICache<TK, TV> WithExpiryPolicy(IExpiryPolicy plc)
{
IgniteArgumentCheck.NotNull(plc, "plc");
var cache0 = DoOutOpObject((int)CacheOp.WithExpiryPolicy, w => ExpiryPolicySerializer.WritePolicy(w, plc));
return new CacheImpl<TK, TV>(_ignite, cache0, Marshaller, _flagSkipStore, _flagKeepBinary, _flagNoRetries);
}
/** <inheritDoc /> */
public bool IsKeepBinary
{
get { return _flagKeepBinary; }
}
/** <inheritDoc /> */
public void LoadCache(ICacheEntryFilter<TK, TV> p, params object[] args)
{
DoOutInOpX((int) CacheOp.LoadCache, writer => WriteLoadCacheData(writer, p, args), ReadException);
}
/** <inheritDoc /> */
public Task LoadCacheAsync(ICacheEntryFilter<TK, TV> p, params object[] args)
{
return DoOutOpAsync(CacheOp.LoadCacheAsync, writer => WriteLoadCacheData(writer, p, args));
}
/** <inheritDoc /> */
public void LocalLoadCache(ICacheEntryFilter<TK, TV> p, params object[] args)
{
DoOutInOpX((int) CacheOp.LocLoadCache, writer => WriteLoadCacheData(writer, p, args), ReadException);
}
/** <inheritDoc /> */
public Task LocalLoadCacheAsync(ICacheEntryFilter<TK, TV> p, params object[] args)
{
return DoOutOpAsync(CacheOp.LocLoadCacheAsync, writer => WriteLoadCacheData(writer, p, args));
}
/// <summary>
/// Writes the load cache data to the writer.
/// </summary>
private void WriteLoadCacheData(BinaryWriter writer, ICacheEntryFilter<TK, TV> p, object[] args)
{
if (p != null)
{
var p0 = new CacheEntryFilterHolder(p, (k, v) => p.Invoke(new CacheEntry<TK, TV>((TK) k, (TV) v)),
Marshaller, IsKeepBinary);
writer.WriteObject(p0);
}
else
writer.WriteObject<CacheEntryFilterHolder>(null);
if (args != null && args.Length > 0)
{
writer.WriteInt(args.Length);
foreach (var o in args)
writer.WriteObject(o);
}
else
{
writer.WriteInt(0);
}
}
/** <inheritDoc /> */
public void LoadAll(IEnumerable<TK> keys, bool replaceExistingValues)
{
LoadAllAsync(keys, replaceExistingValues).Wait();
}
/** <inheritDoc /> */
public Task LoadAllAsync(IEnumerable<TK> keys, bool replaceExistingValues)
{
return DoOutOpAsync(CacheOp.LoadAll, writer =>
{
writer.WriteBoolean(replaceExistingValues);
WriteEnumerable(writer, keys);
});
}
/** <inheritDoc /> */
public bool ContainsKey(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutOp(CacheOp.ContainsKey, key);
}
/** <inheritDoc /> */
public Task<bool> ContainsKeyAsync(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutOpAsync<TK, bool>(CacheOp.ContainsKeyAsync, key);
}
/** <inheritDoc /> */
public bool ContainsKeys(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutOp(CacheOp.ContainsKeys, writer => WriteEnumerable(writer, keys));
}
/** <inheritDoc /> */
public Task<bool> ContainsKeysAsync(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutOpAsync<bool>(CacheOp.ContainsKeysAsync, writer => WriteEnumerable(writer, keys));
}
/** <inheritDoc /> */
public TV LocalPeek(TK key, params CachePeekMode[] modes)
{
IgniteArgumentCheck.NotNull(key, "key");
TV res;
if (TryLocalPeek(key, out res))
return res;
throw GetKeyNotFoundException();
}
/** <inheritDoc /> */
public bool TryLocalPeek(TK key, out TV value, params CachePeekMode[] modes)
{
IgniteArgumentCheck.NotNull(key, "key");
var res = DoOutInOpX((int)CacheOp.Peek,
w =>
{
w.Write(key);
w.WriteInt(EncodePeekModes(modes));
},
(s, r) => r == True ? new CacheResult<TV>(Unmarshal<TV>(s)) : new CacheResult<TV>(),
ReadException);
value = res.Success ? res.Value : default(TV);
return res.Success;
}
/** <inheritDoc /> */
public TV this[TK key]
{
get
{
return Get(key);
}
set
{
Put(key, value);
}
}
/** <inheritDoc /> */
public TV Get(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutInOpX((int) CacheOp.Get,
w => w.Write(key),
(stream, res) =>
{
if (res != True)
throw GetKeyNotFoundException();
return Unmarshal<TV>(stream);
}, ReadException);
}
/** <inheritDoc /> */
public Task<TV> GetAsync(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutOpAsync(CacheOp.GetAsync, w => w.WriteObject(key), reader =>
{
if (reader != null)
return reader.ReadObject<TV>();
throw GetKeyNotFoundException();
});
}
/** <inheritDoc /> */
public bool TryGet(TK key, out TV value)
{
IgniteArgumentCheck.NotNull(key, "key");
var res = DoOutInOpNullable(CacheOp.Get, key);
value = res.Value;
return res.Success;
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> TryGetAsync(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutOpAsync(CacheOp.GetAsync, w => w.WriteObject(key), reader => GetCacheResult(reader));
}
/** <inheritDoc /> */
public IDictionary<TK, TV> GetAll(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutInOpX((int) CacheOp.GetAll,
writer => WriteEnumerable(writer, keys),
(s, r) => r == True ? ReadGetAllDictionary(Marshaller.StartUnmarshal(s, _flagKeepBinary)) : null,
ReadException);
}
/** <inheritDoc /> */
public Task<IDictionary<TK, TV>> GetAllAsync(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutOpAsync(CacheOp.GetAllAsync, w => WriteEnumerable(w, keys), r => ReadGetAllDictionary(r));
}
/** <inheritdoc /> */
public void Put(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
StartTx();
DoOutOp(CacheOp.Put, key, val);
}
/** <inheritDoc /> */
public Task PutAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
StartTx();
return DoOutOpAsync(CacheOp.PutAsync, key, val);
}
/** <inheritDoc /> */
public CacheResult<TV> GetAndPut(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
StartTx();
return DoOutInOpNullable(CacheOp.GetAndPut, key, val);
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndPutAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
StartTx();
return DoOutOpAsync(CacheOp.GetAndPutAsync, w =>
{
w.WriteObject(key);
w.WriteObject(val);
}, r => GetCacheResult(r));
}
/** <inheritDoc /> */
public CacheResult<TV> GetAndReplace(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
StartTx();
return DoOutInOpNullable(CacheOp.GetAndReplace, key, val);
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndReplaceAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
StartTx();
return DoOutOpAsync(CacheOp.GetAndReplaceAsync, w =>
{
w.WriteObject(key);
w.WriteObject(val);
}, r => GetCacheResult(r));
}
/** <inheritDoc /> */
public CacheResult<TV> GetAndRemove(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
StartTx();
return DoOutInOpNullable(CacheOp.GetAndRemove, key);
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndRemoveAsync(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
StartTx();
return DoOutOpAsync(CacheOp.GetAndRemoveAsync, w => w.WriteObject(key), r => GetCacheResult(r));
}
/** <inheritdoc /> */
public bool PutIfAbsent(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
StartTx();
return DoOutOp(CacheOp.PutIfAbsent, key, val);
}
/** <inheritDoc /> */
public Task<bool> PutIfAbsentAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
StartTx();
return DoOutOpAsync<TK, TV, bool>(CacheOp.PutIfAbsentAsync, key, val);
}
/** <inheritdoc /> */
public CacheResult<TV> GetAndPutIfAbsent(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
StartTx();
return DoOutInOpNullable(CacheOp.GetAndPutIfAbsent, key, val);
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndPutIfAbsentAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
StartTx();
return DoOutOpAsync(CacheOp.GetAndPutIfAbsentAsync, w =>
{
w.WriteObject(key);
w.WriteObject(val);
}, r => GetCacheResult(r));
}
/** <inheritdoc /> */
public bool Replace(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
StartTx();
return DoOutOp(CacheOp.Replace2, key, val);
}
/** <inheritDoc /> */
public Task<bool> ReplaceAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
StartTx();
return DoOutOpAsync<TK, TV, bool>(CacheOp.Replace2Async, key, val);
}
/** <inheritdoc /> */
public bool Replace(TK key, TV oldVal, TV newVal)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(oldVal, "oldVal");
IgniteArgumentCheck.NotNull(newVal, "newVal");
StartTx();
return DoOutOp(CacheOp.Replace3, key, oldVal, newVal);
}
/** <inheritDoc /> */
public Task<bool> ReplaceAsync(TK key, TV oldVal, TV newVal)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(oldVal, "oldVal");
IgniteArgumentCheck.NotNull(newVal, "newVal");
StartTx();
return DoOutOpAsync<bool>(CacheOp.Replace3Async, w =>
{
w.WriteObject(key);
w.WriteObject(oldVal);
w.WriteObject(newVal);
});
}
/** <inheritdoc /> */
public void PutAll(IDictionary<TK, TV> vals)
{
IgniteArgumentCheck.NotNull(vals, "vals");
StartTx();
DoOutOp(CacheOp.PutAll, writer => WriteDictionary(writer, vals));
}
/** <inheritDoc /> */
public Task PutAllAsync(IDictionary<TK, TV> vals)
{
IgniteArgumentCheck.NotNull(vals, "vals");
StartTx();
return DoOutOpAsync(CacheOp.PutAllAsync, writer => WriteDictionary(writer, vals));
}
/** <inheritdoc /> */
public void LocalEvict(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
DoOutOp(CacheOp.LocEvict, writer => WriteEnumerable(writer, keys));
}
/** <inheritdoc /> */
public void Clear()
{
DoOutInOp((int) CacheOp.ClearCache);
}
/** <inheritDoc /> */
public Task ClearAsync()
{
return DoOutOpAsync(CacheOp.ClearCacheAsync);
}
/** <inheritdoc /> */
public void Clear(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
DoOutOp(CacheOp.Clear, key);
}
/** <inheritDoc /> */
public Task ClearAsync(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutOpAsync(CacheOp.ClearAsync, key);
}
/** <inheritdoc /> */
public void ClearAll(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
DoOutOp(CacheOp.ClearAll, writer => WriteEnumerable(writer, keys));
}
/** <inheritDoc /> */
public Task ClearAllAsync(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutOpAsync(CacheOp.ClearAllAsync, writer => WriteEnumerable(writer, keys));
}
/** <inheritdoc /> */
public void LocalClear(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
DoOutOp(CacheOp.LocalClear, key);
}
/** <inheritdoc /> */
public void LocalClearAll(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
DoOutOp(CacheOp.LocalClearAll, writer => WriteEnumerable(writer, keys));
}
/** <inheritdoc /> */
public bool Remove(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
StartTx();
return DoOutOp(CacheOp.RemoveObj, key);
}
/** <inheritDoc /> */
public Task<bool> RemoveAsync(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
StartTx();
return DoOutOpAsync<TK, bool>(CacheOp.RemoveObjAsync, key);
}
/** <inheritDoc /> */
public bool Remove(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
StartTx();
return DoOutOp(CacheOp.RemoveBool, key, val);
}
/** <inheritDoc /> */
public Task<bool> RemoveAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
StartTx();
return DoOutOpAsync<TK, TV, bool>(CacheOp.RemoveBoolAsync, key, val);
}
/** <inheritDoc /> */
public void RemoveAll(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
StartTx();
DoOutOp(CacheOp.RemoveAll, writer => WriteEnumerable(writer, keys));
}
/** <inheritDoc /> */
public Task RemoveAllAsync(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
StartTx();
return DoOutOpAsync(CacheOp.RemoveAllAsync, writer => WriteEnumerable(writer, keys));
}
/** <inheritDoc /> */
public void RemoveAll()
{
StartTx();
DoOutInOp((int) CacheOp.RemoveAll2);
}
/** <inheritDoc /> */
public Task RemoveAllAsync()
{
StartTx();
return DoOutOpAsync(CacheOp.RemoveAll2Async);
}
/** <inheritDoc /> */
public int GetLocalSize(params CachePeekMode[] modes)
{
return Size0(true, modes);
}
/** <inheritDoc /> */
public int GetSize(params CachePeekMode[] modes)
{
return Size0(false, modes);
}
/** <inheritDoc /> */
public Task<int> GetSizeAsync(params CachePeekMode[] modes)
{
var modes0 = EncodePeekModes(modes);
return DoOutOpAsync<int>(CacheOp.SizeAsync, w => w.WriteInt(modes0));
}
/// <summary>
/// Internal size routine.
/// </summary>
/// <param name="loc">Local flag.</param>
/// <param name="modes">peek modes</param>
/// <returns>Size.</returns>
private int Size0(bool loc, params CachePeekMode[] modes)
{
var modes0 = EncodePeekModes(modes);
var op = loc ? CacheOp.SizeLoc : CacheOp.Size;
return (int) DoOutInOp((int) op, modes0);
}
/** <inheritDoc /> */
public void LocalPromote(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
DoOutOp(CacheOp.LocPromote, writer => WriteEnumerable(writer, keys));
}
/** <inheritdoc /> */
public TRes Invoke<TArg, TRes>(TK key, ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(processor, "processor");
StartTx();
var holder = new CacheEntryProcessorHolder(processor, arg,
(e, a) => processor.Process((IMutableCacheEntry<TK, TV>)e, (TArg)a), typeof(TK), typeof(TV));
return DoOutInOpX((int) CacheOp.Invoke,
writer =>
{
writer.Write(key);
writer.Write(holder);
},
(input, res) => res == True ? Unmarshal<TRes>(input) : default(TRes),
ReadException);
}
/** <inheritDoc /> */
public Task<TRes> InvokeAsync<TArg, TRes>(TK key, ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(processor, "processor");
StartTx();
var holder = new CacheEntryProcessorHolder(processor, arg,
(e, a) => processor.Process((IMutableCacheEntry<TK, TV>)e, (TArg)a), typeof(TK), typeof(TV));
return DoOutOpAsync(CacheOp.InvokeAsync, writer =>
{
writer.Write(key);
writer.Write(holder);
},
r =>
{
if (r == null)
return default(TRes);
var hasError = r.ReadBoolean();
if (hasError)
throw ReadException(r);
return r.ReadObject<TRes>();
});
}
/** <inheritdoc /> */
public IDictionary<TK, ICacheEntryProcessorResult<TRes>> InvokeAll<TArg, TRes>(IEnumerable<TK> keys,
ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg)
{
IgniteArgumentCheck.NotNull(keys, "keys");
IgniteArgumentCheck.NotNull(processor, "processor");
StartTx();
var holder = new CacheEntryProcessorHolder(processor, arg,
(e, a) => processor.Process((IMutableCacheEntry<TK, TV>)e, (TArg)a), typeof(TK), typeof(TV));
return DoOutInOpX((int) CacheOp.InvokeAll,
writer =>
{
WriteEnumerable(writer, keys);
writer.Write(holder);
},
(input, res) => res == True ? ReadInvokeAllResults<TRes>(Marshaller.StartUnmarshal(input, IsKeepBinary)): null, ReadException);
}
/** <inheritDoc /> */
public Task<IDictionary<TK, ICacheEntryProcessorResult<TRes>>> InvokeAllAsync<TArg, TRes>(IEnumerable<TK> keys,
ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg)
{
IgniteArgumentCheck.NotNull(keys, "keys");
IgniteArgumentCheck.NotNull(processor, "processor");
StartTx();
var holder = new CacheEntryProcessorHolder(processor, arg,
(e, a) => processor.Process((IMutableCacheEntry<TK, TV>)e, (TArg)a), typeof(TK), typeof(TV));
return DoOutOpAsync(CacheOp.InvokeAllAsync,
writer =>
{
WriteEnumerable(writer, keys);
writer.Write(holder);
},
input => ReadInvokeAllResults<TRes>(input));
}
/** <inheritDoc /> */
public T DoOutInOpExtension<T>(int extensionId, int opCode, Action<IBinaryRawWriter> writeAction,
Func<IBinaryRawReader, T> readFunc)
{
return DoOutInOpX((int) CacheOp.Extension, writer =>
{
writer.WriteInt(extensionId);
writer.WriteInt(opCode);
writeAction(writer);
},
(input, res) => res == True
? readFunc(Marshaller.StartUnmarshal(input))
: default(T), ReadException);
}
/** <inheritdoc /> */
public ICacheLock Lock(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutInOpX((int) CacheOp.Lock, w => w.Write(key),
(stream, res) => new CacheLock(stream.ReadInt(), this), ReadException);
}
/** <inheritdoc /> */
public ICacheLock LockAll(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutInOpX((int) CacheOp.LockAll, w => WriteEnumerable(w, keys),
(stream, res) => new CacheLock(stream.ReadInt(), this), ReadException);
}
/** <inheritdoc /> */
public bool IsLocalLocked(TK key, bool byCurrentThread)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutOp(CacheOp.IsLocalLocked, writer =>
{
writer.Write(key);
writer.WriteBoolean(byCurrentThread);
});
}
/** <inheritDoc /> */
public ICacheMetrics GetMetrics()
{
return DoInOp((int) CacheOp.GlobalMetrics, stream =>
{
IBinaryRawReader reader = Marshaller.StartUnmarshal(stream, false);
return new CacheMetricsImpl(reader);
});
}
/** <inheritDoc /> */
public ICacheMetrics GetMetrics(IClusterGroup clusterGroup)
{
IgniteArgumentCheck.NotNull(clusterGroup, "clusterGroup");
var prj = clusterGroup as ClusterGroupImpl;
if (prj == null)
throw new ArgumentException("Unexpected IClusterGroup implementation: " + clusterGroup.GetType());
return prj.GetCacheMetrics(Name);
}
/** <inheritDoc /> */
public ICacheMetrics GetLocalMetrics()
{
return DoInOp((int) CacheOp.LocalMetrics, stream =>
{
IBinaryRawReader reader = Marshaller.StartUnmarshal(stream, false);
return new CacheMetricsImpl(reader);
});
}
/** <inheritDoc /> */
public Task Rebalance()
{
return DoOutOpAsync(CacheOp.Rebalance);
}
/** <inheritDoc /> */
public ICache<TK, TV> WithNoRetries()
{
if (_flagNoRetries)
return this;
return new CacheImpl<TK, TV>(_ignite, DoOutOpObject((int) CacheOp.WithNoRetries), Marshaller,
_flagSkipStore, _flagKeepBinary, true);
}
#region Queries
/** <inheritDoc /> */
public IQueryCursor<IList> QueryFields(SqlFieldsQuery qry)
{
return QueryFields(qry, ReadFieldsArrayList);
}
/// <summary>
/// Reads the fields array list.
/// </summary>
private static IList ReadFieldsArrayList(IBinaryRawReader reader, int count)
{
IList res = new ArrayList(count);
for (var i = 0; i < count; i++)
res.Add(reader.ReadObject<object>());
return res;
}
/** <inheritDoc /> */
public IQueryCursor<T> QueryFields<T>(SqlFieldsQuery qry, Func<IBinaryRawReader, int, T> readerFunc)
{
IgniteArgumentCheck.NotNull(qry, "qry");
IgniteArgumentCheck.NotNull(readerFunc, "readerFunc");
if (string.IsNullOrEmpty(qry.Sql))
throw new ArgumentException("Sql cannot be null or empty");
var cursor = DoOutOpObject((int) CacheOp.QrySqlFields, writer =>
{
writer.WriteBoolean(qry.Local);
writer.WriteString(qry.Sql);
writer.WriteInt(qry.PageSize);
QueryBase.WriteQueryArgs(writer, qry.Arguments);
writer.WriteBoolean(qry.EnableDistributedJoins);
writer.WriteBoolean(qry.EnforceJoinOrder);
});
return new FieldsQueryCursor<T>(cursor, Marshaller, _flagKeepBinary, readerFunc);
}
/** <inheritDoc /> */
public IQueryCursor<ICacheEntry<TK, TV>> Query(QueryBase qry)
{
IgniteArgumentCheck.NotNull(qry, "qry");
var cursor = DoOutOpObject((int) qry.OpId, writer => qry.Write(writer, IsKeepBinary));
return new QueryCursor<TK, TV>(cursor, Marshaller, _flagKeepBinary);
}
/** <inheritdoc /> */
public IContinuousQueryHandle QueryContinuous(ContinuousQuery<TK, TV> qry)
{
IgniteArgumentCheck.NotNull(qry, "qry");
return QueryContinuousImpl(qry, null);
}
/** <inheritdoc /> */
public IContinuousQueryHandle<ICacheEntry<TK, TV>> QueryContinuous(ContinuousQuery<TK, TV> qry, QueryBase initialQry)
{
IgniteArgumentCheck.NotNull(qry, "qry");
IgniteArgumentCheck.NotNull(initialQry, "initialQry");
return QueryContinuousImpl(qry, initialQry);
}
/// <summary>
/// QueryContinuous implementation.
/// </summary>
private IContinuousQueryHandle<ICacheEntry<TK, TV>> QueryContinuousImpl(ContinuousQuery<TK, TV> qry,
QueryBase initialQry)
{
qry.Validate();
return new ContinuousQueryHandleImpl<TK, TV>(qry, Marshaller, _flagKeepBinary,
writeAction => DoOutOpObject((int) CacheOp.QryContinuous, writeAction), initialQry);
}
#endregion
#region Enumerable support
/** <inheritdoc /> */
public IEnumerable<ICacheEntry<TK, TV>> GetLocalEntries(CachePeekMode[] peekModes)
{
return new CacheEnumerable<TK, TV>(this, EncodePeekModes(peekModes));
}
/** <inheritdoc /> */
public IEnumerator<ICacheEntry<TK, TV>> GetEnumerator()
{
return new CacheEnumeratorProxy<TK, TV>(this, false, 0);
}
/** <inheritdoc /> */
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Create real cache enumerator.
/// </summary>
/// <param name="loc">Local flag.</param>
/// <param name="peekModes">Peek modes for local enumerator.</param>
/// <returns>Cache enumerator.</returns>
internal CacheEnumerator<TK, TV> CreateEnumerator(bool loc, int peekModes)
{
if (loc)
{
var target = DoOutOpObject((int) CacheOp.LocIterator, w => w.WriteInt(peekModes));
return new CacheEnumerator<TK, TV>(target, Marshaller, _flagKeepBinary);
}
return new CacheEnumerator<TK, TV>(DoOutOpObject((int) CacheOp.Iterator), Marshaller, _flagKeepBinary);
}
#endregion
/** <inheritDoc /> */
protected override T Unmarshal<T>(IBinaryStream stream)
{
return Marshaller.Unmarshal<T>(stream, _flagKeepBinary);
}
/// <summary>
/// Encodes the peek modes into a single int value.
/// </summary>
private static int EncodePeekModes(CachePeekMode[] modes)
{
int modesEncoded = 0;
if (modes != null)
{
foreach (var mode in modes)
modesEncoded |= (int) mode;
}
return modesEncoded;
}
/// <summary>
/// Reads results of InvokeAll operation.
/// </summary>
/// <typeparam name="T">The type of the result.</typeparam>
/// <param name="reader">Stream.</param>
/// <returns>Results of InvokeAll operation.</returns>
private IDictionary<TK, ICacheEntryProcessorResult<T>> ReadInvokeAllResults<T>(BinaryReader reader)
{
var count = reader.ReadInt();
if (count == -1)
return null;
var results = new Dictionary<TK, ICacheEntryProcessorResult<T>>(count);
for (var i = 0; i < count; i++)
{
var key = reader.ReadObject<TK>();
var hasError = reader.ReadBoolean();
results[key] = hasError
? new CacheEntryProcessorResult<T>(ReadException(reader))
: new CacheEntryProcessorResult<T>(reader.ReadObject<T>());
}
return results;
}
/// <summary>
/// Reads the exception.
/// </summary>
private Exception ReadException(IBinaryStream stream)
{
return ReadException(Marshaller.StartUnmarshal(stream));
}
/// <summary>
/// Reads the exception, either in binary wrapper form, or as a pair of strings.
/// </summary>
/// <param name="reader">The stream.</param>
/// <returns>Exception.</returns>
private Exception ReadException(BinaryReader reader)
{
var item = reader.ReadObject<object>();
var clsName = item as string;
if (clsName == null)
return new CacheEntryProcessorException((Exception) item);
var msg = reader.ReadObject<string>();
var trace = reader.ReadObject<string>();
var inner = reader.ReadBoolean() ? reader.ReadObject<Exception>() : null;
return ExceptionUtils.GetException(_ignite, clsName, msg, trace, reader, inner);
}
/// <summary>
/// Read dictionary returned by GET_ALL operation.
/// </summary>
/// <param name="reader">Reader.</param>
/// <returns>Dictionary.</returns>
private static IDictionary<TK, TV> ReadGetAllDictionary(BinaryReader reader)
{
if (reader == null)
return null;
IBinaryStream stream = reader.Stream;
if (stream.ReadBool())
{
int size = stream.ReadInt();
IDictionary<TK, TV> res = new Dictionary<TK, TV>(size);
for (int i = 0; i < size; i++)
{
TK key = reader.ReadObject<TK>();
TV val = reader.ReadObject<TV>();
res[key] = val;
}
return res;
}
return null;
}
/// <summary>
/// Gets the cache result.
/// </summary>
private static CacheResult<TV> GetCacheResult(BinaryReader reader)
{
var res = reader == null
? new CacheResult<TV>()
: new CacheResult<TV>(reader.ReadObject<TV>());
return res;
}
/// <summary>
/// Throws the key not found exception.
/// </summary>
private static KeyNotFoundException GetKeyNotFoundException()
{
return new KeyNotFoundException("The given key was not present in the cache.");
}
/// <summary>
/// Does the out op.
/// </summary>
private bool DoOutOp<T1>(CacheOp op, T1 x)
{
return DoOutInOpX((int) op, w =>
{
w.Write(x);
}, ReadException);
}
/// <summary>
/// Does the out op.
/// </summary>
private bool DoOutOp<T1, T2>(CacheOp op, T1 x, T2 y)
{
return DoOutInOpX((int) op, w =>
{
w.Write(x);
w.Write(y);
}, ReadException);
}
/// <summary>
/// Does the out op.
/// </summary>
private bool DoOutOp<T1, T2, T3>(CacheOp op, T1 x, T2 y, T3 z)
{
return DoOutInOpX((int) op, w =>
{
w.Write(x);
w.Write(y);
w.Write(z);
}, ReadException);
}
/// <summary>
/// Does the out op.
/// </summary>
private bool DoOutOp(CacheOp op, Action<BinaryWriter> write)
{
return DoOutInOpX((int) op, write, ReadException);
}
/// <summary>
/// Does the out-in op.
/// </summary>
private CacheResult<TV> DoOutInOpNullable(CacheOp cacheOp, TK x)
{
return DoOutInOpX((int)cacheOp,
w => w.Write(x),
(stream, res) => res == True ? new CacheResult<TV>(Unmarshal<TV>(stream)) : new CacheResult<TV>(),
ReadException);
}
/// <summary>
/// Does the out-in op.
/// </summary>
private CacheResult<TV> DoOutInOpNullable<T1, T2>(CacheOp cacheOp, T1 x, T2 y)
{
return DoOutInOpX((int)cacheOp,
w =>
{
w.Write(x);
w.Write(y);
},
(stream, res) => res == True ? new CacheResult<TV>(Unmarshal<TV>(stream)) : new CacheResult<TV>(),
ReadException);
}
/** <inheritdoc /> */
public void Enter(long id)
{
DoOutInOp((int) CacheOp.EnterLock, id);
}
/** <inheritdoc /> */
public bool TryEnter(long id, TimeSpan timeout)
{
return DoOutOp((int) CacheOp.TryEnterLock, (IBinaryStream s) =>
{
s.WriteLong(id);
s.WriteLong((long) timeout.TotalMilliseconds);
}) == True;
}
/** <inheritdoc /> */
public void Exit(long id)
{
DoOutInOp((int) CacheOp.ExitLock, id);
}
/** <inheritdoc /> */
public void Close(long id)
{
DoOutInOp((int) CacheOp.CloseLock, id);
}
/// <summary>
/// Starts a transaction when applicable.
/// </summary>
private void StartTx()
{
if (_txManager != null)
_txManager.StartTx();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;
using Xunit;
namespace System.Reflection.Emit.Tests
{
public class MethodBuilderDefineParameter1b
{
private const int MinStringLength = 1;
private const int MaxStringLength = 256;
private const string TestDynamicAssemblyName = "TestDynamicAssembly";
private const string TestDynamicModuleName = "TestDynamicModule";
private const string TestDynamicTypeName = "TestDynamicType";
private const string PosTestDynamicMethodName = "PosDynamicMethod";
private const string NegTestDynamicMethodName = "NegDynamicMethod";
private const AssemblyBuilderAccess TestAssemblyBuilderAccess = AssemblyBuilderAccess.Run;
private const MethodAttributes TestMethodAttributes = MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual;
private TypeBuilder GetTestTypeBuilder()
{
AssemblyName assemblyName = new AssemblyName(TestDynamicAssemblyName);
AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(
assemblyName, TestAssemblyBuilderAccess);
ModuleBuilder moduleBuilder = TestLibrary.Utilities.GetModuleBuilder(assemblyBuilder, TestDynamicModuleName);
return moduleBuilder.DefineType(TestDynamicTypeName, TypeAttributes.Abstract);
}
[Fact]
public void TestWithHasDefault()
{
string strParamName = null;
strParamName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength);
Type[] paramTypes = new Type[] { typeof(int) };
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(
PosTestDynamicMethodName,
TestMethodAttributes,
typeof(void),
paramTypes);
ParameterBuilder paramBuilder = builder.DefineParameter(
1,
ParameterAttributes.HasDefault,
strParamName);
Assert.NotNull(paramBuilder);
VerifyParameterBuilder(paramBuilder, strParamName, ParameterAttributes.HasDefault, 1);
}
[Fact]
public void TestForEveryParameterAtributeFlag()
{
string strParamName = null;
ParameterAttributes[] attributes = new ParameterAttributes[] {
ParameterAttributes.HasDefault,
ParameterAttributes.HasFieldMarshal,
ParameterAttributes.In,
ParameterAttributes.None,
ParameterAttributes.Optional,
ParameterAttributes.Out,
ParameterAttributes.Retval
};
Type[] paramTypes = new Type[attributes.Length];
for (int i = 0; i < paramTypes.Length; ++i)
{
paramTypes[i] = typeof(int);
}
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(
PosTestDynamicMethodName,
TestMethodAttributes,
typeof(void),
paramTypes);
for (int i = 1; i < attributes.Length; ++i)
{
strParamName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength);
ParameterBuilder paramBuilder = builder.DefineParameter(i, attributes[i], strParamName);
Assert.NotNull(paramBuilder);
VerifyParameterBuilder(paramBuilder, strParamName, attributes[i], i);
}
}
[Fact]
public void TestForCombinationOfParamterAttributeFlags()
{
string strParamName = null;
strParamName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength);
Type[] paramTypes = new Type[] { typeof(int) };
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(
PosTestDynamicMethodName,
TestMethodAttributes,
typeof(void),
paramTypes);
ParameterAttributes attribute =
ParameterAttributes.HasDefault |
ParameterAttributes.HasFieldMarshal |
ParameterAttributes.In |
ParameterAttributes.None |
ParameterAttributes.Optional |
ParameterAttributes.Out |
ParameterAttributes.Retval;
ParameterBuilder paramBuilder = builder.DefineParameter(
1,
attribute,
strParamName);
Assert.NotNull(paramBuilder);
VerifyParameterBuilder(paramBuilder, strParamName, attribute, 1);
}
[Fact]
public void TestForNegativeFlag()
{
string strParamName = null;
strParamName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength);
Type[] paramTypes = new Type[] { typeof(int) };
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(
PosTestDynamicMethodName,
TestMethodAttributes,
typeof(void),
paramTypes);
ParameterBuilder paramBuilder = builder.DefineParameter(
1,
(ParameterAttributes)(-1),
strParamName);
}
[Fact]
public void TestThrowsExceptionWithNoParameter()
{
string strParamName = null;
strParamName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength);
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(
PosTestDynamicMethodName,
TestMethodAttributes);
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
ParameterBuilder paramBuilder = builder.DefineParameter(1, ParameterAttributes.HasDefault, strParamName);
});
}
[Fact]
public void TestThrowsExceptionForNegativePosition()
{
string strParamName = null;
int paramPos = 0;
strParamName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength);
paramPos = TestLibrary.Generator.GetInt32();
if (paramPos > 0)
{
paramPos = 0 - paramPos;
}
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(
PosTestDynamicMethodName,
TestMethodAttributes);
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
ParameterBuilder paramBuilder = builder.DefineParameter(paramPos, ParameterAttributes.HasDefault, strParamName);
});
}
[Fact]
public void TestThrowsExceptionForPositionGreaterThanNumberOfParameters()
{
string strParamName = null;
int paramPos = 0;
strParamName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength);
Type[] paramTypes = new Type[] {
typeof(int)
};
while (paramPos < paramTypes.Length)
{
paramPos = TestLibrary.Generator.GetInt32();
}
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(
PosTestDynamicMethodName,
TestMethodAttributes,
typeof(void),
paramTypes);
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
ParameterBuilder paramBuilder = builder.DefineParameter(paramPos, ParameterAttributes.HasDefault, strParamName);
});
}
[Fact]
public void TestThrowsExceptionForCreateTypeCalled()
{
string strParamName = null;
strParamName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength);
Type[] paramTypes = new Type[] {
typeof(int)
};
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(
PosTestDynamicMethodName,
TestMethodAttributes,
typeof(void),
paramTypes);
typeBuilder.CreateTypeInfo().AsType();
Assert.Throws<InvalidOperationException>(() =>
{
ParameterBuilder paramBuilder = builder.DefineParameter(1, ParameterAttributes.HasDefault, strParamName);
});
}
private void VerifyParameterBuilder(
ParameterBuilder actualBuilder,
string desiredName,
ParameterAttributes desiredAttributes,
int desiredPosition)
{
const int ReservedMaskParameterAttribute = 0xF000; // This constant maps to ParameterAttributes.ReservedMask that is not available in the contract.
Assert.Equal(desiredName, actualBuilder.Name);
int removedReservedAttributes = (int)desiredAttributes & ~ReservedMaskParameterAttribute;
Assert.Equal((int)removedReservedAttributes, (actualBuilder.Attributes & (int)removedReservedAttributes));
Assert.Equal(desiredPosition, actualBuilder.Position);
}
}
}
| |
//
// Author:
// Jb Evain ([email protected])
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.Collections.Generic;
using System.Text;
using Mono.Cecil.PE;
using RVA = System.UInt32;
namespace Mono.Cecil.Metadata {
sealed class TableHeapBuffer : HeapBuffer {
readonly ModuleDefinition module;
readonly MetadataBuilder metadata;
readonly internal TableInformation [] table_infos = new TableInformation [Mixin.TableCount];
readonly internal MetadataTable [] tables = new MetadataTable [Mixin.TableCount];
bool large_string;
bool large_blob;
bool large_guid;
readonly int [] coded_index_sizes = new int [Mixin.CodedIndexCount];
readonly Func<Table, int> counter;
internal uint [] string_offsets;
public override bool IsEmpty {
get { return false; }
}
public TableHeapBuffer (ModuleDefinition module, MetadataBuilder metadata)
: base (24)
{
this.module = module;
this.metadata = metadata;
this.counter = GetTableLength;
}
int GetTableLength (Table table)
{
return (int) table_infos [(int) table].Length;
}
public TTable GetTable<TTable> (Table table) where TTable : MetadataTable, new ()
{
var md_table = (TTable) tables [(int) table];
if (md_table != null)
return md_table;
md_table = new TTable ();
tables [(int) table] = md_table;
return md_table;
}
public void WriteBySize (uint value, int size)
{
if (size == 4)
WriteUInt32 (value);
else
WriteUInt16 ((ushort) value);
}
public void WriteBySize (uint value, bool large)
{
if (large)
WriteUInt32 (value);
else
WriteUInt16 ((ushort) value);
}
public void WriteString (uint @string)
{
WriteBySize (string_offsets [@string], large_string);
}
public void WriteBlob (uint blob)
{
WriteBySize (blob, large_blob);
}
public void WriteGuid (uint guid)
{
WriteBySize (guid, large_guid);
}
public void WriteRID (uint rid, Table table)
{
WriteBySize (rid, table_infos [(int) table].IsLarge);
}
int GetCodedIndexSize (CodedIndex coded_index)
{
var index = (int) coded_index;
var size = coded_index_sizes [index];
if (size != 0)
return size;
return coded_index_sizes [index] = coded_index.GetSize (counter);
}
public void WriteCodedRID (uint rid, CodedIndex coded_index)
{
WriteBySize (rid, GetCodedIndexSize (coded_index));
}
public void WriteTableHeap ()
{
WriteUInt32 (0); // Reserved
WriteByte (GetTableHeapVersion ()); // MajorVersion
WriteByte (0); // MinorVersion
WriteByte (GetHeapSizes ()); // HeapSizes
WriteByte (10); // Reserved2
WriteUInt64 (GetValid ()); // Valid
WriteUInt64 (0xc416003301fa00); // Sorted
WriteRowCount ();
WriteTables ();
}
void WriteRowCount ()
{
for (int i = 0; i < tables.Length; i++) {
var table = tables [i];
if (table == null || table.Length == 0)
continue;
WriteUInt32 ((uint) table.Length);
}
}
void WriteTables ()
{
for (int i = 0; i < tables.Length; i++) {
var table = tables [i];
if (table == null || table.Length == 0)
continue;
table.Write (this);
}
}
ulong GetValid ()
{
ulong valid = 0;
for (int i = 0; i < tables.Length; i++) {
var table = tables [i];
if (table == null || table.Length == 0)
continue;
table.Sort ();
valid |= (1UL << i);
}
return valid;
}
public void ComputeTableInformations ()
{
if (metadata.metadata_builder != null)
ComputeTableInformations (metadata.metadata_builder.table_heap);
ComputeTableInformations (metadata.table_heap);
}
void ComputeTableInformations (TableHeapBuffer table_heap)
{
var tables = table_heap.tables;
for (int i = 0; i < tables.Length; i++) {
var table = tables [i];
if (table != null && table.Length > 0)
table_infos [i].Length = (uint) table.Length;
}
}
byte GetHeapSizes ()
{
byte heap_sizes = 0;
if (metadata.string_heap.IsLarge) {
large_string = true;
heap_sizes |= 0x01;
}
if (metadata.guid_heap.IsLarge) {
large_guid = true;
heap_sizes |= 0x02;
}
if (metadata.blob_heap.IsLarge) {
large_blob = true;
heap_sizes |= 0x04;
}
return heap_sizes;
}
byte GetTableHeapVersion ()
{
switch (module.Runtime) {
case TargetRuntime.Net_1_0:
case TargetRuntime.Net_1_1:
return 1;
default:
return 2;
}
}
public void FixupData (RVA data_rva)
{
var table = GetTable<FieldRVATable> (Table.FieldRVA);
if (table.length == 0)
return;
var field_idx_size = GetTable<FieldTable> (Table.Field).IsLarge ? 4 : 2;
var previous = this.position;
base.position = table.position;
for (int i = 0; i < table.length; i++) {
var rva = ReadUInt32 ();
base.position -= 4;
WriteUInt32 (rva + data_rva);
base.position += field_idx_size;
}
base.position = previous;
}
}
sealed class ResourceBuffer : ByteBuffer {
public ResourceBuffer ()
: base (0)
{
}
public uint AddResource (byte [] resource)
{
var offset = (uint) this.position;
WriteInt32 (resource.Length);
WriteBytes (resource);
return offset;
}
}
sealed class DataBuffer : ByteBuffer {
int buffer_align = 4;
public DataBuffer ()
: base (0)
{
}
void Align (int align)
{
align--;
// Compute the number of bytes to align the current position.
// Values of 0 will be written.
WriteBytes (((position + align) & ~align) - position);
}
public RVA AddData (byte [] data, int align)
{
if (buffer_align < align)
buffer_align = align;
Align (align);
var rva = (RVA) position;
WriteBytes (data);
return rva;
}
public int BufferAlign => buffer_align;
}
abstract class HeapBuffer : ByteBuffer {
public bool IsLarge {
get { return base.length > 65535; }
}
public abstract bool IsEmpty { get; }
protected HeapBuffer (int length)
: base (length)
{
}
}
sealed class GuidHeapBuffer : HeapBuffer {
readonly Dictionary<Guid, uint> guids = new Dictionary<Guid, uint> ();
public override bool IsEmpty {
get { return length == 0; }
}
public GuidHeapBuffer ()
: base (16)
{
}
public uint GetGuidIndex (Guid guid)
{
uint index;
if (guids.TryGetValue (guid, out index))
return index;
index = (uint) guids.Count + 1;
WriteGuid (guid);
guids.Add (guid, index);
return index;
}
void WriteGuid (Guid guid)
{
WriteBytes (guid.ToByteArray ());
}
}
class StringHeapBuffer : HeapBuffer {
protected Dictionary<string, uint> strings = new Dictionary<string, uint> (StringComparer.Ordinal);
public sealed override bool IsEmpty {
get { return length <= 1; }
}
public StringHeapBuffer ()
: base (1)
{
WriteByte (0);
}
public virtual uint GetStringIndex (string @string)
{
uint index;
if (strings.TryGetValue (@string, out index))
return index;
index = (uint) strings.Count + 1;
strings.Add (@string, index);
return index;
}
public uint [] WriteStrings ()
{
var sorted = SortStrings (strings);
strings = null;
// Add 1 for empty string whose index and offset are both 0
var string_offsets = new uint [sorted.Count + 1];
string_offsets [0] = 0;
// Find strings that can be folded
var previous = string.Empty;
foreach (var entry in sorted) {
var @string = entry.Key;
var index = entry.Value;
var position = base.position;
if (previous.EndsWith (@string, StringComparison.Ordinal) && !IsLowSurrogateChar (entry.Key [0])) {
// Map over the tail of prev string. Watch for null-terminator of prev string.
string_offsets [index] = (uint) (position - (Encoding.UTF8.GetByteCount (entry.Key) + 1));
} else {
string_offsets [index] = (uint) position;
WriteString (@string);
}
previous = entry.Key;
}
return string_offsets;
}
static List<KeyValuePair<string, uint>> SortStrings (Dictionary<string, uint> strings)
{
var sorted = new List<KeyValuePair<string, uint>> (strings);
sorted.Sort (new SuffixSort ());
return sorted;
}
static bool IsLowSurrogateChar (int c)
{
return unchecked((uint)(c - 0xDC00)) <= 0xDFFF - 0xDC00;
}
protected virtual void WriteString (string @string)
{
WriteBytes (Encoding.UTF8.GetBytes (@string));
WriteByte (0);
}
// Sorts strings such that a string is followed immediately by all strings
// that are a suffix of it.
private class SuffixSort : IComparer<KeyValuePair<string, uint>> {
public int Compare(KeyValuePair<string, uint> xPair, KeyValuePair<string, uint> yPair)
{
var x = xPair.Key;
var y = yPair.Key;
for (int i = x.Length - 1, j = y.Length - 1; i >= 0 & j >= 0; i--, j--) {
if (x [i] < y [j]) {
return -1;
}
if (x [i] > y [j]) {
return +1;
}
}
return y.Length.CompareTo (x.Length);
}
}
}
sealed class BlobHeapBuffer : HeapBuffer {
readonly Dictionary<ByteBuffer, uint> blobs = new Dictionary<ByteBuffer, uint> (new ByteBufferEqualityComparer ());
public override bool IsEmpty {
get { return length <= 1; }
}
public BlobHeapBuffer ()
: base (1)
{
WriteByte (0);
}
public uint GetBlobIndex (ByteBuffer blob)
{
uint index;
if (blobs.TryGetValue (blob, out index))
return index;
index = (uint) base.position;
WriteBlob (blob);
blobs.Add (blob, index);
return index;
}
void WriteBlob (ByteBuffer blob)
{
WriteCompressedUInt32 ((uint) blob.length);
WriteBytes (blob);
}
}
sealed class UserStringHeapBuffer : StringHeapBuffer {
public override uint GetStringIndex (string @string)
{
uint index;
if (strings.TryGetValue (@string, out index))
return index;
index = (uint) base.position;
WriteString (@string);
strings.Add (@string, index);
return index;
}
protected override void WriteString (string @string)
{
WriteCompressedUInt32 ((uint) @string.Length * 2 + 1);
byte special = 0;
for (int i = 0; i < @string.Length; i++) {
var @char = @string [i];
WriteUInt16 (@char);
if (special == 1)
continue;
if (@char < 0x20 || @char > 0x7e) {
if (@char > 0x7e
|| (@char >= 0x01 && @char <= 0x08)
|| (@char >= 0x0e && @char <= 0x1f)
|| @char == 0x27
|| @char == 0x2d) {
special = 1;
}
}
}
WriteByte (special);
}
}
sealed class PdbHeapBuffer : HeapBuffer {
public override bool IsEmpty {
get { return false; }
}
public PdbHeapBuffer ()
: base (0)
{
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using System.ComponentModel;
using System.Threading;
using System.Collections;
//using Newtonsoft.Json;
//using Newtonsoft.Json.Linq;
using PubNubMessaging.Core;
namespace PubNubMessaging.Tests
{
[TestFixture]
public class WhenSubscribedToAChannelGroup
{
ManualResetEvent subscribeManualEvent = new ManualResetEvent(false);
ManualResetEvent grantManualEvent = new ManualResetEvent(false);
ManualResetEvent mePublish = new ManualResetEvent(false);
bool receivedMessage = false;
bool receivedGrantMessage = false;
bool receivedChannelGroupMessage = false;
bool receivedMessage1 = false;
bool receivedMessage2 = false;
bool receivedChannelGroupMessage1 = false;
bool receivedChannelGroupMessage2 = false;
string currentUnitTestCase = "";
string channelGroupName = "hello_my_group";
string channelGroupName1 = "hello_my_group1";
string channelGroupName2 = "hello_my_group2";
int expectedCallbackResponses = 2;
int currentCallbackResponses = 0;
int manualResetEventsWaitTimeout = 310 * 1000;
Pubnub pubnub = null;
[TestFixtureSetUp]
public void Init()
{
if (!PubnubCommon.PAMEnabled) return;
currentUnitTestCase = "Init";
receivedGrantMessage = false;
pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, PubnubCommon.SecretKey, "", false);
PubnubUnitTest unitTest = new PubnubUnitTest();
unitTest.TestClassName = "GrantRequestUnitTest";
unitTest.TestCaseName = "Init3";
pubnub.PubnubUnitTest = unitTest;
grantManualEvent = new ManualResetEvent(false);
pubnub.ChannelGroupGrantAccess<string>(channelGroupName, true, true, 20, ThenChannelGroupInitializeShouldReturnGrantMessage, DummySubscribeErrorCallback);
Thread.Sleep(1000);
grantManualEvent.WaitOne(310*1000);
grantManualEvent = new ManualResetEvent(false);
pubnub.ChannelGroupGrantAccess<string>(channelGroupName1, true, true, 20, ThenChannelGroupInitializeShouldReturnGrantMessage, DummySubscribeErrorCallback);
Thread.Sleep(1000);
grantManualEvent.WaitOne(310 * 1000);
grantManualEvent = new ManualResetEvent(false);
pubnub.ChannelGroupGrantAccess<string>(channelGroupName2, true, true, 20, ThenChannelGroupInitializeShouldReturnGrantMessage, DummySubscribeErrorCallback);
Thread.Sleep(1000);
grantManualEvent.WaitOne(310 * 1000);
pubnub.EndPendingRequests();
pubnub.PubnubUnitTest = null;
pubnub = null;
Assert.IsTrue(receivedGrantMessage, "WhenSubscribedToAChannelGroup Grant access failed.");
}
[Test]
public void ThenSubscribeShouldReturnReceivedMessage()
{
currentUnitTestCase = "ThenSubscribeShouldReturnReceivedMessage";
receivedMessage = false;
pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, "", "", false);
pubnub.SessionUUID = "myuuid";
PubnubUnitTest unitTest = new PubnubUnitTest();
unitTest.TestClassName = "WhenSubscribedToAChannelGroup";
unitTest.TestCaseName = "ThenSubscribeShouldReturnReceivedMessage";
pubnub.PubnubUnitTest = unitTest;
channelGroupName = "hello_my_group";
string channelName = "hello_my_channel";
subscribeManualEvent = new ManualResetEvent(false);
pubnub.AddChannelsToChannelGroup<string>(new string[] { channelName }, channelGroupName, ChannelGroupAddCallback, DummySubscribeErrorCallback);
subscribeManualEvent.WaitOne(manualResetEventsWaitTimeout);
if (receivedChannelGroupMessage)
{
subscribeManualEvent = new ManualResetEvent(false);
pubnub.Subscribe<string>("", channelGroupName, ReceivedMessageCallbackWhenSubscribed, SubscribeConnectCallback, DummySubscribeErrorCallback);
Thread.Sleep(1000);
pubnub.Publish<string>(channelName, "Test for WhenSubscribedToAChannelGroup ThenItShouldReturnReceivedMessage", dummyPublishCallback, DummyPublishErrorCallback);
manualResetEventsWaitTimeout = (unitTest.EnableStubTest) ? 1000 : 310 * 1000;
mePublish.WaitOne(manualResetEventsWaitTimeout);
subscribeManualEvent.WaitOne(manualResetEventsWaitTimeout);
subscribeManualEvent = new ManualResetEvent(false);
pubnub.Unsubscribe<string>("", channelGroupName, dummyUnsubscribeCallback, SubscribeConnectCallback, UnsubscribeDummyMethodForDisconnectCallback, DummySubscribeErrorCallback);
subscribeManualEvent.WaitOne(manualResetEventsWaitTimeout);
pubnub.EndPendingRequests();
pubnub.PubnubUnitTest = null;
pubnub = null;
Assert.IsTrue(receivedMessage, "WhenSubscribedToAChannelGroup --> ThenItShouldReturnReceivedMessage Failed");
}
else
{
Assert.IsTrue(receivedChannelGroupMessage, "WhenSubscribedToAChannelGroup --> ThenItShouldReturnReceivedMessage Failed");
}
}
[Test]
public void ThenSubscribeShouldReturnConnectStatus()
{
currentUnitTestCase = "ThenSubscribeShouldReturnConnectStatus";
receivedMessage = false;
pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, "", "", false);
pubnub.SessionUUID = "myuuid";
PubnubUnitTest unitTest = new PubnubUnitTest();
unitTest.TestClassName = "WhenSubscribedToAChannelGroup";
unitTest.TestCaseName = "ThenSubscribeShouldReturnConnectStatus";
pubnub.PubnubUnitTest = unitTest;
channelGroupName = "hello_my_group";
string channelName = "hello_my_channel";
subscribeManualEvent = new ManualResetEvent(false);
pubnub.AddChannelsToChannelGroup<string>(new string[] { channelName }, channelGroupName, ChannelGroupAddCallback, DummySubscribeErrorCallback);
subscribeManualEvent.WaitOne(manualResetEventsWaitTimeout);
if (receivedChannelGroupMessage)
{
subscribeManualEvent = new ManualResetEvent(false);
pubnub.Subscribe<string>("", channelGroupName, ReceivedMessageCallbackWhenSubscribed, SubscribeConnectCallback, DummySubscribeErrorCallback);
Thread.Sleep(1000);
manualResetEventsWaitTimeout = (unitTest.EnableStubTest) ? 1000 : 310 * 1000;
subscribeManualEvent.WaitOne(manualResetEventsWaitTimeout);
pubnub.EndPendingRequests();
pubnub.PubnubUnitTest = null;
pubnub = null;
Assert.IsTrue(receivedMessage, "WhenSubscribedToAChannelGroup --> ThenSubscribeShouldReturnConnectStatus Failed");
}
else
{
Assert.IsTrue(receivedChannelGroupMessage, "WhenSubscribedToAChannelGroup --> ThenSubscribeShouldReturnConnectStatus Failed");
}
}
[Test]
public void ThenMultiSubscribeShouldReturnConnectStatus()
{
currentUnitTestCase = "ThenMultiSubscribeShouldReturnConnectStatus";
receivedMessage = false;
receivedChannelGroupMessage1 = false;
receivedChannelGroupMessage2 = false;
expectedCallbackResponses = 2;
currentCallbackResponses = 0;
pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, "", "", false);
pubnub.SessionUUID = "myuuid";
PubnubUnitTest unitTest = new PubnubUnitTest();
unitTest.TestClassName = "WhenSubscribedToAChannelGroup";
unitTest.TestCaseName = "ThenMultiSubscribeShouldReturnConnectStatus";
pubnub.PubnubUnitTest = unitTest;
manualResetEventsWaitTimeout = (unitTest.EnableStubTest) ? 6000 : 310 * 1000;
channelGroupName1 = "hello_my_group1";
channelGroupName2 = "hello_my_group2";
string channelName1 = "hello_my_channel1";
string channelName2 = "hello_my_channel2";
string channel1 = "hello_my_channel1";
subscribeManualEvent = new ManualResetEvent(false);
pubnub.AddChannelsToChannelGroup<string>(new string[] { channelName1 }, channelGroupName1, ChannelGroupAddCallback, DummySubscribeErrorCallback);
Thread.Sleep(1000);
subscribeManualEvent.WaitOne(manualResetEventsWaitTimeout);
subscribeManualEvent = new ManualResetEvent(false);
pubnub.AddChannelsToChannelGroup<string>(new string[] { channelName2 }, channelGroupName2, ChannelGroupAddCallback, DummySubscribeErrorCallback);
Thread.Sleep(1000);
subscribeManualEvent.WaitOne(manualResetEventsWaitTimeout);
if (receivedChannelGroupMessage1 && receivedChannelGroupMessage2)
{
subscribeManualEvent = new ManualResetEvent(false);
pubnub.Subscribe<string>("", string.Format("{0},{1}", channelGroupName1, channelGroupName2), ReceivedMessageCallbackWhenSubscribed, SubscribeConnectCallback, DummySubscribeErrorCallback);
subscribeManualEvent.WaitOne(manualResetEventsWaitTimeout);
pubnub.EndPendingRequests();
pubnub.PubnubUnitTest = null;
pubnub = null;
Assert.IsTrue(receivedMessage, "WhenSubscribedToAChannelGroup --> ThenMultiSubscribeShouldReturnConnectStatusFailed");
}
else
{
Assert.IsTrue(receivedChannelGroupMessage1 && receivedChannelGroupMessage2, "WhenSubscribedToAChannelGroup --> ThenMultiSubscribeShouldReturnConnectStatusFailed");
}
}
private void ReceivedMessageCallbackWhenSubscribed(string result)
{
Console.WriteLine(string.Format("ReceivedMessageCallbackWhenSubscribed = {0}", result));
if (currentUnitTestCase == "ThenMultiSubscribeShouldReturnConnectStatus")
{
return;
}
if (!string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(result.Trim()))
{
List<object> deserializedMessage = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(result);
if (deserializedMessage != null && deserializedMessage.Count > 0)
{
object subscribedObject = (object)deserializedMessage[0];
if (subscribedObject != null)
{
receivedMessage = true;
}
}
}
subscribeManualEvent.Set();
}
void ChannelGroupAddCallback(string receivedMessage)
{
try
{
Console.WriteLine(string.Format("ChannelGroupAddCallback = {0}", receivedMessage));
if (!string.IsNullOrEmpty(receivedMessage) && !string.IsNullOrEmpty(receivedMessage.Trim()))
{
List<object> serializedMessage = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(receivedMessage);
if (serializedMessage != null && serializedMessage.Count > 0)
{
Dictionary<string, object> dictionary = pubnub.JsonPluggableLibrary.ConvertToDictionaryObject(serializedMessage[0]);
if (dictionary != null)
{
int statusCode = Convert.ToInt32(dictionary["status"]);
string serviceType = dictionary["service"].ToString();
bool errorStatus = (bool)dictionary["error"];
string currentChannelGroup = serializedMessage[1].ToString().Substring(1); //assuming no namespace for channel group
string statusMessage = dictionary["message"].ToString();
if (statusCode == 200 && statusMessage.ToLower() == "ok" && serviceType == "channel-registry" && !errorStatus)
{
if (currentUnitTestCase == "ThenMultiSubscribeShouldReturnConnectStatus")
{
if (currentChannelGroup == channelGroupName1)
{
receivedChannelGroupMessage1 = true;
}
else if (currentChannelGroup == channelGroupName2)
{
receivedChannelGroupMessage2 = true;
}
}
else
{
if (currentChannelGroup == channelGroupName)
{
receivedChannelGroupMessage = true;
}
}
}
}
}
}
}
catch { }
finally
{
subscribeManualEvent.Set();
}
}
void SubscribeConnectCallback(string result)
{
if (currentUnitTestCase == "ThenSubscribeShouldReturnConnectStatus")
{
if (!string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(result.Trim()))
{
List<object> deserializedMessage = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(result);
if (deserializedMessage != null && deserializedMessage.Count > 0)
{
long statusCode = Int64.Parse(deserializedMessage[0].ToString());
string statusMessage = (string)deserializedMessage[1];
if (statusCode == 1 && statusMessage.ToLower() == "connected")
{
receivedMessage = true;
}
}
}
subscribeManualEvent.Set();
}
else if (currentUnitTestCase == "ThenMultiSubscribeShouldReturnConnectStatus")
{
if (!string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(result.Trim()))
{
List<object> deserializedMessage = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(result);
if (deserializedMessage != null && deserializedMessage.Count > 0)
{
long statusCode = Int64.Parse(deserializedMessage[0].ToString());
string statusMessage = (string)deserializedMessage[1];
if (statusCode == 1 && statusMessage.ToLower() == "connected")
{
currentCallbackResponses = currentCallbackResponses + 1;
if (expectedCallbackResponses == currentCallbackResponses)
{
receivedMessage = true;
}
}
}
}
if (expectedCallbackResponses == currentCallbackResponses)
{
subscribeManualEvent.Set();
}
}
}
void ThenChannelGroupInitializeShouldReturnGrantMessage(string receivedMessage)
{
try
{
if (!string.IsNullOrEmpty(receivedMessage) && !string.IsNullOrEmpty(receivedMessage.Trim()))
{
List<object> serializedMessage = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(receivedMessage);
if (serializedMessage != null && serializedMessage.Count > 0)
{
Dictionary<string, object> dictionary = pubnub.JsonPluggableLibrary.ConvertToDictionaryObject(serializedMessage[0]);
if (dictionary != null)
{
var status = dictionary["status"].ToString();
if (status == "200")
{
receivedGrantMessage = true;
}
}
}
}
}
catch { }
finally
{
grantManualEvent.Set();
}
}
private void DummySubscribeErrorCallback(PubnubClientError result)
{
Console.WriteLine(result.ToString());
if (currentUnitTestCase == "Init")
{
grantManualEvent.Set();
}
else
{
subscribeManualEvent.Set();
}
}
private void dummyPublishCallback(string result)
{
Console.WriteLine("dummyPublishCallback -> result = " + result);
mePublish.Set();
}
private void DummyPublishErrorCallback(PubnubClientError result)
{
mePublish.Set();
}
private void dummyUnsubscribeCallback(string result)
{
}
void UnsubscribeDummyMethodForDisconnectCallback(string receivedMessage)
{
subscribeManualEvent.Set();
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Region.CoreModules.Capabilities;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.OptionalModules.Avatar.FlexiGroups
{
public class XmlRpcGroupsMessaging : ISharedRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private List<Scene> m_sceneList = new List<Scene>();
private IMessageTransferModule m_msgTransferModule = null;
private IGroupsModule m_groupsModule = null;
// TODO: Move this off to the xmlrpc server
private object m_sessionLock = new object();
private Dictionary<Guid, List<Guid>> m_agentsInGroupSession = new Dictionary<Guid, List<Guid>>();
private Dictionary<Guid, List<Guid>> m_agentsDroppedSession = new Dictionary<Guid, List<Guid>>();
// Config Options
private bool m_groupMessagingEnabled = false;
private bool m_debugEnabled = true;
#region IRegionModuleBase Members
public void Initialize(IConfigSource config)
{
IConfig groupsConfig = config.Configs["Groups"];
if (groupsConfig == null)
{
// Do not run this module by default.
return;
}
else
{
if (!groupsConfig.GetBoolean("Enabled", false))
{
return;
}
if (groupsConfig.GetString("Module", "Default") != "FlexiGroups")
{
m_groupMessagingEnabled = false;
return;
}
m_groupMessagingEnabled = groupsConfig.GetBoolean("XmlRpcMessagingEnabled", true);
if (!m_groupMessagingEnabled)
{
return;
}
m_log.Info("[GROUPS-MESSAGING]: Initializing XmlRpcGroupsMessaging");
m_debugEnabled = groupsConfig.GetBoolean("XmlRpcDebugEnabled", true);
}
m_log.Info("[GROUPS-MESSAGING]: XmlRpcGroupsMessaging starting up");
}
public void AddRegion(Scene scene)
{
// NoOp
}
public void RegionLoaded(Scene scene)
{
if (!m_groupMessagingEnabled)
return;
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
m_groupsModule = scene.RequestModuleInterface<IGroupsModule>();
// No groups module, no groups messaging
if (m_groupsModule == null)
{
m_log.Error("[GROUPS-MESSAGING]: Could not get IGroupsModule, XmlRpcGroupsMessaging is now disabled.");
Close();
m_groupMessagingEnabled = false;
return;
}
m_msgTransferModule = scene.RequestModuleInterface<IMessageTransferModule>();
// No message transfer module, no groups messaging
if (m_msgTransferModule == null)
{
m_log.Error("[GROUPS-MESSAGING]: Could not get MessageTransferModule");
Close();
m_groupMessagingEnabled = false;
return;
}
m_sceneList.Add(scene);
scene.EventManager.OnNewClient += OnNewClient;
scene.EventManager.OnRemovePresence += OnRemovePresence;
scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage;
}
public void RemoveRegion(Scene scene)
{
if (!m_groupMessagingEnabled)
return;
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
m_sceneList.Remove(scene);
}
public void Close()
{
if (!m_groupMessagingEnabled)
return;
if (m_debugEnabled) m_log.Debug("[GROUPS-MESSAGING]: Shutting down XmlRpcGroupsMessaging module.");
foreach (Scene scene in m_sceneList)
{
scene.EventManager.OnNewClient -= OnNewClient;
scene.EventManager.OnIncomingInstantMessage -= OnGridInstantMessage;
}
m_sceneList.Clear();
m_groupsModule = null;
m_msgTransferModule = null;
}
public string Name
{
get { return "XmlRpcGroupsMessaging"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
#region ISharedRegionModule Members
public void PostInitialize()
{
// NoOp
}
#endregion
#region SimGridEventHandlers
private void OnNewClient(IClientAPI client)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: OnInstantMessage registered for {0}", client.Name);
client.OnInstantMessage += OnInstantMessage;
}
private void OnRemovePresence(UUID agentId)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: OnRemovePresence registered for {0}", agentId.ToString());
RemoveAgentFromAllGroupSessions(agentId.Guid);
}
private void OnGridInstantMessage(GridInstantMessage msg)
{
// The instant message module will only deliver messages of dialog types:
// MessageFromAgent, StartTyping, StopTyping, MessageFromObject
//
// Any other message type will not be delivered to a client by the
// Instant Message Module
if (m_debugEnabled)
{
m_log.DebugFormat("[GROUPS-MESSAGING]: {0} called with {1}", System.Reflection.MethodBase.GetCurrentMethod().Name,msg.dialog);
DebugGridInstantMessage(msg);
}
// Incoming message from a group
if ((msg.fromGroup == true) &&
((msg.dialog == (byte)InstantMessageDialog.SessionSend)
|| (msg.dialog == (byte)InstantMessageDialog.SessionAdd)
|| (msg.dialog == (byte)InstantMessageDialog.SessionDrop)))
{
ProcessMessageFromGroupSession(msg);
}
}
private void ProcessMessageFromGroupSession(GridInstantMessage msg)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Session message from {0} going to agent {1}", msg.fromAgentName, msg.toAgentID);
switch (msg.dialog)
{
case (byte)InstantMessageDialog.SessionAdd:
AddAgentToGroupSession(msg.fromAgentID, msg.imSessionID);
NotifyNewSessionUserOfExisting(msg.imSessionID, msg.fromAgentID);
NotifySessionUserTransition(msg.imSessionID, msg.fromAgentID, msg.dialog);
break;
case (byte)InstantMessageDialog.SessionDrop:
RemoveAgentFromGroupSession(msg.fromAgentID, msg.imSessionID);
NotifySessionUserTransition(msg.imSessionID, msg.fromAgentID, msg.dialog);
break;
case (byte)InstantMessageDialog.SessionSend:
bool needsSessionAdd = false;
bool agentDroppedSession = false;
lock (m_sessionLock)
{
needsSessionAdd = (!HasAgentBeenInvited(msg.toAgentID, msg.imSessionID)) && (!HasAgentDroppedSession(msg.toAgentID, msg.imSessionID));
agentDroppedSession = HasAgentDroppedSession(msg.toAgentID, msg.imSessionID);
}
if (needsSessionAdd)
{
// Agent not in session and hasn't dropped from session
// Add them to the session for now, and Invite them
AddAgentToGroupSession(msg.toAgentID, msg.imSessionID);
UUID toAgentID = new UUID(msg.toAgentID);
IClientAPI activeClient = GetActiveClient(toAgentID);
if (activeClient != null)
{
UUID groupID = new UUID(msg.imSessionID); // caller passes the group ID here
GroupRecord groupInfo = m_groupsModule.GetGroupRecord(groupID);
if (groupInfo != null)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Sending chatterbox invite instant message");
// UUID sessionID = new UUID(groupInfo.GroupID);
// msg.imSessionID = sessionID.Guid;
UUID sessionID = new UUID(msg.imSessionID);
// Force? open the group session dialog???
IEventQueue eq = activeClient.Scene.RequestModuleInterface<IEventQueue>();
eq.ChatterboxInvitation(
sessionID // session ID
, groupInfo.GroupName // session name
, new UUID(msg.fromAgentID) // from agent ID
, msg.message // message text
, new UUID(msg.toAgentID) // to agent ID
, msg.fromAgentName // from agent name
, msg.dialog // IM dialog type
, msg.timestamp // time stamp
, msg.offline == 1 // offline
, 0 // parent estate ID
, Vector3.Zero // agent position
, 1 // TTL
, groupID // transaction ID (caller passes the group ID here)
, msg.fromGroup // from group boolean (true)
, Utils.StringToBytes(groupInfo.GroupName) // binary bucket
);
NotifyNewSessionUserOfExisting(msg.imSessionID, msg.fromAgentID);
NotifySessionUserTransition(msg.imSessionID, msg.fromAgentID, (byte)InstantMessageDialog.SessionAdd);
((Scene)activeClient.Scene).EventManager.TriggerOnChatToClient(msg.message,
UUID.Parse(msg.fromAgentID.ToString()), UUID.Parse(msg.toAgentID.ToString()),
activeClient.Scene.RegionInfo.RegionID, msg.timestamp,
ChatToClientType.GroupMessage);
}
}
}
else if (!agentDroppedSession)
{
// User hasn't dropped, so they're in the session,
// maybe we should deliver it.
IClientAPI client = GetActiveClient(new UUID(msg.toAgentID));
if (client != null)
{
// Deliver locally, directly
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Delivering to {0} locally", client.Name);
client.SendInstantMessage(msg);
}
else
{
m_log.WarnFormat("[GROUPS-MESSAGING]: Received a message over the grid for a client that isn't here: {0}", msg.toAgentID);
}
}
break;
default:
m_log.WarnFormat("[GROUPS-MESSAGING]: I don't know how to proccess a {0} message.", ((InstantMessageDialog)msg.dialog).ToString());
break;
}
}
#endregion
#region ClientEvents
private void RemoveAgentFromGroupSession(Guid agentID, Guid sessionID)
{
// Add Session Status if it doesn't exist for this session
CreateGroupSessionTracking(sessionID); // for dropped tracking
lock (m_sessionLock)
{
if (m_agentsInGroupSession.ContainsKey(sessionID))
{
// If in session remove
if (m_agentsInGroupSession[sessionID].Contains(agentID))
{
m_agentsInGroupSession[sessionID].Remove(agentID);
}
// If not in dropped list, add
if (!m_agentsDroppedSession[sessionID].Contains(agentID))
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Dropped {0} from session {1}", agentID, sessionID);
m_agentsDroppedSession[sessionID].Add(agentID);
}
}
}
}
private void RemoveAgentFromAllGroupSessions(Guid agentID)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Dropped {0} from group IM sessions", agentID);
lock (m_sessionLock)
{
foreach (KeyValuePair<Guid, List<Guid>> session in m_agentsInGroupSession)
{
if (session.Value.Contains(agentID))
{
session.Value.Remove(agentID);
}
}
foreach (KeyValuePair<Guid, List<Guid>> session in m_agentsDroppedSession)
{
if (session.Value.Contains(agentID))
{
session.Value.Remove(agentID);
}
}
}
}
private void AddAgentToGroupSession(Guid agentID, Guid sessionID)
{
// Add Session Status if it doesn't exist for this session
CreateGroupSessionTracking(sessionID);
lock (m_sessionLock)
{
// If nessesary, remove from dropped list
if (m_agentsDroppedSession[sessionID].Contains(agentID))
{
m_agentsDroppedSession[sessionID].Remove(agentID);
}
// If nessesary, add to in session list
if (!m_agentsInGroupSession[sessionID].Contains(agentID))
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Added {1} to session {0}", sessionID, agentID);
m_agentsInGroupSession[sessionID].Add(agentID);
}
}
}
private bool HasAgentBeenInvited(Guid agentID, Guid sessionID)
{
lock (m_sessionLock)
{
if (!m_agentsInGroupSession.ContainsKey(sessionID))
return false;
return m_agentsInGroupSession[sessionID].Contains(agentID);
}
}
private bool HasAgentDroppedSession(Guid agentID, Guid sessionID)
{
lock (m_sessionLock)
{
if (!m_agentsDroppedSession.ContainsKey(sessionID))
return false;
return m_agentsDroppedSession[sessionID].Contains(agentID);
}
}
private void CreateGroupSessionTracking(Guid sessionID)
{
lock (m_sessionLock)
{
if (!m_agentsInGroupSession.ContainsKey(sessionID))
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Creating session tracking for : {0}", sessionID);
m_agentsInGroupSession.Add(sessionID, new List<Guid>());
m_agentsDroppedSession.Add(sessionID, new List<Guid>());
}
}
}
private void NotifySessionUserTransition(Guid sessionID, Guid userID, byte transition)
{
Guid[] participants;
lock (m_sessionLock)
{
if (!m_agentsInGroupSession.ContainsKey(sessionID))
return;
participants = new Guid[m_agentsInGroupSession[sessionID].Count];
m_agentsInGroupSession[sessionID].CopyTo(participants);
}
IEventQueue queue = this.m_sceneList[0].RequestModuleInterface<IEventQueue>();
foreach (Guid participant in participants)
{
// This condition disables participant list updates, except for the current user,
// because it only supports participants in the current region.
// When they support notification across regions, we can remove the condition.
if (participant != userID)
continue;
// Notify existing participant of user transition.
queue.ChatterBoxSessionAgentListUpdates(
new UUID(sessionID)
, new UUID(userID)
, new UUID(participant)
, false //canVoiceChat
, false //isModerator
, false //text mute
, transition
);
}
}
private void NotifyNewSessionUserOfExisting(Guid sessionID, Guid userID)
{
Guid[] participants;
lock (m_sessionLock)
{
if (!m_agentsInGroupSession.ContainsKey(sessionID))
return;
participants = new Guid[m_agentsInGroupSession[sessionID].Count];
m_agentsInGroupSession[sessionID].CopyTo(participants);
}
IEventQueue queue = this.m_sceneList[0].RequestModuleInterface<IEventQueue>();
foreach (Guid participant in participants)
{
// This condition disables participant list updates, except for the current user,
// because it only supports participants in the current region.
// When they support notification across regions, we can remove the condition.
if (participant != userID)
continue;
// Notify existing participant of user transition.
queue.ChatterBoxSessionAgentListUpdates(
new UUID(sessionID)
, new UUID(participant)
, new UUID(userID)
, false //canVoiceChat
, false //isModerator
, false //text mute
, (byte)InstantMessageDialog.SessionGroupStart
);
}
}
private bool CanJoinGroupIM(UUID agentID, UUID groupID)
{
GroupMembershipData data = m_groupsModule.GetMembershipData(groupID, agentID);
if (data == null)
return false;
return ((data.GroupPowers & (ulong)GroupPowers.JoinChat) == (ulong)GroupPowers.JoinChat);
}
private bool VerifyIMSecurity(IClientAPI remoteClient, UUID groupID, ref GridInstantMessage im)
{
if (!CanJoinGroupIM(remoteClient.AgentId, groupID))
{
remoteClient.SendAgentAlertMessage("You do not have permission to send an instant messaging in that group.", true);
return false;
}
if ((im.fromAgentID != remoteClient.AgentId.Guid) || (im.fromAgentName != remoteClient.Name))
{
m_log.ErrorFormat("[HACKER]: IM type {0} from {1} [{2}] misidentified as being from {3} [{4}]. Fixed.",
im.dialog.ToString(), remoteClient.AgentId, remoteClient.Name, im.fromAgentID, im.fromAgentName);
remoteClient.SendAgentAlertMessage("You are not allowed to change your identity in an instant messaging.", true);
return false;
}
return true;
}
private void OnInstantMessage(IClientAPI remoteClient, GridInstantMessage im)
{
UUID groupID = new UUID(im.imSessionID);
if (m_debugEnabled)
{
m_log.DebugFormat("[GROUPS-MESSAGING]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
DebugGridInstantMessage(im);
}
// Start group IM session
if ((im.dialog == (byte)InstantMessageDialog.SessionGroupStart))
{
GroupRecord groupInfo = m_groupsModule.GetGroupRecord(groupID);
if (groupInfo != null)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Start Group Session for {0}", groupInfo.GroupName);
im.imSessionID = groupInfo.GroupID.Guid;
bool success = CanJoinGroupIM(remoteClient.AgentId, groupID);
string error = null;
if (success)
AddAgentToGroupSession(im.fromAgentID, im.imSessionID);
else
error = "no_ability";
ChatterBoxSessionStartReplyViaCaps(remoteClient, groupInfo.GroupName, groupID, error);
if (success)
{
NotifyNewSessionUserOfExisting(im.imSessionID, remoteClient.AgentId.Guid);
NotifySessionUserTransition(im.imSessionID, remoteClient.AgentId.Guid, im.dialog);
}
}
}
if (im.dialog == (byte)InstantMessageDialog.SessionDrop)
{
GroupRecord groupInfo = m_groupsModule.GetGroupRecord(groupID);
if (groupInfo != null)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Drop Session with {0} for {1}", groupInfo.GroupName, im.fromAgentName);
RemoveAgentFromGroupSession(im.fromAgentID, im.imSessionID);
NotifySessionUserTransition(im.imSessionID, im.fromAgentID, im.dialog);
}
}
// Send a message from locally connected client to a group
if ((im.dialog == (byte)InstantMessageDialog.SessionSend))
{
if (!VerifyIMSecurity(remoteClient, groupID, ref im))
return;
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Send message to session for group {0} with session ID {1}", groupID, im.imSessionID.ToString());
SendMessageToGroup(remoteClient, im, groupID);
}
}
#endregion
private void SendMessageToGroup(IClientAPI remoteClient, GridInstantMessage im, UUID groupID)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
List<UUID> muters;
IMuteListModule m_muteListModule = m_sceneList[0].RequestModuleInterface<IMuteListModule>();
if (m_muteListModule != null)
muters = m_muteListModule.GetInverseMuteList(remoteClient.AgentId);
else
muters = new List<UUID>();
List<GroupMembersData> members = m_groupsModule.GroupMembersRequest(null, null, UUID.Zero, groupID);
foreach (GroupMembersData member in members)
{
if (HasAgentDroppedSession(member.AgentID.Guid, im.imSessionID))
{
// Don't deliver messages to people who have dropped this session
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: {0} has dropped session, not delivering to them", member.AgentID);
continue;
}
if (member.OnlineStatus == false)
{
continue;
}
if ((member.AgentPowers & (ulong)GroupPowers.JoinChat) != (ulong)GroupPowers.JoinChat)
{
continue;
}
if (muters.Contains(member.AgentID))
{ // Don't deliver messages to people who have the sender muted.
continue;
}
// Copy Message
GridInstantMessage msg = new GridInstantMessage();
msg.imSessionID = groupID.Guid;
msg.fromAgentName = im.fromAgentName;
msg.message = im.message;
msg.dialog = im.dialog;
msg.offline = im.offline;
msg.ParentEstateID = im.ParentEstateID;
msg.Position = im.Position;
msg.RegionID = im.RegionID;
msg.binaryBucket = im.binaryBucket;
msg.timestamp = (uint)Util.UnixTimeSinceEpoch();
// Update pertinent fields to make it a "group message"
msg.fromAgentID = im.fromAgentID;
msg.fromGroup = true;
msg.toAgentID = member.AgentID.Guid;
IClientAPI client = GetActiveClient(member.AgentID);
if (client == null)
{
// If they're not local, forward across the grid
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Delivering to {0} via Grid", member.AgentID);
m_msgTransferModule.SendInstantMessage(msg, delegate(bool success) { });
}
else
{
// Deliver locally, directly
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Passing to ProcessMessageFromGroupSession to deliver to {0} locally", client.Name);
ProcessMessageFromGroupSession(msg);
}
}
}
void ChatterBoxSessionStartReplyViaCaps(IClientAPI remoteClient, string groupName, UUID groupID, string error)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
OSDMap moderatedMap = new OSDMap(4);
moderatedMap.Add("voice", OSD.FromBoolean(false));
OSDMap sessionMap = new OSDMap(4);
sessionMap.Add("moderated_mode", moderatedMap);
sessionMap.Add("session_name", OSD.FromString(groupName));
sessionMap.Add("type", OSD.FromInteger(0));
sessionMap.Add("voice_enabled", OSD.FromBoolean(false));
OSDMap bodyMap = new OSDMap((error==null)?4:5);
bodyMap.Add("session_id", OSD.FromUUID(groupID));
bodyMap.Add("temp_session_id", OSD.FromUUID(groupID));
bodyMap.Add("success", OSD.FromBoolean(error == null));
bodyMap.Add("session_info", sessionMap);
if (error != null)
bodyMap.Add("error", OSD.FromString(error));
IEventQueue queue = remoteClient.Scene.RequestModuleInterface<IEventQueue>();
if (queue != null)
{
queue.Enqueue(EventQueueHelper.BuildEvent("ChatterBoxSessionStartReply", bodyMap), remoteClient.AgentId);
}
}
private void DebugGridInstantMessage(GridInstantMessage im)
{
// Don't log any normal IMs (privacy!)
if (m_debugEnabled && im.dialog != (byte)InstantMessageDialog.MessageFromAgent)
{
m_log.WarnFormat("[GROUPS-MESSAGING]: IM: fromGroup({0})", im.fromGroup ? "True" : "False");
m_log.WarnFormat("[GROUPS-MESSAGING]: IM: Dialog({0})", ((InstantMessageDialog)im.dialog).ToString());
m_log.WarnFormat("[GROUPS-MESSAGING]: IM: fromAgentID({0})", im.fromAgentID.ToString());
m_log.WarnFormat("[GROUPS-MESSAGING]: IM: fromAgentName({0})", im.fromAgentName.ToString());
m_log.WarnFormat("[GROUPS-MESSAGING]: IM: imSessionID({0})", im.imSessionID.ToString());
m_log.WarnFormat("[GROUPS-MESSAGING]: IM: message({0})", im.message.ToString());
m_log.WarnFormat("[GROUPS-MESSAGING]: IM: offline({0})", im.offline.ToString());
m_log.WarnFormat("[GROUPS-MESSAGING]: IM: toAgentID({0})", im.toAgentID.ToString());
m_log.WarnFormat("[GROUPS-MESSAGING]: IM: binaryBucket({0})", OpenMetaverse.Utils.BytesToHexString(im.binaryBucket, "BinaryBucket"));
}
}
#region Client Tools
/// <summary>
/// Try to find an active IClientAPI reference for agentID giving preference to root connections
/// </summary>
private IClientAPI GetActiveClient(UUID agentID)
{
IClientAPI child = null;
// Try root avatar first
foreach (Scene scene in m_sceneList)
{
if (scene.Entities.ContainsKey(agentID) &&
scene.Entities[agentID] is ScenePresence)
{
ScenePresence user = (ScenePresence)scene.Entities[agentID];
if (!user.IsChildAgent)
{
return user.ControllingClient;
}
else
{
child = user.ControllingClient;
}
}
}
// If we didn't find a root, then just return whichever child we found, or null if none
return child;
}
#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.
/*============================================================
**
**
**
**
**
** Purpose: Culture-specific collection of resources.
**
**
===========================================================*/
namespace System.Resources {
using System;
using System.Collections;
using System.IO;
using System.Globalization;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
// A ResourceSet stores all the resources defined in one particular CultureInfo.
//
// The method used to load resources is straightforward - this class
// enumerates over an IResourceReader, loading every name and value, and
// stores them in a hash table. Custom IResourceReaders can be used.
//
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class ResourceSet : IDisposable, IEnumerable
{
[NonSerialized] protected IResourceReader Reader;
#if FEATURE_CORECLR
internal Hashtable Table;
#else
protected Hashtable Table;
#endif
private Hashtable _caseInsensitiveTable; // For case-insensitive lookups.
#if LOOSELY_LINKED_RESOURCE_REFERENCE
[OptionalField]
private Assembly _assembly; // For LooselyLinkedResourceReferences
#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
protected ResourceSet()
{
// To not inconvenience people subclassing us, we should allocate a new
// hashtable here just so that Table is set to something.
CommonInit();
}
// For RuntimeResourceSet, ignore the Table parameter - it's a wasted
// allocation.
internal ResourceSet(bool junk)
{
}
// Creates a ResourceSet using the system default ResourceReader
// implementation. Use this constructor to open & read from a file
// on disk.
//
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public ResourceSet(String fileName)
{
Reader = new ResourceReader(fileName);
CommonInit();
ReadResources();
}
#if LOOSELY_LINKED_RESOURCE_REFERENCE
public ResourceSet(String fileName, Assembly assembly)
{
Reader = new ResourceReader(fileName);
CommonInit();
_assembly = assembly;
ReadResources();
}
#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
// Creates a ResourceSet using the system default ResourceReader
// implementation. Use this constructor to read from an open stream
// of data.
//
[System.Security.SecurityCritical] // auto-generated_required
public ResourceSet(Stream stream)
{
Reader = new ResourceReader(stream);
CommonInit();
ReadResources();
}
#if LOOSELY_LINKED_RESOURCE_REFERENCE
[System.Security.SecurityCritical] // auto_generated_required
public ResourceSet(Stream stream, Assembly assembly)
{
Reader = new ResourceReader(stream);
CommonInit();
_assembly = assembly;
ReadResources();
}
#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
public ResourceSet(IResourceReader reader)
{
if (reader == null)
throw new ArgumentNullException("reader");
Contract.EndContractBlock();
Reader = reader;
CommonInit();
ReadResources();
}
#if LOOSELY_LINKED_RESOURCE_REFERENCE
public ResourceSet(IResourceReader reader, Assembly assembly)
{
if (reader == null)
throw new ArgumentNullException("reader");
Contract.EndContractBlock();
Reader = reader;
CommonInit();
_assembly = assembly;
ReadResources();
}
#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
private void CommonInit()
{
Table = new Hashtable();
}
// Closes and releases any resources used by this ResourceSet, if any.
// All calls to methods on the ResourceSet after a call to close may
// fail. Close is guaranteed to be safely callable multiple times on a
// particular ResourceSet, and all subclasses must support these semantics.
public virtual void Close()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing) {
// Close the Reader in a thread-safe way.
IResourceReader copyOfReader = Reader;
Reader = null;
if (copyOfReader != null)
copyOfReader.Close();
}
Reader = null;
_caseInsensitiveTable = null;
Table = null;
}
public void Dispose()
{
Dispose(true);
}
#if LOOSELY_LINKED_RESOURCE_REFERENCE
// Optional - used for resolving assembly manifest resource references.
// This can safely be null.
[ComVisible(false)]
public Assembly Assembly {
get { return _assembly; }
/*protected*/ set { _assembly = value; }
}
#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
// Returns the preferred IResourceReader class for this kind of ResourceSet.
// Subclasses of ResourceSet using their own Readers &; should override
// GetDefaultReader and GetDefaultWriter.
public virtual Type GetDefaultReader()
{
return typeof(ResourceReader);
}
// Returns the preferred IResourceWriter class for this kind of ResourceSet.
// Subclasses of ResourceSet using their own Readers &; should override
// GetDefaultReader and GetDefaultWriter.
public virtual Type GetDefaultWriter()
{
#if FEATURE_CORECLR
return Type.GetType("System.Resources.ResourceWriter, System.Resources.Writer, Version=4.0.1.0, Culture=neutral, PublicKeyToken=" + AssemblyRef.MicrosoftPublicKeyToken, throwOnError: true);
#else
return typeof(ResourceWriter);
#endif
}
[ComVisible(false)]
public virtual IDictionaryEnumerator GetEnumerator()
{
return GetEnumeratorHelper();
}
/// <internalonly/>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumeratorHelper();
}
private IDictionaryEnumerator GetEnumeratorHelper()
{
Hashtable copyOfTable = Table; // Avoid a race with Dispose
if (copyOfTable == null)
throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_ResourceSet"));
return copyOfTable.GetEnumerator();
}
// Look up a string value for a resource given its name.
//
public virtual String GetString(String name)
{
Object obj = GetObjectInternal(name);
try {
return (String)obj;
}
catch (InvalidCastException) {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceNotString_Name", name));
}
}
public virtual String GetString(String name, bool ignoreCase)
{
Object obj;
String s;
// Case-sensitive lookup
obj = GetObjectInternal(name);
try {
s = (String)obj;
}
catch (InvalidCastException) {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceNotString_Name", name));
}
// case-sensitive lookup succeeded
if (s != null || !ignoreCase) {
return s;
}
// Try doing a case-insensitive lookup
obj = GetCaseInsensitiveObjectInternal(name);
try {
return (String)obj;
}
catch (InvalidCastException) {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceNotString_Name", name));
}
}
// Look up an object value for a resource given its name.
//
public virtual Object GetObject(String name)
{
return GetObjectInternal(name);
}
public virtual Object GetObject(String name, bool ignoreCase)
{
Object obj = GetObjectInternal(name);
if (obj != null || !ignoreCase)
return obj;
return GetCaseInsensitiveObjectInternal(name);
}
protected virtual void ReadResources()
{
IDictionaryEnumerator en = Reader.GetEnumerator();
while (en.MoveNext()) {
Object value = en.Value;
#if LOOSELY_LINKED_RESOURCE_REFERENCE
if (Assembly != null && value is LooselyLinkedResourceReference) {
LooselyLinkedResourceReference assRef = (LooselyLinkedResourceReference) value;
value = assRef.Resolve(Assembly);
}
#endif //LOOSELYLINKEDRESOURCEREFERENCE
Table.Add(en.Key, value);
}
// While technically possible to close the Reader here, don't close it
// to help with some WinRes lifetime issues.
}
private Object GetObjectInternal(String name)
{
if (name == null)
throw new ArgumentNullException("name");
Contract.EndContractBlock();
Hashtable copyOfTable = Table; // Avoid a race with Dispose
if (copyOfTable == null)
throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_ResourceSet"));
return copyOfTable[name];
}
private Object GetCaseInsensitiveObjectInternal(String name)
{
Hashtable copyOfTable = Table; // Avoid a race with Dispose
if (copyOfTable == null)
throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_ResourceSet"));
Hashtable caseTable = _caseInsensitiveTable; // Avoid a race condition with Close
if (caseTable == null)
{
caseTable = new Hashtable(StringComparer.OrdinalIgnoreCase);
#if _DEBUG
//Console.WriteLine("ResourceSet::GetObject loading up case-insensitive data");
BCLDebug.Perf(false, "Using case-insensitive lookups is bad perf-wise. Consider capitalizing "+name+" correctly in your source");
#endif
IDictionaryEnumerator en = copyOfTable.GetEnumerator();
while (en.MoveNext())
{
caseTable.Add(en.Key, en.Value);
}
_caseInsensitiveTable = caseTable;
}
return caseTable[name];
}
}
}
| |
// <copyright file="V85Network.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium.DevTools.V85.Fetch;
using OpenQA.Selenium.DevTools.V85.Network;
namespace OpenQA.Selenium.DevTools.V85
{
/// <summary>
/// Class providing functionality for manipulating network calls using version 86 of the DevTools Protocol
/// </summary>
public class V85Network : DevTools.Network
{
private FetchAdapter fetch;
private NetworkAdapter network;
/// <summary>
/// Initializes a new instance of the <see cref="V85Network"/> class.
/// </summary>
/// <param name="network">The adapter for the Network domain.</param>
/// <param name="fetch">The adapter for the Fetch domain.</param>
public V85Network(NetworkAdapter network, FetchAdapter fetch)
{
this.network = network;
this.fetch = fetch;
fetch.AuthRequired += OnFetchAuthRequired;
fetch.RequestPaused += OnFetchRequestPaused;
}
/// <summary>
/// Asynchronously disables network caching.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
public override async Task DisableNetworkCaching()
{
await network.SetCacheDisabled(new SetCacheDisabledCommandSettings() { CacheDisabled = true });
}
/// <summary>
/// Asynchronously enables network caching.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
public override async Task EnableNetworkCaching()
{
await network.SetCacheDisabled(new SetCacheDisabledCommandSettings() { CacheDisabled = false });
}
public override async Task EnableNetwork()
{
await network.Enable(new Network.EnableCommandSettings());
}
public override async Task DisableNetwork()
{
await network.Disable();
}
/// <summary>
/// Asynchronously enables the fetch domain for all URL patterns.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
public override async Task EnableFetchForAllPatterns()
{
await fetch.Enable(new OpenQA.Selenium.DevTools.V85.Fetch.EnableCommandSettings()
{
Patterns = new OpenQA.Selenium.DevTools.V85.Fetch.RequestPattern[]
{
new OpenQA.Selenium.DevTools.V85.Fetch.RequestPattern() { UrlPattern = "*", RequestStage = RequestStage.Request },
new OpenQA.Selenium.DevTools.V85.Fetch.RequestPattern() { UrlPattern = "*", RequestStage = RequestStage.Response }
},
HandleAuthRequests = true
});
}
/// <summary>
/// Asynchronously diables the fetch domain.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
public override async Task DisableFetch()
{
await fetch.Disable();
}
/// <summary>
/// Asynchronously sets the override of the user agent settings.
/// </summary>
/// <param name="userAgent">A <see cref="UserAgent"/> object containing the user agent values to override.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public override async Task SetUserAgentOverride(UserAgent userAgent)
{
await network.SetUserAgentOverride(new SetUserAgentOverrideCommandSettings()
{
UserAgent = userAgent.UserAgentString,
AcceptLanguage = userAgent.AcceptLanguage,
Platform = userAgent.Platform
});
}
/// <summary>
/// Asynchronously continues an intercepted network request.
/// </summary>
/// <param name="requestData">The <see cref="HttpRequestData"/> of the request.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public override async Task ContinueRequest(HttpRequestData requestData)
{
var commandSettings = new ContinueRequestCommandSettings()
{
RequestId = requestData.RequestId,
Method = requestData.Method,
Url = requestData.Url,
};
if (requestData.Headers.Count > 0)
{
List<HeaderEntry> headers = new List<HeaderEntry>();
foreach (KeyValuePair<string, string> headerPair in requestData.Headers)
{
headers.Add(new HeaderEntry() { Name = headerPair.Key, Value = headerPair.Value });
}
commandSettings.Headers = headers.ToArray();
}
if (!string.IsNullOrEmpty(requestData.PostData))
{
commandSettings.PostData = requestData.PostData;
}
await fetch.ContinueRequest(commandSettings);
}
/// <summary>
/// Asynchronously continues an intercepted network request and returns the specified response.
/// </summary>
/// <param name="requestData">The <see cref="HttpRequestData"/> of the request.</param>
/// <param name="responseData">The <see cref="HttpResponseData"/> with which to respond to the request</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public override async Task ContinueRequestWithResponse(HttpRequestData requestData, HttpResponseData responseData)
{
var commandSettings = new FulfillRequestCommandSettings()
{
RequestId = requestData.RequestId,
ResponseCode = responseData.StatusCode,
};
if (responseData.Headers.Count > 0 || responseData.CookieHeaders.Count > 0)
{
List<HeaderEntry> headers = new List<HeaderEntry>();
foreach (KeyValuePair<string, string> headerPair in responseData.Headers)
{
headers.Add(new HeaderEntry() { Name = headerPair.Key, Value = headerPair.Value });
}
foreach (string cookieHeader in responseData.CookieHeaders)
{
headers.Add(new HeaderEntry() { Name = "Set-Cookie", Value = cookieHeader });
}
commandSettings.ResponseHeaders = headers.ToArray();
}
if (!string.IsNullOrEmpty(responseData.Body))
{
commandSettings.Body = Convert.ToBase64String(Encoding.UTF8.GetBytes(responseData.Body));
}
await fetch.FulfillRequest(commandSettings);
}
/// <summary>
/// Asynchronously contines an intercepted network call without modification.
/// </summary>
/// <param name="requestData">The <see cref="HttpRequestData"/> of the network call.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public override async Task ContinueRequestWithoutModification(HttpRequestData requestData)
{
await fetch.ContinueRequest(new ContinueRequestCommandSettings() { RequestId = requestData.RequestId });
}
/// <summary>
/// Asynchronously continues an intercepted network call using authentication.
/// </summary>
/// <param name="requestId">The ID of the network request for which to continue with authentication.</param>
/// <param name="userName">The user name with which to authenticate.</param>
/// <param name="password">The password with which to authenticate.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public override async Task ContinueWithAuth(string requestId, string userName, string password)
{
await fetch.ContinueWithAuth(new ContinueWithAuthCommandSettings()
{
RequestId = requestId,
AuthChallengeResponse = new V85.Fetch.AuthChallengeResponse()
{
Response = V85.Fetch.AuthChallengeResponseResponseValues.ProvideCredentials,
Username = userName,
Password = password
}
});
}
/// <summary>
/// Asynchronously cancels authorization of an intercepted network request.
/// </summary>
/// <param name="requestId">The ID of the network request for which to cancel authentication.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public override async Task CancelAuth(string requestId)
{
await fetch.ContinueWithAuth(new ContinueWithAuthCommandSettings()
{
RequestId = requestId,
AuthChallengeResponse = new OpenQA.Selenium.DevTools.V85.Fetch.AuthChallengeResponse()
{
Response = V85.Fetch.AuthChallengeResponseResponseValues.CancelAuth
}
});
}
/// <summary>
/// Asynchronously adds the response body to the provided <see cref="HttpResponseData"/> object.
/// </summary>
/// <param name="responseData">The <see cref="HttpResponseData"/> object to which to add the response body.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public override async Task AddResponseBody(HttpResponseData responseData)
{
// If the response is a redirect, retrieving the body will throw an error in CDP.
if (responseData.StatusCode < 300 || responseData.StatusCode > 399)
{
var bodyResponse = await fetch.GetResponseBody(new Fetch.GetResponseBodyCommandSettings() { RequestId = responseData.RequestId });
if (bodyResponse.Base64Encoded)
{
responseData.Body = Encoding.UTF8.GetString(Convert.FromBase64String(bodyResponse.Body));
}
else
{
responseData.Body = bodyResponse.Body;
}
}
}
/// <summary>
/// Asynchronously contines an intercepted network response without modification.
/// </summary>
/// <param name="responseData">The <see cref="HttpResponseData"/> of the network response.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public override async Task ContinueResponseWithoutModification(HttpResponseData responseData)
{
await fetch.ContinueRequest(new ContinueRequestCommandSettings() { RequestId = responseData.RequestId });
}
private void OnFetchAuthRequired(object sender, Fetch.AuthRequiredEventArgs e)
{
AuthRequiredEventArgs wrapped = new AuthRequiredEventArgs()
{
RequestId = e.RequestId,
Uri = e.Request.Url
};
this.OnAuthRequired(wrapped);
}
private void OnFetchRequestPaused(object sender, Fetch.RequestPausedEventArgs e)
{
if (e.ResponseErrorReason == null && e.ResponseStatusCode == null)
{
RequestPausedEventArgs wrapped = new RequestPausedEventArgs();
wrapped.RequestData = new HttpRequestData()
{
RequestId = e.RequestId,
Method = e.Request.Method,
Url = e.Request.Url,
PostData = e.Request.PostData,
Headers = new Dictionary<string, string>(e.Request.Headers)
};
this.OnRequestPaused(wrapped);
}
else
{
ResponsePausedEventArgs wrappedResponse = new ResponsePausedEventArgs();
wrappedResponse.ResponseData = new HttpResponseData()
{
RequestId = e.RequestId,
Url = e.Request.Url,
ResourceType = e.ResourceType.ToString()
};
if (e.ResponseStatusCode.HasValue)
{
wrappedResponse.ResponseData.StatusCode = e.ResponseStatusCode.Value;
}
if (e.ResponseHeaders != null)
{
foreach (var header in e.ResponseHeaders)
{
if (header.Name.ToLowerInvariant() == "set-cookie")
{
wrappedResponse.ResponseData.CookieHeaders.Add(header.Value);
}
else
{
if (wrappedResponse.ResponseData.Headers.ContainsKey(header.Name))
{
string currentHeaderValue = wrappedResponse.ResponseData.Headers[header.Name];
wrappedResponse.ResponseData.Headers[header.Name] = currentHeaderValue + ", " + header.Value;
}
else
{
wrappedResponse.ResponseData.Headers.Add(header.Name, header.Value);
}
}
}
}
this.OnResponsePaused(wrappedResponse);
}
}
}
}
| |
// 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.Linq;
using System.Threading.Tasks;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Microsoft.CodeAnalysis.Editor.Implementation.NavigateTo;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Language.NavigateTo.Interfaces;
using Moq;
using Roslyn.Test.EditorUtilities.NavigateTo;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.NavigateTo
{
public class NavigateToTests
{
private readonly Mock<IGlyphService> _glyphServiceMock = new Mock<IGlyphService>(MockBehavior.Strict);
private INavigateToItemProvider _provider;
private NavigateToTestAggregator _aggregator;
private async Task<TestWorkspace> SetupWorkspaceAsync(string content)
{
var workspace = await TestWorkspace.CreateCSharpAsync(content);
var aggregateListener = AggregateAsynchronousOperationListener.CreateEmptyListener();
_provider = new NavigateToItemProvider(
workspace,
_glyphServiceMock.Object,
aggregateListener);
_aggregator = new NavigateToTestAggregator(_provider);
return workspace;
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task NoItemsForEmptyFile()
{
using (var workspace = await SetupWorkspaceAsync(""))
{
Assert.Empty(_aggregator.GetItems("Hello"));
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindClass()
{
using (var workspace = await SetupWorkspaceAsync("class Foo { }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemFriend);
var item = _aggregator.GetItems("Foo").Single(x => x.Kind != "Method");
VerifyNavigateToResultItem(item, "Foo", MatchKind.Exact, NavigateToItemKind.Class);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindVerbatimClass()
{
using (var workspace = await SetupWorkspaceAsync("class @static { }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemFriend);
var item = _aggregator.GetItems("static").Single(x => x.Kind != "Method");
VerifyNavigateToResultItem(item, "static", MatchKind.Exact, NavigateToItemKind.Class, displayName: "@static");
// Check searching for @static too
item = _aggregator.GetItems("@static").Single(x => x.Kind != "Method");
VerifyNavigateToResultItem(item, "static", MatchKind.Exact, NavigateToItemKind.Class, displayName: "@static");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindNestedClass()
{
using (var workspace = await SetupWorkspaceAsync("class Foo { class Bar { internal class DogBed { } } }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemFriend);
var item = _aggregator.GetItems("DogBed").Single(x => x.Kind != "Method");
VerifyNavigateToResultItem(item, "DogBed", MatchKind.Exact, NavigateToItemKind.Class);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindMemberInANestedClass()
{
using (var workspace = await SetupWorkspaceAsync("class Foo { class Bar { class DogBed { public void Method() { } } } }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic);
var item = _aggregator.GetItems("Method").Single();
VerifyNavigateToResultItem(item, "Method", MatchKind.Exact, NavigateToItemKind.Method, "Method()", $"{EditorFeaturesResources.type}Foo.Bar.DogBed");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindGenericClassWithConstraints()
{
using (var workspace = await SetupWorkspaceAsync("using System.Collections; class Foo<T> where T : IEnumerable { }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemFriend);
var item = _aggregator.GetItems("Foo").Single(x => x.Kind != "Method");
VerifyNavigateToResultItem(item, "Foo", MatchKind.Exact, NavigateToItemKind.Class, displayName: "Foo<T>");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindGenericMethodWithConstraints()
{
using (var workspace = await SetupWorkspaceAsync("using System; class Foo<U> { public void Bar<T>(T item) where T:IComparable<T> {} }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic);
var item = _aggregator.GetItems("Bar").Single();
VerifyNavigateToResultItem(item, "Bar", MatchKind.Exact, NavigateToItemKind.Method, "Bar<T>(T)", $"{EditorFeaturesResources.type}Foo<U>");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindPartialClass()
{
using (var workspace = await SetupWorkspaceAsync("public partial class Foo { int a; } partial class Foo { int b; }"))
{
var expecteditem1 = new NavigateToItem("Foo", NavigateToItemKind.Class, "csharp", null, null, MatchKind.Exact, true, null);
var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem1 };
var items = _aggregator.GetItems("Foo");
VerifyNavigateToResultItems(expecteditems, items);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindTypesInMetadata()
{
using (var workspace = await SetupWorkspaceAsync("using System; Class Program {FileStyleUriParser f;}"))
{
var items = _aggregator.GetItems("FileStyleUriParser");
Assert.Equal(items.Count(), 0);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindClassInNamespace()
{
using (var workspace = await SetupWorkspaceAsync("namespace Bar { class Foo { } }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemFriend);
var item = _aggregator.GetItems("Foo").Single(x => x.Kind != "Method");
VerifyNavigateToResultItem(item, "Foo", MatchKind.Exact, NavigateToItemKind.Class);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindStruct()
{
using (var workspace = await SetupWorkspaceAsync("struct Bar { }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupStruct, StandardGlyphItem.GlyphItemFriend);
var item = _aggregator.GetItems("B").Single(x => x.Kind != "Method");
VerifyNavigateToResultItem(item, "Bar", MatchKind.Prefix, NavigateToItemKind.Structure);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindEnum()
{
using (var workspace = await SetupWorkspaceAsync("enum Colors {Red, Green, Blue}"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupEnum, StandardGlyphItem.GlyphItemFriend);
var item = _aggregator.GetItems("Colors").Single(x => x.Kind != "Method");
VerifyNavigateToResultItem(item, "Colors", MatchKind.Exact, NavigateToItemKind.Enum);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindEnumMember()
{
using (var workspace = await SetupWorkspaceAsync("enum Colors {Red, Green, Blue}"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupEnumMember, StandardGlyphItem.GlyphItemPublic);
var item = _aggregator.GetItems("R").Single();
VerifyNavigateToResultItem(item, "Red", MatchKind.Prefix, NavigateToItemKind.EnumItem);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindField1()
{
using (var workspace = await SetupWorkspaceAsync("class Foo { int bar;}"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate);
var item = _aggregator.GetItems("b").Single();
VerifyNavigateToResultItem(item, "bar", MatchKind.Prefix, NavigateToItemKind.Field, additionalInfo: $"{EditorFeaturesResources.type}Foo");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindField2()
{
using (var workspace = await SetupWorkspaceAsync("class Foo { int bar;}"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate);
var item = _aggregator.GetItems("ba").Single();
VerifyNavigateToResultItem(item, "bar", MatchKind.Prefix, NavigateToItemKind.Field, additionalInfo: $"{EditorFeaturesResources.type}Foo");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindField3()
{
using (var workspace = await SetupWorkspaceAsync("class Foo { int bar;}"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate);
Assert.Empty(_aggregator.GetItems("ar"));
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindVerbatimField()
{
using (var workspace = await SetupWorkspaceAsync("class Foo { int @string;}"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate);
var item = _aggregator.GetItems("string").Single();
VerifyNavigateToResultItem(item, "string", MatchKind.Exact, NavigateToItemKind.Field, displayName: "@string", additionalInfo: $"{EditorFeaturesResources.type}Foo");
// Check searching for@string too
item = _aggregator.GetItems("@string").Single();
VerifyNavigateToResultItem(item, "string", MatchKind.Exact, NavigateToItemKind.Field, displayName: "@string", additionalInfo: $"{EditorFeaturesResources.type}Foo");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindPtrField1()
{
using (var workspace = await SetupWorkspaceAsync("class Foo { int* bar; }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate);
Assert.Empty(_aggregator.GetItems("ar"));
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindPtrField2()
{
using (var workspace = await SetupWorkspaceAsync("class Foo { int* bar; }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate);
var item = _aggregator.GetItems("b").Single();
VerifyNavigateToResultItem(item, "bar", MatchKind.Prefix, NavigateToItemKind.Field);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindConstField()
{
using (var workspace = await SetupWorkspaceAsync("class Foo { const int bar = 7;}"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupConstant, StandardGlyphItem.GlyphItemPrivate);
var item = _aggregator.GetItems("ba").Single();
VerifyNavigateToResultItem(item, "bar", MatchKind.Prefix, NavigateToItemKind.Constant);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindIndexer()
{
var program = @"class Foo { int[] arr; public int this[int i] { get { return arr[i]; } set { arr[i] = value; } } }";
using (var workspace = await SetupWorkspaceAsync(program))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupProperty, StandardGlyphItem.GlyphItemPublic);
var item = _aggregator.GetItems("this").Single();
VerifyNavigateToResultItem(item, "this[]", MatchKind.Exact, NavigateToItemKind.Property, displayName: "this[int]", additionalInfo: $"{EditorFeaturesResources.type}Foo");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindEvent()
{
var program = "class Foo { public event EventHandler ChangedEventHandler; }";
using (var workspace = await SetupWorkspaceAsync(program))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupEvent, StandardGlyphItem.GlyphItemPublic);
var item = _aggregator.GetItems("CEH").Single();
VerifyNavigateToResultItem(item, "ChangedEventHandler", MatchKind.Regular, NavigateToItemKind.Event, additionalInfo: $"{EditorFeaturesResources.type}Foo");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindAutoProperty()
{
using (var workspace = await SetupWorkspaceAsync("class Foo { int Bar { get; set; } }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupProperty, StandardGlyphItem.GlyphItemPrivate);
var item = _aggregator.GetItems("B").Single();
VerifyNavigateToResultItem(item, "Bar", MatchKind.Prefix, NavigateToItemKind.Property, additionalInfo: $"{EditorFeaturesResources.type}Foo");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindMethod()
{
using (var workspace = await SetupWorkspaceAsync("class Foo { void DoSomething(); }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate);
var item = _aggregator.GetItems("DS").Single();
VerifyNavigateToResultItem(item, "DoSomething", MatchKind.Regular, NavigateToItemKind.Method, "DoSomething()", $"{EditorFeaturesResources.type}Foo");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindVerbatimMethod()
{
using (var workspace = await SetupWorkspaceAsync("class Foo { void @static(); }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate);
var item = _aggregator.GetItems("static").Single();
VerifyNavigateToResultItem(item, "static", MatchKind.Exact, NavigateToItemKind.Method, "@static()", $"{EditorFeaturesResources.type}Foo");
// Verify if we search for @static too
item = _aggregator.GetItems("@static").Single();
VerifyNavigateToResultItem(item, "static", MatchKind.Exact, NavigateToItemKind.Method, "@static()", $"{EditorFeaturesResources.type}Foo");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindParameterizedMethod()
{
using (var workspace = await SetupWorkspaceAsync("class Foo { void DoSomething(int a, string b) {} }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate);
var item = _aggregator.GetItems("DS").Single();
VerifyNavigateToResultItem(item, "DoSomething", MatchKind.Regular, NavigateToItemKind.Method, "DoSomething(int, string)", $"{EditorFeaturesResources.type}Foo");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindConstructor()
{
using (var workspace = await SetupWorkspaceAsync("class Foo { public Foo(){} }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic);
var item = _aggregator.GetItems("Foo").Single(t => t.Kind == NavigateToItemKind.Method);
VerifyNavigateToResultItem(item, "Foo", MatchKind.Exact, NavigateToItemKind.Method, "Foo()", $"{EditorFeaturesResources.type}Foo");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindParameterizedConstructor()
{
using (var workspace = await SetupWorkspaceAsync("class Foo { public Foo(int i){} }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic);
var item = _aggregator.GetItems("Foo").Single(t => t.Kind == NavigateToItemKind.Method);
VerifyNavigateToResultItem(item, "Foo", MatchKind.Exact, NavigateToItemKind.Method, "Foo(int)", $"{EditorFeaturesResources.type}Foo");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindStaticConstructor()
{
using (var workspace = await SetupWorkspaceAsync("class Foo { static Foo(){} }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate);
var item = _aggregator.GetItems("Foo").Single(t => t.Kind == NavigateToItemKind.Method && t.Name != ".ctor");
VerifyNavigateToResultItem(item, "Foo", MatchKind.Exact, NavigateToItemKind.Method, "static Foo()", $"{EditorFeaturesResources.type}Foo");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindPartialMethods()
{
using (var workspace = await SetupWorkspaceAsync("partial class Foo { partial void Bar(); } partial class Foo { partial void Bar() { Console.Write(\"hello\"); } }"))
{
var expecteditem1 = new NavigateToItem("Bar", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Exact, true, null);
var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem1 };
var items = _aggregator.GetItems("Bar");
VerifyNavigateToResultItems(expecteditems, items);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindPartialMethodDefinitionOnly()
{
using (var workspace = await SetupWorkspaceAsync("partial class Foo { partial void Bar(); }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate);
var item = _aggregator.GetItems("Bar").Single();
VerifyNavigateToResultItem(item, "Bar", MatchKind.Exact, NavigateToItemKind.Method, "Bar()", $"{EditorFeaturesResources.type}Foo");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindPartialMethodImplementationOnly()
{
using (var workspace = await SetupWorkspaceAsync("partial class Foo { partial void Bar() { } }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate);
var item = _aggregator.GetItems("Bar").Single();
VerifyNavigateToResultItem(item, "Bar", MatchKind.Exact, NavigateToItemKind.Method, "Bar()", $"{EditorFeaturesResources.type}Foo");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindOverriddenMembers()
{
var program = "class Foo { public virtual string Name { get; set; } } class DogBed : Foo { public override string Name { get { return base.Name; } set {} } }";
using (var workspace = await SetupWorkspaceAsync(program))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupProperty, StandardGlyphItem.GlyphItemPublic);
var expecteditem1 = new NavigateToItem("Name", NavigateToItemKind.Property, "csharp", null, null, MatchKind.Exact, true, null);
var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem1 };
var items = _aggregator.GetItems("Name");
VerifyNavigateToResultItems(expecteditems, items);
var item = items.ElementAt(0);
var itemDisplay = item.DisplayFactory.CreateItemDisplay(item);
var unused = itemDisplay.Glyph;
Assert.Equal("Name", itemDisplay.Name);
Assert.Equal($"{EditorFeaturesResources.type}DogBed", itemDisplay.AdditionalInformation);
_glyphServiceMock.Verify();
item = items.ElementAt(1);
itemDisplay = item.DisplayFactory.CreateItemDisplay(item);
unused = itemDisplay.Glyph;
Assert.Equal("Name", itemDisplay.Name);
Assert.Equal($"{EditorFeaturesResources.type}Foo", itemDisplay.AdditionalInformation);
_glyphServiceMock.Verify();
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindInterface()
{
using (var workspace = await SetupWorkspaceAsync("public interface IFoo { }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupInterface, StandardGlyphItem.GlyphItemPublic);
var item = _aggregator.GetItems("IF").Single();
VerifyNavigateToResultItem(item, "IFoo", MatchKind.Prefix, NavigateToItemKind.Interface);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindDelegateInNamespace()
{
using (var workspace = await SetupWorkspaceAsync("namespace Foo { delegate void DoStuff(); }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupDelegate, StandardGlyphItem.GlyphItemFriend);
var item = _aggregator.GetItems("DoStuff").Single(x => x.Kind != "Method");
VerifyNavigateToResultItem(item, "DoStuff", MatchKind.Exact, NavigateToItemKind.Delegate);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindLambdaExpression()
{
using (var workspace = await SetupWorkspaceAsync("using System; class Foo { Func<int, int> sqr = x => x*x; }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate);
var item = _aggregator.GetItems("sqr").Single();
VerifyNavigateToResultItem(item, "sqr", MatchKind.Exact, NavigateToItemKind.Field, "sqr", $"{EditorFeaturesResources.type}Foo");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindArray()
{
using (var workspace = await SetupWorkspaceAsync("class Foo { object[] itemArray; }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate);
var item = _aggregator.GetItems("itemArray").Single();
VerifyNavigateToResultItem(item, "itemArray", MatchKind.Exact, NavigateToItemKind.Field, "itemArray", $"{EditorFeaturesResources.type}Foo");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindClassAndMethodWithSameName()
{
using (var workspace = await SetupWorkspaceAsync("class Foo { } class Test { void Foo() { } }"))
{
var expectedItems = new List<NavigateToItem>
{
new NavigateToItem("Foo", NavigateToItemKind.Method, "csharp", "Foo", null, MatchKind.Exact, true, null),
new NavigateToItem("Foo", NavigateToItemKind.Class, "csharp", "Foo", null, MatchKind.Exact, true, null)
};
var items = _aggregator.GetItems("Foo");
VerifyNavigateToResultItems(expectedItems, items);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindMethodNestedInGenericTypes()
{
using (var workspace = await SetupWorkspaceAsync("class A<T> { class B { struct C<U> { void M() { } } } }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate);
var item = _aggregator.GetItems("M").Single();
VerifyNavigateToResultItem(item, "M", MatchKind.Exact, NavigateToItemKind.Method, displayName: "M()", additionalInfo: $"{EditorFeaturesResources.type}A<T>.B.C<U>");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task OrderingOfConstructorsAndTypes()
{
using (var workspace = await SetupWorkspaceAsync(@"
class C1
{
C1(int i) {}
}
class C2
{
C2(float f) {}
static C2() {}
}"))
{
var expecteditems = new List<NavigateToItem>
{
new NavigateToItem("C1", NavigateToItemKind.Class, "csharp", "C1", null, MatchKind.Prefix, true, null),
new NavigateToItem("C1", NavigateToItemKind.Method, "csharp", "C1", null, MatchKind.Prefix, true, null),
new NavigateToItem("C2", NavigateToItemKind.Class, "csharp", "C2", null, MatchKind.Prefix, true, null),
new NavigateToItem("C2", NavigateToItemKind.Method, "csharp", "C2", null, MatchKind.Prefix, true, null), // this is the static ctor
new NavigateToItem("C2", NavigateToItemKind.Method, "csharp", "C2", null, MatchKind.Prefix, true, null),
};
var items = _aggregator.GetItems("C").ToList();
items.Sort(CompareNavigateToItems);
VerifyNavigateToResultItems(expecteditems, items);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task NavigateToMethodWithNullableParameter()
{
using (var workspace = await SetupWorkspaceAsync("class C { void M(object? o) {} }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate);
var item = _aggregator.GetItems("M").Single();
VerifyNavigateToResultItem(item, "M", MatchKind.Exact, NavigateToItemKind.Method, "M(object?)");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task StartStopSanity()
{
// Verify that multiple calls to start/stop and dispose don't blow up
using (var workspace = await SetupWorkspaceAsync("public class Foo { }"))
{
// Do one set of queries
Assert.Single(_aggregator.GetItems("Foo").Where(x => x.Kind != "Method"));
_provider.StopSearch();
// Do the same query again, make sure nothing was left over
Assert.Single(_aggregator.GetItems("Foo").Where(x => x.Kind != "Method"));
_provider.StopSearch();
// Dispose the provider
_provider.Dispose();
}
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task DescriptionItems()
{
using (var workspace = await SetupWorkspaceAsync("public\r\nclass\r\nFoo\r\n{ }"))
{
var item = _aggregator.GetItems("F").Single(x => x.Kind != "Method");
var itemDisplay = item.DisplayFactory.CreateItemDisplay(item);
var descriptionItems = itemDisplay.DescriptionItems;
Action<string, string> assertDescription = (label, value) =>
{
var descriptionItem = descriptionItems.Single(i => i.Category.Single().Text == label);
Assert.Equal(value, descriptionItem.Details.Single().Text);
};
assertDescription("File:", workspace.Documents.Single().Name);
assertDescription("Line:", "3"); // one based line number
assertDescription("Project:", "Test");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task TermSplittingTest1()
{
var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}";
using (var workspace = await SetupWorkspaceAsync(source))
{
var expecteditem1 = new NavigateToItem("get_keyword", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, null);
var expecteditem2 = new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, null);
var expecteditem3 = new NavigateToItem("GetKeyWord", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, true, null);
var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem2, expecteditem3 };
var items = _aggregator.GetItems("GK");
Assert.Equal(expecteditems.Count(), items.Count());
VerifyNavigateToResultItems(expecteditems, items);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task TermSplittingTest2()
{
var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}";
using (var workspace = await SetupWorkspaceAsync(source))
{
var expecteditem1 = new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, null);
var expecteditem2 = new NavigateToItem("GetKeyWord", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, true, null);
var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem2 };
var items = _aggregator.GetItems("GKW");
VerifyNavigateToResultItems(expecteditems, items);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task TermSplittingTest3()
{
var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}";
using (var workspace = await SetupWorkspaceAsync(source))
{
var expecteditem1 = new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, null);
var expecteditem2 = new NavigateToItem("GetKeyWord", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Substring, true, null);
var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem2 };
var items = _aggregator.GetItems("K W");
VerifyNavigateToResultItems(expecteditems, items);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task TermSplittingTest4()
{
var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}";
using (var workspace = await SetupWorkspaceAsync(source))
{
var items = _aggregator.GetItems("WKG");
Assert.Empty(items);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task TermSplittingTest5()
{
var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}";
using (var workspace = await SetupWorkspaceAsync(source))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate);
var item = _aggregator.GetItems("G_K_W").Single();
VerifyNavigateToResultItem(item, "get_key_word", MatchKind.Regular, NavigateToItemKind.Field);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task TermSplittingTest6()
{
var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}";
using (var workspace = await SetupWorkspaceAsync(source))
{
var expecteditems = new List<NavigateToItem>
{
new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Prefix, true, null),
new NavigateToItem("GetKeyWord", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Prefix, null)
};
var items = _aggregator.GetItems("get word");
VerifyNavigateToResultItems(expecteditems, items);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task TermSplittingTest7()
{
var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}";
using (var workspace = await SetupWorkspaceAsync(source))
{
var items = _aggregator.GetItems("GTW");
Assert.Empty(items);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task TermIndexer1()
{
var source =
@"class C
{
public int this[int y] { get { } }
}
class D
{
void Foo()
{
var q = new C();
var b = q[4];
}
}";
using (var workspace = await SetupWorkspaceAsync(source))
{
var expecteditems = new List<NavigateToItem>
{
new NavigateToItem("this[]", NavigateToItemKind.Property, "csharp", null, null, MatchKind.Exact, true, null),
};
var items = _aggregator.GetItems("this");
VerifyNavigateToResultItems(expecteditems, items);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task DottedPattern1()
{
var source = "namespace Foo { namespace Bar { class Baz { void Quux() { } } } }";
using (var workspace = await SetupWorkspaceAsync(source))
{
var expecteditems = new List<NavigateToItem>
{
new NavigateToItem("Quux", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Prefix, true, null)
};
var items = _aggregator.GetItems("B.Q");
VerifyNavigateToResultItems(expecteditems, items);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task DottedPattern2()
{
var source = "namespace Foo { namespace Bar { class Baz { void Quux() { } } } }";
using (var workspace = await SetupWorkspaceAsync(source))
{
var expecteditems = new List<NavigateToItem>
{
};
var items = _aggregator.GetItems("C.Q");
VerifyNavigateToResultItems(expecteditems, items);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task DottedPattern3()
{
var source = "namespace Foo { namespace Bar { class Baz { void Quux() { } } } }";
using (var workspace = await SetupWorkspaceAsync(source))
{
var expecteditems = new List<NavigateToItem>
{
new NavigateToItem("Quux", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Prefix, true, null)
};
var items = _aggregator.GetItems("B.B.Q");
VerifyNavigateToResultItems(expecteditems, items);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task DottedPattern4()
{
var source = "namespace Foo { namespace Bar { class Baz { void Quux() { } } } }";
using (var workspace = await SetupWorkspaceAsync(source))
{
var expecteditems = new List<NavigateToItem>
{
new NavigateToItem("Quux", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Exact, true, null)
};
var items = _aggregator.GetItems("Baz.Quux");
VerifyNavigateToResultItems(expecteditems, items);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task DottedPattern5()
{
var source = "namespace Foo { namespace Bar { class Baz { void Quux() { } } } }";
using (var workspace = await SetupWorkspaceAsync(source))
{
var expecteditems = new List<NavigateToItem>
{
new NavigateToItem("Quux", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Exact, true, null)
};
var items = _aggregator.GetItems("F.B.B.Quux");
VerifyNavigateToResultItems(expecteditems, items);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task DottedPattern6()
{
var source = "namespace Foo { namespace Bar { class Baz { void Quux() { } } } }";
using (var workspace = await SetupWorkspaceAsync(source))
{
var expecteditems = new List<NavigateToItem>
{
};
var items = _aggregator.GetItems("F.F.B.B.Quux");
VerifyNavigateToResultItems(expecteditems, items);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
[WorkItem(7855, "https://github.com/dotnet/Roslyn/issues/7855")]
public async Task DottedPattern7()
{
var source = "namespace Foo { namespace Bar { class Baz<X,Y,Z> { void Quux() { } } } }";
using (var workspace = await SetupWorkspaceAsync(source))
{
var expecteditems = new List<NavigateToItem>
{
new NavigateToItem("Quux", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Prefix, true, null)
};
var items = _aggregator.GetItems("Baz.Q");
VerifyNavigateToResultItems(expecteditems, items);
}
}
[WorkItem(1174255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1174255")]
[WorkItem(8009, "https://github.com/dotnet/roslyn/issues/8009")]
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task NavigateToGeneratedFiles()
{
using (var workspace = await TestWorkspace.CreateAsync(@"
<Workspace>
<Project Language=""C#"" CommonReferences=""true"">
<Document FilePath=""File1.cs"">
namespace N
{
public partial class C
{
public void VisibleMethod() { }
}
}
</Document>
<Document FilePath=""File1.g.cs"">
namespace N
{
public partial class C
{
public void VisibleMethod_Generated() { }
}
}
</Document>
</Project>
</Workspace>
"))
{
var aggregateListener = AggregateAsynchronousOperationListener.CreateEmptyListener();
_provider = new NavigateToItemProvider(workspace, _glyphServiceMock.Object, aggregateListener);
_aggregator = new NavigateToTestAggregator(_provider);
var items = _aggregator.GetItems("VisibleMethod");
var expectedItems = new List<NavigateToItem>()
{
new NavigateToItem("VisibleMethod", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Exact, true, null),
new NavigateToItem("VisibleMethod_Generated", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Prefix, true, null)
};
// The pattern matcher should match 'VisibleMethod' to both 'VisibleMethod' and 'VisibleMethod_Not', except that
// the _Not method is declared in a generated file.
VerifyNavigateToResultItems(expectedItems, items);
}
}
[WorkItem(11474, "https://github.com/dotnet/roslyn/pull/11474")]
[Fact, Trait(Traits.Feature, Traits.Features.NavigateTo)]
public async Task FindFuzzy1()
{
using (var workspace = await SetupWorkspaceAsync("class C { public void ToError() { } }"))
{
SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic);
var item = _aggregator.GetItems("ToEror").Single();
VerifyNavigateToResultItem(item, "ToError", MatchKind.Regular, NavigateToItemKind.Method, displayName: "ToError()");
}
}
private void VerifyNavigateToResultItems(List<NavigateToItem> expecteditems, IEnumerable<NavigateToItem> items)
{
expecteditems = expecteditems.OrderBy(i => i.Name).ToList();
items = items.OrderBy(i => i.Name).ToList();
Assert.Equal(expecteditems.Count(), items.Count());
for (int i = 0; i < expecteditems.Count; i++)
{
var expectedItem = expecteditems[i];
var actualItem = items.ElementAt(i);
Assert.Equal(expectedItem.Name, actualItem.Name);
Assert.Equal(expectedItem.MatchKind, actualItem.MatchKind);
Assert.Equal(expectedItem.Language, actualItem.Language);
Assert.Equal(expectedItem.Kind, actualItem.Kind);
Assert.Equal(expectedItem.IsCaseSensitive, actualItem.IsCaseSensitive);
if (!string.IsNullOrEmpty(expectedItem.SecondarySort))
{
Assert.Contains(expectedItem.SecondarySort, actualItem.SecondarySort, StringComparison.Ordinal);
}
}
}
private void VerifyNavigateToResultItem(NavigateToItem result, string name, MatchKind matchKind, string navigateToItemKind,
string displayName = null, string additionalInfo = null)
{
// Verify symbol information
Assert.Equal(name, result.Name);
Assert.Equal(matchKind, result.MatchKind);
Assert.Equal("csharp", result.Language);
Assert.Equal(navigateToItemKind, result.Kind);
// Verify display
var itemDisplay = result.DisplayFactory.CreateItemDisplay(result);
Assert.Equal(displayName ?? name, itemDisplay.Name);
if (additionalInfo != null)
{
Assert.Equal(additionalInfo, itemDisplay.AdditionalInformation);
}
// Make sure to fetch the glyph
var unused = itemDisplay.Glyph;
_glyphServiceMock.Verify();
}
private void SetupVerifiableGlyph(StandardGlyphGroup standardGlyphGroup, StandardGlyphItem standardGlyphItem)
{
_glyphServiceMock.Setup(service => service.GetGlyph(standardGlyphGroup, standardGlyphItem))
.Returns(CreateIconBitmapSource())
.Verifiable();
}
private BitmapSource CreateIconBitmapSource()
{
int stride = PixelFormats.Bgr32.BitsPerPixel / 8 * 16;
return BitmapSource.Create(16, 16, 96, 96, PixelFormats.Bgr32, null, new byte[16 * stride], stride);
}
// For ordering of NavigateToItems, see
// http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.language.navigateto.interfaces.navigatetoitem.aspx
private static int CompareNavigateToItems(NavigateToItem a, NavigateToItem b)
{
int result = ((int)a.MatchKind) - ((int)b.MatchKind);
if (result != 0)
{
return result;
}
result = a.Name.CompareTo(b.Name);
if (result != 0)
{
return result;
}
result = a.Kind.CompareTo(b.Kind);
if (result != 0)
{
return result;
}
result = a.SecondarySort.CompareTo(b.SecondarySort);
return result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// The Regex class represents a single compiled instance of a regular
// expression.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Threading;
namespace System.Text.RegularExpressions
{
/// <summary>
/// Represents an immutable, compiled regular expression. Also
/// contains static methods that allow use of regular expressions without instantiating
/// a Regex explicitly.
/// </summary>
public class Regex
{
internal string _pattern; // The string pattern provided
internal RegexOptions _roptions; // the top-level options from the options string
// *********** Match timeout fields { ***********
// We need this because time is queried using Environment.TickCount for performance reasons
// (Environment.TickCount returns milliseconds as an int and cycles):
private static readonly TimeSpan MaximumMatchTimeout = TimeSpan.FromMilliseconds(Int32.MaxValue - 1);
// InfiniteMatchTimeout specifies that match timeout is switched OFF. It allows for faster code paths
// compared to simply having a very large timeout.
// We do not want to ask users to use System.Threading.Timeout.InfiniteTimeSpan as a parameter because:
// (1) We do not want to imply any relation between having using a RegEx timeout and using multi-threading.
// (2) We do not want to require users to take ref to a contract assembly for threading just to use RegEx.
// There may in theory be a SKU that has RegEx, but no multithreading.
// We create a public Regex.InfiniteMatchTimeout constant, which for consistency uses the save underlying
// value as Timeout.InfiniteTimeSpan creating an implementation detail dependency only.
public static readonly TimeSpan InfiniteMatchTimeout = Timeout.InfiniteTimeSpan;
internal TimeSpan _internalMatchTimeout; // timeout for the execution of this regex
// DefaultMatchTimeout specifies the match timeout to use if no other timeout was specified
// by one means or another. Typically, it is set to InfiniteMatchTimeout.
internal static readonly TimeSpan DefaultMatchTimeout = InfiniteMatchTimeout;
// *********** } match timeout fields ***********
internal Dictionary<Int32, Int32> _caps; // if captures are sparse, this is the hashtable capnum->index
internal Dictionary<String, Int32> _capnames; // if named captures are used, this maps names->index
internal String[] _capslist; // if captures are sparse or named captures are used, this is the sorted list of names
internal int _capsize; // the size of the capture array
internal ExclusiveReference _runnerref; // cached runner
internal SharedReference _replref; // cached parsed replacement pattern
internal RegexCode _code; // if interpreted, this is the code for RegexInterpreter
internal bool _refsInitialized = false;
internal static LinkedList<CachedCodeEntry> s_livecode = new LinkedList<CachedCodeEntry>();// the cache of code and factories that are currently loaded
internal static int s_cacheSize = 15;
internal const int MaxOptionShift = 10;
protected Regex()
{
_internalMatchTimeout = DefaultMatchTimeout;
}
/// <summary>
/// Creates and compiles a regular expression object for the specified regular
/// expression.
/// </summary>
public Regex(String pattern)
: this(pattern, RegexOptions.None, DefaultMatchTimeout, false)
{
}
/// <summary>
/// Creates and compiles a regular expression object for the
/// specified regular expression with options that modify the pattern.
/// </summary>
public Regex(String pattern, RegexOptions options)
: this(pattern, options, DefaultMatchTimeout, false)
{
}
public Regex(String pattern, RegexOptions options, TimeSpan matchTimeout)
: this(pattern, options, matchTimeout, false)
{
}
private Regex(String pattern, RegexOptions options, TimeSpan matchTimeout, bool useCache)
{
RegexTree tree;
CachedCodeEntry cached = null;
string cultureKey = null;
if (pattern == null)
throw new ArgumentNullException(nameof(pattern));
if (options < RegexOptions.None || (((int)options) >> MaxOptionShift) != 0)
throw new ArgumentOutOfRangeException(nameof(options));
if ((options & RegexOptions.ECMAScript) != 0
&& (options & ~(RegexOptions.ECMAScript |
RegexOptions.IgnoreCase |
RegexOptions.Multiline |
RegexOptions.CultureInvariant
#if DEBUG
| RegexOptions.Debug
#endif
)) != 0)
throw new ArgumentOutOfRangeException(nameof(options));
ValidateMatchTimeout(matchTimeout);
// Try to look up this regex in the cache. We do this regardless of whether useCache is true since there's
// really no reason not to.
if ((options & RegexOptions.CultureInvariant) != 0)
cultureKey = CultureInfo.InvariantCulture.ToString(); // "English (United States)"
else
cultureKey = CultureInfo.CurrentCulture.ToString();
var key = new CachedCodeEntryKey(options, cultureKey, pattern);
cached = LookupCachedAndUpdate(key);
_pattern = pattern;
_roptions = options;
_internalMatchTimeout = matchTimeout;
if (cached == null)
{
// Parse the input
tree = RegexParser.Parse(pattern, _roptions);
// Extract the relevant information
_capnames = tree._capnames;
_capslist = tree._capslist;
_code = RegexWriter.Write(tree);
_caps = _code._caps;
_capsize = _code._capsize;
InitializeReferences();
tree = null;
if (useCache)
cached = CacheCode(key);
}
else
{
_caps = cached._caps;
_capnames = cached._capnames;
_capslist = cached._capslist;
_capsize = cached._capsize;
_code = cached._code;
_runnerref = cached._runnerref;
_replref = cached._replref;
_refsInitialized = true;
}
}
// Note: "<" is the XML entity for smaller ("<").
/// <summary>
/// Validates that the specified match timeout value is valid.
/// The valid range is <code>TimeSpan.Zero < matchTimeout <= Regex.MaximumMatchTimeout</code>.
/// </summary>
/// <param name="matchTimeout">The timeout value to validate.</param>
/// <exception cref="System.ArgumentOutOfRangeException">If the specified timeout is not within a valid range.
/// </exception>
internal static void ValidateMatchTimeout(TimeSpan matchTimeout)
{
if (InfiniteMatchTimeout == matchTimeout)
return;
// Change this to make sure timeout is not longer then Environment.Ticks cycle length:
if (TimeSpan.Zero < matchTimeout && matchTimeout <= MaximumMatchTimeout)
return;
throw new ArgumentOutOfRangeException(nameof(matchTimeout));
}
/// <summary>
/// Escapes a minimal set of metacharacters (\, *, +, ?, |, {, [, (, ), ^, $, ., #, and
/// whitespace) by replacing them with their \ codes. This converts a string so that
/// it can be used as a constant within a regular expression safely. (Note that the
/// reason # and whitespace must be escaped is so the string can be used safely
/// within an expression parsed with x mode. If future Regex features add
/// additional metacharacters, developers should depend on Escape to escape those
/// characters as well.)
/// </summary>
public static String Escape(String str)
{
if (str == null)
throw new ArgumentNullException(nameof(str));
return RegexParser.Escape(str);
}
/// <summary>
/// Unescapes any escaped characters in the input string.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Unescape", Justification = "Already shipped since v1 - can't fix without causing a breaking change")]
public static String Unescape(String str)
{
if (str == null)
throw new ArgumentNullException(nameof(str));
return RegexParser.Unescape(str);
}
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety")]
public static int CacheSize
{
get
{
return s_cacheSize;
}
set
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value));
s_cacheSize = value;
if (s_livecode.Count > s_cacheSize)
{
lock (s_livecode)
{
while (s_livecode.Count > s_cacheSize)
s_livecode.RemoveLast();
}
}
}
}
/// <summary>
/// Returns the options passed into the constructor
/// </summary>
public RegexOptions Options
{
get { return _roptions; }
}
/// <summary>
/// The match timeout used by this Regex instance.
/// </summary>
public TimeSpan MatchTimeout
{
get { return _internalMatchTimeout; }
}
/// <summary>
/// Indicates whether the regular expression matches from right to left.
/// </summary>
public bool RightToLeft
{
get
{
return UseOptionR();
}
}
/// <summary>
/// Returns the regular expression pattern passed into the constructor
/// </summary>
public override string ToString()
{
return _pattern;
}
/*
* Returns an array of the group names that are used to capture groups
* in the regular expression. Only needed if the regex is not known until
* runtime, and one wants to extract captured groups. (Probably unusual,
* but supplied for completeness.)
*/
/// <summary>
/// Returns the GroupNameCollection for the regular expression. This collection contains the
/// set of strings used to name capturing groups in the expression.
/// </summary>
public String[] GetGroupNames()
{
String[] result;
if (_capslist == null)
{
int max = _capsize;
result = new String[max];
for (int i = 0; i < max; i++)
{
result[i] = Convert.ToString(i, CultureInfo.InvariantCulture);
}
}
else
{
result = new String[_capslist.Length];
System.Array.Copy(_capslist, 0, result, 0, _capslist.Length);
}
return result;
}
/*
* Returns an array of the group numbers that are used to capture groups
* in the regular expression. Only needed if the regex is not known until
* runtime, and one wants to extract captured groups. (Probably unusual,
* but supplied for completeness.)
*/
/// <summary>
/// Returns the integer group number corresponding to a group name.
/// </summary>
public int[] GetGroupNumbers()
{
int[] result;
if (_caps == null)
{
int max = _capsize;
result = new int[max];
for (int i = 0; i < max; i++)
{
result[i] = i;
}
}
else
{
result = new int[_caps.Count];
foreach (KeyValuePair<int, int> kvp in _caps)
{
result[kvp.Value] = kvp.Key;
}
}
return result;
}
/*
* Given a group number, maps it to a group name. Note that numbered
* groups automatically get a group name that is the decimal string
* equivalent of its number.
*
* Returns null if the number is not a recognized group number.
*/
/// <summary>
/// Retrieves a group name that corresponds to a group number.
/// </summary>
public String GroupNameFromNumber(int i)
{
if (_capslist == null)
{
if (i >= 0 && i < _capsize)
return i.ToString(CultureInfo.InvariantCulture);
return String.Empty;
}
else
{
if (_caps != null)
{
if (!_caps.TryGetValue(i, out i))
return String.Empty;
}
if (i >= 0 && i < _capslist.Length)
return _capslist[i];
return String.Empty;
}
}
/*
* Given a group name, maps it to a group number. Note that numbered
* groups automatically get a group name that is the decimal string
* equivalent of its number.
*
* Returns -1 if the name is not a recognized group name.
*/
/// <summary>
/// Returns a group number that corresponds to a group name.
/// </summary>
public int GroupNumberFromName(String name)
{
int result = -1;
if (name == null)
throw new ArgumentNullException(nameof(name));
// look up name if we have a hashtable of names
if (_capnames != null)
{
if (!_capnames.TryGetValue(name, out result))
return -1;
return result;
}
// convert to an int if it looks like a number
result = 0;
for (int i = 0; i < name.Length; i++)
{
char ch = name[i];
if (ch > '9' || ch < '0')
return -1;
result *= 10;
result += (ch - '0');
}
// return int if it's in range
if (result >= 0 && result < _capsize)
return result;
return -1;
}
/*
* Static version of simple IsMatch call
*/
/// <summary>
/// Searches the input string for one or more occurrences of the text supplied in the given pattern.
/// </summary>
public static bool IsMatch(String input, String pattern)
{
return IsMatch(input, pattern, RegexOptions.None, DefaultMatchTimeout);
}
/*
* Static version of simple IsMatch call
*/
/// <summary>
/// Searches the input string for one or more occurrences of the text
/// supplied in the pattern parameter with matching options supplied in the options
/// parameter.
/// </summary>
public static bool IsMatch(String input, String pattern, RegexOptions options)
{
return IsMatch(input, pattern, options, DefaultMatchTimeout);
}
public static bool IsMatch(String input, String pattern, RegexOptions options, TimeSpan matchTimeout)
{
return new Regex(pattern, options, matchTimeout, true).IsMatch(input);
}
/*
* Returns true if the regex finds a match within the specified string
*/
/// <summary>
/// Searches the input string for one or more matches using the previous pattern,
/// options, and starting position.
/// </summary>
public bool IsMatch(String input)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return IsMatch(input, UseOptionR() ? input.Length : 0);
}
/*
* Returns true if the regex finds a match after the specified position
* (proceeding leftward if the regex is leftward and rightward otherwise)
*/
/// <summary>
/// Searches the input string for one or more matches using the previous pattern and options,
/// with a new starting position.
/// </summary>
public bool IsMatch(String input, int startat)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return (null == Run(true, -1, input, 0, input.Length, startat));
}
/*
* Static version of simple Match call
*/
/// <summary>
/// Searches the input string for one or more occurrences of the text
/// supplied in the pattern parameter.
/// </summary>
public static Match Match(String input, String pattern)
{
return Match(input, pattern, RegexOptions.None, DefaultMatchTimeout);
}
/*
* Static version of simple Match call
*/
/// <summary>
/// Searches the input string for one or more occurrences of the text
/// supplied in the pattern parameter. Matching is modified with an option
/// string.
/// </summary>
public static Match Match(String input, String pattern, RegexOptions options)
{
return Match(input, pattern, options, DefaultMatchTimeout);
}
public static Match Match(String input, String pattern, RegexOptions options, TimeSpan matchTimeout)
{
return new Regex(pattern, options, matchTimeout, true).Match(input);
}
/*
* Finds the first match for the regular expression starting at the beginning
* of the string (or at the end of the string if the regex is leftward)
*/
/// <summary>
/// Matches a regular expression with a string and returns
/// the precise result as a RegexMatch object.
/// </summary>
public Match Match(String input)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return Match(input, UseOptionR() ? input.Length : 0);
}
/*
* Finds the first match, starting at the specified position
*/
/// <summary>
/// Matches a regular expression with a string and returns
/// the precise result as a RegexMatch object.
/// </summary>
public Match Match(String input, int startat)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return Run(false, -1, input, 0, input.Length, startat);
}
/*
* Finds the first match, restricting the search to the specified interval of
* the char array.
*/
/// <summary>
/// Matches a regular expression with a string and returns the precise result as a
/// RegexMatch object.
/// </summary>
public Match Match(String input, int beginning, int length)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return Run(false, -1, input, beginning, length, UseOptionR() ? beginning + length : beginning);
}
/*
* Static version of simple Matches call
*/
/// <summary>
/// Returns all the successful matches as if Match were called iteratively numerous times.
/// </summary>
public static MatchCollection Matches(String input, String pattern)
{
return Matches(input, pattern, RegexOptions.None, DefaultMatchTimeout);
}
/*
* Static version of simple Matches call
*/
/// <summary>
/// Returns all the successful matches as if Match were called iteratively numerous times.
/// </summary>
public static MatchCollection Matches(String input, String pattern, RegexOptions options)
{
return Matches(input, pattern, options, DefaultMatchTimeout);
}
public static MatchCollection Matches(String input, String pattern, RegexOptions options, TimeSpan matchTimeout)
{
return new Regex(pattern, options, matchTimeout, true).Matches(input);
}
/*
* Finds the first match for the regular expression starting at the beginning
* of the string Enumerator(or at the end of the string if the regex is leftward)
*/
/// <summary>
/// Returns all the successful matches as if Match was called iteratively numerous times.
/// </summary>
public MatchCollection Matches(String input)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return Matches(input, UseOptionR() ? input.Length : 0);
}
/*
* Finds the first match, starting at the specified position
*/
/// <summary>
/// Returns all the successful matches as if Match was called iteratively numerous times.
/// </summary>
public MatchCollection Matches(String input, int startat)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return new MatchCollection(this, input, 0, input.Length, startat);
}
/// <summary>
/// Replaces all occurrences of the pattern with the <paramref name="replacement"/> pattern, starting at
/// the first character in the input string.
/// </summary>
public static String Replace(String input, String pattern, String replacement)
{
return Replace(input, pattern, replacement, RegexOptions.None, DefaultMatchTimeout);
}
/// <summary>
/// Replaces all occurrences of
/// the <paramref name="pattern "/>with the <paramref name="replacement "/>
/// pattern, starting at the first character in the input string.
/// </summary>
public static String Replace(String input, String pattern, String replacement, RegexOptions options)
{
return Replace(input, pattern, replacement, options, DefaultMatchTimeout);
}
public static String Replace(String input, String pattern, String replacement, RegexOptions options, TimeSpan matchTimeout)
{
return new Regex(pattern, options, matchTimeout, true).Replace(input, replacement);
}
/// <summary>
/// Replaces all occurrences of the previously defined pattern with the
/// <paramref name="replacement"/> pattern, starting at the first character in the
/// input string.
/// </summary>
public String Replace(String input, String replacement)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return Replace(input, replacement, -1, UseOptionR() ? input.Length : 0);
}
/// <summary>
/// Replaces all occurrences of the previously defined pattern with the
/// <paramref name="replacement"/> pattern, starting at the first character in the
/// input string.
/// </summary>
public String Replace(String input, String replacement, int count)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return Replace(input, replacement, count, UseOptionR() ? input.Length : 0);
}
/// <summary>
/// Replaces all occurrences of the previously defined pattern with the
/// <paramref name="replacement"/> pattern, starting at the character position
/// <paramref name="startat"/>.
/// </summary>
public String Replace(String input, String replacement, int count, int startat)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
if (replacement == null)
throw new ArgumentNullException(nameof(replacement));
// a little code to grab a cached parsed replacement object
RegexReplacement repl = (RegexReplacement)_replref.Get();
if (repl == null || !repl.Pattern.Equals(replacement))
{
repl = RegexParser.ParseReplacement(replacement, _caps, _capsize, _capnames, _roptions);
_replref.Cache(repl);
}
return repl.Replace(this, input, count, startat);
}
/// <summary>
/// Replaces all occurrences of the <paramref name="pattern"/> with the recent
/// replacement pattern.
/// </summary>
public static String Replace(String input, String pattern, MatchEvaluator evaluator)
{
return Replace(input, pattern, evaluator, RegexOptions.None, DefaultMatchTimeout);
}
/// <summary>
/// Replaces all occurrences of the <paramref name="pattern"/> with the recent
/// replacement pattern, starting at the first character.
/// </summary>
public static String Replace(String input, String pattern, MatchEvaluator evaluator, RegexOptions options)
{
return Replace(input, pattern, evaluator, options, DefaultMatchTimeout);
}
public static String Replace(String input, String pattern, MatchEvaluator evaluator, RegexOptions options, TimeSpan matchTimeout)
{
return new Regex(pattern, options, matchTimeout, true).Replace(input, evaluator);
}
/// <summary>
/// Replaces all occurrences of the previously defined pattern with the recent
/// replacement pattern, starting at the first character position.
/// </summary>
public String Replace(String input, MatchEvaluator evaluator)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return Replace(input, evaluator, -1, UseOptionR() ? input.Length : 0);
}
/// <summary>
/// Replaces all occurrences of the previously defined pattern with the recent
/// replacement pattern, starting at the first character position.
/// </summary>
public String Replace(String input, MatchEvaluator evaluator, int count)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return Replace(input, evaluator, count, UseOptionR() ? input.Length : 0);
}
/// <summary>
/// Replaces all occurrences of the previously defined pattern with the recent
/// replacement pattern, starting at the character position
/// <paramref name="startat"/>.
/// </summary>
public String Replace(String input, MatchEvaluator evaluator, int count, int startat)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return RegexReplacement.Replace(evaluator, this, input, count, startat);
}
/// <summary>
/// Splits the <paramref name="input "/>string at the position defined
/// by <paramref name="pattern"/>.
/// </summary>
public static String[] Split(String input, String pattern)
{
return Split(input, pattern, RegexOptions.None, DefaultMatchTimeout);
}
/// <summary>
/// Splits the <paramref name="input "/>string at the position defined by <paramref name="pattern"/>.
/// </summary>
public static String[] Split(String input, String pattern, RegexOptions options)
{
return Split(input, pattern, options, DefaultMatchTimeout);
}
public static String[] Split(String input, String pattern, RegexOptions options, TimeSpan matchTimeout)
{
return new Regex(pattern, options, matchTimeout, true).Split(input);
}
/// <summary>
/// Splits the <paramref name="input"/> string at the position defined by a
/// previous pattern.
/// </summary>
public String[] Split(String input)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return Split(input, 0, UseOptionR() ? input.Length : 0);
}
/// <summary>
/// Splits the <paramref name="input"/> string at the position defined by a
/// previous pattern.
/// </summary>
public String[] Split(String input, int count)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return RegexReplacement.Split(this, input, count, UseOptionR() ? input.Length : 0);
}
/// <summary>
/// Splits the <paramref name="input"/> string at the position defined by a
/// previous pattern.
/// </summary>
public String[] Split(String input, int count, int startat)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return RegexReplacement.Split(this, input, count, startat);
}
internal void InitializeReferences()
{
if (_refsInitialized)
throw new NotSupportedException(SR.OnlyAllowedOnce);
_refsInitialized = true;
_runnerref = new ExclusiveReference();
_replref = new SharedReference();
}
/*
* Internal worker called by all the public APIs
*/
internal Match Run(bool quick, int prevlen, String input, int beginning, int length, int startat)
{
Match match;
RegexRunner runner = null;
if (startat < 0 || startat > input.Length)
throw new ArgumentOutOfRangeException("start", SR.BeginIndexNotNegative);
if (length < 0 || length > input.Length)
throw new ArgumentOutOfRangeException(nameof(length), SR.LengthNotNegative);
// There may be a cached runner; grab ownership of it if we can.
runner = (RegexRunner)_runnerref.Get();
// Create a RegexRunner instance if we need to
if (runner == null)
{
runner = new RegexInterpreter(_code, UseOptionInvariant() ? CultureInfo.InvariantCulture : CultureInfo.CurrentCulture);
}
try
{
// Do the scan starting at the requested position
match = runner.Scan(this, input, beginning, beginning + length, startat, prevlen, quick, _internalMatchTimeout);
}
finally
{
// Release or fill the cache slot
_runnerref.Release(runner);
}
#if DEBUG
if (Debug && match != null)
match.Dump();
#endif
return match;
}
/*
* Find code cache based on options+pattern
*/
private static CachedCodeEntry LookupCachedAndUpdate(CachedCodeEntryKey key)
{
lock (s_livecode)
{
for (LinkedListNode<CachedCodeEntry> current = s_livecode.First; current != null; current = current.Next)
{
if (current.Value._key == key)
{
// If we find an entry in the cache, move it to the head at the same time.
s_livecode.Remove(current);
s_livecode.AddFirst(current);
return current.Value;
}
}
}
return null;
}
/*
* Add current code to the cache
*/
private CachedCodeEntry CacheCode(CachedCodeEntryKey key)
{
CachedCodeEntry newcached = null;
lock (s_livecode)
{
// first look for it in the cache and move it to the head
for (LinkedListNode<CachedCodeEntry> current = s_livecode.First; current != null; current = current.Next)
{
if (current.Value._key == key)
{
s_livecode.Remove(current);
s_livecode.AddFirst(current);
return current.Value;
}
}
// it wasn't in the cache, so we'll add a new one. Shortcut out for the case where cacheSize is zero.
if (s_cacheSize != 0)
{
newcached = new CachedCodeEntry(key, _capnames, _capslist, _code, _caps, _capsize, _runnerref, _replref);
s_livecode.AddFirst(newcached);
if (s_livecode.Count > s_cacheSize)
s_livecode.RemoveLast();
}
}
return newcached;
}
/*
* True if the L option was set
*/
internal bool UseOptionR()
{
return (_roptions & RegexOptions.RightToLeft) != 0;
}
internal bool UseOptionInvariant()
{
return (_roptions & RegexOptions.CultureInvariant) != 0;
}
#if DEBUG
/*
* True if the regex has debugging enabled
*/
internal bool Debug
{
get
{
return (_roptions & RegexOptions.Debug) != 0;
}
}
#endif
}
/*
* Callback class
*/
public delegate String MatchEvaluator(Match match);
/*
* Used as a key for CacheCodeEntry
*/
internal struct CachedCodeEntryKey : IEquatable<CachedCodeEntryKey>
{
private readonly RegexOptions _options;
private readonly string _cultureKey;
private readonly string _pattern;
internal CachedCodeEntryKey(RegexOptions options, string cultureKey, string pattern)
{
_options = options;
_cultureKey = cultureKey;
_pattern = pattern;
}
public override bool Equals(object obj)
{
return obj is CachedCodeEntryKey && Equals((CachedCodeEntryKey)obj);
}
public bool Equals(CachedCodeEntryKey other)
{
return this == other;
}
public static bool operator ==(CachedCodeEntryKey left, CachedCodeEntryKey right)
{
return left._options == right._options && left._cultureKey == right._cultureKey && left._pattern == right._pattern;
}
public static bool operator !=(CachedCodeEntryKey left, CachedCodeEntryKey right)
{
return !(left == right);
}
public override int GetHashCode()
{
return ((int)_options) ^ _cultureKey.GetHashCode() ^ _pattern.GetHashCode();
}
}
/*
* Used to cache byte codes
*/
internal sealed class CachedCodeEntry
{
internal CachedCodeEntryKey _key;
internal RegexCode _code;
internal Dictionary<Int32, Int32> _caps;
internal Dictionary<String, Int32> _capnames;
internal String[] _capslist;
internal int _capsize;
internal ExclusiveReference _runnerref;
internal SharedReference _replref;
internal CachedCodeEntry(CachedCodeEntryKey key, Dictionary<String, Int32> capnames, String[] capslist, RegexCode code, Dictionary<Int32, Int32> caps, int capsize, ExclusiveReference runner, SharedReference repl)
{
_key = key;
_capnames = capnames;
_capslist = capslist;
_code = code;
_caps = caps;
_capsize = capsize;
_runnerref = runner;
_replref = repl;
}
}
/*
* Used to cache one exclusive runner reference
*/
internal sealed class ExclusiveReference
{
private RegexRunner _ref;
private Object _obj;
private int _locked;
/*
* Return an object and grab an exclusive lock.
*
* If the exclusive lock can't be obtained, null is returned;
* if the object can't be returned, the lock is released.
*
*/
internal Object Get()
{
// try to obtain the lock
if (0 == Interlocked.Exchange(ref _locked, 1))
{
// grab reference
Object obj = _ref;
// release the lock and return null if no reference
if (obj == null)
{
_locked = 0;
return null;
}
// remember the reference and keep the lock
_obj = obj;
return obj;
}
return null;
}
/*
* Release an object back to the cache
*
* If the object is the one that's under lock, the lock
* is released.
*
* If there is no cached object, then the lock is obtained
* and the object is placed in the cache.
*
*/
internal void Release(Object obj)
{
if (obj == null)
throw new ArgumentNullException(nameof(obj));
// if this reference owns the lock, release it
if (_obj == obj)
{
_obj = null;
_locked = 0;
return;
}
// if no reference owns the lock, try to cache this reference
if (_obj == null)
{
// try to obtain the lock
if (0 == Interlocked.Exchange(ref _locked, 1))
{
// if there's really no reference, cache this reference
if (_ref == null)
_ref = (RegexRunner)obj;
// release the lock
_locked = 0;
return;
}
}
}
}
/*
* Used to cache a weak reference in a threadsafe way
*/
internal sealed class SharedReference
{
private WeakReference _ref = new WeakReference(null);
private int _locked;
/*
* Return an object from a weakref, protected by a lock.
*
* If the exclusive lock can't be obtained, null is returned;
*
* Note that _ref.Target is referenced only under the protection
* of the lock. (Is this necessary?)
*/
internal Object Get()
{
if (0 == Interlocked.Exchange(ref _locked, 1))
{
Object obj = _ref.Target;
_locked = 0;
return obj;
}
return null;
}
/*
* Suggest an object into a weakref, protected by a lock.
*
* Note that _ref.Target is referenced only under the protection
* of the lock. (Is this necessary?)
*/
internal void Cache(Object obj)
{
if (0 == Interlocked.Exchange(ref _locked, 1))
{
_ref.Target = obj;
_locked = 0;
}
}
}
}
| |
// Copyright (c) Martin Costello, 2017. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
using JustEat.HttpClientInterception;
using MartinCostello.LondonTravel.Site.Options;
using Microsoft.Extensions.Caching.Memory;
using Refit;
namespace MartinCostello.LondonTravel.Site.Services.Tfl;
public sealed class TflServiceTests : IDisposable
{
private readonly IMemoryCache _cache;
private readonly HttpClientInterceptorOptions _interceptor;
private readonly TflOptions _options;
public TflServiceTests()
{
_interceptor = new HttpClientInterceptorOptions()
{
ThrowOnMissingRegistration = true,
};
_options = CreateOptions();
_cache = CreateCache();
}
public void Dispose()
{
_cache?.Dispose();
}
[Fact]
public async Task Can_Get_Line_Information_If_Response_Can_Be_Cached()
{
// Arrange
var builder = CreateBuilder()
.Requests()
.ForPath("Line/Mode/dlr%2Coverground%2Ctflrail%2Ctube")
.Responds()
.WithResponseHeader("Cache-Control", "max-age=3600")
.WithJsonContent(new[] { new { id = "waterloo-city", name = "Waterloo & City" } });
_interceptor.Register(builder);
using var httpClient = _interceptor.CreateHttpClient();
httpClient.BaseAddress = _options.BaseUri;
var client = Refit.RestService.For<ITflClient>(httpClient);
var target = new TflService(client, _cache, _options);
// Act
ICollection<LineInfo> actual1 = await target.GetLinesAsync();
ICollection<LineInfo> actual2 = await target.GetLinesAsync();
// Assert
Assert.NotNull(actual1);
Assert.Equal(1, actual1.Count);
var item = actual1.First();
Assert.Equal("waterloo-city", item.Id);
Assert.Equal("Waterloo & City", item.Name);
Assert.Same(actual1, actual2);
}
[Fact]
public async Task Can_Get_Line_Information_If_Response_Cannot_Be_Cached()
{
// Arrange
var builder = CreateBuilder()
.Requests()
.ForPath("Line/Mode/dlr%2Coverground%2Ctflrail%2Ctube")
.Responds()
.WithJsonContent(new[] { new { id = "district", name = "District" } });
_interceptor.Register(builder);
using var httpClient = _interceptor.CreateHttpClient();
httpClient.BaseAddress = _options.BaseUri;
ITflClient client = CreateClient(httpClient);
var target = new TflService(client, _cache, _options);
// Act
ICollection<LineInfo> actual1 = await target.GetLinesAsync();
ICollection<LineInfo> actual2 = await target.GetLinesAsync();
// Assert
Assert.NotNull(actual1);
Assert.Equal(1, actual1.Count);
var item = actual1.First();
Assert.Equal("district", item.Id);
Assert.Equal("District", item.Name);
Assert.NotSame(actual1, actual2);
}
[Fact]
public async Task Can_Get_Stop_Points_If_Response_Can_Be_Cached()
{
// Arrange
var builder = CreateBuilder()
.Requests()
.ForPath("Line/victoria/StopPoints")
.Responds()
.WithResponseHeader("Cache-Control", "max-age=3600")
.WithJsonContent(new[] { new { id = "940GZZLUOXC", commonName = "Oxford Circus Underground Station", lat = 51.515224, lon = -0.141903 } });
_interceptor.Register(builder);
using var httpClient = _interceptor.CreateHttpClient();
httpClient.BaseAddress = _options.BaseUri;
ITflClient client = CreateClient(httpClient);
var target = new TflService(client, _cache, _options);
// Act
ICollection<StopPoint> actual1 = await target.GetStopPointsByLineAsync("victoria");
ICollection<StopPoint> actual2 = await target.GetStopPointsByLineAsync("victoria");
// Assert
Assert.NotNull(actual1);
Assert.Equal(1, actual1.Count);
var item = actual1.First();
Assert.Equal("940GZZLUOXC", item.Id);
Assert.Equal("Oxford Circus Underground Station", item.Name);
Assert.Equal(51.515224, item.Latitude);
Assert.Equal(-0.141903, item.Longitude);
Assert.Same(actual1, actual2);
}
[Fact]
public async Task Can_Get_Stop_Points_If_Response_Cannot_Be_Cached()
{
// Arrange
var builder = CreateBuilder()
.Requests()
.ForPath("Line/victoria/StopPoints")
.Responds()
.WithJsonContent(new[] { new { id = "940GZZLUGPK", commonName = "Green Park Underground Station", lat = 51.506947, lon = -0.142787 } });
_interceptor.Register(builder);
using var httpClient = _interceptor.CreateHttpClient();
httpClient.BaseAddress = _options.BaseUri;
ITflClient client = CreateClient(httpClient);
var target = new TflService(client, _cache, _options);
// Act
ICollection<StopPoint> actual1 = await target.GetStopPointsByLineAsync("victoria");
ICollection<StopPoint> actual2 = await target.GetStopPointsByLineAsync("victoria");
// Assert
Assert.NotNull(actual1);
Assert.Equal(1, actual1.Count);
var item = actual1.First();
Assert.Equal("940GZZLUGPK", item.Id);
Assert.Equal("Green Park Underground Station", item.Name);
Assert.Equal(51.506947, item.Latitude);
Assert.Equal(-0.142787, item.Longitude);
Assert.NotSame(actual1, actual2);
}
private static HttpRequestInterceptionBuilder CreateBuilder()
{
return new HttpRequestInterceptionBuilder()
.ForHttps()
.ForHost("api.tfl.gov.uk")
.ForQuery("app_id=My-App-Id&app_key=My-App-Key");
}
private static IMemoryCache CreateCache()
{
var cacheOptions = new MemoryCacheOptions();
var options = Microsoft.Extensions.Options.Options.Create(cacheOptions);
return new MemoryCache(options);
}
private static ITflClient CreateClient(HttpClient httpClient)
{
var settings = new RefitSettings() { ContentSerializer = new SystemTextJsonContentSerializer() };
return RestService.For<ITflClient>(httpClient, settings);
}
private static TflOptions CreateOptions()
{
return new TflOptions()
{
AppId = "My-App-Id",
AppKey = "My-App-Key",
BaseUri = new Uri("https://api.tfl.gov.uk/"),
SupportedModes = new[] { "dlr", "overground", "tflrail", "tube" },
};
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.IdentityModel
{
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Security.Principal;
using System.ServiceModel.Diagnostics;
using System.Runtime.Versioning;
class Privilege
{
static Dictionary<string, LUID> luids = new Dictionary<string, LUID>();
public const string SeAuditPrivilege = "SeAuditPrivilege";
public const string SeTcbPrivilege = "SeTcbPrivilege";
const uint SE_PRIVILEGE_DISABLED = 0x00000000;
const uint SE_PRIVILEGE_ENABLED_BY_DEFAULT = 0x00000001;
const uint SE_PRIVILEGE_ENABLED = 0x00000002;
const uint SE_PRIVILEGE_USED_FOR_ACCESS = 0x80000000;
const int ERROR_SUCCESS = 0x0;
const int ERROR_NO_TOKEN = 0x3F0;
const int ERROR_NOT_ALL_ASSIGNED = 0x514;
string privilege;
LUID luid;
bool needToRevert = false;
bool initialEnabled = false;
bool isImpersonating = false;
SafeCloseHandle threadToken = null;
public Privilege(string privilege)
{
this.privilege = privilege;
this.luid = LuidFromPrivilege(privilege);
}
public void Enable()
{
// Note: AdjustTokenPrivileges should not try to adjust if the token is
// Primary token (process). Duplicate the process token (impersonation) and
// then set token to current thread and unsetting (RevertToSelf) later.
DiagnosticUtility.DebugAssert(this.threadToken == null, "");
this.threadToken = GetThreadToken();
EnableTokenPrivilege(this.threadToken);
}
// Have to run in CER
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public int Revert()
{
if (!this.isImpersonating)
{
if (this.needToRevert && !this.initialEnabled)
{
TOKEN_PRIVILEGE newState;
newState.PrivilegeCount = 1;
newState.Privilege.Luid = this.luid;
newState.Privilege.Attributes = SE_PRIVILEGE_DISABLED;
TOKEN_PRIVILEGE previousState;
uint previousSize = 0;
if (!NativeMethods.AdjustTokenPrivileges(
this.threadToken,
false,
ref newState,
TOKEN_PRIVILEGE.Size,
out previousState,
out previousSize))
{
return Marshal.GetLastWin32Error();
}
}
this.needToRevert = false;
}
else
{
if (!NativeMethods.RevertToSelf())
{
return Marshal.GetLastWin32Error();
}
this.isImpersonating = false;
}
if (this.threadToken != null)
{
this.threadToken.Close();
this.threadToken = null;
}
return ERROR_SUCCESS;
}
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption( ResourceScope.Process, ResourceScope.Process )]
SafeCloseHandle GetThreadToken()
{
//
// Open the thread token; if there is no thread token, get one from
// the process token by impersonating self.
//
SafeCloseHandle threadToken;
if (!NativeMethods.OpenThreadToken(
NativeMethods.GetCurrentThread(),
TokenAccessLevels.Query | TokenAccessLevels.AdjustPrivileges,
true,
out threadToken))
{
int error = Marshal.GetLastWin32Error();
Utility.CloseInvalidOutSafeHandle(threadToken);
if (error != ERROR_NO_TOKEN)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error));
}
else
{
SafeCloseHandle processToken;
if (!NativeMethods.OpenProcessToken(
NativeMethods.GetCurrentProcess(),
TokenAccessLevels.Duplicate,
out processToken))
{
error = Marshal.GetLastWin32Error();
Utility.CloseInvalidOutSafeHandle(processToken);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error));
}
try
{
if (!NativeMethods.DuplicateTokenEx(
processToken,
TokenAccessLevels.Impersonate | TokenAccessLevels.Query | TokenAccessLevels.AdjustPrivileges,
IntPtr.Zero,
SECURITY_IMPERSONATION_LEVEL.Impersonation,
TokenType.TokenImpersonation,
out threadToken))
{
error = Marshal.GetLastWin32Error();
Utility.CloseInvalidOutSafeHandle(threadToken);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error));
}
SetThreadToken(threadToken);
}
finally
{
processToken.Close();
}
}
}
return threadToken;
}
void EnableTokenPrivilege(SafeCloseHandle threadToken)
{
DiagnosticUtility.DebugAssert(!this.needToRevert, "");
TOKEN_PRIVILEGE newState;
newState.PrivilegeCount = 1;
newState.Privilege.Luid = this.luid;
newState.Privilege.Attributes = SE_PRIVILEGE_ENABLED;
TOKEN_PRIVILEGE previousState;
uint previousSize = 0;
bool success = false;
int error = 0;
// CER
RuntimeHelpers.PrepareConstrainedRegions();
try
{
}
finally
{
success = NativeMethods.AdjustTokenPrivileges(
threadToken,
false,
ref newState,
TOKEN_PRIVILEGE.Size,
out previousState,
out previousSize);
error = Marshal.GetLastWin32Error();
if (success && error == ERROR_SUCCESS)
{
this.initialEnabled = (0 != (previousState.Privilege.Attributes & SE_PRIVILEGE_ENABLED));
this.needToRevert = true;
}
}
if (error == ERROR_NOT_ALL_ASSIGNED)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new PrivilegeNotHeldException(this.privilege));
}
else if (!success)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error));
}
}
void SetThreadToken(SafeCloseHandle threadToken)
{
DiagnosticUtility.DebugAssert(!this.isImpersonating, "");
int error = 0;
// CER
RuntimeHelpers.PrepareConstrainedRegions();
try
{
}
finally
{
if (!NativeMethods.SetThreadToken(IntPtr.Zero, threadToken))
{
error = Marshal.GetLastWin32Error();
}
else
{
this.isImpersonating = true;
}
}
if (!this.isImpersonating)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error));
}
}
static LUID LuidFromPrivilege(string privilege)
{
LUID luid;
lock (luids)
{
if (luids.TryGetValue(privilege, out luid))
{
return luid;
}
}
if (!NativeMethods.LookupPrivilegeValueW(null, privilege, out luid))
{
int error = Marshal.GetLastWin32Error();
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error));
}
lock (luids)
{
if (!luids.ContainsKey(privilege))
{
luids[privilege] = luid;
}
}
return luid;
}
}
}
| |
/*
Copyright 2014 David Bordoley
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;
using System.Collections.Generic;
using System.Linq;
using System.Reactive;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using System.Threading;
using System.Threading.Tasks;
namespace SQLitePCL.pretty
{
/// <summary>
/// Extensions methods for <see cref="IAsyncStatement"/>.
/// </summary>
public static class AsyncStatement
{
/// <summary>
/// Schedules the <see cref="Action"/> <paramref name="f"/> on the statement's operations queue.
/// </summary>
/// <param name="This">The async statement.</param>
/// <param name="f">The action.</param>
/// <param name="cancellationToken">Cancellation token that can be used to cancel the task.</param>
/// <returns>A task that completes when <paramref name="f"/> returns.</returns>
public static Task Use(
this IAsyncStatement This,
Action<IStatement, CancellationToken> f,
CancellationToken cancellationToken)
{
Contract.Requires(f != null);
return This.Use((stmt, ct) =>
{
f(stmt, ct);
return Enumerable.Empty<Unit>();
}, cancellationToken);
}
/// <summary>
/// Schedules the <see cref="Action"/> <paramref name="f"/> on the statement's operations queue.
/// </summary>
/// <param name="This">The async statement.</param>
/// <param name="f">The action.</param>
/// <returns>A task that completes when <paramref name="f"/> returns.</returns>
public static Task Use(this IAsyncStatement This, Action<IStatement> f) =>
This.Use((stmt, ct) => f(stmt), CancellationToken.None);
/// <summary>
/// Schedules the <see cref="Func<T,TResult>"/> <paramref name="f"/> on the statement's operations queue.
/// </summary>
/// <typeparam name="T">The result type.</typeparam>
/// <param name="This">The async statement.</param>
/// <param name="f">A function from <see cref="IAsyncStatement"/> to <typeparamref name="T"/>.</param>
/// <param name="cancellationToken">Cancellation token that can be used to cancel the task.</param>
/// <returns>A task that completes with the result of <paramref name="f"/>.</returns>
public static Task<T> Use<T>(
this IAsyncStatement This,
Func<IStatement, CancellationToken, T> f,
CancellationToken cancellationToken)
{
Contract.Requires(This != null);
Contract.Requires(f != null);
return This.Use((conn, ct) => new[] { f(conn, ct) }).ToTask(cancellationToken);
}
/// <summary>
/// Schedules the <see cref="Func<T,TResult>"/> <paramref name="f"/> on the statement's operations queue.
/// </summary>
/// <typeparam name="T">The result type.</typeparam>
/// <param name="This">The async statement.</param>
/// <param name="f">A function from <see cref="IAsyncStatement"/> to <typeparamref name="T"/>.</param>
/// <returns>A task that completes with the result of <paramref name="f"/>.</returns>
public static Task<T> Use<T>(this IAsyncStatement This, Func<IStatement, T> f) =>
This.Use((stmt, ct) => f(stmt), CancellationToken.None);
/// <summary>
/// Returns a cold IObservable which schedules the function f on the statement's database operation queue each
/// time it is is subscribed to. The published values are generated by enumerating the IEnumerable returned by f.
/// </summary>
/// <typeparam name="T">The result type.</typeparam>
/// <param name="This">The async statement.</param>
/// <param name="f">
/// A function that may synchronously use the provided IStatement and returns
/// an IEnumerable of produced values that are published to the subscribed IObserver.
/// The returned IEnumerable may block. This allows the IEnumerable to provide the results of
/// enumerating the prepared statement for instance.
/// </param>
/// <returns>A cold observable of the values produced by the function f.</returns>
public static IObservable<T> Use<T>(this IAsyncStatement This, Func<IStatement, IEnumerable<T>> f) =>
This.Use((stmt, ct) => f(stmt));
/// <summary>
/// Executes the <see cref="IStatement"/> with provided bind parameter values.
/// </summary>
/// <param name="This">The async statement.</param>
/// <param name="cancellationToken">Cancellation token that can be used to cancel the task.</param>
/// <param name="values">The position indexed values to bind.</param>
/// <returns>A <see cref="Task"/> that completes when the statement is executed.</returns>
public static Task ExecuteAsync(
this IAsyncStatement This,
CancellationToken cancellationToken,
params object[] values) =>
This.Use((stmt, ct) => { stmt.Execute(values); }, cancellationToken);
/// <summary>
/// Executes the <see cref="IStatement"/> with provided bind parameter values.
/// </summary>
/// <param name="This">The async statement.</param>
/// <param name="values">The position indexed values to bind.</param>
/// <returns>A <see cref="Task"/> that completes when the statement is executed.</returns>
public static Task ExecuteAsync(this IAsyncStatement This, params object[] values) =>
This.ExecuteAsync(CancellationToken.None, values);
/// <summary>
/// Queries the database asynchronously using the provided IStatement and provided bind variables.
/// </summary>
/// <param name="This">The async statement.</param>
/// <param name="values">The position indexed values to bind.</param>
/// <returns>A cold IObservable of the rows in the result set.</returns>
public static IObservable<IReadOnlyList<IResultSetValue>> Query(this IAsyncStatement This, params object[] values) =>
This.Use<IReadOnlyList<IResultSetValue>>(stmt => stmt.Query(values));
/// <summary>
/// Queries the database asynchronously using the provided IStatement
/// </summary>
/// <param name="This">The async statement.</param>
/// <returns>A cold IObservable of the rows in the result set.</returns>
public static IObservable<IReadOnlyList<IResultSetValue>> Query(this IAsyncStatement This) =>
This.Use<IReadOnlyList<IResultSetValue>>(stmt => stmt.Query());
}
internal class AsyncStatementImpl : IAsyncStatement
{
private readonly IStatement stmt;
private readonly IAsyncDatabaseConnection conn;
private bool disposed = false;
internal AsyncStatementImpl(IStatement stmt, IAsyncDatabaseConnection conn)
{
this.stmt = stmt;
this.conn = conn;
}
public IObservable<T> Use<T>(Func<IStatement, CancellationToken, IEnumerable<T>> f)
{
Contract.Requires(f != null);
if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); }
return Observable.Create((IObserver<T> observer, CancellationToken cancellationToken) =>
{
// Prevent calls to subscribe after the statement is disposed
if (this.disposed)
{
observer.OnError(new ObjectDisposedException(this.GetType().FullName));
return Task.FromResult(Unit.Default);
}
return conn.Use((_, ct) =>
{
ct.ThrowIfCancellationRequested();
// Note: Diposing the statement wrapper doesn't dispose the underlying statement
// The intent here is to prevent access to the underlying statement outside of the
// function call.
using (var stmt = new StatementWrapper(this.stmt))
{
foreach (var e in f(stmt, ct))
{
observer.OnNext(e);
cancellationToken.ThrowIfCancellationRequested();
}
}
}, cancellationToken);
});
}
public void Dispose()
{
if (disposed)
{
return;
}
disposed = true;
conn.Use(_ =>
{
stmt.Dispose();
});
}
private sealed class StatementWrapper : IStatement
{
private readonly IStatement stmt;
private bool disposed = false;
internal StatementWrapper(IStatement stmt)
{
this.stmt = stmt;
}
public IReadOnlyOrderedDictionary<string, IBindParameter> BindParameters
{
get
{
if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); }
// FIXME: If someone keeps a reference to this list it leaks the implementation out
return stmt.BindParameters;
}
}
public IReadOnlyList<ColumnInfo> Columns
{
get
{
if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); }
// FIXME: If someone keeps a reference to this list it leaks the implementation out
return stmt.Columns;
}
}
public string SQL
{
get
{
if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); }
return stmt.SQL;
}
}
public bool IsReadOnly
{
get
{
if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); }
return stmt.IsReadOnly;
}
}
public bool IsBusy
{
get
{
if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); }
return stmt.IsBusy;
}
}
public void ClearBindings()
{
if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); }
stmt.ClearBindings();
}
public IReadOnlyList<IResultSetValue> Current
{
get
{
if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); }
// FIXME: If someone keeps a reference to this list it leaks the implementation out
return stmt.Current;
}
}
object IEnumerator.Current
{
get
{
return this.Current;
}
}
public bool MoveNext()
{
if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); }
return stmt.MoveNext();
}
public void Reset()
{
if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); }
stmt.Reset();
}
public void Dispose()
{
// Guard against someone taking a reference to this and trying to use it outside of
// the Use function delegate
disposed = true;
// We don't actually own the statement so its not disposed
}
public int Status(StatementStatusCode statusCode, bool reset)
{
if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); }
return stmt.Status(statusCode, reset);
}
}
}
}
| |
using System.ComponentModel;
using System.Windows.Forms;
namespace WebDump
{
partial class SelectBoards
{
/// <summary>
/// Required designer variable.
/// </summary>
private IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
this.startButton = new System.Windows.Forms.Button();
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openConfigFileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveConfigFileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
this.newSiteButton = new System.Windows.Forms.Button();
this.sortSwapButton = new System.Windows.Forms.Button();
this.configureButton = new System.Windows.Forms.Button();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.menuStrip1.SuspendLayout();
this.tableLayoutPanel1.SuspendLayout();
this.SuspendLayout();
//
// flowLayoutPanel1
//
this.flowLayoutPanel1.AllowDrop = true;
this.flowLayoutPanel1.AutoScroll = true;
this.tableLayoutPanel1.SetColumnSpan(this.flowLayoutPanel1, 4);
this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.flowLayoutPanel1.Location = new System.Drawing.Point(3, 3);
this.flowLayoutPanel1.Name = "flowLayoutPanel1";
this.flowLayoutPanel1.Size = new System.Drawing.Size(891, 358);
this.flowLayoutPanel1.TabIndex = 0;
//
// startButton
//
this.startButton.Dock = System.Windows.Forms.DockStyle.Fill;
this.startButton.Location = new System.Drawing.Point(675, 367);
this.startButton.Name = "startButton";
this.startButton.Size = new System.Drawing.Size(219, 24);
this.startButton.TabIndex = 1;
this.startButton.Text = "Go";
this.startButton.UseVisualStyleBackColor = true;
this.startButton.Click += new System.EventHandler(this.startButton_Click);
//
// openFileDialog1
//
this.openFileDialog1.FileName = "openFileDialog1";
//
// menuStrip1
//
this.menuStrip1.ImageScalingSize = new System.Drawing.Size(24, 24);
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(897, 24);
this.menuStrip1.TabIndex = 20;
this.menuStrip1.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.openConfigFileToolStripMenuItem,
this.saveConfigFileToolStripMenuItem,
this.toolStripSeparator1,
this.toolStripMenuItem2,
this.toolStripMenuItem1,
this.toolStripSeparator2,
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
this.fileToolStripMenuItem.Text = "File";
//
// openConfigFileToolStripMenuItem
//
this.openConfigFileToolStripMenuItem.Name = "openConfigFileToolStripMenuItem";
this.openConfigFileToolStripMenuItem.Size = new System.Drawing.Size(259, 22);
this.openConfigFileToolStripMenuItem.Text = "Open ImageFilterFormConfig File...";
this.openConfigFileToolStripMenuItem.Click += new System.EventHandler(this.openConfigFileToolStripMenuItem_Click);
//
// saveConfigFileToolStripMenuItem
//
this.saveConfigFileToolStripMenuItem.Name = "saveConfigFileToolStripMenuItem";
this.saveConfigFileToolStripMenuItem.Size = new System.Drawing.Size(259, 22);
this.saveConfigFileToolStripMenuItem.Text = "Save ImageFilterFormConfig File...";
this.saveConfigFileToolStripMenuItem.Click += new System.EventHandler(this.saveConfigFileToolStripMenuItem_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(256, 6);
//
// toolStripMenuItem2
//
this.toolStripMenuItem2.Name = "toolStripMenuItem2";
this.toolStripMenuItem2.Size = new System.Drawing.Size(259, 22);
this.toolStripMenuItem2.Text = "Open Targets File...";
this.toolStripMenuItem2.Click += new System.EventHandler(this.openTargetsFileToolStripMenuItem_Click);
//
// toolStripMenuItem1
//
this.toolStripMenuItem1.Name = "toolStripMenuItem1";
this.toolStripMenuItem1.Size = new System.Drawing.Size(259, 22);
this.toolStripMenuItem1.Text = "Save Targets File...";
this.toolStripMenuItem1.Click += new System.EventHandler(this.saveTargetsFileToolStripMenuItem_Click);
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
this.toolStripSeparator2.Size = new System.Drawing.Size(256, 6);
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(259, 22);
this.exitToolStripMenuItem.Text = "Exit";
this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
//
// newSiteButton
//
this.newSiteButton.Dock = System.Windows.Forms.DockStyle.Fill;
this.newSiteButton.Location = new System.Drawing.Point(3, 367);
this.newSiteButton.Name = "newSiteButton";
this.newSiteButton.Size = new System.Drawing.Size(218, 24);
this.newSiteButton.TabIndex = 24;
this.newSiteButton.Text = "New Target";
this.newSiteButton.UseVisualStyleBackColor = true;
this.newSiteButton.Click += new System.EventHandler(this.newSiteButton_Click);
//
// sortSwapButton
//
this.sortSwapButton.Dock = System.Windows.Forms.DockStyle.Fill;
this.sortSwapButton.Location = new System.Drawing.Point(227, 367);
this.sortSwapButton.Name = "sortSwapButton";
this.sortSwapButton.Size = new System.Drawing.Size(218, 24);
this.sortSwapButton.TabIndex = 27;
this.sortSwapButton.Text = "Sort Boards by Name";
this.sortSwapButton.UseVisualStyleBackColor = true;
this.sortSwapButton.Click += new System.EventHandler(this.sortSwapButton_Click);
//
// configureButton
//
this.configureButton.Dock = System.Windows.Forms.DockStyle.Fill;
this.configureButton.Location = new System.Drawing.Point(451, 367);
this.configureButton.Name = "configureButton";
this.configureButton.Size = new System.Drawing.Size(218, 24);
this.configureButton.TabIndex = 28;
this.configureButton.Text = "Configure WebDump";
this.configureButton.UseVisualStyleBackColor = true;
this.configureButton.Click += new System.EventHandler(this.configureButton_Click);
//
// tableLayoutPanel1
//
this.tableLayoutPanel1.ColumnCount = 4;
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F));
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F));
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F));
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F));
this.tableLayoutPanel1.Controls.Add(this.startButton, 3, 1);
this.tableLayoutPanel1.Controls.Add(this.flowLayoutPanel1, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.newSiteButton, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.sortSwapButton, 1, 1);
this.tableLayoutPanel1.Controls.Add(this.configureButton, 2, 1);
this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 24);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
this.tableLayoutPanel1.RowCount = 2;
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 30F));
this.tableLayoutPanel1.Size = new System.Drawing.Size(897, 394);
this.tableLayoutPanel1.TabIndex = 29;
//
// SelectBoards
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(897, 418);
this.Controls.Add(this.tableLayoutPanel1);
this.Controls.Add(this.menuStrip1);
this.MainMenuStrip = this.menuStrip1;
this.Name = "SelectBoards";
this.Text = "Select Subreddits";
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.tableLayoutPanel1.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private FlowLayoutPanel flowLayoutPanel1;
private Button startButton;
private OpenFileDialog openFileDialog1;
private MenuStrip menuStrip1;
private ToolStripMenuItem fileToolStripMenuItem;
private ToolStripMenuItem openConfigFileToolStripMenuItem;
private ToolStripMenuItem saveConfigFileToolStripMenuItem;
private ToolStripMenuItem exitToolStripMenuItem;
private SaveFileDialog saveFileDialog1;
private ToolStripSeparator toolStripSeparator1;
private Button newSiteButton;
private ToolStripMenuItem toolStripMenuItem2;
private ToolStripMenuItem toolStripMenuItem1;
private ToolStripSeparator toolStripSeparator2;
private Button sortSwapButton;
private Button configureButton;
private TableLayoutPanel tableLayoutPanel1;
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.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 Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using Aurora.Framework;
using Aurora.Framework.Capabilities;
using Aurora.Framework.Servers.HttpServer;
using Aurora.Modules.AbuseReportsGUI;
using Aurora.Simulation.Base;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Services.Interfaces;
namespace Aurora.Modules.AbuseReports
{
public class AbuseReportsGUIService : IService
{
#region IService Members
private IRegistryCore m_registry;
public void Initialize(IConfigSource config, IRegistryCore registry)
{
m_registry = registry;
if (MainConsole.Instance != null)
MainConsole.Instance.Commands.AddCommand("open abusereportsGUI",
"open abusereportsGUI",
"Opens the abuse reports GUI", OpenGUI);
}
public void Start(IConfigSource config, IRegistryCore registry)
{
}
public void FinishedStartup()
{
}
#endregion
#region GUI Code
protected void OpenGUI(string[] cmdparams)
{
Thread t = new Thread(ThreadProcARGUI);
t.Start();
}
public void ThreadProcARGUI()
{
Culture.SetCurrentCulture();
Application.Run(new Abuse(m_registry.RequestModuleInterface<IAssetService>(), m_registry.RequestModuleInterface<IJ2KDecoder>()));
}
#endregion
}
/// <summary>
/// Enables the saving of abuse reports to the database
/// </summary>
public class AbuseReportsModule : ISharedRegionModule
{
//private static readonly ILog MainConsole.Instance = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private readonly List<IScene> m_SceneList = new List<IScene>();
private bool m_enabled;
#region ISharedRegionModule Members
public void Initialise(IConfigSource source)
{
IConfig cnf = source.Configs["AbuseReports"];
if (cnf != null)
m_enabled = cnf.GetBoolean("Enabled", true);
}
public void AddRegion(IScene scene)
{
if (!m_enabled)
return;
lock (m_SceneList)
{
if (!m_SceneList.Contains(scene))
m_SceneList.Add(scene);
}
scene.EventManager.OnNewClient += OnNewClient;
scene.EventManager.OnClosingClient += OnClosingClient;
//Disabled until complete
//scene.EventManager.OnRegisterCaps += OnRegisterCaps;
}
public void RemoveRegion(IScene scene)
{
if (!m_enabled)
return;
lock (m_SceneList)
{
if (m_SceneList.Contains(scene))
m_SceneList.Remove(scene);
}
scene.EventManager.OnNewClient -= OnNewClient;
scene.EventManager.OnClosingClient -= OnClosingClient;
//Disabled until complete
//scene.EventManager.OnRegisterCaps -= OnRegisterCaps;
}
public void RegionLoaded(IScene scene)
{
}
public void PostInitialise()
{
}
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "AbuseReportsModule"; }
}
public void Close()
{
}
#endregion
private void OnClosingClient(IClientAPI client)
{
client.OnUserReport -= UserReport;
}
private void OnNewClient(IClientAPI client)
{
client.OnUserReport += UserReport;
}
/// <summary>
/// This deals with saving the report into the database.
/// </summary>
/// <param name = "client"></param>
/// <param name = "regionName"></param>
/// <param name = "abuserID"></param>
/// <param name = "catagory"></param>
/// <param name = "checkflags"></param>
/// <param name = "details"></param>
/// <param name = "objectID"></param>
/// <param name = "position"></param>
/// <param name = "reportType"></param>
/// <param name = "screenshotID"></param>
/// <param name = "summery"></param>
/// <param name = "reporter"></param>
private void UserReport(IClientAPI client, string regionName, UUID abuserID, byte catagory, byte checkflags,
string details, UUID objectID, Vector3 position, byte reportType, UUID screenshotID,
string summery, UUID reporter)
{
AbuseReport report = new AbuseReport
{
ObjectUUID = objectID,
ObjectPosition = position.ToString(),
Active = true,
Checked = false,
Notes = "",
AssignedTo = "No One",
ScreenshotID = screenshotID
};
if (objectID != UUID.Zero)
{
ISceneChildEntity Object = client.Scene.GetSceneObjectPart(objectID);
report.ObjectName = Object.Name;
}
else
report.ObjectName = "";
string[] detailssplit = details.Split('\n');
string AbuseDetails = detailssplit[detailssplit.Length - 1];
report.AbuseDetails = AbuseDetails;
report.ReporterName = client.Name;
string[] findRegion = summery.Split('|');
report.RegionName = findRegion[1];
string[] findLocation = summery.Split('(');
string[] findLocationend = findLocation[1].Split(')');
report.AbuseLocation = findLocationend[0];
string[] findCategory = summery.Split('[');
string[] findCategoryend = findCategory[1].Split(']');
report.Category = findCategoryend[0];
string[] findAbuserName = summery.Split('{');
string[] findAbuserNameend = findAbuserName[1].Split('}');
report.AbuserName = findAbuserNameend[0];
string[] findSummary = summery.Split('\"');
string abuseSummary = findSummary[1];
if (findSummary.Length != 0)
{
abuseSummary = findSummary[1];
}
report.AbuseSummary = abuseSummary;
report.Number = (-1);
EstateSettings ES = client.Scene.RegionInfo.EstateSettings;
//If the abuse email is set up and the email module is available, send the email
if (ES.AbuseEmailToEstateOwner && ES.AbuseEmail != "")
{
IEmailModule Email = m_SceneList[0].RequestModuleInterface<IEmailModule>();
if (Email != null)
Email.SendEmail(UUID.Zero, ES.AbuseEmail, "Abuse Report", "This abuse report was submitted by " +
report.ReporterName + " against " +
report.AbuserName + " at " +
report.AbuseLocation + " in your region " +
report.RegionName +
". Summary: " + report.AbuseSummary +
". Details: " + report.AbuseDetails + ".", client.Scene);
}
//Tell the DB about it
IAbuseReports conn = m_SceneList[0].RequestModuleInterface<IAbuseReports>();
if (conn != null)
conn.AddAbuseReport(report);
}
#region Disabled CAPS code
/*private void OnRegisterCaps(UUID agentID, IRegionClientCapsService caps)
{
caps.AddStreamHandler("SendUserReportWithScreenshot",
new GenericStreamHandler("POST", CapsUtil.CreateCAPS("SendUserReportWithScreenshot", ""),
delegate(string path, Stream request,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
return ProcessSendUserReportWithScreenshot(request, agentID);
}));
}
private byte[] ProcessSendUserReportWithScreenshot(Stream request, UUID agentID)
{
IScenePresence SP = findScenePresence(agentID);
OSDMap map = (OSDMap)OSDParser.DeserializeLLSDXml(request);
string RegionName = map["abuse-region-name"];
UUID AbuserID = map["abuser-id"];
uint Category = map["category"];
uint CheckFlags = map["check-flags"];
string details = map["details"];
UUID objectID = map["object-id"];
Vector3 position = map["position"];
uint ReportType = map["report-type"];
UUID ScreenShotID = map["screenshot-id"];
string summary = map["summary"];
//UserReport(SP.ControllingClient, RegionName, AbuserID, Category, CheckFlags,
// details, objectID, position, ReportType, ScreenShotID, summary, SP.UUID);
//TODO: Figure this out later
return new byte[0];
}*/
#endregion
#region Helpers
public IScenePresence findScenePresence(UUID avID)
{
#if (!ISWIN)
foreach (IScene s in m_SceneList)
{
IScenePresence SP = s.GetScenePresence(avID);
if (SP != null)
return SP;
}
return null;
#else
return m_SceneList.Select(s => s.GetScenePresence(avID)).FirstOrDefault(SP => SP != null);
#endif
}
#endregion
}
}
| |
#nullable enable
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NBitcoin.DataEncoders;
using Newtonsoft.Json;
using UnKnownKVMap = System.Collections.Generic.SortedDictionary<byte[], byte[]>;
using NBitcoin.BuilderExtensions;
using System.Diagnostics.CodeAnalysis;
namespace NBitcoin
{
static class PSBTConstants
{
public static byte[] PSBT_GLOBAL_ALL { get; }
public static byte[] PSBT_IN_ALL { get; }
public static byte[] PSBT_OUT_ALL { get; }
static PSBTConstants()
{
PSBT_GLOBAL_ALL = new byte[] { PSBT_GLOBAL_UNSIGNED_TX, PSBT_GLOBAL_XPUB };
PSBT_IN_ALL = new byte[]
{
PSBT_IN_NON_WITNESS_UTXO,
PSBT_IN_WITNESS_UTXO,
PSBT_IN_PARTIAL_SIG,
PSBT_IN_SIGHASH,
PSBT_IN_REDEEMSCRIPT,
PSBT_IN_WITNESSSCRIPT,
PSBT_IN_SCRIPTSIG,
PSBT_IN_SCRIPTWITNESS,
PSBT_IN_BIP32_DERIVATION
};
PSBT_OUT_ALL = new byte[] {
PSBT_OUT_REDEEMSCRIPT,
PSBT_OUT_WITNESSSCRIPT,
PSBT_OUT_BIP32_DERIVATION
};
}
// Note: These constants are in reverse byte order because serialization uses LSB
// Global types
public const byte PSBT_GLOBAL_UNSIGNED_TX = 0x00;
public const byte PSBT_GLOBAL_XPUB = 0x01;
// Input types
public const byte PSBT_IN_NON_WITNESS_UTXO = 0x00;
public const byte PSBT_IN_WITNESS_UTXO = 0x01;
public const byte PSBT_IN_PARTIAL_SIG = 0x02;
public const byte PSBT_IN_SIGHASH = 0x03;
public const byte PSBT_IN_REDEEMSCRIPT = 0x04;
public const byte PSBT_IN_WITNESSSCRIPT = 0x05;
public const byte PSBT_IN_BIP32_DERIVATION = 0x06;
public const byte PSBT_IN_SCRIPTSIG = 0x07;
public const byte PSBT_IN_SCRIPTWITNESS = 0x08;
public const byte PSBT_OUT_TAP_INTERNAL_KEY = 0x05;
public const byte PSBT_IN_TAP_KEY_SIG = 0x13;
public const byte PSBT_IN_TAP_INTERNAL_KEY = 0x17;
public const byte PSBT_IN_TAP_BIP32_DERIVATION = 0x16;
public const byte PSBT_OUT_TAP_BIP32_DERIVATION = 0x07;
public const byte PSBT_IN_TAP_MERKLE_ROOT = 0x18;
// Output types
public const byte PSBT_OUT_REDEEMSCRIPT = 0x00;
public const byte PSBT_OUT_WITNESSSCRIPT = 0x01;
public const byte PSBT_OUT_BIP32_DERIVATION = 0x02;
// The separator is 0x00. Reading this in means that the unserializer can interpret it
// as a 0 length key which indicates that this is the separator. The separator has no value.
public const byte PSBT_SEPARATOR = 0x00;
}
public class PSBTSettings
{
/// <summary>
/// Use custom builder extensions to customize finalization
/// </summary>
public IEnumerable<BuilderExtension>? CustomBuilderExtensions { get; set; }
/// <summary>
/// Try to do anything that is possible to deduce PSBT information from input information
/// </summary>
public bool IsSmart { get; set; } = true;
public bool SkipVerifyScript { get; set; } = false;
public SigningOptions SigningOptions { get; set; } = new SigningOptions();
public ScriptVerify ScriptVerify { get; internal set; } = ScriptVerify.Standard;
public PSBTSettings Clone()
{
return new PSBTSettings()
{
SigningOptions = SigningOptions.Clone(),
CustomBuilderExtensions = CustomBuilderExtensions?.ToArray(),
IsSmart = IsSmart
};
}
}
public class PSBT : IEquatable<PSBT>
{
// Magic bytes
readonly static byte[] PSBT_MAGIC_BYTES = Encoders.ASCII.DecodeData("psbt\xff");
internal byte[]? _XPubVersionBytes;
byte[] XPubVersionBytes => _XPubVersionBytes = _XPubVersionBytes ?? Network.GetVersionBytes(Base58Type.EXT_PUBLIC_KEY, true)
?? throw new InvalidOperationException("The network does not allow xpubs");
internal Transaction tx;
public SortedDictionary<BitcoinExtPubKey, RootedKeyPath> GlobalXPubs { get; } = new SortedDictionary<BitcoinExtPubKey, RootedKeyPath>(BitcoinExtPubKeyComparer.Instance);
internal class BitcoinExtPubKeyComparer : IComparer<BitcoinExtPubKey>
{
BitcoinExtPubKeyComparer()
{
}
public static BitcoinExtPubKeyComparer Instance { get; } = new BitcoinExtPubKeyComparer();
public int Compare(BitcoinExtPubKey x, BitcoinExtPubKey y)
{
return BytesComparer.Instance.Compare(x.ExtPubKey.ToBytes(), y.ExtPubKey.ToBytes());
}
}
public PSBTInputList Inputs { get; }
public PSBTOutputList Outputs { get; }
internal UnKnownKVMap unknown = new UnKnownKVMap(BytesComparer.Instance);
public static PSBT Parse(string hexOrBase64, Network network)
{
if (network == null)
throw new ArgumentNullException(nameof(network));
if (hexOrBase64 == null)
throw new ArgumentNullException(nameof(hexOrBase64));
if (network == null)
throw new ArgumentNullException(nameof(network));
byte[] raw;
if (HexEncoder.IsWellFormed(hexOrBase64))
raw = Encoders.Hex.DecodeData(hexOrBase64);
else
raw = Encoders.Base64.DecodeData(hexOrBase64);
return Load(raw, network);
}
public static bool TryParse(string hexOrBase64, Network network, [MaybeNullWhen(false)] out PSBT psbt)
{
if (hexOrBase64 == null)
throw new ArgumentNullException(nameof(hexOrBase64));
if (network == null)
throw new ArgumentNullException(nameof(network));
try
{
psbt = Parse(hexOrBase64, network);
return true;
}
catch
{
psbt = null;
return false;
}
}
public static PSBT Load(byte[] rawBytes, Network network)
{
if (network == null)
throw new ArgumentNullException(nameof(network));
var stream = new BitcoinStream(rawBytes);
stream.ConsensusFactory = network.Consensus.ConsensusFactory;
var ret = new PSBT(stream, network);
return ret;
}
internal ConsensusFactory GetConsensusFactory()
{
return Network.Consensus.ConsensusFactory;
}
public Network Network { get; }
private PSBT(Transaction transaction, Network network)
{
if (transaction == null)
throw new ArgumentNullException(nameof(transaction));
if (network == null)
throw new ArgumentNullException(nameof(network));
Network = network;
tx = transaction.Clone();
Inputs = new PSBTInputList();
Outputs = new PSBTOutputList();
for (var i = 0; i < tx.Inputs.Count; i++)
this.Inputs.Add(new PSBTInput(this, (uint)i, tx.Inputs[i]));
for (var i = 0; i < tx.Outputs.Count; i++)
this.Outputs.Add(new PSBTOutput(this, (uint)i, tx.Outputs[i]));
foreach (var input in tx.Inputs)
{
input.ScriptSig = Script.Empty;
input.WitScript = WitScript.Empty;
}
}
internal PSBT(BitcoinStream stream, Network network)
{
if (network == null)
throw new ArgumentNullException(nameof(network));
Network = network;
Inputs = new PSBTInputList();
Outputs = new PSBTOutputList();
var magicBytes = stream.Inner.ReadBytes(PSBT_MAGIC_BYTES.Length);
if (!magicBytes.SequenceEqual(PSBT_MAGIC_BYTES))
{
throw new FormatException("Invalid PSBT magic bytes");
}
// It will be reassigned in `ReadWriteAsVarString` so no worry to assign 0 length array here.
byte[] k = new byte[0];
byte[] v = new byte[0];
stream.ReadWriteAsVarString(ref k);
while (k.Length != 0)
{
switch (k[0])
{
case PSBTConstants.PSBT_GLOBAL_UNSIGNED_TX:
if (k.Length != 1)
throw new FormatException("Invalid PSBT. Contains illegal value in key global tx");
if (tx != null)
throw new FormatException("Duplicate Key, unsigned tx already provided");
tx = stream.ConsensusFactory.CreateTransaction();
uint size = 0;
stream.ReadWriteAsVarInt(ref size);
var pos = stream.Counter.ReadenBytes;
tx.ReadWrite(stream);
if (stream.Counter.ReadenBytes - pos != size)
throw new FormatException("Malformed global tx. Unexpected size.");
if (tx.Inputs.Any(txin => txin.ScriptSig != Script.Empty || txin.WitScript != WitScript.Empty))
throw new FormatException("Malformed global tx. It should not contain any scriptsig or witness by itself");
break;
case PSBTConstants.PSBT_GLOBAL_XPUB when XPubVersionBytes != null:
if (k.Length != 1 + XPubVersionBytes.Length + 74)
throw new FormatException("Malformed global xpub.");
for (int ii = 0; ii < XPubVersionBytes.Length; ii++)
{
if (k[1 + ii] != XPubVersionBytes[ii])
throw new FormatException("Malformed global xpub.");
}
stream.ReadWriteAsVarString(ref v);
KeyPath path = KeyPath.FromBytes(v.Skip(4).ToArray());
var rootedKeyPath = new RootedKeyPath(new HDFingerprint(v.Take(4).ToArray()), path);
GlobalXPubs.Add(new ExtPubKey(k, 1 + XPubVersionBytes.Length, 74).GetWif(Network), rootedKeyPath);
break;
default:
if (unknown.ContainsKey(k))
throw new FormatException("Invalid PSBTInput, duplicate key for unknown value");
stream.ReadWriteAsVarString(ref v);
unknown.Add(k, v);
break;
}
stream.ReadWriteAsVarString(ref k);
}
if (tx is null)
throw new FormatException("Invalid PSBT. No global TX");
int i = 0;
while (stream.Inner.CanRead && i < tx.Inputs.Count)
{
var psbtin = new PSBTInput(stream, this, (uint)i, tx.Inputs[i]);
Inputs.Add(psbtin);
i++;
}
if (i != tx.Inputs.Count)
throw new FormatException("Invalid PSBT. Number of input does not match to the global tx");
i = 0;
while (stream.Inner.CanRead && i < tx.Outputs.Count)
{
var psbtout = new PSBTOutput(stream, this, (uint)i, tx.Outputs[i]);
Outputs.Add(psbtout);
i++;
}
if (i != tx.Outputs.Count)
throw new FormatException("Invalid PSBT. Number of outputs does not match to the global tx");
// tx should never be null, but dotnet compiler complains...
tx = tx ?? Network.CreateTransaction();
}
public PSBT AddCoins(params ICoin?[] coins)
{
if (coins == null)
return this;
foreach (var coin in coins)
{
if (coin is null)
continue;
var indexedInput = this.Inputs.FindIndexedInput(coin.Outpoint);
if (indexedInput == null)
continue;
indexedInput.UpdateFromCoin(coin);
}
foreach (var coin in coins)
{
if (coin is null)
continue;
foreach (var output in this.Outputs)
{
if (output.ScriptPubKey == coin.TxOut.ScriptPubKey)
{
output.UpdateFromCoin(coin);
}
}
}
return this;
}
public PSBT AddCoins(params Transaction[] transactions)
{
if (transactions == null)
throw new ArgumentNullException(nameof(transactions));
return AddTransactions(transactions).AddCoins(transactions.SelectMany(t => t.Outputs.AsCoins()).ToArray());
}
/// <summary>
/// Add transactions to non segwit outputs
/// </summary>
/// <param name="parentTransactions">Parent transactions</param>
/// <returns>This PSBT</returns>
public PSBT AddTransactions(params Transaction[] parentTransactions)
{
if (parentTransactions == null)
return this;
Dictionary<uint256, Transaction> txsById = new Dictionary<uint256, Transaction>();
foreach (var tx in parentTransactions)
txsById.TryAdd(tx.GetHash(), tx);
foreach (var input in Inputs)
{
if (txsById.TryGetValue(input.TxIn.PrevOut.Hash, out var tx))
{
if (input.TxIn.PrevOut.N >= tx.Outputs.Count)
continue;
var output = tx.Outputs[input.TxIn.PrevOut.N];
input.NonWitnessUtxo = tx;
if (input.GetCoin()?.IsMalleable is false)
input.WitnessUtxo = output;
}
}
return this;
}
/// <summary>
/// If an other PSBT has a specific field and this does not have it, then inject that field to this.
/// otherwise leave it as it is.
///
/// If you need to call this on transactions with different global transaction, use <see cref="PSBT.UpdateFrom(PSBT)"/> instead.
/// </summary>
/// <param name="other">Another PSBT to takes information from</param>
/// <exception cref="System.ArgumentException">Can not Combine PSBT with different global tx.</exception>
/// <returns>This instance</returns>
public PSBT Combine(PSBT other)
{
if (other == null)
{
throw new ArgumentNullException(nameof(other));
}
if (other.tx.GetHash() != this.tx.GetHash())
throw new ArgumentException(paramName: nameof(other), message: "Can not Combine PSBT with different global tx.");
foreach (var xpub in other.GlobalXPubs)
this.GlobalXPubs.TryAdd(xpub.Key, xpub.Value);
for (int i = 0; i < Inputs.Count; i++)
this.Inputs[i].UpdateFrom(other.Inputs[i]);
for (int i = 0; i < Outputs.Count; i++)
this.Outputs[i].UpdateFrom(other.Outputs[i]);
foreach (var uk in other.unknown)
this.unknown.TryAdd(uk.Key, uk.Value);
return this;
}
/// <summary>
/// If an other PSBT has a specific field and this does not have it, then inject that field to this.
/// otherwise leave it as it is.
///
/// Contrary to <see cref="PSBT.Combine(PSBT)"/>, it can be called on PSBT with a different global transaction.
/// </summary>
/// <param name="other">Another PSBT to takes information from</param>
/// <returns>This instance</returns>
public PSBT UpdateFrom(PSBT other)
{
if (other == null)
{
throw new ArgumentNullException(nameof(other));
}
foreach (var xpub in other.GlobalXPubs)
this.GlobalXPubs.TryAdd(xpub.Key, xpub.Value);
foreach (var otherInput in other.Inputs)
this.Inputs.FindIndexedInput(otherInput.PrevOut)?.UpdateFrom(otherInput);
foreach (var otherOutput in other.Outputs)
foreach (var thisOutput in this.Outputs.Where(o => o.ScriptPubKey == otherOutput.ScriptPubKey))
thisOutput.UpdateFrom(otherOutput);
foreach (var uk in other.unknown)
this.unknown.TryAdd(uk.Key, uk.Value);
return this;
}
/// <summary>
/// Join two PSBT into one CoinJoin PSBT.
/// This is an immutable method.
/// TODO: May need assertion for sighash type?
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public PSBT CoinJoin(PSBT other)
{
if (other == null)
throw new ArgumentNullException(nameof(other));
other.AssertSanity();
var result = this.Clone();
for (int i = 0; i < other.Inputs.Count; i++)
{
result.tx.Inputs.Add(other.tx.Inputs[i]);
result.Inputs.Add(other.Inputs[i]);
}
for (int i = 0; i < other.Outputs.Count; i++)
{
result.tx.Outputs.Add(other.tx.Outputs[i]);
result.Outputs.Add(other.Outputs[i]);
}
return result;
}
public PSBT Finalize()
{
if (!TryFinalize(out var errors))
throw new PSBTException(errors);
return this;
}
public bool TryFinalize([MaybeNullWhen(true)] out IList<PSBTError> errors)
{
var signingOptions = GetSigningOptions(null);
var localErrors = new List<PSBTError>();
foreach (var input in Inputs)
{
if (!input.TryFinalizeInput(signingOptions, out var e))
{
localErrors.AddRange(e);
}
}
if (localErrors.Count != 0)
{
errors = localErrors;
return false;
}
errors = null;
return true;
}
internal SigningOptions GetSigningOptions(SigningOptions? signingOptions)
{
signingOptions ??= Settings.SigningOptions;
if (signingOptions.PrecomputedTransactionData is null)
{
signingOptions = signingOptions.Clone();
signingOptions.PrecomputedTransactionData = PrecomputeTransactionData();
}
return signingOptions;
}
public bool IsReadyToSign()
{
return IsReadyToSign(out _);
}
public bool IsReadyToSign([MaybeNullWhen(true)] out PSBTError[] errors)
{
var errorList = new List<PSBTError>();
foreach (var input in Inputs)
{
var localErrors = input.CheckSanity();
if (localErrors.Count != 0)
{
errorList.AddRange(localErrors);
}
else
{
if (input.GetSignableCoin(out var err) == null)
errorList.Add(new PSBTError(input.Index, err));
}
}
if (errorList.Count != 0)
{
errors = errorList.ToArray();
return false;
}
errors = null;
return true;
}
public PSBTSettings Settings { get; set; } = new PSBTSettings();
/// <summary>
/// Sign all inputs which derive <paramref name="accountKey"/> of type <paramref name="scriptPubKeyType"/>.
/// </summary>
/// <param name="scriptPubKeyType">The way to derive addresses from the accountKey</param>
/// <param name="accountKey">The account key with which to sign</param>
/// <param name="accountKeyPath">The account key path (eg. [masterFP]/49'/0'/0')</param>
/// <param name="sigHash">The SigHash</param>
/// <returns>This PSBT</returns>
public PSBT SignAll(ScriptPubKeyType scriptPubKeyType, IHDKey accountKey, RootedKeyPath accountKeyPath)
{
if (accountKey == null)
throw new ArgumentNullException(nameof(accountKey));
return SignAll(new HDKeyScriptPubKey(accountKey, scriptPubKeyType), accountKey, accountKeyPath);
}
/// <summary>
/// Sign all inputs which derive <paramref name="accountKey"/> of type <paramref name="scriptPubKeyType"/>.
/// </summary>
/// <param name="scriptPubKeyType">The way to derive addresses from the accountKey</param>
/// <param name="accountKey">The account key with which to sign</param>
/// <param name="sigHash">The SigHash</param>
/// <returns>This PSBT</returns>
public PSBT SignAll(ScriptPubKeyType scriptPubKeyType, IHDKey accountKey)
{
if (accountKey == null)
throw new ArgumentNullException(nameof(accountKey));
return SignAll(new HDKeyScriptPubKey(accountKey, scriptPubKeyType), accountKey);
}
/// <summary>
/// Sign all inputs which derive addresses from <paramref name="accountHDScriptPubKey"/> and that need to be signed by <paramref name="accountKey"/>.
/// </summary>
/// <param name="accountHDScriptPubKey">The address generator</param>
/// <param name="accountKey">The account key with which to sign</param>
/// <param name="sigHash">The SigHash</param>
/// <returns>This PSBT</returns>
public PSBT SignAll(IHDScriptPubKey accountHDScriptPubKey, IHDKey accountKey)
{
return SignAll(accountHDScriptPubKey, accountKey, null);
}
/// <summary>
/// Sign all inputs which derive addresses from <paramref name="accountHDScriptPubKey"/> and that need to be signed by <paramref name="accountKey"/>.
/// </summary>
/// <param name="accountHDScriptPubKey">The address generator</param>
/// <param name="accountKey">The account key with which to sign</param>
/// <param name="accountKeyPath">The account key path (eg. [masterFP]/49'/0'/0')</param>
/// <returns>This PSBT</returns>
public PSBT SignAll(IHDScriptPubKey accountHDScriptPubKey, IHDKey accountKey, RootedKeyPath? accountKeyPath)
{
if (accountKey == null)
throw new ArgumentNullException(nameof(accountKey));
if (accountHDScriptPubKey == null)
throw new ArgumentNullException(nameof(accountHDScriptPubKey));
accountHDScriptPubKey = accountHDScriptPubKey.AsHDKeyCache();
accountKey = accountKey.AsHDKeyCache();
Money total = Money.Zero;
var signingOptions = GetSigningOptions(null);
foreach (var o in Inputs.CoinsFor(accountHDScriptPubKey, accountKey, accountKeyPath))
{
o.TrySign(accountHDScriptPubKey, accountKey, accountKeyPath, signingOptions);
}
return this;
}
/// <summary>
/// Returns the fee of the transaction being signed
/// </summary>
/// <param name="fee"></param>
/// <returns></returns>
public bool TryGetFee(out Money fee)
{
fee = tx.GetFee(GetAllCoins().ToArray());
return fee != null;
}
/// <summary>
/// Returns the fee of the transaction being signed
/// </summary>
/// <returns>The fees</returns>
/// <exception cref="System.InvalidOperationException">Not enough information to know about the fee</exception>
public Money GetFee()
{
if (!TryGetFee(out var fee))
throw new InvalidOperationException("Not enough information to know about the fee");
return fee;
}
/// <summary>
/// Returns the fee rate of the transaction. If the PSBT is finalized, then the exact rate is returned, else an estimation is made.
/// </summary>
/// <param name="estimatedFeeRate"></param>
/// <returns>True if could get the estimated fee rate</returns>
public bool TryGetEstimatedFeeRate([MaybeNullWhen(false)] out FeeRate estimatedFeeRate)
{
if (IsAllFinalized())
{
estimatedFeeRate = ExtractTransaction().GetFeeRate(GetAllCoins().ToArray());
return estimatedFeeRate != null;
}
if (!TryGetFee(out var fee))
{
estimatedFeeRate = null;
return false;
}
var transactionBuilder = CreateTransactionBuilder();
transactionBuilder.AddCoins(GetAllCoins());
try
{
var vsize = transactionBuilder.EstimateSize(this.tx, true);
estimatedFeeRate = new FeeRate(fee, vsize);
return true;
}
catch
{
estimatedFeeRate = null;
return false;
}
}
/// <summary>
/// Returns the virtual transaction size of the transaction. If the PSBT is finalized, then the exact virtual size.
/// </summary>
/// <param name="vsize">The calculated virtual size</param>
/// <returns>True if could get the virtual size could get estimated</returns>
public bool TryGetVirtualSize(out int vsize)
{
if (IsAllFinalized())
{
vsize = ExtractTransaction().GetVirtualSize();
return true;
}
var transactionBuilder = CreateTransactionBuilder();
transactionBuilder.AddCoins(GetAllCoins());
try
{
vsize = transactionBuilder.EstimateSize(this.tx, true);
return true;
}
catch
{
vsize = -1;
return false;
}
}
/// <summary>
/// Returns the fee rate of the transaction. If the PSBT is finalized, then the exact rate is returned, else an estimation is made.
/// </summary>
/// <returns>The estimated fee</returns>
/// <exception cref="System.InvalidOperationException">Not enough information to know about the fee rate</exception>
public FeeRate GetEstimatedFeeRate()
{
if (!TryGetEstimatedFeeRate(out var feeRate))
throw new InvalidOperationException("Not enough information to know about the fee rate");
return feeRate;
}
public PSBT SignWithKeys(params ISecret[] keys)
{
return SignWithKeys(keys.Select(k => k.PrivateKey).ToArray());
}
public PSBT SignWithKeys(params Key[] keys)
{
AssertSanity();
var signingOptions = GetSigningOptions(null);
foreach (var key in keys)
{
foreach (var input in this.Inputs)
{
input.Sign(key, signingOptions);
}
}
return this;
}
/// <summary>
/// Returns a data structure precomputing some hash values that are needed for all inputs to be signed in the transaction.
/// </summary>
/// <returns>The PrecomputedTransactionData</returns>
/// <exception cref="NBitcoin.PSBTException">Throw if the PSBT is missing some previous outputs.</exception>
public PrecomputedTransactionData PrecomputeTransactionData()
{
var outputs = GetSpentTxOuts(out var errors);
if (errors != null)
return tx.PrecomputeTransactionData();
return tx.PrecomputeTransactionData(outputs);
}
public TransactionValidator CreateTransactionValidator()
{
var outputs = GetSpentTxOuts(out var errors);
if (errors != null)
throw new PSBTException(errors);
return tx.CreateValidator(outputs);
}
internal bool TryCreateTransactionValidator([MaybeNullWhen(false)] out TransactionValidator validator, [MaybeNullWhen(true)] out IList<PSBTError> errors)
{
var outputs = GetSpentTxOuts(out errors);
if (errors != null)
{
validator = null;
return false;
}
validator = tx.CreateValidator(outputs);
return true;
}
private TxOut[] GetSpentTxOuts(out IList<PSBTError>? errors)
{
errors = null;
TxOut[] spentOutputs = new TxOut[Inputs.Count];
foreach (var input in Inputs)
{
if (input.GetTxOut() is TxOut txOut)
spentOutputs[input.Index] = txOut;
else
{
errors ??= new List<PSBTError>();
errors.Add(new PSBTError((uint)input.Index, "Some inputs are missing witness_utxo or non_witness_utxo"));
}
}
return spentOutputs;
}
internal TransactionBuilder CreateTransactionBuilder()
{
var transactionBuilder = Network.CreateTransactionBuilder();
if (Settings.CustomBuilderExtensions != null)
{
transactionBuilder.Extensions.Clear();
transactionBuilder.Extensions.AddRange(Settings.CustomBuilderExtensions);
}
transactionBuilder.SetSigningOptions(Settings.SigningOptions.Clone());
return transactionBuilder;
}
private IEnumerable<ICoin> GetAllCoins()
{
foreach (var c in this.Inputs.Select(i => i.GetSignableCoin() ?? i.GetCoin()))
{
if (c is null)
continue;
yield return c;
}
}
/// <summary>
/// Extract the fully signed transaction from the PSBT
/// </summary>
/// <returns>The fully signed transaction</returns>
/// <exception cref="System.InvalidOperationException">PSBTInputs are not all finalized</exception>
public Transaction ExtractTransaction()
{
if (!this.CanExtractTransaction())
throw new InvalidOperationException("PSBTInputs are not all finalized!");
var copy = tx.Clone();
for (var i = 0; i < tx.Inputs.Count; i++)
{
copy.Inputs[i].ScriptSig = Inputs[i].FinalScriptSig ?? Script.Empty;
copy.Inputs[i].WitScript = Inputs[i].FinalScriptWitness ?? WitScript.Empty;
}
return copy;
}
public bool CanExtractTransaction() => IsAllFinalized();
public bool IsAllFinalized() => this.Inputs.All(i => i.IsFinalized());
public IList<PSBTError> CheckSanity()
{
List<PSBTError> errors = new List<PSBTError>();
foreach (var input in Inputs)
{
errors.AddRange(input.CheckSanity());
}
return errors;
}
public void AssertSanity()
{
var errors = CheckSanity();
if (errors.Count != 0)
throw new PSBTException(errors);
}
/// <summary>
/// Get the expected hash once the transaction is fully signed
/// </summary>
/// <param name="hash">The hash once fully signed</param>
/// <returns>True if we can know the expected hash. False if we can't (unsigned non-segwit).</returns>
public bool TryGetFinalizedHash([MaybeNullWhen(false)] out uint256 hash)
{
var tx = GetGlobalTransaction();
for (int i = 0; i < Inputs.Count; i++)
{
var utxo = Inputs[i].GetTxOut();
if (Inputs[i].IsFinalized())
{
tx.Inputs[i].ScriptSig = Inputs[i].FinalScriptSig ?? Script.Empty;
tx.Inputs[i].WitScript = Inputs[i].FinalScriptWitness ?? Script.Empty;
if (tx.Inputs[i].ScriptSig == Script.Empty
&& (utxo is null || utxo.ScriptPubKey.IsScriptType(ScriptType.P2SH)))
{
hash = null;
return false;
}
}
else if (utxo is null ||
!Network.Consensus.SupportSegwit)
{
hash = null;
return false;
}
else if (utxo.ScriptPubKey.IsScriptType(ScriptType.P2SH) &&
Inputs[i].RedeemScript is Script p2shRedeem &&
(p2shRedeem.IsScriptType(ScriptType.P2WSH) ||
p2shRedeem.IsScriptType(ScriptType.P2WPKH)))
{
tx.Inputs[i].ScriptSig = PayToScriptHashTemplate.Instance.GenerateScriptSig(null as byte[][], p2shRedeem);
}
else if (utxo.ScriptPubKey.IsMalleable)
{
hash = null;
return false;
}
}
hash = tx.GetHash();
return true;
}
#region IBitcoinSerializable Members
private static uint defaultKeyLen = 1;
public void Serialize(BitcoinStream stream)
{
// magic bytes
stream.Inner.Write(PSBT_MAGIC_BYTES, 0, PSBT_MAGIC_BYTES.Length);
// unsigned tx flag
stream.ReadWriteAsVarInt(ref defaultKeyLen);
stream.ReadWrite(PSBTConstants.PSBT_GLOBAL_UNSIGNED_TX);
// Write serialized tx to a stream
stream.TransactionOptions &= TransactionOptions.None;
uint txLength = (uint)tx.GetSerializedSize(TransactionOptions.None);
stream.ReadWriteAsVarInt(ref txLength);
stream.ReadWrite(tx);
foreach (var xpub in GlobalXPubs)
{
if (xpub.Key.Network != Network)
throw new InvalidOperationException("Invalid key inside the global xpub collection");
var len = (uint)(1 + XPubVersionBytes.Length + 74);
stream.ReadWriteAsVarInt(ref len);
stream.ReadWrite(PSBTConstants.PSBT_GLOBAL_XPUB);
var vb = XPubVersionBytes;
stream.ReadWrite(ref vb);
var bytes = xpub.Key.ExtPubKey.ToBytes();
stream.ReadWrite(ref bytes);
var path = xpub.Value.KeyPath.ToBytes();
var pathInfo = xpub.Value.MasterFingerprint.ToBytes().Concat(path);
stream.ReadWriteAsVarString(ref pathInfo);
}
// Write the unknown things
foreach (var kv in unknown)
{
byte[] k = kv.Key;
byte[] v = kv.Value;
stream.ReadWriteAsVarString(ref k);
stream.ReadWriteAsVarString(ref v);
}
// Separator
var sep = PSBTConstants.PSBT_SEPARATOR;
stream.ReadWrite(ref sep);
// Write inputs
foreach (var psbtin in Inputs)
{
psbtin.Serialize(stream);
}
// Write outputs
foreach (var psbtout in Outputs)
{
psbtout.Serialize(stream);
}
}
#endregion
public override string ToString()
{
var strWriter = new StringWriter();
var jsonWriter = new JsonTextWriter(strWriter);
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.WriteStartObject();
if (TryGetFee(out var fee))
{
jsonWriter.WritePropertyValue("fee", $"{fee} BTC");
}
else
{
jsonWriter.WritePropertyName("fee");
jsonWriter.WriteToken(JsonToken.Null);
}
if (TryGetEstimatedFeeRate(out var feeRate))
{
jsonWriter.WritePropertyValue("feeRate", $"{feeRate}");
}
else
{
jsonWriter.WritePropertyName("feeRate");
jsonWriter.WriteToken(JsonToken.Null);
}
jsonWriter.WritePropertyName("tx");
jsonWriter.WriteStartObject();
RPC.BlockExplorerFormatter.WriteTransaction(jsonWriter, tx);
jsonWriter.WriteEndObject();
if (GlobalXPubs.Count != 0)
{
jsonWriter.WritePropertyName("xpubs");
jsonWriter.WriteStartArray();
foreach (var xpub in GlobalXPubs)
{
jsonWriter.WriteStartObject();
jsonWriter.WritePropertyValue("key", xpub.Key.ToString());
jsonWriter.WritePropertyValue("value", xpub.Value.ToString());
jsonWriter.WriteEndObject();
}
jsonWriter.WriteEndArray();
}
if (unknown.Count != 0)
{
jsonWriter.WritePropertyName("unknown");
jsonWriter.WriteStartObject();
foreach (var el in unknown)
{
jsonWriter.WritePropertyValue(Encoders.Hex.EncodeData(el.Key), Encoders.Hex.EncodeData(el.Value));
}
jsonWriter.WriteEndObject();
}
jsonWriter.WritePropertyName("inputs");
jsonWriter.WriteStartArray();
foreach (var input in this.Inputs)
{
input.Write(jsonWriter);
}
jsonWriter.WriteEndArray();
jsonWriter.WritePropertyName("outputs");
jsonWriter.WriteStartArray();
foreach (var output in this.Outputs)
{
output.Write(jsonWriter);
}
jsonWriter.WriteEndArray();
jsonWriter.WriteEndObject();
jsonWriter.Flush();
return strWriter.ToString();
}
public byte[] ToBytes()
{
MemoryStream ms = new MemoryStream();
var bs = new BitcoinStream(ms, true);
bs.ConsensusFactory = tx.GetConsensusFactory();
this.Serialize(bs);
return ms.ToArrayEfficient();
}
/// <summary>
/// Clone this PSBT
/// </summary>
/// <returns>A cloned PSBT</returns>
public PSBT Clone()
{
return Clone(true);
}
/// <summary>
/// Clone this PSBT
/// </summary>
/// <param name="keepOriginalTransactionInformation">Whether the original scriptSig and witScript or inputs is saved</param>
/// <returns>A cloned PSBT</returns>
public PSBT Clone(bool keepOriginalTransactionInformation)
{
var bytes = ToBytes();
var psbt = PSBT.Load(bytes, Network);
if (keepOriginalTransactionInformation)
{
for (int i = 0; i < Inputs.Count; i++)
{
psbt.Inputs[i].originalScriptSig = this.Inputs[i].originalScriptSig;
psbt.Inputs[i].originalWitScript = this.Inputs[i].originalWitScript;
psbt.Inputs[i].orphanTxOut = this.Inputs[i].orphanTxOut;
}
}
psbt.Settings = Settings.Clone();
return psbt;
}
public string ToBase64() => Encoders.Base64.EncodeData(this.ToBytes());
public string ToHex() => Encoders.Hex.EncodeData(this.ToBytes());
public override bool Equals(object obj)
{
var item = obj as PSBT;
if (item == null)
return false;
return item.Equals(this);
}
public bool Equals(PSBT b)
{
if (b is null)
return false;
return this.ToBytes().SequenceEqual(b.ToBytes());
}
public override int GetHashCode() => Utils.GetHashCode(this.ToBytes());
public static PSBT FromTransaction(Transaction transaction, Network network)
{
if (transaction == null)
throw new ArgumentNullException(nameof(transaction));
if (network == null)
throw new ArgumentNullException(nameof(network));
return new PSBT(transaction, network);
}
public PSBT AddScripts(params Script[] redeems)
{
if (redeems == null)
throw new ArgumentNullException(nameof(redeems));
var unused = new OutPoint(uint256.Zero, 0);
foreach (var redeem in redeems)
{
var p2sh = redeem.Hash.ScriptPubKey;
var p2wsh = redeem.WitHash.ScriptPubKey;
var p2shp2wsh = redeem.WitHash.ScriptPubKey.Hash.ScriptPubKey;
foreach (var o in this.Inputs.OfType<PSBTCoin>().Concat(this.Outputs))
{
if (o is PSBTInput ii && ii.IsFinalized())
continue;
var txout = o.GetCoin()?.TxOut;
if (txout == null)
continue;
if (txout.ScriptPubKey == p2sh)
{
o.RedeemScript = redeem;
}
else if (txout.ScriptPubKey == p2wsh)
{
o.WitnessScript = redeem;
if (o is PSBTInput i)
i.TrySlimUTXO();
}
else if (txout.ScriptPubKey == p2shp2wsh)
{
o.WitnessScript = redeem;
o.RedeemScript = redeem.WitHash.ScriptPubKey;
if (o is PSBTInput i)
i.TrySlimUTXO();
}
}
}
return this;
}
/// <summary>
/// Get the balance change if you were signing this transaction.
/// </summary>
/// <param name="accountHDScriptPubKey">The hdScriptPubKey used to generate addresses</param>
/// <param name="accountKey">The account key that will be used to sign (ie. 49'/0'/0')</param>
/// <param name="accountKeyPath">The account key path</param>
/// <returns>The balance change</returns>
public Money GetBalance(ScriptPubKeyType scriptPubKeyType, IHDKey accountKey, RootedKeyPath? accountKeyPath = null)
{
if (accountKey == null)
throw new ArgumentNullException(nameof(accountKey));
return GetBalance(new HDKeyScriptPubKey(accountKey, scriptPubKeyType), accountKey, accountKeyPath);
}
/// <summary>
/// Get the balance change if you were signing this transaction.
/// </summary>
/// <param name="accountHDScriptPubKey">The hdScriptPubKey used to generate addresses</param>
/// <param name="accountKey">The account key that will be used to sign (ie. 49'/0'/0')</param>
/// <param name="accountKeyPath">The account key path</param>
/// <returns>The balance change</returns>
public Money GetBalance(IHDScriptPubKey accountHDScriptPubKey, IHDKey accountKey, RootedKeyPath? accountKeyPath = null)
{
if (accountHDScriptPubKey == null)
throw new ArgumentNullException(nameof(accountHDScriptPubKey));
Money total = Money.Zero;
foreach (var o in CoinsFor(accountHDScriptPubKey, accountKey, accountKeyPath))
{
var amount = o.GetCoin()?.Amount;
if (amount == null)
continue;
total += o is PSBTInput ? -amount : amount;
}
return total;
}
/// <summary>
/// Filter the coins which contains the <paramref name="accountKey"/> and <paramref name="accountKeyPath"/> in the HDKeys and derive
/// the same scriptPubKeys as <paramref name="accountHDScriptPubKey"/>.
/// </summary>
/// <param name="accountHDScriptPubKey">The hdScriptPubKey used to generate addresses</param>
/// <param name="accountKey">The account key that will be used to sign (ie. 49'/0'/0')</param>
/// <param name="accountKeyPath">The account key path</param>
/// <returns>Inputs with HD keys matching masterFingerprint and account key</returns>
public IEnumerable<PSBTCoin> CoinsFor(IHDScriptPubKey accountHDScriptPubKey, IHDKey accountKey, RootedKeyPath? accountKeyPath = null)
{
if (accountKey == null)
throw new ArgumentNullException(nameof(accountKey));
if (accountHDScriptPubKey == null)
throw new ArgumentNullException(nameof(accountHDScriptPubKey));
accountHDScriptPubKey = accountHDScriptPubKey.AsHDKeyCache();
accountKey = accountKey.AsHDKeyCache();
return Inputs.CoinsFor(accountHDScriptPubKey, accountKey, accountKeyPath).OfType<PSBTCoin>().Concat(Outputs.CoinsFor(accountHDScriptPubKey, accountKey, accountKeyPath).OfType<PSBTCoin>());
}
/// <summary>
/// Filter the keys which contains the <paramref name="accountKey"/> and <paramref name="accountKeyPath"/> in the HDKeys and whose input/output
/// the same scriptPubKeys as <paramref name="accountHDScriptPubKey"/>.
/// </summary>
/// <param name="accountHDScriptPubKey">The hdScriptPubKey used to generate addresses</param>
/// <param name="accountKey">The account key that will be used to sign (ie. 49'/0'/0')</param>
/// <param name="accountKeyPath">The account key path</param>
/// <returns>HD Keys matching master root key</returns>
public IEnumerable<PSBTHDKeyMatch> HDKeysFor(IHDScriptPubKey accountHDScriptPubKey, IHDKey accountKey, RootedKeyPath? accountKeyPath = null)
{
if (accountKey == null)
throw new ArgumentNullException(nameof(accountKey));
if (accountHDScriptPubKey == null)
throw new ArgumentNullException(nameof(accountHDScriptPubKey));
accountHDScriptPubKey = accountHDScriptPubKey.AsHDKeyCache();
accountKey = accountKey.AsHDKeyCache();
return Inputs.HDKeysFor(accountHDScriptPubKey, accountKey, accountKeyPath).OfType<PSBTHDKeyMatch>().Concat(Outputs.HDKeysFor(accountHDScriptPubKey, accountKey, accountKeyPath));
}
/// <summary>
/// Filter the keys which contains the <paramref name="accountKey"/> and <paramref name="accountKeyPath"/>.
/// </summary>
/// <param name="accountKey">The account key that will be used to sign (ie. 49'/0'/0')</param>
/// <param name="accountKeyPath">The account key path</param>
/// <returns>HD Keys matching master root key</returns>
public IEnumerable<PSBTHDKeyMatch> HDKeysFor(IHDKey accountKey, RootedKeyPath? accountKeyPath = null)
{
if (accountKey == null)
throw new ArgumentNullException(nameof(accountKey));
accountKey = accountKey.AsHDKeyCache();
return Inputs.HDKeysFor(accountKey, accountKeyPath).OfType<PSBTHDKeyMatch>().Concat(Outputs.HDKeysFor(accountKey, accountKeyPath));
}
/// <summary>
/// Add keypath information to this PSBT for each input or output involving it
/// </summary>
/// <param name="masterKey">The master key of the keypaths</param>
/// <param name="paths">The path of the public keys</param>
/// <returns>This PSBT</returns>
public PSBT AddKeyPath(IHDKey masterKey, params KeyPath[] paths)
{
return AddKeyPath(masterKey, paths.Select(p => Tuple.Create(p, null as Script)).ToArray());
}
/// <summary>
/// Add keypath information to this PSBT for each input or output involving it
/// </summary>
/// <param name="masterKey">The master key of the keypaths</param>
/// <param name="paths">The path of the public keys with their expected scriptPubKey</param>
/// <returns>This PSBT</returns>
public PSBT AddKeyPath(IHDKey masterKey, params Tuple<KeyPath, Script?>[] paths)
{
if (masterKey == null)
throw new ArgumentNullException(nameof(masterKey));
if (paths == null)
throw new ArgumentNullException(nameof(paths));
masterKey = masterKey.AsHDKeyCache();
var masterKeyFP = masterKey.GetPublicKey().GetHDFingerPrint();
foreach (var path in paths)
{
var key = masterKey.Derive(path.Item1);
AddKeyPath(key.GetPublicKey(), new RootedKeyPath(masterKeyFP, path.Item1), path.Item2);
}
return this;
}
/// <summary>
/// Add keypath information to this PSBT for each input or output involving it
/// </summary>
/// <param name="pubkey">The public key which need to sign</param>
/// <param name="rootedKeyPath">The keypath to this public key</param>
/// <returns>This PSBT</returns>
public PSBT AddKeyPath(PubKey pubkey, RootedKeyPath rootedKeyPath)
{
return AddKeyPath(pubkey, rootedKeyPath, null);
}
/// <summary>
/// Add keypath information to this PSBT, if the PSBT all finalized this operation is a no-op
/// </summary>
/// <param name="pubkey">The public key which need to sign</param>
/// <param name="rootedKeyPath">The keypath to this public key</param>
/// <param name="scriptPubKey">A specific scriptPubKey this pubkey is involved with</param>
/// <returns>This PSBT</returns>
public PSBT AddKeyPath(PubKey pubkey, RootedKeyPath rootedKeyPath, Script? scriptPubKey)
{
if (pubkey == null)
throw new ArgumentNullException(nameof(pubkey));
if (rootedKeyPath == null)
throw new ArgumentNullException(nameof(rootedKeyPath));
if (IsAllFinalized())
return this;
var txBuilder = CreateTransactionBuilder();
foreach (var o in this.Inputs.OfType<PSBTCoin>().Concat(this.Outputs))
{
if (o is PSBTInput i && i.IsFinalized())
continue;
var coin = o.GetCoin();
if (coin == null)
continue;
if ((scriptPubKey != null && coin.ScriptPubKey == scriptPubKey) ||
((o.GetSignableCoin() ?? coin.TryToScriptCoin(pubkey)) is Coin c && txBuilder.IsCompatibleKeyFromScriptCode(pubkey, c.GetScriptCode())) ||
txBuilder.IsCompatibleKeyFromScriptCode(pubkey, coin.ScriptPubKey))
{
o.AddKeyPath(pubkey, rootedKeyPath);
}
}
return this;
}
/// <summary>
/// Rebase the keypaths.
/// If a PSBT updater only know the child HD public key but not the root one, another updater knowing the parent master key it is based on
/// can rebase the paths. If the PSBT is all finalized this operation is a no-op
/// </summary>
/// <param name="accountKey">The current account key</param>
/// <param name="newRoot">The KeyPath with the fingerprint of the new root key</param>
/// <returns>This PSBT</returns>
public PSBT RebaseKeyPaths(IHDKey accountKey, RootedKeyPath newRoot)
{
if (accountKey == null)
throw new ArgumentNullException(nameof(accountKey));
if (newRoot == null)
throw new ArgumentNullException(nameof(newRoot));
if (IsAllFinalized())
return this;
accountKey = accountKey.AsHDKeyCache();
foreach (var o in HDKeysFor(accountKey).GroupBy(c => c.Coin))
{
if (o.Key is PSBTInput i && i.IsFinalized())
continue;
foreach (var keyPath in o)
{
if (keyPath.RootedKeyPath.MasterFingerprint != newRoot.MasterFingerprint)
{
if (keyPath.PubKey is PubKey ecdsa)
{
o.Key.HDKeyPaths.Remove(ecdsa);
o.Key.HDKeyPaths.Add(ecdsa, newRoot.Derive(keyPath.RootedKeyPath.KeyPath));
}
}
}
}
foreach (var xpub in GlobalXPubs.ToList())
{
if (xpub.Key.ExtPubKey.PubKey.Equals(accountKey.GetPublicKey()))
{
if (xpub.Value.MasterFingerprint != newRoot.MasterFingerprint)
{
GlobalXPubs.Remove(xpub.Key);
GlobalXPubs.Add(xpub.Key, newRoot.Derive(xpub.Value.KeyPath));
}
}
}
return this;
}
public Transaction GetOriginalTransaction()
{
var clone = tx.Clone();
for (int i = 0; i < Inputs.Count; i++)
{
clone.Inputs[i].ScriptSig = Inputs[i].originalScriptSig;
clone.Inputs[i].WitScript = Inputs[i].originalWitScript;
}
return clone;
}
public Transaction GetGlobalTransaction()
{
return tx.Clone();
}
}
}
#nullable disable
| |
/*
* Copyright (c) 2015, InWorldz Halcyon Developers
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of halcyon nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using NUnit.Framework;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Serialization;
using OpenMetaverse;
using KellermanSoftware.CompareNetObjects;
using OpenSim.Framework;
using System.IO;
using System.Xml.Serialization;
namespace OpenSim.Region.FrameworkTests
{
[TestFixture]
public class XMLSerializerTests
{
private readonly List<string> PrimCompareIgnoreList = new List<string> { "ParentGroup", "FullUpdateCounter", "TerseUpdateCounter",
"TimeStamp", "SerializedVelocity", "InventorySerial", "Rezzed" };
[Test]
public void TestGroupSerializationDeserialization()
{
var sop1 = SceneUtil.RandomSOP("Root", 1);
var sop2 = SceneUtil.RandomSOP("Child1", 2);
var sop3 = SceneUtil.RandomSOP("Child2", 3);
SceneObjectGroup group = new SceneObjectGroup(sop1);
group.AddPart(sop2);
group.AddPart(sop3);
SceneObjectGroup deserGroup = null;
string grpBytes = null;
Assert.DoesNotThrow(() =>
{
grpBytes = SceneObjectSerializer.ToXml2Format(group, true);
});
Assert.NotNull(grpBytes);
Assert.DoesNotThrow(() =>
{
deserGroup = SceneObjectSerializer.FromXml2Format(grpBytes);
});
CompareObjects comp = new CompareObjects();
comp.CompareStaticFields = false;
comp.CompareStaticProperties = false;
comp.ElementsToIgnore = PrimCompareIgnoreList;
Assert.IsTrue(comp.Compare(group, deserGroup), comp.DifferencesString);
}
[Test]
public void TestPrimitiveBaseShapeDeserialization()
{
var shape = SceneUtil.MockPrmitiveBaseShape();;
var serializer = new XmlSerializer(shape.GetType());
Assert.NotNull(serializer);
string shapeBytes = null;
Assert.DoesNotThrow(() =>
{
using (StringWriter stringwriter = new System.IO.StringWriter())
{
serializer.Serialize(stringwriter, shape);
shapeBytes = stringwriter.ToString();
}
});
Assert.NotNull(shapeBytes);
PrimitiveBaseShape deserShape = null;
Assert.DoesNotThrow(() =>
{
using (StringReader stringReader = new System.IO.StringReader(shapeBytes))
{
deserShape = (PrimitiveBaseShape)serializer.Deserialize(stringReader);
}
});
CompareObjects comp = new CompareObjects();
comp.CompareStaticFields = false;
comp.CompareStaticProperties = false;
Assert.IsTrue(comp.Compare(shape, deserShape), comp.DifferencesString);
}
[Test]
public void TestNullMediaListIsNotAnError()
{
var sop1 = SceneUtil.RandomSOP("Root", 1);
var sop2 = SceneUtil.RandomSOP("Child1", 2);
var sop3 = SceneUtil.RandomSOP("Child2", 3);
SceneObjectGroup group = new SceneObjectGroup(sop1);
group.AddPart(sop2);
group.AddPart(sop3);
sop1.Shape.Media = null;
SceneObjectGroup deserGroup = null;
string grpBytes = null;
Assert.DoesNotThrow(() =>
{
grpBytes = SceneObjectSerializer.ToXml2Format(group, true);
});
Assert.NotNull(grpBytes);
Assert.DoesNotThrow(() =>
{
deserGroup = SceneObjectSerializer.FromXml2Format(grpBytes);
});
}
[Test]
public void TestNullMediaEntryIsNotAnError()
{
var sop1 = SceneUtil.RandomSOP("Root", 1);
var sop2 = SceneUtil.RandomSOP("Child1", 2);
var sop3 = SceneUtil.RandomSOP("Child2", 3);
sop1.Shape.Media = new PrimitiveBaseShape.PrimMedia(3);
sop1.Shape.Media[0] = null;
sop1.Shape.Media[1] = new MediaEntry();
sop1.Shape.Media[2] = null;
SceneObjectGroup group = new SceneObjectGroup(sop1);
group.AddPart(sop2);
group.AddPart(sop3);
SceneObjectGroup deserGroup = null;
string grpBytes = null;
Assert.DoesNotThrow(() =>
{
grpBytes = SceneObjectSerializer.ToXml2Format(group, true);
});
Assert.NotNull(grpBytes);
Assert.DoesNotThrow(() =>
{
deserGroup = SceneObjectSerializer.FromXml2Format(grpBytes);
});
}
[Test]
public void TestRenderMaterialsSerialization()
{
var sop1 = SceneUtil.RandomSOP("Root", 1);
var sop2 = SceneUtil.RandomSOP("Child1", 2);
var sop3 = SceneUtil.RandomSOP("Child2", 3);
var mat1 = new RenderMaterial(UUID.Random(), UUID.Random());
var mat2 = new RenderMaterial(UUID.Random(), UUID.Random());
sop1.Shape.RenderMaterials.AddMaterial(mat1);
sop2.Shape.RenderMaterials.AddMaterial(mat2);
SceneObjectGroup group = new SceneObjectGroup(sop1);
group.AddPart(sop2);
group.AddPart(sop3);
SceneObjectGroup deserGroup = null;
string grpBytes = null;
Assert.DoesNotThrow(() =>
{
grpBytes = SceneObjectSerializer.ToXml2Format(group, true);
});
Assert.NotNull(grpBytes);
Assert.DoesNotThrow(() =>
{
deserGroup = SceneObjectSerializer.FromXml2Format(grpBytes);
});
var newsop1 = deserGroup.GetChildPart(1);
var newsop2 = deserGroup.GetChildPart(2);
var newsop3 = deserGroup.GetChildPart(3);
Assert.That(sop1.Shape.RenderMaterials, Is.EqualTo(newsop1.Shape.RenderMaterials));
Assert.That(sop2.Shape.RenderMaterials, Is.EqualTo(newsop2.Shape.RenderMaterials));
Assert.That(sop3.Shape.RenderMaterials, Is.EqualTo(newsop3.Shape.RenderMaterials));
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using lro = Google.LongRunning;
using proto = Google.Protobuf;
using wkt = Google.Protobuf.WellKnownTypes;
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.AppEngine.V1
{
/// <summary>Settings for <see cref="ServicesClient"/> instances.</summary>
public sealed partial class ServicesSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="ServicesSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="ServicesSettings"/>.</returns>
public static ServicesSettings GetDefault() => new ServicesSettings();
/// <summary>Constructs a new <see cref="ServicesSettings"/> object with default settings.</summary>
public ServicesSettings()
{
}
private ServicesSettings(ServicesSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
ListServicesSettings = existing.ListServicesSettings;
GetServiceSettings = existing.GetServiceSettings;
UpdateServiceSettings = existing.UpdateServiceSettings;
UpdateServiceOperationsSettings = existing.UpdateServiceOperationsSettings.Clone();
DeleteServiceSettings = existing.DeleteServiceSettings;
DeleteServiceOperationsSettings = existing.DeleteServiceOperationsSettings.Clone();
OnCopy(existing);
}
partial void OnCopy(ServicesSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to <c>ServicesClient.ListServices</c>
/// and <c>ServicesClient.ListServicesAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings ListServicesSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to <c>ServicesClient.GetService</c>
/// and <c>ServicesClient.GetServiceAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetServiceSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>ServicesClient.UpdateService</c> and <c>ServicesClient.UpdateServiceAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings UpdateServiceSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// Long Running Operation settings for calls to <c>ServicesClient.UpdateService</c> and
/// <c>ServicesClient.UpdateServiceAsync</c>.
/// </summary>
/// <remarks>
/// Uses default <see cref="gax::PollSettings"/> of:
/// <list type="bullet">
/// <item><description>Initial delay: 20 seconds.</description></item>
/// <item><description>Delay multiplier: 1.5</description></item>
/// <item><description>Maximum delay: 45 seconds.</description></item>
/// <item><description>Total timeout: 24 hours.</description></item>
/// </list>
/// </remarks>
public lro::OperationsSettings UpdateServiceOperationsSettings { get; set; } = new lro::OperationsSettings
{
DefaultPollSettings = new gax::PollSettings(gax::Expiration.FromTimeout(sys::TimeSpan.FromHours(24)), sys::TimeSpan.FromSeconds(20), 1.5, sys::TimeSpan.FromSeconds(45)),
};
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>ServicesClient.DeleteService</c> and <c>ServicesClient.DeleteServiceAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings DeleteServiceSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// Long Running Operation settings for calls to <c>ServicesClient.DeleteService</c> and
/// <c>ServicesClient.DeleteServiceAsync</c>.
/// </summary>
/// <remarks>
/// Uses default <see cref="gax::PollSettings"/> of:
/// <list type="bullet">
/// <item><description>Initial delay: 20 seconds.</description></item>
/// <item><description>Delay multiplier: 1.5</description></item>
/// <item><description>Maximum delay: 45 seconds.</description></item>
/// <item><description>Total timeout: 24 hours.</description></item>
/// </list>
/// </remarks>
public lro::OperationsSettings DeleteServiceOperationsSettings { get; set; } = new lro::OperationsSettings
{
DefaultPollSettings = new gax::PollSettings(gax::Expiration.FromTimeout(sys::TimeSpan.FromHours(24)), sys::TimeSpan.FromSeconds(20), 1.5, sys::TimeSpan.FromSeconds(45)),
};
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="ServicesSettings"/> object.</returns>
public ServicesSettings Clone() => new ServicesSettings(this);
}
/// <summary>
/// Builder class for <see cref="ServicesClient"/> to provide simple configuration of credentials, endpoint etc.
/// </summary>
public sealed partial class ServicesClientBuilder : gaxgrpc::ClientBuilderBase<ServicesClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public ServicesSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public ServicesClientBuilder()
{
UseJwtAccessWithScopes = ServicesClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref ServicesClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<ServicesClient> task);
/// <summary>Builds the resulting client.</summary>
public override ServicesClient Build()
{
ServicesClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<ServicesClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<ServicesClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private ServicesClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return ServicesClient.Create(callInvoker, Settings);
}
private async stt::Task<ServicesClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return ServicesClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => ServicesClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => ServicesClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => ServicesClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>Services client wrapper, for convenient use.</summary>
/// <remarks>
/// Manages services of an application.
/// </remarks>
public abstract partial class ServicesClient
{
/// <summary>
/// The default endpoint for the Services service, which is a host of "appengine.googleapis.com" and a port of
/// 443.
/// </summary>
public static string DefaultEndpoint { get; } = "appengine.googleapis.com:443";
/// <summary>The default Services scopes.</summary>
/// <remarks>
/// The default Services scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/appengine.admin</description></item>
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// <item><description>https://www.googleapis.com/auth/cloud-platform.read-only</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/appengine.admin",
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only",
});
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="ServicesClient"/> using the default credentials, endpoint and settings.
/// To specify custom credentials or other settings, use <see cref="ServicesClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="ServicesClient"/>.</returns>
public static stt::Task<ServicesClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new ServicesClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="ServicesClient"/> using the default credentials, endpoint and settings.
/// To specify custom credentials or other settings, use <see cref="ServicesClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="ServicesClient"/>.</returns>
public static ServicesClient Create() => new ServicesClientBuilder().Build();
/// <summary>
/// Creates a <see cref="ServicesClient"/> 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="ServicesSettings"/>.</param>
/// <returns>The created <see cref="ServicesClient"/>.</returns>
internal static ServicesClient Create(grpccore::CallInvoker callInvoker, ServicesSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
Services.ServicesClient grpcClient = new Services.ServicesClient(callInvoker);
return new ServicesClientImpl(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 Services client</summary>
public virtual Services.ServicesClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Lists all the services in the application.
/// </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="Service"/> resources.</returns>
public virtual gax::PagedEnumerable<ListServicesResponse, Service> ListServices(ListServicesRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Lists all the services in the application.
/// </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="Service"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ListServicesResponse, Service> ListServicesAsync(ListServicesRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets the current configuration of the specified service.
/// </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 Service GetService(GetServiceRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets the current configuration of the specified service.
/// </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<Service> GetServiceAsync(GetServiceRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets the current configuration of the specified service.
/// </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<Service> GetServiceAsync(GetServiceRequest request, st::CancellationToken cancellationToken) =>
GetServiceAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Updates the configuration of the specified service.
/// </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 lro::Operation<Service, OperationMetadataV1> UpdateService(UpdateServiceRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Updates the configuration of the specified service.
/// </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<lro::Operation<Service, OperationMetadataV1>> UpdateServiceAsync(UpdateServiceRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Updates the configuration of the specified service.
/// </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<lro::Operation<Service, OperationMetadataV1>> UpdateServiceAsync(UpdateServiceRequest request, st::CancellationToken cancellationToken) =>
UpdateServiceAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>The long-running operations client for <c>UpdateService</c>.</summary>
public virtual lro::OperationsClient UpdateServiceOperationsClient => throw new sys::NotImplementedException();
/// <summary>
/// Poll an operation once, using an <c>operationName</c> from a previous invocation of <c>UpdateService</c>.
/// </summary>
/// <param name="operationName">
/// The name of a previously invoked operation. Must not be <c>null</c> or empty.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The result of polling the operation.</returns>
public virtual lro::Operation<Service, OperationMetadataV1> PollOnceUpdateService(string operationName, gaxgrpc::CallSettings callSettings = null) =>
lro::Operation<Service, OperationMetadataV1>.PollOnceFromName(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), UpdateServiceOperationsClient, callSettings);
/// <summary>
/// Asynchronously poll an operation once, using an <c>operationName</c> from a previous invocation of
/// <c>UpdateService</c>.
/// </summary>
/// <param name="operationName">
/// The name of a previously invoked operation. Must not be <c>null</c> or empty.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A task representing the result of polling the operation.</returns>
public virtual stt::Task<lro::Operation<Service, OperationMetadataV1>> PollOnceUpdateServiceAsync(string operationName, gaxgrpc::CallSettings callSettings = null) =>
lro::Operation<Service, OperationMetadataV1>.PollOnceFromNameAsync(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), UpdateServiceOperationsClient, callSettings);
/// <summary>
/// Deletes the specified service and all enclosed versions.
/// </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 lro::Operation<wkt::Empty, OperationMetadataV1> DeleteService(DeleteServiceRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Deletes the specified service and all enclosed versions.
/// </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<lro::Operation<wkt::Empty, OperationMetadataV1>> DeleteServiceAsync(DeleteServiceRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Deletes the specified service and all enclosed versions.
/// </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<lro::Operation<wkt::Empty, OperationMetadataV1>> DeleteServiceAsync(DeleteServiceRequest request, st::CancellationToken cancellationToken) =>
DeleteServiceAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>The long-running operations client for <c>DeleteService</c>.</summary>
public virtual lro::OperationsClient DeleteServiceOperationsClient => throw new sys::NotImplementedException();
/// <summary>
/// Poll an operation once, using an <c>operationName</c> from a previous invocation of <c>DeleteService</c>.
/// </summary>
/// <param name="operationName">
/// The name of a previously invoked operation. Must not be <c>null</c> or empty.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The result of polling the operation.</returns>
public virtual lro::Operation<wkt::Empty, OperationMetadataV1> PollOnceDeleteService(string operationName, gaxgrpc::CallSettings callSettings = null) =>
lro::Operation<wkt::Empty, OperationMetadataV1>.PollOnceFromName(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), DeleteServiceOperationsClient, callSettings);
/// <summary>
/// Asynchronously poll an operation once, using an <c>operationName</c> from a previous invocation of
/// <c>DeleteService</c>.
/// </summary>
/// <param name="operationName">
/// The name of a previously invoked operation. Must not be <c>null</c> or empty.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A task representing the result of polling the operation.</returns>
public virtual stt::Task<lro::Operation<wkt::Empty, OperationMetadataV1>> PollOnceDeleteServiceAsync(string operationName, gaxgrpc::CallSettings callSettings = null) =>
lro::Operation<wkt::Empty, OperationMetadataV1>.PollOnceFromNameAsync(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), DeleteServiceOperationsClient, callSettings);
}
/// <summary>Services client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Manages services of an application.
/// </remarks>
public sealed partial class ServicesClientImpl : ServicesClient
{
private readonly gaxgrpc::ApiCall<ListServicesRequest, ListServicesResponse> _callListServices;
private readonly gaxgrpc::ApiCall<GetServiceRequest, Service> _callGetService;
private readonly gaxgrpc::ApiCall<UpdateServiceRequest, lro::Operation> _callUpdateService;
private readonly gaxgrpc::ApiCall<DeleteServiceRequest, lro::Operation> _callDeleteService;
/// <summary>
/// Constructs a client wrapper for the Services service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="ServicesSettings"/> used within this client.</param>
public ServicesClientImpl(Services.ServicesClient grpcClient, ServicesSettings settings)
{
GrpcClient = grpcClient;
ServicesSettings effectiveSettings = settings ?? ServicesSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
UpdateServiceOperationsClient = new lro::OperationsClientImpl(grpcClient.CreateOperationsClient(), effectiveSettings.UpdateServiceOperationsSettings);
DeleteServiceOperationsClient = new lro::OperationsClientImpl(grpcClient.CreateOperationsClient(), effectiveSettings.DeleteServiceOperationsSettings);
_callListServices = clientHelper.BuildApiCall<ListServicesRequest, ListServicesResponse>(grpcClient.ListServicesAsync, grpcClient.ListServices, effectiveSettings.ListServicesSettings).WithGoogleRequestParam("parent", request => request.Parent);
Modify_ApiCall(ref _callListServices);
Modify_ListServicesApiCall(ref _callListServices);
_callGetService = clientHelper.BuildApiCall<GetServiceRequest, Service>(grpcClient.GetServiceAsync, grpcClient.GetService, effectiveSettings.GetServiceSettings).WithGoogleRequestParam("name", request => request.Name);
Modify_ApiCall(ref _callGetService);
Modify_GetServiceApiCall(ref _callGetService);
_callUpdateService = clientHelper.BuildApiCall<UpdateServiceRequest, lro::Operation>(grpcClient.UpdateServiceAsync, grpcClient.UpdateService, effectiveSettings.UpdateServiceSettings).WithGoogleRequestParam("name", request => request.Name);
Modify_ApiCall(ref _callUpdateService);
Modify_UpdateServiceApiCall(ref _callUpdateService);
_callDeleteService = clientHelper.BuildApiCall<DeleteServiceRequest, lro::Operation>(grpcClient.DeleteServiceAsync, grpcClient.DeleteService, effectiveSettings.DeleteServiceSettings).WithGoogleRequestParam("name", request => request.Name);
Modify_ApiCall(ref _callDeleteService);
Modify_DeleteServiceApiCall(ref _callDeleteService);
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_ListServicesApiCall(ref gaxgrpc::ApiCall<ListServicesRequest, ListServicesResponse> call);
partial void Modify_GetServiceApiCall(ref gaxgrpc::ApiCall<GetServiceRequest, Service> call);
partial void Modify_UpdateServiceApiCall(ref gaxgrpc::ApiCall<UpdateServiceRequest, lro::Operation> call);
partial void Modify_DeleteServiceApiCall(ref gaxgrpc::ApiCall<DeleteServiceRequest, lro::Operation> call);
partial void OnConstruction(Services.ServicesClient grpcClient, ServicesSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC Services client</summary>
public override Services.ServicesClient GrpcClient { get; }
partial void Modify_ListServicesRequest(ref ListServicesRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_GetServiceRequest(ref GetServiceRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_UpdateServiceRequest(ref UpdateServiceRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_DeleteServiceRequest(ref DeleteServiceRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Lists all the services in the application.
/// </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="Service"/> resources.</returns>
public override gax::PagedEnumerable<ListServicesResponse, Service> ListServices(ListServicesRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListServicesRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedEnumerable<ListServicesRequest, ListServicesResponse, Service>(_callListServices, request, callSettings);
}
/// <summary>
/// Lists all the services in the application.
/// </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="Service"/> resources.</returns>
public override gax::PagedAsyncEnumerable<ListServicesResponse, Service> ListServicesAsync(ListServicesRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListServicesRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedAsyncEnumerable<ListServicesRequest, ListServicesResponse, Service>(_callListServices, request, callSettings);
}
/// <summary>
/// Gets the current configuration of the specified service.
/// </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 Service GetService(GetServiceRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetServiceRequest(ref request, ref callSettings);
return _callGetService.Sync(request, callSettings);
}
/// <summary>
/// Gets the current configuration of the specified service.
/// </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<Service> GetServiceAsync(GetServiceRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetServiceRequest(ref request, ref callSettings);
return _callGetService.Async(request, callSettings);
}
/// <summary>The long-running operations client for <c>UpdateService</c>.</summary>
public override lro::OperationsClient UpdateServiceOperationsClient { get; }
/// <summary>
/// Updates the configuration of the specified service.
/// </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 lro::Operation<Service, OperationMetadataV1> UpdateService(UpdateServiceRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_UpdateServiceRequest(ref request, ref callSettings);
return new lro::Operation<Service, OperationMetadataV1>(_callUpdateService.Sync(request, callSettings), UpdateServiceOperationsClient);
}
/// <summary>
/// Updates the configuration of the specified service.
/// </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 async stt::Task<lro::Operation<Service, OperationMetadataV1>> UpdateServiceAsync(UpdateServiceRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_UpdateServiceRequest(ref request, ref callSettings);
return new lro::Operation<Service, OperationMetadataV1>(await _callUpdateService.Async(request, callSettings).ConfigureAwait(false), UpdateServiceOperationsClient);
}
/// <summary>The long-running operations client for <c>DeleteService</c>.</summary>
public override lro::OperationsClient DeleteServiceOperationsClient { get; }
/// <summary>
/// Deletes the specified service and all enclosed versions.
/// </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 lro::Operation<wkt::Empty, OperationMetadataV1> DeleteService(DeleteServiceRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_DeleteServiceRequest(ref request, ref callSettings);
return new lro::Operation<wkt::Empty, OperationMetadataV1>(_callDeleteService.Sync(request, callSettings), DeleteServiceOperationsClient);
}
/// <summary>
/// Deletes the specified service and all enclosed versions.
/// </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 async stt::Task<lro::Operation<wkt::Empty, OperationMetadataV1>> DeleteServiceAsync(DeleteServiceRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_DeleteServiceRequest(ref request, ref callSettings);
return new lro::Operation<wkt::Empty, OperationMetadataV1>(await _callDeleteService.Async(request, callSettings).ConfigureAwait(false), DeleteServiceOperationsClient);
}
}
public partial class ListServicesRequest : gaxgrpc::IPageRequest
{
}
public partial class ListServicesResponse : gaxgrpc::IPageResponse<Service>
{
/// <summary>Returns an enumerator that iterates through the resources in this response.</summary>
public scg::IEnumerator<Service> GetEnumerator() => Services.GetEnumerator();
sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator();
}
public static partial class Services
{
public partial class ServicesClient
{
/// <summary>
/// Creates a new instance of <see cref="lro::Operations.OperationsClient"/> using the same call invoker as
/// this client.
/// </summary>
/// <returns>A new Operations client for the same target as this client.</returns>
public virtual lro::Operations.OperationsClient CreateOperationsClient() =>
new lro::Operations.OperationsClient(CallInvoker);
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig.Runtime
{
using System;
using System.Runtime.CompilerServices;
using TS = Microsoft.Zelig.Runtime.TypeSystem;
public class SyncBlockTable
{
internal const int BlocksInACluster = 32;
//
// State
//
private Synchronization.YieldLock m_lock;
private SyncBlock[][] m_clusters;
internal SyncBlock m_freeList;
private int m_uniqueHashCode;
//
// Helper Methods
//
public static int GetHashCode( object target )
{
ObjectHeader oh = ObjectHeader.Unpack( target );
int hashCode;
switch(oh.ExtensionKind)
{
case ObjectHeader.ExtensionKinds.HashCode:
return oh.Payload;
case ObjectHeader.ExtensionKinds.Empty:
using(var hnd = new SmartHandles.YieldLockHolder( Instance.Lock ))
{
if(oh.IsImmutable == false)
{
//
// Check again, under lock, in case we had a race condition.
//
if(oh.ExtensionKind == ObjectHeader.ExtensionKinds.Empty)
{
hashCode = Instance.m_uniqueHashCode++;
oh.UpdateExtension( ObjectHeader.ExtensionKinds.HashCode, hashCode );
return hashCode;
}
}
}
break;
}
//--//
int idx = AssignSyncBlock( target );
hashCode = Instance.GetHashCode( idx );
GC.KeepAlive( target );
return hashCode;
}
public static Synchronization.CriticalSection GetLock( object target )
{
BugCheck.Assert(null != target, BugCheck.StopCode.SyncBlockCorruption );
int idx = AssignSyncBlock( target );
Synchronization.CriticalSection res = Instance.GetLock( idx );
GC.KeepAlive( target );
return res;
}
//--//
[Inline]
private static int AssignSyncBlock( object obj )
{
BugCheck.Assert(null != obj, BugCheck.StopCode.SyncBlockCorruption);
ObjectHeader oh = ObjectHeader.Unpack( obj );
if(oh.ExtensionKind == ObjectHeader.ExtensionKinds.SyncBlock)
{
return oh.Payload;
}
return Instance.AssignSyncBlockSlow( obj );
}
private int AssignSyncBlockSlow( object obj )
{
ObjectHeader oh = ObjectHeader.Unpack( obj );
using(new SmartHandles.YieldLockHolder( this.Lock ))
{
//
// Check again, under lock, in case we had a race condition.
//
if(oh.ExtensionKind == ObjectHeader.ExtensionKinds.SyncBlock)
{
return oh.Payload;
}
int idx = -1;
if(oh.IsImmutable)
{
if(m_clusters != null)
{
foreach(var blocks in m_clusters)
{
for(int pos = 0; pos < BlocksInACluster; pos++)
{
var sb = blocks[pos];
if(sb.AssociatedObject == obj)
{
idx = sb.Index;
break;
}
}
if(idx >= 0)
{
break;
}
}
}
}
if(idx < 0)
{
while(true)
{
var sb = SyncBlock.ExtractFromFreeList();
if(sb != null)
{
sb.Prepare( obj, m_uniqueHashCode++ );
idx = sb.Index;
break;
}
ExpandClusters();
}
}
switch(oh.ExtensionKind)
{
case ObjectHeader.ExtensionKinds.Empty:
//
// Hash code automatically assigned.
//
break;
case ObjectHeader.ExtensionKinds.HashCode:
//
// Copy hash code from header.
//
SetHashCode( idx, oh.Payload );
break;
case ObjectHeader.ExtensionKinds.SyncBlock:
BugCheck.Raise( BugCheck.StopCode.SyncBlockCorruption );
break;
default:
//
// Not implemented yet, so it has to be a corruption.
//
BugCheck.Raise( BugCheck.StopCode.SyncBlockCorruption );
break;
}
if(oh.IsImmutable == false)
{
oh.UpdateExtension( ObjectHeader.ExtensionKinds.SyncBlock, idx );
}
return idx;
}
}
//--//
public int GetHashCode( int idx )
{
int clusterIndex = idx / BlocksInACluster;
int blockIndex = idx % BlocksInACluster;
return m_clusters[clusterIndex][blockIndex].HashCode;
}
public void SetHashCode( int idx ,
int hashCode )
{
int clusterIndex = idx / BlocksInACluster;
int blockIndex = idx % BlocksInACluster;
m_clusters[clusterIndex][blockIndex].HashCode = hashCode;
}
public Synchronization.CriticalSection GetLock( int idx )
{
int clusterIndex = idx / BlocksInACluster;
int blockIndex = idx % BlocksInACluster;
return m_clusters[clusterIndex][blockIndex].Lock;
}
//--//
private void ExpandClusters()
{
int clusterIndex = (m_clusters == null) ? 0 : m_clusters.Length;
var blocks = new SyncBlock[BlocksInACluster];
//
// Link each block to the next one, except for the last one.
//
int index = clusterIndex * BlocksInACluster;
for(int i = 0; i < BlocksInACluster; i++)
{
blocks[i] = new SyncBlock( index++ );
}
m_clusters = ArrayUtility.AppendToArray( m_clusters, blocks );
}
//
// Access Methods
//
public static extern SyncBlockTable Instance
{
[SingletonFactory()]
[MethodImpl( MethodImplOptions.InternalCall )]
get;
}
public Synchronization.YieldLock Lock
{
get
{
return TypeSystemManager.AtomicAllocator( ref m_lock );
}
}
}
}
| |
//! \file ImageMNG.cs
//! \date 2018 Jan 16
//! \brief Multiple-image Network Graphics format.
//
// Copyright (C) 2018 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Windows.Media.Imaging;
using GameRes.Utility;
namespace GameRes.Formats
{
internal class MngMetaData : ImageMetaData
{
public long PngOffset;
}
/// <summary>
/// MNG may contain multiple frames, only the first one is loaded here.
/// </summary>
[Export(typeof(ImageFormat))]
public class MngFormat : ImageFormat
{
public override string Tag { get { return "MNG"; } }
public override string Description { get { return "Multiple-image Network Graphics"; } }
public override uint Signature { get { return 0x474E4D8A; } }
public override ImageMetaData ReadMetaData (IBinaryStream file)
{
var header = file.ReadHeader (8);
if (!header.AsciiEqual (4, "\x0D\x0A\x1A\x0A"))
return null;
uint chunk_size = Binary.BigEndian (file.ReadUInt32());
var chunk_type = file.ReadBytes (4);
if (!chunk_type.AsciiEqual ("MHDR"))
return null;
long chunk_pos = file.Position + chunk_size + 4;
var info = new MngMetaData { BPP = 32 };
info.Width = Binary.BigEndian (file.ReadUInt32());
info.Height = Binary.BigEndian (file.ReadUInt32());
for (;;)
{
file.Position = chunk_pos;
chunk_size = Binary.BigEndian (file.ReadUInt32());
file.Read (chunk_type, 0, 4);
if (Binary.AsciiEqual (chunk_type, "MEND") || Binary.AsciiEqual (chunk_type, "IEND"))
break;
if (Binary.AsciiEqual (chunk_type, "IHDR"))
{
info.PngOffset = chunk_pos;
break;
}
chunk_pos += chunk_size + 12;
}
if (0 == info.PngOffset)
return null;
return info;
}
public override ImageData Read (IBinaryStream file, ImageMetaData info)
{
var meta = (MngMetaData)info;
var body = new StreamRegion (file.AsStream, meta.PngOffset, true);
using (var png = new PrefixStream (PngFormat.HeaderBytes, body))
{
var decoder = new PngBitmapDecoder (png, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
var frame = decoder.Frames[0];
frame.Freeze();
return new ImageData (frame, info);
}
}
public override void Write (Stream file, ImageData image)
{
throw new System.NotImplementedException ("MngFormat.Write not implemented");
}
}
[Export(typeof(ArchiveFormat))]
public class MngOpener : ArchiveFormat
{
public override string Tag { get { return "MNG"; } }
public override string Description { get { return "Multiple-image Network Graphics"; } }
public override uint Signature { get { return 0x474E4D8A; } }
public override bool IsHierarchic { get { return false; } }
public override bool CanWrite { get { return false; } }
public override ArcFile TryOpen (ArcView file)
{
using (var input = file.CreateStream())
{
var info = MngFormat.ReadMetaData (input) as MngMetaData;
if (null == info)
return null;
var base_name = Path.GetFileNameWithoutExtension (file.Name);
long chunk_pos = info.PngOffset;
var chunk_type = new byte[4];
long ihdr_pos = 0;
var dir = new List<Entry>();
while (chunk_pos < file.MaxOffset)
{
input.Position = chunk_pos;
uint chunk_size = Binary.BigEndian (input.ReadUInt32());
input.Read (chunk_type, 0, 4);
if (Binary.AsciiEqual (chunk_type, "MEND"))
break;
if (Binary.AsciiEqual (chunk_type, "IHDR"))
{
ihdr_pos = chunk_pos;
}
else if (Binary.AsciiEqual (chunk_type, "IEND"))
{
if (0 == ihdr_pos) // IEND chunk without corresponding IHDR
return null;
var entry = new Entry {
Name = string.Format ("{0}#{1:D2}.png", base_name, dir.Count),
Type = "image",
Offset = ihdr_pos,
Size = (uint)(chunk_pos + chunk_size + 12 - ihdr_pos),
};
dir.Add (entry);
ihdr_pos = 0;
}
chunk_pos += chunk_size + 12;
}
if (0 == dir.Count)
return null;
return new ArcFile (file, this, dir);
}
}
public override IImageDecoder OpenImage (ArcFile arc, Entry entry)
{
var input = arc.File.CreateStream (entry.Offset, entry.Size);
return new MngFrameDecoder (input);
}
ImageFormat MngFormat { get { return s_MngFormat.Value; } }
static readonly ResourceInstance<ImageFormat> s_MngFormat = new ResourceInstance<ImageFormat> ("MNG");
}
internal sealed class MngFrameDecoder : IImageDecoder
{
IBinaryStream m_input;
ImageData m_image;
public Stream Source { get { m_input.Position = 0; return m_input.AsStream; } }
public ImageFormat SourceFormat { get { return ImageFormat.Png; } }
public ImageMetaData Info { get; private set; }
public ImageData Image {
get {
if (null == m_image)
{
var decoder = new PngBitmapDecoder (Source, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
var frame = decoder.Frames[0];
frame.Freeze();
m_image = new ImageData (frame, Info);
}
return m_image;
}
}
public MngFrameDecoder (IBinaryStream input)
{
var png = new PrefixStream (PngFormat.HeaderBytes, input.AsStream);
m_input = new BinaryStream (png, input.Name);
try
{
Info = ImageFormat.Png.ReadMetaData (m_input);
if (null == Info)
throw new InvalidFormatException();
}
catch
{
m_input.Dispose();
throw;
}
}
#region IDisposable members
bool m_disposed = false;
public void Dispose ()
{
if (!m_disposed)
{
m_input.Dispose();
m_disposed = true;
}
}
#endregion
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
extern alias MSDataServicesClient;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Caching;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security.AntiXss;
using System.Web.WebPages;
using Adxstudio.Xrm;
using Adxstudio.Xrm.AspNet.Cms;
using Adxstudio.Xrm.AspNet.Identity;
using Adxstudio.Xrm.AspNet.Mvc;
using Adxstudio.Xrm.Configuration;
using Adxstudio.Xrm.Core.Flighting;
using Adxstudio.Xrm.Resources;
using Adxstudio.Xrm.Services;
using Adxstudio.Xrm.Web;
using Adxstudio.Xrm.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Sdk;
using MSDataServicesClient::System.Data.Services.Client;
using Site.Areas.Account.Models;
using Site.Areas.Account.ViewModels;
using Site.Areas.AccountManagement;
namespace Site.Areas.Account.Controllers
{
[Authorize]
[PortalView, UnwrapNotFoundException]
[OutputCache(NoStore = true, Duration = 0)]
public class LoginController : Controller
{
public LoginController()
{
}
public LoginController(
ApplicationUserManager userManager,
ApplicationSignInManager signInManager,
ApplicationInvitationManager invitationManager,
ApplicationOrganizationManager organizationManager)
{
UserManager = userManager;
SignInManager = signInManager;
InvitationManager = invitationManager;
OrganizationManager = organizationManager;
}
private ApplicationUserManager _userManager;
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
private ApplicationInvitationManager _invitationManager;
public ApplicationInvitationManager InvitationManager
{
get
{
return _invitationManager ?? HttpContext.GetOwinContext().Get<ApplicationInvitationManager>();
}
private set
{
_invitationManager = value;
}
}
private ApplicationOrganizationManager _organizationManager;
public ApplicationOrganizationManager OrganizationManager
{
get
{
return _organizationManager ?? HttpContext.GetOwinContext().Get<ApplicationOrganizationManager>();
}
private set
{
_organizationManager = value;
}
}
private ApplicationStartupSettingsManager _startupSettingsManager;
public ApplicationStartupSettingsManager StartupSettingsManager
{
get
{
return _startupSettingsManager ?? HttpContext.GetOwinContext().Get<ApplicationStartupSettingsManager>();
}
private set
{
_startupSettingsManager = value;
}
}
private static Dictionary<string, bool> _validEssLicenses;
private static Dictionary<string, bool> ValidEssLicenses
{
get
{
if (_validEssLicenses == null)
{
// get a comma delimited list of license skus from config
var licenseConfigValue = PortalSettings.Instance.Ess.ValidLicenseSkus;
var licenses = licenseConfigValue.Split(new[] { ',' });
_validEssLicenses = new Dictionary<string, bool>();
// build the dictionary
foreach (var license in licenses)
{
_validEssLicenses[license] = true; // we don't really care about the value. just need a quick lookup of the sku as key
}
}
return _validEssLicenses;
}
}
// the duration in minutes to allow cached ESS graph pieces to stay cached
private const int GraphCacheTtlMinutes = 5;
//
// GET: /Login/Login
[HttpGet]
[AllowAnonymous]
[LanguageActionFilter]
[OutputCache(CacheProfile = "UserShared")]
public ActionResult Login(string returnUrl, string invitationCode)
{
if (!string.IsNullOrWhiteSpace(ViewBag.Settings.LoginButtonAuthenticationType))
{
return RedirectToAction("ExternalLogin", "Login", new { returnUrl, area = "Account", provider = ViewBag.Settings.LoginButtonAuthenticationType });
}
// if the portal is ess, don't use regular local signin (this page shows signin options)
if (ViewBag.IsESS)
{
// this action will redirect to the specified provider's login page
return RedirectToAction("ExternalLogin", "Login", new { returnUrl, area = "Account", provider = StartupSettingsManager.AzureAdOptions.AuthenticationType });
}
// this seems to be the only easy way to get this setting to the master page
this.Request.RequestContext.RouteData.Values["DisableChatWidget"] = true;
return View(GetLoginViewModel(null, null, returnUrl, invitationCode));
}
private ApplicationSignInManager _signInManager;
public ApplicationSignInManager SignInManager
{
get
{
return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
}
private set { _signInManager = value; }
}
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
var isLocal = requestContext.HttpContext.IsDebuggingEnabled && requestContext.HttpContext.Request.IsLocal;
var website = requestContext.HttpContext.GetWebsite();
ViewBag.Settings = website.GetAuthenticationSettings(isLocal);
ViewBag.IsESS = PortalSettings.Instance.Ess.IsEss;
ViewBag.AzureAdOrExternalLoginEnabled = ViewBag.Settings.ExternalLoginEnabled || StartupSettingsManager.AzureAdOptions != null;
ViewBag.ExternalRegistrationEnabled = StartupSettingsManager.ExternalRegistrationEnabled;
ViewBag.IdentityErrors = website.GetIdentityErrors(this.HttpContext.GetOwinContext());
}
//
// POST: /Login/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
[LocalLogin]
[Throttle(Name= "LoginThrottle")]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl, string invitationCode)
{
ViewBag.LoginSuccessful = false;
if (ViewBag.Locked == true)
{
AddErrors(ViewBag.IdentityErrors.TooManyAttempts());
return View(GetLoginViewModel(null, null, returnUrl, invitationCode));
}
if (!ModelState.IsValid
|| (ViewBag.Settings.LocalLoginByEmail && string.IsNullOrWhiteSpace(model.Email))
|| (!ViewBag.Settings.LocalLoginByEmail && string.IsNullOrWhiteSpace(model.Username)))
{
AddErrors(ViewBag.IdentityErrors.InvalidLogin());
return View(GetLoginViewModel(model, null, returnUrl, invitationCode));
}
var rememberMe = ViewBag.Settings.RememberMeEnabled && model.RememberMe;
// This doen't count login failures towards lockout only two factor authentication
// To enable password failures to trigger lockout, change to shouldLockout: true
SignInStatus result = ViewBag.Settings.LocalLoginByEmail
? await SignInManager.PasswordSignInByEmailAsync(model.Email, model.Password, rememberMe, ViewBag.Settings.TriggerLockoutOnFailedPassword)
: await SignInManager.PasswordSignInAsync(model.Username, model.Password, rememberMe, ViewBag.Settings.TriggerLockoutOnFailedPassword);
switch (result)
{
case SignInStatus.Success:
ViewBag.LoginSuccessful = true;
return await RedirectOnPostAuthenticate(returnUrl, invitationCode);
case SignInStatus.LockedOut:
AddErrors(ViewBag.IdentityErrors.UserLocked());
return View(GetLoginViewModel(model, null, returnUrl, invitationCode));
case SignInStatus.RequiresVerification:
ViewBag.LoginSuccessful = true;
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, InvitationCode = invitationCode, RememberMe = rememberMe });
case SignInStatus.Failure:
default:
AddErrors(ViewBag.IdentityErrors.InvalidLogin());
return View(GetLoginViewModel(model, null, returnUrl, invitationCode));
}
}
//
// GET: /Login/VerifyCode
[HttpGet]
[AllowAnonymous]
public async Task<ActionResult> VerifyCode(string provider, string returnUrl, bool rememberMe, string invitationCode)
{
if (PortalSettings.Instance.Ess.IsEss)
{
return HttpNotFound();
}
// Require that the user has already logged in via username/password or external login
if (!await SignInManager.HasBeenVerifiedAsync())
{
return HttpNotFound();
}
if (ViewBag.Settings.IsDemoMode)
{
var user = await UserManager.FindByIdAsync(await SignInManager.GetVerifiedUserIdAsync());
if (user != null && user.LogonEnabled)
{
var code = await UserManager.GenerateTwoFactorTokenAsync(user.Id, provider);
ViewBag.DemoModeCode = code;
}
}
return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe, InvitationCode = invitationCode });
}
//
// POST: /Login/VerifyCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> VerifyCode(VerifyCodeViewModel model)
{
if (PortalSettings.Instance.Ess.IsEss)
{
return HttpNotFound();
}
if (!ModelState.IsValid)
{
return View(model);
}
var rememberMe = ViewBag.Settings.RememberMeEnabled && model.RememberMe;
var rememberBrowser = ViewBag.Settings.TwoFactorEnabled && ViewBag.Settings.RememberBrowserEnabled && model.RememberBrowser;
SignInStatus result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, isPersistent: rememberMe, rememberBrowser: rememberBrowser);
switch (result)
{
case SignInStatus.Success:
return await RedirectOnPostAuthenticate(model.ReturnUrl, model.InvitationCode);
case SignInStatus.LockedOut:
AddErrors(ViewBag.IdentityErrors.UserLocked());
return View(model);
case SignInStatus.Failure:
default:
AddErrors(ViewBag.IdentityErrors.InvalidTwoFactorCode());
return View(model);
}
}
//
// GET: /Login/ForgotPassword
[HttpGet]
[AllowAnonymous]
[LocalLogin]
[LanguageActionFilter]
public ActionResult ForgotPassword()
{
if (!ViewBag.Settings.ResetPasswordEnabled)
{
return HttpNotFound();
}
return View();
}
//
// POST: /Login/ForgotPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
[LocalLogin]
public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (!ViewBag.Settings.ResetPasswordEnabled)
{
return HttpNotFound();
}
if (ModelState.IsValid)
{
if (string.IsNullOrWhiteSpace(model.Email))
{
return HttpNotFound();
}
var user = await UserManager.FindByEmailAsync(model.Email);
if (user == null || !user.LogonEnabled || (ViewBag.Settings.ResetPasswordRequiresConfirmedEmail && !(await UserManager.IsEmailConfirmedAsync(user.Id))))
{
// Don't reveal that the user does not exist or is not confirmed
return View("ForgotPasswordConfirmation");
}
var code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
var callbackUrl = Url.Action("ResetPassword", "Login", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
var parameters = new Dictionary<string, object> { { "UserId", user.Id }, { "Code", code }, { "UrlCode", AntiXssEncoder.UrlEncode(code) }, { "CallbackUrl", callbackUrl }, { "Email", model.Email } };
try
{
await OrganizationManager.InvokeProcessAsync("adx_SendPasswordResetToContact", user.ContactId, parameters);
}
catch (System.ServiceModel.FaultException ex)
{
var guid = WebEventSource.Log.GenericErrorException(ex);
ViewBag.ErrorMessage = string.Format(ResourceManager.GetString("Generic_Error_Message"), guid);
return View("ForgotPassword");
}
//await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking here: <a href=\"" + callbackUrl + "\">link</a>");
if (ViewBag.Settings.IsDemoMode)
{
ViewBag.DemoModeLink = callbackUrl;
}
return View("ForgotPasswordConfirmation");
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Login/ForgotPasswordConfirmation
[HttpGet]
[AllowAnonymous]
[LocalLogin]
public ActionResult ForgotPasswordConfirmation()
{
if (!ViewBag.Settings.ResetPasswordEnabled)
{
return HttpNotFound();
}
return View();
}
//
// GET: /Login/ResetPassword
[HttpGet]
[AllowAnonymous]
[LocalLogin]
[LanguageActionFilter]
public ActionResult ResetPassword(string userId, string code)
{
if (!ViewBag.Settings.ResetPasswordEnabled)
{
return HttpNotFound();
}
if (userId == null || code == null)
{
return HttpNotFound();
}
return View();
}
//
// POST: /Login/ResetPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
[LocalLogin]
public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model)
{
if (!ViewBag.Settings.ResetPasswordEnabled)
{
return HttpNotFound();
}
if (!string.Equals(model.Password, model.ConfirmPassword))
{
ModelState.AddModelError("Password", ViewBag.IdentityErrors.PasswordConfirmationFailure().Description);
}
if (!ModelState.IsValid)
{
return View(model);
}
var user = await UserManager.FindByIdAsync(model.UserId);
if (user == null || !user.LogonEnabled)
{
// Don't reveal that the user does not exist
return RedirectToAction("ResetPasswordConfirmation", "Login");
}
var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);
if (result.Succeeded)
{
return RedirectToAction("ResetPasswordConfirmation", "Login");
}
AddErrors(result);
return View();
}
//
// GET: /Login/ResetPasswordConfirmation
[HttpGet]
[AllowAnonymous]
[LocalLogin]
public ActionResult ResetPasswordConfirmation()
{
if (!ViewBag.Settings.ResetPasswordEnabled)
{
return HttpNotFound();
}
return View();
}
//
// GET: /Login/ConfirmEmail
[HttpGet]
[AllowAnonymous]
public ActionResult ConfirmEmail()
{
if (User.Identity.IsAuthenticated)
{
return RedirectToProfile(null);
}
return View();
}
//
// POST: /Login/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
[ExternalLogin]
public ActionResult ExternalLogin(string provider, string returnUrl, string invitationCode)
{
//StartupSettingsManager.AzureAdOptions.Notifications.AuthorizationCodeReceived
// Request a redirect to the external login provider
return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Login", new { ReturnUrl = returnUrl, InvitationCode = invitationCode, Provider = provider }));
}
//
// GET: /Login/ExternalLogin
[HttpGet]
[AllowAnonymous]
[ExternalLogin]
[ActionName("ExternalLogin")]
public ActionResult GetExternalLogin(string provider, string returnUrl, string invitationCode)
{
return ExternalLogin(provider, returnUrl, invitationCode);
}
//
// GET: /Login/ExternalPasswordReset
[HttpGet]
[AllowAnonymous]
[ExternalLogin]
public void ExternalPasswordReset(string passwordResetPolicyId, string provider)
{
if (string.IsNullOrWhiteSpace(passwordResetPolicyId) || string.IsNullOrWhiteSpace(provider))
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "External Password Reset could not be invoked. Password Reset Policy ID was not specified or the provider was not defined.");
Redirect("~/");
}
// Let the middleware know you are trying to use the password reset policy
HttpContext.GetOwinContext().Set("Policy", passwordResetPolicyId);
var redirectUri = Url.Action("ExternalLogin", "Login", new { area = "Account", provider });
// Set the page to redirect to after password has been successfully changed.
var authenticationProperties = new AuthenticationProperties { RedirectUri = redirectUri };
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "External Password Reset invoked.");
HttpContext.GetOwinContext().Authentication.Challenge(authenticationProperties, provider);
}
//
// GET: /Login/SendCode
[HttpGet]
[AllowAnonymous]
public async Task<ActionResult> SendCode(string returnUrl, string invitationCode, bool rememberMe = false)
{
if (PortalSettings.Instance.Ess.IsEss)
{
return HttpNotFound();
}
var userId = await SignInManager.GetVerifiedUserIdAsync();
if (userId == null)
{
throw new ApplicationException("Account error.");
}
var userFactors = await UserManager.GetValidTwoFactorProvidersAsync(userId);
if (userFactors.Count() == 1)
{
// Send the code directly for a single option
return await SendCode(new SendCodeViewModel { SelectedProvider = userFactors.Single(), ReturnUrl = returnUrl, RememberMe = rememberMe, InvitationCode = invitationCode });
}
var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe, InvitationCode = invitationCode });
}
//
// POST: /Login/SendCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> SendCode(SendCodeViewModel model)
{
if (PortalSettings.Instance.Ess.IsEss)
{
return HttpNotFound();
}
if (!ModelState.IsValid)
{
return View();
}
// Generate the token and send it
if (!await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider))
{
throw new ApplicationException("Account error.");
}
return RedirectToAction("VerifyCode", new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe, InvitationCode = model.InvitationCode });
}
//
// GET: /Login/ExternalLoginCallback
[HttpGet]
[AllowAnonymous]
[ExternalLogin]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl, string invitationCode, string provider)
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
return RedirectToAction("Login");
}
if (ViewBag.IsESS)
{
var graphResult = await DoAdditionalEssGraphWork(loginInfo);
// will be passed as query parameter to Access Denied - Missing License liquid template
// to determine correct error message to display
string error = string.Empty;
switch (graphResult)
{
case Enums.AzureADGraphAuthResults.NoValidLicense:
error = "missing_license";
break;
case Enums.AzureADGraphAuthResults.UserHasNoEmail:
break;
case Enums.AzureADGraphAuthResults.UserNotFound:
break;
}
if (graphResult != Enums.AzureADGraphAuthResults.NoErrors)
{
return new RedirectToSiteMarkerResult("Access Denied - Missing License", new NameValueCollection { { "error", error } });
}
}
// Sign in the user with this external login provider if the user already has a login
var result = await SignInManager.ExternalSignInAsync(loginInfo, false, (bool)ViewBag.Settings.TriggerLockoutOnFailedPassword);
switch (result)
{
case SignInStatus.Success:
return await RedirectOnPostAuthenticate(returnUrl, invitationCode, loginInfo);
case SignInStatus.LockedOut:
AddErrors(ViewBag.IdentityErrors.UserLocked());
return View("Login", GetLoginViewModel(null, null, returnUrl, invitationCode));
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, InvitationCode = invitationCode });
case SignInStatus.Failure:
default:
// If the user does not have an account, then prompt the user to create an account
ViewBag.ReturnUrl = returnUrl;
ViewBag.InvitationCode = invitationCode;
var contactId = ToContactId(await FindInvitationByCodeAsync(invitationCode));
var email = (contactId != null ? contactId.Name : null) ?? await ToEmail(loginInfo);
var username = loginInfo.Login.ProviderKey;
var firstName = loginInfo.ExternalIdentity.FindFirstValue(System.Security.Claims.ClaimTypes.GivenName);
var lastName = loginInfo.ExternalIdentity.FindFirstValue(System.Security.Claims.ClaimTypes.Surname);
return await ExternalLoginConfirmation(username, email, firstName, lastName, returnUrl, invitationCode, loginInfo);
}
}
private async Task<string> ToEmail(ExternalLoginInfo loginInfo, CancellationToken cancellationToken = default(CancellationToken))
{
if (!string.IsNullOrWhiteSpace(loginInfo?.Email))
{
return loginInfo.Email;
}
if (this.StartupSettingsManager.AzureAdOptions != null
&& !string.IsNullOrWhiteSpace(this.StartupSettingsManager.AzureAdOptions.AuthenticationType)
&& !string.IsNullOrWhiteSpace(PortalSettings.Instance.Graph.RootUrl))
{
var authenticationType = await this.StartupSettingsManager.GetAuthenticationTypeAsync(loginInfo, cancellationToken);
if (this.StartupSettingsManager.AzureAdOptions.AuthenticationType == authenticationType)
{
// this is an Azure AD sign-in
Microsoft.Azure.ActiveDirectory.GraphClient.IUser graphUser;
try
{
graphUser = await GetGraphUser(loginInfo);
}
catch (Exception ex)
{
var guid = WebEventSource.Log.GenericErrorException(ex);
ViewBag.ErrorMessage = string.Format(ResourceManager.GetString("Generic_Error_Message"), guid);
graphUser = null;
}
if (graphUser != null)
{
return ToEmail(graphUser);
}
}
}
var identity = loginInfo?.ExternalIdentity;
if (identity != null)
{
var claim = identity.FindFirst(System.Security.Claims.ClaimTypes.Email)
?? identity.FindFirst("email")
?? identity.FindFirst("emails")
?? identity.FindFirst(System.Security.Claims.ClaimTypes.Upn);
if (claim != null)
{
return claim.Value;
}
}
return null;
}
private static string ToEmail(Microsoft.Azure.ActiveDirectory.GraphClient.IUser graphUser)
{
if (!string.IsNullOrWhiteSpace(graphUser.Mail)) return graphUser.Mail;
return graphUser.OtherMails != null ? graphUser.OtherMails.FirstOrDefault() : graphUser.UserPrincipalName;
}
private async Task<Enums.AzureADGraphAuthResults> DoAdditionalEssGraphWork(ExternalLoginInfo loginInfo)
{
var userCacheKey = $"{loginInfo.Login.ProviderKey}_graphUser";
var userAuthResultCacheKey = $"{loginInfo.Login.ProviderKey}_userAuthResult";
Microsoft.Azure.ActiveDirectory.GraphClient.IUser user = null;
// if the user's already gone through the Graph check, this will be set with the error that happened
if (HttpContext.Cache[userAuthResultCacheKey] != null)
{
return OutputGraphError((Enums.AzureADGraphAuthResults)HttpContext.Cache[userAuthResultCacheKey], userAuthResultCacheKey, loginInfo);
}
// if the cache here is null, we haven't retrieved the Graph user yet. retrieve it
if (HttpContext.Cache[userCacheKey] == null)
{
user = await GetGraphUser(loginInfo, userCacheKey, userAuthResultCacheKey);
if (user == null)
{
// resharper warns that Cache[] here might be null. won't be null since we're calling something that sets this if the return is null
return (Enums.AzureADGraphAuthResults)HttpContext.Cache[userAuthResultCacheKey];
}
}
else
{
user = (Microsoft.Azure.ActiveDirectory.GraphClient.IUser)HttpContext.Cache[userCacheKey];
}
// if the user doesn't have an email address, try to use the UPN
if (string.IsNullOrEmpty(user.Mail))
{
ADXTrace.Instance.TraceWarning(TraceCategory.Application, "Email was not set on user. Trying UPN.");
// if the UPN isn't set, fail
if (string.IsNullOrEmpty(user.UserPrincipalName))
{
return OutputGraphError(Enums.AzureADGraphAuthResults.UserHasNoEmail, userAuthResultCacheKey, loginInfo);
}
loginInfo.Email = user.UserPrincipalName;
}
else
{
// retrieve email
loginInfo.Email = user.Mail;
}
// do license check
foreach (var plan in user.AssignedPlans)
{
if (ValidEssLicenses.ContainsKey(plan.ServicePlanId.ToString()) && plan.CapabilityStatus.Equals("Enabled", StringComparison.InvariantCultureIgnoreCase))
{
return Enums.AzureADGraphAuthResults.NoErrors;
}
}
return OutputGraphError(Enums.AzureADGraphAuthResults.NoValidLicense, userAuthResultCacheKey, loginInfo);
}
private async Task<Microsoft.Azure.ActiveDirectory.GraphClient.IUser> GetGraphUser(ExternalLoginInfo loginInfo)
{
var userCacheKey = $"{loginInfo.Login.ProviderKey}_graphUser";
var userAuthResultCacheKey = $"{loginInfo.Login.ProviderKey}_userAuthResult";
// if the user's already gone through the Graph check, this will be set with the error that happened
if (HttpContext.Cache[userAuthResultCacheKey] != null)
{
return null;
}
// if the cache here is null, we haven't retrieved the Graph user yet. retrieve it
if (HttpContext.Cache[userCacheKey] == null)
{
return await GetGraphUser(loginInfo, userCacheKey, userAuthResultCacheKey);
}
return (Microsoft.Azure.ActiveDirectory.GraphClient.IUser)HttpContext.Cache[userCacheKey];
}
private async Task<Microsoft.Azure.ActiveDirectory.GraphClient.IUser> GetGraphUser(ExternalLoginInfo loginInfo, string userCacheKey, string userAuthResultCacheKey)
{
const int tokenRetryCount = 3;
var client = this.GetGraphClient(loginInfo,
PortalSettings.Instance.Graph.RootUrl,
PortalSettings.Instance.Authentication.TenantId);
Microsoft.Azure.ActiveDirectory.GraphClient.IUser user = null;
// retry tokenRetryCount times to retrieve the users. each time it fails, it will nullify the cache and try again
for (var x = 0; x < tokenRetryCount; x++)
{
try
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Attempting to retrieve user from Graph with UPN ");
// when we call this, the client will try to retrieve a token from GetAuthTokenTask()
user = await client.Me.ExecuteAsync();
// if we get here then everything is alright. stop looping
break;
}
catch (AggregateException ex)
{
var handled = false;
foreach (var innerEx in ex.InnerExceptions)
{
if (innerEx.InnerException == null)
{
break;
}
var clientException = innerEx.InnerException as DataServiceClientException;
if (clientException?.StatusCode == (int)HttpStatusCode.Unauthorized)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Current GraphClient auth token didn't seem to work. Discarding...");
// the token didn't seem to work. throw away cached token to retrieve new one
this.TokenManager.Reset();
handled = true;
}
}
if (!handled)
{
throw;
}
}
}
// if user is null here, we have a config problem where we can't get correct auth tokens despite repeated attempts
if (user == null)
{
OutputGraphError(Enums.AzureADGraphAuthResults.AuthConfigProblem, userAuthResultCacheKey, loginInfo);
return null;
}
// add cache entry for graph user object. it will expire in GraphCacheTtlMinutes minutes
HttpRuntime.Cache.Add(userCacheKey, user, null, DateTime.MaxValue, TimeSpan.FromMinutes(GraphCacheTtlMinutes), CacheItemPriority.Normal, null);
return user;
}
private Enums.AzureADGraphAuthResults OutputGraphError(Enums.AzureADGraphAuthResults result, string userAuthResultCacheKey, ExternalLoginInfo loginInfo)
{
// add cache entry for graph check result. it will expire in GraphCacheTtlMinutes minutes
HttpRuntime.Cache.Add(userAuthResultCacheKey, result, null, DateTime.MaxValue, TimeSpan.FromMinutes(GraphCacheTtlMinutes), CacheItemPriority.Normal, null);
switch (result)
{
case Enums.AzureADGraphAuthResults.UserNotFound:
ADXTrace.Instance.TraceError(TraceCategory.Application, "Azure AD didn't have the user with the specified NameIdentifier");
return Enums.AzureADGraphAuthResults.UserNotFound;
case Enums.AzureADGraphAuthResults.UserHasNoEmail:
ADXTrace.Instance.TraceError(TraceCategory.Application, "UPN was not set on user.");
return Enums.AzureADGraphAuthResults.UserHasNoEmail;
case Enums.AzureADGraphAuthResults.NoValidLicense:
ADXTrace.Instance.TraceError(TraceCategory.Application, "No valid license was found assigned to the user");
return Enums.AzureADGraphAuthResults.NoValidLicense;
case Enums.AzureADGraphAuthResults.AuthConfigProblem:
ADXTrace.Instance.TraceError(TraceCategory.Application, "There's a critical problem with retrieving Graph auth tokens.");
return Enums.AzureADGraphAuthResults.AuthConfigProblem;
}
ADXTrace.Instance.TraceError(TraceCategory.Application, "An unknown graph error occurred. Passed through UserNotFound, UserHasNoEmail, and NoValidLicense.");
return Enums.AzureADGraphAuthResults.UnknownError;
}
private readonly Lazy<CrmTokenManager> tokenManager = new Lazy<CrmTokenManager>(CreateCrmTokenManager);
private static CrmTokenManager CreateCrmTokenManager()
{
return new CrmTokenManager(PortalSettings.Instance.Authentication, PortalSettings.Instance.Certificate, PortalSettings.Instance.Graph.RootUrl);
}
private ICrmTokenManager TokenManager => this.tokenManager.Value;
private Microsoft.Azure.ActiveDirectory.GraphClient.ActiveDirectoryClient GetGraphClient(ExternalLoginInfo loginInfo, string graphRoot, string tenantId) {
var accessCodeClaim = loginInfo.ExternalIdentity.FindFirst("AccessCode");
var accessCode = accessCodeClaim?.Value;
return new Microsoft.Azure.ActiveDirectory.GraphClient.ActiveDirectoryClient(
new Uri(graphRoot + "/" + tenantId),
async () => await this.TokenManager.GetTokenAsync(accessCode));
}
//
// POST: /Login/ExternalLoginConfirmation
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
[ExternalLogin]
public Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl, string invitationCode, CancellationToken cancellationToken)
{
return ExternalLoginConfirmation(model.Username ?? model.Email, model.Email, model.FirstName, model.LastName, returnUrl, invitationCode, null, cancellationToken);
}
protected virtual async Task<ActionResult> ExternalLoginConfirmation(string username, string email, string firstName, string lastName, string returnUrl, string invitationCode, ExternalLoginInfo loginInfo, CancellationToken cancellationToken = default(CancellationToken))
{
loginInfo = loginInfo ?? await AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, "External Login Failure. Could not get ExternalLoginInfo.");
return View("ExternalLoginFailure");
}
var options = await this.StartupSettingsManager.GetAuthenticationOptionsExtendedAsync(loginInfo, cancellationToken);
var providerRegistrationEnabled = options?.RegistrationEnabled ?? false;
if (!ViewBag.Settings.RegistrationEnabled
|| !providerRegistrationEnabled
|| (!ViewBag.Settings.OpenRegistrationEnabled && !ViewBag.Settings.InvitationEnabled))
{
AddErrors(ViewBag.IdentityErrors.InvalidLogin());
// Registration is disabled
ViewBag.ExternalRegistrationFailure = true;
ADXTrace.Instance.TraceWarning(TraceCategory.Application, "User Registration Failed. Registration is not enabled.");
return View("Login", GetLoginViewModel(null, null, returnUrl, invitationCode));
}
if (!ViewBag.Settings.OpenRegistrationEnabled && ViewBag.Settings.InvitationEnabled && string.IsNullOrWhiteSpace(invitationCode))
{
// Registration requires an invitation
return RedirectToAction("RedeemInvitation", new { ReturnUrl = returnUrl });
}
if (User.Identity.IsAuthenticated)
{
return Redirect(returnUrl ?? "~/");
}
if (ModelState.IsValid)
{
var invitation = await FindInvitationByCodeAsync(invitationCode);
var essUserByEmail = await FindEssUserByEmailAsync(email);
var associatedUserByEmail = await FindAssociatedUserByEmailAsync(loginInfo, email);
var contactId = ToContactId(essUserByEmail) ?? ToContactId(invitation) ?? ToContactId(associatedUserByEmail);
if (ModelState.IsValid)
{
// Validate the username and email
var user = contactId != null
? new ApplicationUser { UserName = username, Email = email, FirstName = firstName, LastName = lastName, Id = contactId.Id.ToString() }
: new ApplicationUser { UserName = username, Email = email, FirstName = firstName, LastName = lastName };
var validateResult = await UserManager.UserValidator.ValidateAsync(user);
if (validateResult.Succeeded)
{
IdentityResult result;
if (contactId == null)
{
if (!ViewBag.Settings.OpenRegistrationEnabled)
{
throw new InvalidOperationException("Open registration is not enabled.");
}
// Create a new user
result = await UserManager.CreateAsync(user);
}
else
{
// Update the existing invited user
user = await UserManager.FindByIdAsync(contactId.Id.ToString());
if (user != null)
{
result = await UserManager.InitializeUserAsync(user, username, null, !string.IsNullOrWhiteSpace(email) ? email : contactId.Name, ViewBag.Settings.TriggerLockoutOnFailedPassword);
}
else
{
// Contact does not exist or login is disabled
if (!ViewBag.Settings.OpenRegistrationEnabled)
{
throw new InvalidOperationException("Open registration is not enabled.");
}
// Create a new user
result = await UserManager.CreateAsync(user);
}
if (!result.Succeeded)
{
AddErrors(result);
ViewBag.ReturnUrl = returnUrl;
ViewBag.InvitationCode = invitationCode;
return View("RedeemInvitation", new RedeemInvitationViewModel { InvitationCode = invitationCode });
}
}
if (result.Succeeded)
{
var addResult = await UserManager.AddLoginAsync(user.Id, loginInfo.Login);
// Treat email as confirmed on external login success
var confirmEmailResult = await UserManager.AutoConfirmEmailAsync(user.Id);
if (!confirmEmailResult.Succeeded)
{
AddErrors(confirmEmailResult);
}
if (addResult.Succeeded)
{
// AddLoginAsync added related entity adx_externalidentity and we must re-retrieve the user so the related collection ids are loaded, otherwise the adx_externalidentity will be deleted on subsequent user updates.
user = await this.UserManager.FindByIdAsync(user.Id);
var claimsMapping = options?.RegistrationClaimsMapping;
if (!string.IsNullOrWhiteSpace(claimsMapping))
{
ApplyClaimsMapping(user, loginInfo, claimsMapping);
}
if (invitation != null)
{
var redeemResult = await InvitationManager.RedeemAsync(invitation, user, Request.UserHostAddress);
if (redeemResult.Succeeded)
{
return await SignInAsync(user, returnUrl, loginInfo);
}
else
{
AddErrors(redeemResult);
}
}
else
{
return await SignInAsync(user, returnUrl, loginInfo);
}
}
else
{
AddErrors(addResult);
}
}
else
{
AddErrors(result);
}
}
else
{
AddErrors(validateResult);
}
}
}
ViewBag.ReturnUrl = returnUrl;
ViewBag.InvitationCode = invitationCode;
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email, FirstName = firstName, LastName = lastName, Username = username });
}
//
// GET: /Login/LogOff
[HttpGet]
public async Task<ActionResult> LogOff(string returnUrl, CancellationToken cancellationToken)
{
if (ViewBag.Settings.SignOutEverywhereEnabled)
{
UserManager.UpdateSecurityStamp(User.Identity.GetUserId());
}
var authenticationTypes = ViewBag.IsESS
? GetSignOutAuthenticationTypes(StartupSettingsManager.AzureAdOptions.AuthenticationType)
: await this.GetSignOutAuthenticationTypes(cancellationToken);
if (authenticationTypes != null)
{
AuthenticationManager.SignOut(authenticationTypes);
}
else
{
AuthenticationManager.SignOut(new AuthenticationProperties { RedirectUri = returnUrl });
}
AuthenticationManager.AuthenticationResponseGrant = null;
try
{
if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.TelemetryFeatureUsage))
{
PortalFeatureTrace.TraceInstance.LogAuthentication(FeatureTraceCategory.Authentication, this.HttpContext, "logOut", "authentication");
}
}
catch (Exception e)
{
WebEventSource.Log.GenericErrorException(e);
}
return Redirect(!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl) ? returnUrl : "~/");
}
private static string[] GetSignOutAuthenticationTypes(params string[] authenticationTypes)
{
var defaultAuthenticationTypes = new[]
{
DefaultAuthenticationTypes.ApplicationCookie,
DefaultAuthenticationTypes.ExternalCookie,
DefaultAuthenticationTypes.TwoFactorCookie,
};
return defaultAuthenticationTypes.Concat(authenticationTypes).ToArray();
}
private async Task<string[]> GetSignOutAuthenticationTypes(CancellationToken cancellationToken)
{
var provider =
((ClaimsIdentity)User.Identity).Claims
.FirstOrDefault(c => c.Type == "http://schemas.adxstudio.com/xrm/2014/02/identity/claims/loginprovider")
?.Value;
if (provider != null)
{
var options = await this.StartupSettingsManager.GetAuthenticationOptionsExtendedAsync(provider, cancellationToken);
if (options != null && options.ExternalLogoutEnabled)
{
return GetSignOutAuthenticationTypes(options.AuthenticationType);
}
}
return null;
}
//
// GET: /Login/ExternalLoginFailure
[HttpGet]
[AllowAnonymous]
[ExternalLogin]
public ActionResult ExternalLoginFailure()
{
return View();
}
// OWINAuthenticationFailedAccessDeniedMsg = "access_denied";
private const string OwinAuthenticationFailedAccessDeniedMsg = "access_denied";
private const string MessageQueryStringParameter = "message";
//
// GET: /Login/ExternalAuthenticationFailed
[HttpGet]
[AllowAnonymous]
[ExternalLogin]
public ActionResult ExternalAuthenticationFailed()
{
if ((this.Request?.QueryString.GetValues(MessageQueryStringParameter) ?? new string[] { })
.Any(m => m == OwinAuthenticationFailedAccessDeniedMsg))
{
ViewBag.AccessDeniedError = true;
}
// Because AuthenticationFailedNotification doesn't pass an initial returnUrl from which user might tried to SignIn,
// and when having redidected to this view makes SignIn link become "SignIn?returnUrl=/Account/Login/ExternalAuthenticationFailed?message=access_denied"
// which makes an infinite redirect loop - just set returnUrl to root
ViewBag.ReturnUrl = "/";
return View();
}
//
// GET: /Login/RedeemInvitation
[HttpGet]
[AllowAnonymous]
[LanguageActionFilter]
public ActionResult RedeemInvitation(string returnUrl, [Bind(Prefix="invitation")]string invitationCode = "", bool invalid = false)
{
if (!ViewBag.Settings.RegistrationEnabled || !ViewBag.Settings.InvitationEnabled)
{
return HttpNotFound();
}
if (invalid)
{
ModelState.AddModelError("InvitationCode", ViewBag.IdentityErrors.InvalidInvitationCode().Description);
}
ViewBag.ReturnUrl = returnUrl;
// Decoding invitation code
invitationCode = HttpUtility.HtmlDecode(invitationCode).Trim();
ViewBag.InvitationCode = invitationCode;
return View(new RedeemInvitationViewModel { InvitationCode = invitationCode });
}
//
// POST: /Login/RedeemInvitation
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> RedeemInvitation(RedeemInvitationViewModel model, string returnUrl)
{
if (!ViewBag.Settings.RegistrationEnabled || !ViewBag.Settings.InvitationEnabled)
{
return HttpNotFound();
}
if (ModelState.IsValid)
{
var applicationInvitation = await FindInvitationByCodeAsync(model.InvitationCode);
var contactId = ToContactId(applicationInvitation);
ViewBag.ReturnUrl = returnUrl;
ViewBag.InvitationCode = model.InvitationCode;
if (contactId != null || applicationInvitation != null)
{
if (!string.IsNullOrWhiteSpace(ViewBag.Settings.LoginButtonAuthenticationType))
{
return RedirectToAction("ExternalLogin", "Login", new {
returnUrl,
area = "Account",
invitationCode = model.InvitationCode,
provider = ViewBag.Settings.LoginButtonAuthenticationType
});
}
if (model.RedeemByLogin)
{
return View("Login", GetLoginViewModel(null, null, returnUrl, model.InvitationCode));
}
return Redirect(Site.Helpers.UrlHelpers.SecureRegistrationUrl(this.Url, returnUrl, model.InvitationCode));
}
ModelState.AddModelError("InvitationCode", ViewBag.IdentityErrors.InvalidInvitationCode().Description);
}
ViewBag.ReturnUrl = returnUrl;
return View(model);
}
[HttpGet]
[AllowAnonymous]
[ExternalLogin]
public Task<ActionResult> FacebookExternalLogin()
{
Response.SuppressFormsAuthenticationRedirect = true;
var website = HttpContext.GetWebsite();
var authenticationType = website.GetFacebookAuthenticationType();
var returnUrl = Url.Action("FacebookReloadParent", "Login");
var redirectUri = Url.Action("ExternalLoginCallback", "Login", new { ReturnUrl = returnUrl });
var result = new ChallengeResult(authenticationType.LoginProvider, redirectUri);
return Task.FromResult(result as ActionResult);
}
[HttpGet]
[AllowAnonymous]
[ExternalLogin]
public ActionResult FacebookReloadParent()
{
return View("LoginReloadParent");
}
[HttpPost]
[AllowAnonymous]
[ExternalLogin, SuppressMessage("ASP.NET.MVC.Security", "CA5332:MarkVerbHandlersWithValidateAntiforgeryToken", Justification = "External caller cannot provide anti-forgery token, signed_request value is validated.")]
public async Task<ActionResult> FacebookExternalLoginCallback(string signed_request, string returnUrl, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(signed_request))
{
return HttpNotFound();
}
var website = HttpContext.GetWebsite();
var loginInfo = website.GetFacebookLoginInfo(signed_request);
if (loginInfo == null)
{
return RedirectToLocal(returnUrl);
}
// Sign in the user with this external login provider if the user already has a login
var result = await SignInManager.ExternalSignInAsync(loginInfo, false, (bool)ViewBag.Settings.TriggerLockoutOnFailedPassword);
switch (result)
{
case SignInStatus.Success:
case SignInStatus.LockedOut:
return RedirectToLocal(returnUrl);
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl });
case SignInStatus.Failure:
default:
// If the user does not have an account, then prompt the user to create an account
ViewBag.ReturnUrl = returnUrl;
var email = loginInfo.Email;
var username = loginInfo.Login.ProviderKey;
var firstName = loginInfo.ExternalIdentity.FindFirstValue(System.Security.Claims.ClaimTypes.GivenName);
var lastName = loginInfo.ExternalIdentity.FindFirstValue(System.Security.Claims.ClaimTypes.Surname);
return await ExternalLoginConfirmation(username, email, firstName, lastName, returnUrl, null, loginInfo, cancellationToken);
}
}
#region Helpers
// Used for XSRF protection when adding external logins
private const string XsrfKey = "XsrfId";
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
}
private void AddErrors(IdentityError error)
{
AddErrors(IdentityResult.Failed(error.Description));
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error);
}
}
private async Task<ActionResult> RedirectOnPostAuthenticate(string returnUrl, string invitationCode, ExternalLoginInfo loginInfo = null, CancellationToken cancellationToken = default(CancellationToken))
{
var identity = this.AuthenticationManager.AuthenticationResponseGrant.Identity;
var userId = identity.GetUserId();
var user = await this.UserManager.FindByIdAsync(userId);
if (user != null && loginInfo != null)
{
var options = await this.StartupSettingsManager.GetAuthenticationOptionsExtendedAsync(loginInfo, cancellationToken);
var claimsMapping = options?.LoginClaimsMapping;
if (!string.IsNullOrWhiteSpace(claimsMapping))
{
ApplyClaimsMapping(user, loginInfo, claimsMapping);
}
}
return await this.RedirectOnPostAuthenticate(user, returnUrl, invitationCode, loginInfo, cancellationToken);
}
private async Task<ActionResult> RedirectOnPostAuthenticate(ApplicationUser user, string returnUrl, string invitationCode, ExternalLoginInfo loginInfo = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (user != null)
{
this.UpdateCurrentLanguage(user, ref returnUrl);
this.UpdateLastSuccessfulLogin(user);
await this.ApplyGraphUser(user, loginInfo, cancellationToken);
if (user.IsDirty)
{
await UserManager.UpdateAsync(user);
user.IsDirty = false;
}
IdentityResult redeemResult;
var invitation = await FindInvitationByCodeAsync(invitationCode);
if (invitation != null)
{
// Redeem invitation for the existing/registered contact
redeemResult = await InvitationManager.RedeemAsync(invitation, user, Request.UserHostAddress);
}
else if (!string.IsNullOrWhiteSpace(invitationCode))
{
redeemResult = IdentityResult.Failed(ViewBag.IdentityErrors.InvalidInvitationCode().Description);
}
else
{
redeemResult = IdentityResult.Success;
}
if (!redeemResult.Succeeded)
{
return RedirectToAction("RedeemInvitation", new { ReturnUrl = returnUrl, invitation = invitationCode, invalid = true });
}
if (!DisplayModeIsActive()
&& (user.HasProfileAlert || user.ProfileModifiedOn == null)
&& ViewBag.Settings.ProfileRedirectEnabled)
{
return RedirectToProfile(returnUrl);
}
}
return RedirectToLocal(returnUrl);
}
/// <summary>
/// Updates the current request language based on user preferences. If needed, updates the return URL as well.
/// </summary>
/// <param name="user">Application User that is currently being logged in.</param>
/// <param name="returnUrl">Return URL to be updated if needed.</param>
private void UpdateCurrentLanguage(ApplicationUser user, ref string returnUrl)
{
var languageContext = this.HttpContext.GetContextLanguageInfo();
if (languageContext.IsCrmMultiLanguageEnabled)
{
var preferredLanguage = user.Entity.GetAttributeValue<EntityReference>("adx_preferredlanguageid");
if (preferredLanguage != null)
{
var websiteLangauges = languageContext.ActiveWebsiteLanguages.ToArray();
// Only consider published website languages for users
var newLanguage = languageContext.GetWebsiteLanguageByPortalLanguageId(preferredLanguage.Id, websiteLangauges, true);
if (newLanguage != null)
{
if (ContextLanguageInfo.DisplayLanguageCodeInUrl)
{
returnUrl = languageContext.FormatUrlWithLanguage(false, newLanguage.Code, (returnUrl ?? string.Empty).AsAbsoluteUri(Request.Url));
}
}
}
}
}
/// <summary>
/// Updates date and time of last successful login
/// </summary>
/// <param name="user">Application User that is currently being logged in.</param>
private void UpdateLastSuccessfulLogin(ApplicationUser user)
{
if (!ViewBag.Settings.LoginTrackingEnabled)
{
return;
}
user.Entity.SetAttributeValue("adx_identity_lastsuccessfullogin", DateTime.UtcNow);
user.IsDirty = true;
}
private static void ApplyClaimsMapping(ApplicationUser user, ExternalLoginInfo loginInfo, string claimsMapping)
{
try
{
if (user != null && !string.IsNullOrWhiteSpace(claimsMapping))
{
foreach (var pair in claimsMapping.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
var pieces = pair.Split('=');
var claimValue = loginInfo.ExternalIdentity.Claims.FirstOrDefault(c => c.Type == pieces[1]);
if (pieces.Length == 2 && claimValue != null)
{
user.Entity.SetAttributeValue(pieces[0], claimValue.Value);
user.IsDirty = true;
}
}
}
}
catch (Exception ex)
{
WebEventSource.Log.GenericErrorException(ex);
}
}
private async Task ApplyGraphUser(ApplicationUser user, ExternalLoginInfo loginInfo, CancellationToken cancellationToken)
{
if (loginInfo != null
&& this.StartupSettingsManager.AzureAdOptions != null
&& !string.IsNullOrWhiteSpace(this.StartupSettingsManager.AzureAdOptions.AuthenticationType)
&& !string.IsNullOrWhiteSpace(PortalSettings.Instance.Graph.RootUrl)
&& string.IsNullOrWhiteSpace(user.FirstName)
&& string.IsNullOrWhiteSpace(user.LastName)
&& string.IsNullOrWhiteSpace(user.Email))
{
var authenticationType = await this.StartupSettingsManager.GetAuthenticationTypeAsync(loginInfo, cancellationToken);
if (this.StartupSettingsManager.AzureAdOptions.AuthenticationType == authenticationType)
{
// update the contact using Graph
try
{
var graphUser = await this.GetGraphUser(loginInfo);
user.FirstName = graphUser.GivenName;
user.LastName = graphUser.Surname;
user.Email = ToEmail(graphUser);
user.IsDirty = true;
}
catch (Exception ex)
{
var guid = WebEventSource.Log.GenericErrorException(ex);
this.ViewBag.ErrorMessage = string.Format(ResourceManager.GetString("Generic_Error_Message"), guid);
}
}
}
}
private bool DisplayModeIsActive()
{
return DisplayModeProvider.Instance
.GetAvailableDisplayModesForContext(HttpContext, null)
.OfType<HostNameSettingDisplayMode>()
.Any();
}
private static ActionResult RedirectToProfile(string returnUrl)
{
var query = !string.IsNullOrWhiteSpace(returnUrl) ? new NameValueCollection { { "ReturnUrl", returnUrl } } : null;
return new RedirectToSiteMarkerResult("Profile", query);
}
private ActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
return Redirect("~/");
}
internal class ChallengeResult : HttpUnauthorizedResult
{
public ChallengeResult(string provider, string redirectUri)
: this(provider, redirectUri, null)
{
}
public ChallengeResult(string provider, string redirectUri, string userId)
{
LoginProvider = provider;
RedirectUri = redirectUri;
UserId = userId;
}
public string LoginProvider { get; set; }
public string RedirectUri { get; set; }
public string UserId { get; set; }
public override void ExecuteResult(ControllerContext context)
{
var properties = new AuthenticationProperties { RedirectUri = RedirectUri };
if (UserId != null)
{
properties.Dictionary[XsrfKey] = UserId;
}
context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
}
}
private object GetLoginViewModel(LoginViewModel local, IEnumerable<AuthenticationDescription> external, string returnUrl, string invitationCode)
{
ViewData["local"] = local ?? new LoginViewModel();
ViewData["external"] = external ?? GetExternalAuthenticationTypes();
ViewBag.ReturnUrl = returnUrl;
ViewBag.InvitationCode = invitationCode;
return ViewData;
}
private IEnumerable<AuthenticationDescription> GetExternalAuthenticationTypes()
{
var authTypes = this.HttpContext.GetOwinContext().Authentication
.GetExternalAuthenticationTypes()
.OrderBy(type => type.AuthenticationType)
.ToList();
foreach (var authType in authTypes)
{
if (!authType.Properties.ContainsKey("RegistrationEnabled"))
{
var options = this.StartupSettingsManager.GetAuthenticationOptionsExtended(authType.AuthenticationType);
authType.Properties["RegistrationEnabled"] = options.RegistrationEnabled;
}
}
return authTypes;
}
private async Task<ApplicationInvitation> FindInvitationByCodeAsync(string invitationCode)
{
if (string.IsNullOrWhiteSpace(invitationCode)) return null;
if (!ViewBag.Settings.InvitationEnabled) return null;
return await InvitationManager.FindByCodeAsync(invitationCode);
}
private async Task<ApplicationUser> FindEssUserByEmailAsync(string email)
{
return ViewBag.IsEss
? await UserManager.FindByEmailAsync(email)
: null;
}
/// <summary>
/// If AllowContactMappingWithEmail property on the appropriate authentication options class for the provider
/// is true - finds a single unique contact where emailaddress1 equals email on the ExternalLoginInfo
/// </summary>
/// <param name="loginInfo">ExternalLoginIfo to find if AllowContactMappingWithEmail is true</param>
/// <param name="email">Email to match againts emailaddress1 from portal contacts</param>
/// <returns>ApplicationUser with unique email same as in external login, otherwise null.</returns>
private async Task<ApplicationUser> FindAssociatedUserByEmailAsync(ExternalLoginInfo loginInfo, string email)
{
return GetLoginProviderSetting<bool>(loginInfo, "AllowContactMappingWithEmail", false)
? await UserManager.FindByEmailAsync(email)
: null;
}
private static EntityReference ToContactId(ApplicationInvitation invitation)
{
return invitation != null && invitation.InvitedContact != null
? new EntityReference(invitation.InvitedContact.LogicalName, invitation.InvitedContact.Id) { Name = invitation.Email }
: null;
}
private static EntityReference ToContactId(ApplicationUser user)
{
return user != null
? user.ContactId
: null;
}
private async Task<ActionResult> SignInAsync(ApplicationUser user, string returnUrl, ExternalLoginInfo loginInfo = null, bool isPersistent = false, bool rememberBrowser = false)
{
await this.SignInManager.SignInAsync(user, isPersistent, rememberBrowser);
return await this.RedirectOnPostAuthenticate(user, returnUrl, null, loginInfo);
}
/// <summary>
/// Finds setting from the appropriate authentication options class of LoginProvider
/// </summary>
/// <typeparam name="T">Type of setting</typeparam>
/// <param name="loginInfo">Defines LoginProvider</param>
/// <param name="name">Name of a property in authentication options class</param>
/// <param name="defaultValue">Will be returned on any exception</param>
/// <returns>Value if exists. Otherwise - defaultValue</returns>
private T GetLoginProviderSetting<T>(ExternalLoginInfo loginInfo, string name, T defaultValue)
{
if (loginInfo == null)
{
return defaultValue;
}
T result = defaultValue;
string loginProvider = loginInfo.Login.LoginProvider;
try
{
// Getting the correct provider options
switch (loginProvider)
{
// OAuth
case "Twitter":
result = (T)StartupSettingsManager.Twitter?.GetType()
.GetProperty(name)?.GetValue(StartupSettingsManager.Twitter);
break;
case "Google":
result = (T)StartupSettingsManager.Google?.GetType()
.GetProperty(name)?.GetValue(StartupSettingsManager.Google);
break;
case "Facebook":
result = (T)StartupSettingsManager.Facebook?.GetType()
.GetProperty(name)?.GetValue(StartupSettingsManager.Facebook);
break;
case "LinkedIn":
result = (T)StartupSettingsManager.LinkedIn?.GetType()
.GetProperty(name)?.GetValue(StartupSettingsManager.LinkedIn);
break;
case "Yahoo":
result = (T)StartupSettingsManager.Yahoo?.GetType()
.GetProperty(name)?.GetValue(StartupSettingsManager.Yahoo);
break;
case "MicrosoftAccount":
result = (T)StartupSettingsManager.MicrosoftAccount?.GetType()
.GetProperty(name)?.GetValue(StartupSettingsManager.MicrosoftAccount);
break;
default:
// OpenIdConnect - checking Authority
var options = StartupSettingsManager.OpenIdConnectOptions?.FirstOrDefault(o =>
string.Equals(o.Authority, loginProvider, StringComparison.InvariantCultureIgnoreCase));
if (options != null)
{
result = (T)options.GetType().GetProperty(name)?.GetValue(options);
}
else
{
// wsFed - checking Caption
var wsFedOptions = StartupSettingsManager.WsFederationOptions?.FirstOrDefault(o =>
string.Equals(o.Caption, loginProvider, StringComparison.InvariantCultureIgnoreCase));
if (wsFedOptions != null)
{
result = (T)wsFedOptions.GetType().GetProperty(name)?.GetValue(wsFedOptions);
}
else
{
// saml2 - checking Caption
var saml2options = StartupSettingsManager.Saml2Options?.FirstOrDefault(o =>
string.Equals(o.Caption, loginProvider, StringComparison.InvariantCultureIgnoreCase));
if (saml2options != null)
{
result = (T)saml2options.GetType().GetProperty(name)?.GetValue(saml2options);
}
}
}
break;
}
}
catch (Exception)
{
return defaultValue;
}
return result;
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="XmlQualifiedName.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Xml {
using System.Collections;
using System.Diagnostics;
#if !SILVERLIGHT
using Microsoft.Win32;
using System.Reflection;
using System.Security;
using System.Security.Permissions;
#endif
/// <include file='doc\XmlQualifiedName.uex' path='docs/doc[@for="XmlQualifiedName"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
#if !SILVERLIGHT
[Serializable]
#endif
public class XmlQualifiedName {
#if !SILVERLIGHT
delegate int HashCodeOfStringDelegate(string s, int sLen, long additionalEntropy);
static HashCodeOfStringDelegate hashCodeDelegate = null;
#endif
string name;
string ns;
#if !SILVERLIGHT
[NonSerialized]
#endif
Int32 hash;
/// <include file='doc\XmlQualifiedName.uex' path='docs/doc[@for="XmlQualifiedName.Empty"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static readonly XmlQualifiedName Empty = new XmlQualifiedName(string.Empty);
/// <include file='doc\XmlQualifiedName.uex' path='docs/doc[@for="XmlQualifiedName.XmlQualifiedName"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlQualifiedName() : this(string.Empty, string.Empty) {}
/// <include file='doc\XmlQualifiedName.uex' path='docs/doc[@for="XmlQualifiedName.XmlQualifiedName1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlQualifiedName(string name) : this(name, string.Empty) {}
/// <include file='doc\XmlQualifiedName.uex' path='docs/doc[@for="XmlQualifiedName.XmlQualifiedName2"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlQualifiedName(string name, string ns) {
this.ns = ns == null ? string.Empty : ns;
this.name = name == null ? string.Empty : name;
}
/// <include file='doc\XmlQualifiedName.uex' path='docs/doc[@for="XmlQualifiedName.Namespace"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public string Namespace {
get { return ns; }
}
/// <include file='doc\XmlQualifiedName.uex' path='docs/doc[@for="XmlQualifiedName.Name"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public string Name {
get { return name; }
}
/// <include file='doc\XmlQualifiedName.uex' path='docs/doc[@for="XmlQualifiedName.GetHashCode"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override int GetHashCode() {
if(hash == 0) {
#if !SILVERLIGHT
if (hashCodeDelegate == null) {
hashCodeDelegate = GetHashCodeDelegate();
}
hash = hashCodeDelegate(Name, Name.Length, 0);
#else
hash = Name.GetHashCode() /*+ Namespace.GetHashCode()*/; // for perf reasons we are not taking ns's hashcode.
#endif
}
return hash;
}
/// <include file='doc\XmlQualifiedName.uex' path='docs/doc[@for="XmlQualifiedName.IsEmpty"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public bool IsEmpty {
get { return Name.Length == 0 && Namespace.Length == 0; }
}
/// <include file='doc\XmlQualifiedName.uex' path='docs/doc[@for="XmlQualifiedName.ToString"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override string ToString() {
return Namespace.Length == 0 ? Name : string.Concat(Namespace, ":" , Name);
}
/// <include file='doc\XmlQualifiedName.uex' path='docs/doc[@for="XmlQualifiedName.Equals"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override bool Equals(object other) {
XmlQualifiedName qname;
if ((object) this == other) {
return true;
}
qname = other as XmlQualifiedName;
if (qname != null) {
return (Name == qname.Name && Namespace == qname.Namespace);
}
return false;
}
/// <include file='doc\XmlQualifiedName.uex' path='docs/doc[@for="XmlQualifiedName.operator=="]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static bool operator ==(XmlQualifiedName a, XmlQualifiedName b) {
if ((object) a == (object) b)
return true;
if ((object) a == null || (object) b == null)
return false;
return (a.Name == b.Name && a.Namespace == b.Namespace);
}
/// <include file='doc\XmlQualifiedName.uex' path='docs/doc[@for="XmlQualifiedName.operator!="]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static bool operator !=(XmlQualifiedName a, XmlQualifiedName b) {
return !(a == b);
}
/// <include file='doc\XmlQualifiedName.uex' path='docs/doc[@for="XmlQualifiedName.ToString1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string ToString(string name, string ns) {
return ns == null || ns.Length == 0 ? name : ns + ":" + name;
}
#if !SILVERLIGHT // These methods are not used in Silverlight
[SecuritySafeCritical]
[ReflectionPermission(SecurityAction.Assert, Unrestricted = true)]
private static HashCodeOfStringDelegate GetHashCodeDelegate() {
// If we are using randomized hashing and we find the Marving hash method, we use that
// Otherwise, we use the old string hashing function.
if (!IsRandomizedHashingDisabled())
{
MethodInfo getHashCodeMethodInfo = typeof(String).GetMethod("InternalMarvin32HashString", BindingFlags.NonPublic | BindingFlags.Static);
if (getHashCodeMethodInfo != null)
{
return (HashCodeOfStringDelegate)Delegate.CreateDelegate(typeof(HashCodeOfStringDelegate), getHashCodeMethodInfo);
}
// This will fall through and return a delegate to the old hash function
Debug.Assert(false, "Randomized hashing is not supported.");
}
return new HashCodeOfStringDelegate(GetHashCodeOfString);
}
[SecuritySafeCritical]
[RegistryPermission(SecurityAction.Assert, Unrestricted = true)]
private static bool IsRandomizedHashingDisabled() {
const string regValueName = "DisableRandomizedHashingOnXmlQualifiedName";
bool disableHashing = false; // default value
if (!ReadBoolFromXmlRegistrySettings(Registry.CurrentUser, regValueName, ref disableHashing)) {
ReadBoolFromXmlRegistrySettings(Registry.LocalMachine, regValueName, ref disableHashing);
}
return disableHashing;
}
[SecurityCritical]
private static bool ReadBoolFromXmlRegistrySettings(RegistryKey hive, string regValueName, ref bool value) {
const string regValuePath = @"SOFTWARE\Microsoft\.NETFramework\XML";
try {
using (RegistryKey xmlRegKey = hive.OpenSubKey(regValuePath, false)) {
if (xmlRegKey != null) {
if (xmlRegKey.GetValueKind(regValueName) == RegistryValueKind.DWord) {
value = ((int)xmlRegKey.GetValue(regValueName)) == 1;
return true;
}
}
}
}
catch { /* use the default if we couldn't read the key */ }
return false;
}
private static int GetHashCodeOfString(string s, int length, long additionalEntropy)
{
// This is the fallback method for calling the regular hashcode method
return s.GetHashCode();
}
// --------- Some useful internal stuff -----------------
internal void Init(string name, string ns) {
Debug.Assert(name != null && ns != null);
this.name = name;
this.ns = ns;
this.hash = 0;
}
internal void SetNamespace(string ns) {
Debug.Assert(ns != null);
this.ns = ns; //Not changing hash since ns is not used to compute hashcode
}
internal void Verify() {
XmlConvert.VerifyNCName(name);
if (ns.Length != 0) {
XmlConvert.ToUri(ns);
}
}
internal void Atomize(XmlNameTable nameTable) {
Debug.Assert(name != null);
name = nameTable.Add(name);
ns = nameTable.Add(ns);
}
internal static XmlQualifiedName Parse(string s, IXmlNamespaceResolver nsmgr, out string prefix) {
string localName;
ValidateNames.ParseQNameThrow(s, out prefix, out localName);
string uri = nsmgr.LookupNamespace(prefix);
if (uri == null) {
if (prefix.Length != 0) {
throw new XmlException(Res.Xml_UnknownNs, prefix);
}
else { //Re-map namespace of empty prefix to string.Empty when there is no default namespace declared
uri = string.Empty;
}
}
return new XmlQualifiedName(localName, uri);
}
internal XmlQualifiedName Clone() {
return (XmlQualifiedName)MemberwiseClone();
}
internal static int Compare(XmlQualifiedName a, XmlQualifiedName b) {
if (null == a) {
return (null == b) ? 0 : -1;
}
if (null == b) {
return 1;
}
int i = String.CompareOrdinal(a.Namespace, b.Namespace);
if (i == 0) {
i = String.CompareOrdinal(a.Name, b.Name);
}
return i;
}
#endif
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Internal.Runtime.CompilerServices;
#if BIT64
using nuint = System.UInt64;
#else
using nuint = System.UInt32;
#endif
namespace System
{
/// <summary>
/// Extension methods and non-generic helpers for Span, ReadOnlySpan, Memory, and ReadOnlyMemory.
/// </summary>
public static class Span
{
/// <summary>Creates a new <see cref="ReadOnlyMemory{char}"/> over the portion of the target string.</summary>
/// <param name="text">The target string.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="text"/> is a null reference (Nothing in Visual Basic).</exception>
public static ReadOnlyMemory<char> AsReadOnlyMemory(this string text)
{
if (text == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text);
return new ReadOnlyMemory<char>(text, 0, text.Length);
}
/// <summary>Creates a new <see cref="ReadOnlyMemory{char}"/> over the portion of the target string.</summary>
/// <param name="text">The target string.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="text"/> is a null reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >text.Length).
/// </exception>
public static ReadOnlyMemory<char> AsReadOnlyMemory(this string text, int start)
{
if (text == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text);
if ((uint)start > (uint)text.Length)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
return new ReadOnlyMemory<char>(text, start, text.Length - start);
}
/// <summary>Creates a new <see cref="ReadOnlyMemory{char}"/> over the portion of the target string.</summary>
/// <param name="text">The target string.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="text"/> is a null reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> index or <paramref name="length"/> is not in range.
/// </exception>
public static ReadOnlyMemory<char> AsReadOnlyMemory(this string text, int start, int length)
{
if (text == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text);
if ((uint)start > (uint)text.Length || (uint)length > (uint)(text.Length - start))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
return new ReadOnlyMemory<char>(text, start, length);
}
/// <summary>Attempts to get the underlying <see cref="string"/> from a <see cref="ReadOnlyMemory{T}"/>.</summary>
/// <param name="readOnlyMemory">The memory that may be wrapping a <see cref="string"/> object.</param>
/// <param name="text">The string.</param>
/// <param name="start">The starting location in <paramref name="text"/>.</param>
/// <param name="length">The number of items in <paramref name="text"/>.</param>
/// <returns></returns>
public static bool TryGetString(this ReadOnlyMemory<char> readOnlyMemory, out string text, out int start, out int length)
{
if (readOnlyMemory.GetObjectStartLength(out int offset, out int count) is string s)
{
text = s;
start = offset;
length = count;
return true;
}
else
{
text = null;
start = 0;
length = 0;
return false;
}
}
/// <summary>
/// Casts a Span of one primitive type <typeparamref name="T"/> to Span of bytes.
/// That type may not contain pointers or references. This is checked at runtime in order to preserve type safety.
/// </summary>
/// <param name="source">The source slice, of type <typeparamref name="T"/>.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when <typeparamref name="T"/> contains pointers.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Span<byte> AsBytes<T>(this Span<T> source)
where T : struct
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T));
return new Span<byte>(
ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(source)),
checked(source.Length * Unsafe.SizeOf<T>()));
}
/// <summary>
/// Casts a ReadOnlySpan of one primitive type <typeparamref name="T"/> to ReadOnlySpan of bytes.
/// That type may not contain pointers or references. This is checked at runtime in order to preserve type safety.
/// </summary>
/// <param name="source">The source slice, of type <typeparamref name="T"/>.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when <typeparamref name="T"/> contains pointers.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpan<byte> AsBytes<T>(this ReadOnlySpan<T> source)
where T : struct
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T));
return new ReadOnlySpan<byte>(
ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(source)),
checked(source.Length * Unsafe.SizeOf<T>()));
}
/// <summary>
/// Casts a Span of one primitive type <typeparamref name="TFrom"/> to another primitive type <typeparamref name="TTo"/>.
/// These types may not contain pointers or references. This is checked at runtime in order to preserve type safety.
/// </summary>
/// <remarks>
/// Supported only for platforms that support misaligned memory access.
/// </remarks>
/// <param name="source">The source slice, of type <typeparamref name="TFrom"/>.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when <typeparamref name="TFrom"/> or <typeparamref name="TTo"/> contains pointers.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Span<TTo> NonPortableCast<TFrom, TTo>(this Span<TFrom> source)
where TFrom : struct
where TTo : struct
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<TFrom>())
ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(TFrom));
if (RuntimeHelpers.IsReferenceOrContainsReferences<TTo>())
ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(TTo));
return new Span<TTo>(
ref Unsafe.As<TFrom, TTo>(ref source.DangerousGetPinnableReference()),
checked((int)((long)source.Length * Unsafe.SizeOf<TFrom>() / Unsafe.SizeOf<TTo>())));
}
/// <summary>
/// Casts a ReadOnlySpan of one primitive type <typeparamref name="TFrom"/> to another primitive type <typeparamref name="TTo"/>.
/// These types may not contain pointers or references. This is checked at runtime in order to preserve type safety.
/// </summary>
/// <remarks>
/// Supported only for platforms that support misaligned memory access.
/// </remarks>
/// <param name="source">The source slice, of type <typeparamref name="TFrom"/>.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when <typeparamref name="TFrom"/> or <typeparamref name="TTo"/> contains pointers.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpan<TTo> NonPortableCast<TFrom, TTo>(this ReadOnlySpan<TFrom> source)
where TFrom : struct
where TTo : struct
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<TFrom>())
ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(TFrom));
if (RuntimeHelpers.IsReferenceOrContainsReferences<TTo>())
ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(TTo));
return new ReadOnlySpan<TTo>(
ref Unsafe.As<TFrom, TTo>(ref MemoryMarshal.GetReference(source)),
checked((int)((long)source.Length * Unsafe.SizeOf<TFrom>() / Unsafe.SizeOf<TTo>())));
}
/// <summary>
/// Creates a new readonly span over the portion of the target string.
/// </summary>
/// <param name="text">The target string.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="text"/> is a null
/// reference (Nothing in Visual Basic).</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpan<char> AsReadOnlySpan(this string text)
{
if (text == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text);
return new ReadOnlySpan<char>(ref text.GetRawStringData(), text.Length);
}
/// <summary>
/// Creates a new readonly span over the portion of the target string.
/// </summary>
/// <param name="text">The target string.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="text"/> is a null
/// reference (Nothing in Visual Basic).
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >text.Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpan<char> AsReadOnlySpan(this string text, int start)
{
if (text == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text);
if ((uint)start > (uint)text.Length)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
return new ReadOnlySpan<char>(ref Unsafe.Add(ref text.GetRawStringData(), start), text.Length - start);
}
/// <summary>
/// Creates a new readonly span over the portion of the target string.
/// </summary>
/// <param name="text">The target string.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="text"/> is a null
/// reference (Nothing in Visual Basic).
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> index or <paramref name="length"/> is not in range.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpan<char> AsReadOnlySpan(this string text, int start, int length)
{
if (text == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text);
if ((uint)start > (uint)text.Length || (uint)length > (uint)(text.Length - start))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
return new ReadOnlySpan<char>(ref Unsafe.Add(ref text.GetRawStringData(), start), length);
}
internal static unsafe void CopyTo<T>(ref T destination, ref T source, int elementsCount)
{
if (Unsafe.AreSame(ref destination, ref source))
return;
if (elementsCount <= 1)
{
if (elementsCount == 1)
{
destination = source;
}
return;
}
nuint byteCount = (nuint)elementsCount * (nuint)Unsafe.SizeOf<T>();
if (!RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
fixed (byte* pDestination = &Unsafe.As<T, byte>(ref destination))
{
fixed (byte* pSource = &Unsafe.As<T, byte>(ref source))
{
Buffer.Memmove(pDestination, pSource, byteCount);
}
}
}
else
{
RuntimeImports.RhBulkMoveWithWriteBarrier(
ref Unsafe.As<T, byte>(ref destination),
ref Unsafe.As<T, byte>(ref source),
byteCount);
}
}
internal static unsafe void ClearWithoutReferences(ref byte b, nuint byteLength)
{
if (byteLength == 0)
return;
#if CORECLR && (AMD64 || ARM64)
if (byteLength > 4096) goto PInvoke;
Unsafe.InitBlockUnaligned(ref b, 0, (uint)byteLength);
return;
#else
// TODO: Optimize other platforms to be on par with AMD64 CoreCLR
// Note: It's important that this switch handles lengths at least up to 22.
// See notes below near the main loop for why.
// The switch will be very fast since it can be implemented using a jump
// table in assembly. See http://stackoverflow.com/a/449297/4077294 for more info.
switch (byteLength)
{
case 1:
b = 0;
return;
case 2:
Unsafe.As<byte, short>(ref b) = 0;
return;
case 3:
Unsafe.As<byte, short>(ref b) = 0;
Unsafe.Add<byte>(ref b, 2) = 0;
return;
case 4:
Unsafe.As<byte, int>(ref b) = 0;
return;
case 5:
Unsafe.As<byte, int>(ref b) = 0;
Unsafe.Add<byte>(ref b, 4) = 0;
return;
case 6:
Unsafe.As<byte, int>(ref b) = 0;
Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 4)) = 0;
return;
case 7:
Unsafe.As<byte, int>(ref b) = 0;
Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 4)) = 0;
Unsafe.Add<byte>(ref b, 6) = 0;
return;
case 8:
#if BIT64
Unsafe.As<byte, long>(ref b) = 0;
#else
Unsafe.As<byte, int>(ref b) = 0;
Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0;
#endif
return;
case 9:
#if BIT64
Unsafe.As<byte, long>(ref b) = 0;
#else
Unsafe.As<byte, int>(ref b) = 0;
Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0;
#endif
Unsafe.Add<byte>(ref b, 8) = 0;
return;
case 10:
#if BIT64
Unsafe.As<byte, long>(ref b) = 0;
#else
Unsafe.As<byte, int>(ref b) = 0;
Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0;
#endif
Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
return;
case 11:
#if BIT64
Unsafe.As<byte, long>(ref b) = 0;
#else
Unsafe.As<byte, int>(ref b) = 0;
Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0;
#endif
Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
Unsafe.Add<byte>(ref b, 10) = 0;
return;
case 12:
#if BIT64
Unsafe.As<byte, long>(ref b) = 0;
#else
Unsafe.As<byte, int>(ref b) = 0;
Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0;
#endif
Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
return;
case 13:
#if BIT64
Unsafe.As<byte, long>(ref b) = 0;
#else
Unsafe.As<byte, int>(ref b) = 0;
Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0;
#endif
Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
Unsafe.Add<byte>(ref b, 12) = 0;
return;
case 14:
#if BIT64
Unsafe.As<byte, long>(ref b) = 0;
#else
Unsafe.As<byte, int>(ref b) = 0;
Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0;
#endif
Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 12)) = 0;
return;
case 15:
#if BIT64
Unsafe.As<byte, long>(ref b) = 0;
#else
Unsafe.As<byte, int>(ref b) = 0;
Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0;
#endif
Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 12)) = 0;
Unsafe.Add<byte>(ref b, 14) = 0;
return;
case 16:
#if BIT64
Unsafe.As<byte, long>(ref b) = 0;
Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
#else
Unsafe.As<byte, int>(ref b) = 0;
Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0;
Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0;
#endif
return;
case 17:
#if BIT64
Unsafe.As<byte, long>(ref b) = 0;
Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
#else
Unsafe.As<byte, int>(ref b) = 0;
Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0;
Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0;
#endif
Unsafe.Add<byte>(ref b, 16) = 0;
return;
case 18:
#if BIT64
Unsafe.As<byte, long>(ref b) = 0;
Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
#else
Unsafe.As<byte, int>(ref b) = 0;
Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0;
Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0;
#endif
Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 16)) = 0;
return;
case 19:
#if BIT64
Unsafe.As<byte, long>(ref b) = 0;
Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
#else
Unsafe.As<byte, int>(ref b) = 0;
Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0;
Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0;
#endif
Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 16)) = 0;
Unsafe.Add<byte>(ref b, 18) = 0;
return;
case 20:
#if BIT64
Unsafe.As<byte, long>(ref b) = 0;
Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
#else
Unsafe.As<byte, int>(ref b) = 0;
Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0;
Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0;
#endif
Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 16)) = 0;
return;
case 21:
#if BIT64
Unsafe.As<byte, long>(ref b) = 0;
Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
#else
Unsafe.As<byte, int>(ref b) = 0;
Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0;
Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0;
#endif
Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 16)) = 0;
Unsafe.Add<byte>(ref b, 20) = 0;
return;
case 22:
#if BIT64
Unsafe.As<byte, long>(ref b) = 0;
Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
#else
Unsafe.As<byte, int>(ref b) = 0;
Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0;
Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0;
#endif
Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 16)) = 0;
Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 20)) = 0;
return;
}
// P/Invoke into the native version for large lengths
if (byteLength >= 512) goto PInvoke;
nuint i = 0; // byte offset at which we're copying
if ((Unsafe.As<byte, int>(ref b) & 3) != 0)
{
if ((Unsafe.As<byte, int>(ref b) & 1) != 0)
{
Unsafe.AddByteOffset<byte>(ref b, i) = 0;
i += 1;
if ((Unsafe.As<byte, int>(ref b) & 2) != 0)
goto IntAligned;
}
Unsafe.As<byte, short>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0;
i += 2;
}
IntAligned:
// On 64-bit IntPtr.Size == 8, so we want to advance to the next 8-aligned address. If
// (int)b % 8 is 0, 5, 6, or 7, we will already have advanced by 0, 3, 2, or 1
// bytes to the next aligned address (respectively), so do nothing. On the other hand,
// if it is 1, 2, 3, or 4 we will want to copy-and-advance another 4 bytes until
// we're aligned.
// The thing 1, 2, 3, and 4 have in common that the others don't is that if you
// subtract one from them, their 3rd lsb will not be set. Hence, the below check.
if (((Unsafe.As<byte, int>(ref b) - 1) & 4) == 0)
{
Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0;
i += 4;
}
nuint end = byteLength - 16;
byteLength -= i; // lower 4 bits of byteLength represent how many bytes are left *after* the unrolled loop
// We know due to the above switch-case that this loop will always run 1 iteration; max
// bytes we clear before checking is 23 (7 to align the pointers, 16 for 1 iteration) so
// the switch handles lengths 0-22.
Debug.Assert(end >= 7 && i <= end);
// This is separated out into a different variable, so the i + 16 addition can be
// performed at the start of the pipeline and the loop condition does not have
// a dependency on the writes.
nuint counter;
do
{
counter = i + 16;
// This loop looks very costly since there appear to be a bunch of temporary values
// being created with the adds, but the jit (for x86 anyways) will convert each of
// these to use memory addressing operands.
// So the only cost is a bit of code size, which is made up for by the fact that
// we save on writes to b.
#if BIT64
Unsafe.As<byte, long>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0;
Unsafe.As<byte, long>(ref Unsafe.AddByteOffset<byte>(ref b, i + 8)) = 0;
#else
Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0;
Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i + 4)) = 0;
Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i + 8)) = 0;
Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i + 12)) = 0;
#endif
i = counter;
// See notes above for why this wasn't used instead
// i += 16;
}
while (counter <= end);
if ((byteLength & 8) != 0)
{
#if BIT64
Unsafe.As<byte, long>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0;
#else
Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0;
Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i + 4)) = 0;
#endif
i += 8;
}
if ((byteLength & 4) != 0)
{
Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0;
i += 4;
}
if ((byteLength & 2) != 0)
{
Unsafe.As<byte, short>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0;
i += 2;
}
if ((byteLength & 1) != 0)
{
Unsafe.AddByteOffset<byte>(ref b, i) = 0;
// We're not using i after this, so not needed
// i += 1;
}
return;
#endif
PInvoke:
RuntimeImports.RhZeroMemory(ref b, byteLength);
}
internal static unsafe void ClearWithReferences(ref IntPtr ip, nuint pointerSizeLength)
{
if (pointerSizeLength == 0)
return;
// TODO: Perhaps do switch casing to improve small size perf
nuint i = 0;
nuint n = 0;
while ((n = i + 8) <= (pointerSizeLength))
{
Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 0) * (nuint)sizeof(IntPtr)) = default(IntPtr);
Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 1) * (nuint)sizeof(IntPtr)) = default(IntPtr);
Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 2) * (nuint)sizeof(IntPtr)) = default(IntPtr);
Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 3) * (nuint)sizeof(IntPtr)) = default(IntPtr);
Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 4) * (nuint)sizeof(IntPtr)) = default(IntPtr);
Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 5) * (nuint)sizeof(IntPtr)) = default(IntPtr);
Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 6) * (nuint)sizeof(IntPtr)) = default(IntPtr);
Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 7) * (nuint)sizeof(IntPtr)) = default(IntPtr);
i = n;
}
if ((n = i + 4) <= (pointerSizeLength))
{
Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 0) * (nuint)sizeof(IntPtr)) = default(IntPtr);
Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 1) * (nuint)sizeof(IntPtr)) = default(IntPtr);
Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 2) * (nuint)sizeof(IntPtr)) = default(IntPtr);
Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 3) * (nuint)sizeof(IntPtr)) = default(IntPtr);
i = n;
}
if ((n = i + 2) <= (pointerSizeLength))
{
Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 0) * (nuint)sizeof(IntPtr)) = default(IntPtr);
Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 1) * (nuint)sizeof(IntPtr)) = default(IntPtr);
i = n;
}
if ((i + 1) <= (pointerSizeLength))
{
Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 0) * (nuint)sizeof(IntPtr)) = default(IntPtr);
}
}
}
}
| |
#region License
// Copyright (c) 2018, FluentMigrator Project
//
// 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.Data;
using System.Linq;
using System.Text.RegularExpressions;
using FluentMigrator.Expressions;
using FluentMigrator.Runner.Generators;
using FluentMigrator.Runner.Generators.Oracle;
using FluentMigrator.Runner.Helpers;
using FluentMigrator.Runner.Initialization;
using JetBrains.Annotations;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace FluentMigrator.Runner.Processors.Oracle
{
public class OracleProcessorBase : GenericProcessorBase
{
[Obsolete]
protected OracleProcessorBase(
[NotNull] string databaseType,
IDbConnection connection,
IMigrationGenerator generator,
IAnnouncer announcer,
IMigrationProcessorOptions options,
IDbFactory factory)
: base(connection, factory, generator, announcer, options)
{
DatabaseType = databaseType;
}
protected OracleProcessorBase(
[NotNull] string databaseType,
[NotNull] OracleBaseDbFactory factory,
[NotNull] IMigrationGenerator generator,
[NotNull] ILogger logger,
[NotNull] IOptionsSnapshot<ProcessorOptions> options,
[NotNull] IConnectionStringAccessor connectionStringAccessor)
: base(() => factory.Factory, generator, logger, options.Value, connectionStringAccessor)
{
DatabaseType = databaseType;
}
public override string DatabaseType { get; }
public override IList<string> DatabaseTypeAliases { get; } = new List<string>() { "Oracle" };
public IQuoter Quoter => ((OracleGenerator) Generator).Quoter;
public override bool SchemaExists(string schemaName)
{
if (schemaName == null)
{
throw new ArgumentNullException(nameof(schemaName));
}
if (schemaName.Length == 0)
{
return false;
}
return Exists("SELECT 1 FROM ALL_USERS WHERE USERNAME = '{0}'", schemaName.ToUpper());
}
public override bool TableExists(string schemaName, string tableName)
{
if (tableName == null)
{
throw new ArgumentNullException(nameof(tableName));
}
if (tableName.Length == 0)
{
return false;
}
if (string.IsNullOrEmpty(schemaName))
{
return Exists("SELECT 1 FROM USER_TABLES WHERE upper(TABLE_NAME) = '{0}'",
FormatHelper.FormatSqlEscape(tableName.ToUpper()));
}
return Exists("SELECT 1 FROM ALL_TABLES WHERE upper(OWNER) = '{0}' AND upper(TABLE_NAME) = '{1}'",
schemaName.ToUpper(), FormatHelper.FormatSqlEscape(tableName.ToUpper()));
}
public override bool ColumnExists(string schemaName, string tableName, string columnName)
{
if (tableName == null)
{
throw new ArgumentNullException(nameof(tableName));
}
if (columnName == null)
{
throw new ArgumentNullException(nameof(columnName));
}
if (columnName.Length == 0 || tableName.Length == 0)
{
return false;
}
if (string.IsNullOrEmpty(schemaName))
{
return Exists(
"SELECT 1 FROM USER_TAB_COLUMNS WHERE upper(TABLE_NAME) = '{0}' AND upper(COLUMN_NAME) = '{1}'",
FormatHelper.FormatSqlEscape(tableName.ToUpper()),
FormatHelper.FormatSqlEscape(columnName.ToUpper()));
}
return Exists(
"SELECT 1 FROM ALL_TAB_COLUMNS WHERE upper(OWNER) = '{0}' AND upper(TABLE_NAME) = '{1}' AND upper(COLUMN_NAME) = '{2}'",
schemaName.ToUpper(), FormatHelper.FormatSqlEscape(tableName.ToUpper()),
FormatHelper.FormatSqlEscape(columnName.ToUpper()));
}
public override bool ConstraintExists(string schemaName, string tableName, string constraintName)
{
if (tableName == null)
{
throw new ArgumentNullException(nameof(tableName));
}
if (constraintName == null)
{
throw new ArgumentNullException(nameof(constraintName));
}
//In Oracle DB constraint name is unique within the schema, so the table name is not used in the query
if (constraintName.Length == 0)
{
return false;
}
if (string.IsNullOrEmpty(schemaName))
{
return Exists("SELECT 1 FROM USER_CONSTRAINTS WHERE upper(CONSTRAINT_NAME) = '{0}'",
FormatHelper.FormatSqlEscape(constraintName.ToUpper()));
}
return Exists("SELECT 1 FROM ALL_CONSTRAINTS WHERE upper(OWNER) = '{0}' AND upper(CONSTRAINT_NAME) = '{1}'",
schemaName.ToUpper(),
FormatHelper.FormatSqlEscape(constraintName.ToUpper()));
}
public override bool IndexExists(string schemaName, string tableName, string indexName)
{
if (tableName == null)
{
throw new ArgumentNullException(nameof(tableName));
}
if (indexName == null)
{
throw new ArgumentNullException(nameof(indexName));
}
//In Oracle DB index name is unique within the schema, so the table name is not used in the query
if (indexName.Length == 0)
{
return false;
}
if (string.IsNullOrEmpty(schemaName))
{
return Exists("SELECT 1 FROM USER_INDEXES WHERE upper(INDEX_NAME) = '{0}'",
FormatHelper.FormatSqlEscape(indexName.ToUpper()));
}
return Exists("SELECT 1 FROM ALL_INDEXES WHERE upper(OWNER) = '{0}' AND upper(INDEX_NAME) = '{1}'",
schemaName.ToUpper(), FormatHelper.FormatSqlEscape(indexName.ToUpper()));
}
public override bool SequenceExists(string schemaName, string sequenceName)
{
return false;
}
public override bool DefaultValueExists(string schemaName, string tableName, string columnName,
object defaultValue)
{
return false;
}
public override void Execute(string template, params object[] args)
{
Process(string.Format(template, args));
}
public override bool Exists(string template, params object[] args)
{
if (template == null)
{
throw new ArgumentNullException(nameof(template));
}
EnsureConnectionIsOpen();
Logger.LogSql(string.Format(template, args));
using (var command = CreateCommand(string.Format(template, args)))
using (var reader = command.ExecuteReader())
{
return reader.Read();
}
}
public override DataSet ReadTableData(string schemaName, string tableName)
{
if (tableName == null)
{
throw new ArgumentNullException(nameof(tableName));
}
if (string.IsNullOrEmpty(schemaName))
{
return Read("SELECT * FROM {0}", Quoter.QuoteTableName(tableName));
}
return Read("SELECT * FROM {0}.{1}", Quoter.QuoteSchemaName(schemaName), Quoter.QuoteTableName(tableName));
}
public override DataSet Read(string template, params object[] args)
{
if (template == null)
{
throw new ArgumentNullException(nameof(template));
}
EnsureConnectionIsOpen();
using (var command = CreateCommand(string.Format(template, args)))
using (var reader = command.ExecuteReader())
{
return reader.ReadDataSet();
}
}
public override void Process(PerformDBOperationExpression expression)
{
Logger.LogSay("Performing DB Operation");
if (Options.PreviewOnly)
{
return;
}
EnsureConnectionIsOpen();
expression.Operation?.Invoke(Connection, Transaction);
}
protected override void Process(string sql)
{
Logger.LogSql(sql);
if (Options.PreviewOnly || string.IsNullOrEmpty(sql))
{
return;
}
EnsureConnectionIsOpen();
var batches = Regex.Split(sql, @"^\s*;\s*$", RegexOptions.Multiline)
.Select(x => x.Trim())
.Where(x => !string.IsNullOrEmpty(x));
foreach (var batch in batches)
{
using (var command = CreateCommand(batch))
{
command.ExecuteNonQuery();
}
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using OpenSim.Framework;
using OpenSim.Data.MySQL;
using OpenMetaverse;
using MySql.Data.MySqlClient;
namespace OpenSim.Data.MySQL
{
public class MySQLGroupsData : IGroupsData
{
private MySqlGroupsGroupsHandler m_Groups;
private MySqlGroupsMembershipHandler m_Membership;
private MySqlGroupsRolesHandler m_Roles;
private MySqlGroupsRoleMembershipHandler m_RoleMembership;
private MySqlGroupsInvitesHandler m_Invites;
private MySqlGroupsNoticesHandler m_Notices;
private MySqlGroupsPrincipalsHandler m_Principals;
public MySQLGroupsData(string connectionString, string realm)
{
m_Groups = new MySqlGroupsGroupsHandler(connectionString, realm + "_groups", realm + "_Store");
m_Membership = new MySqlGroupsMembershipHandler(connectionString, realm + "_membership");
m_Roles = new MySqlGroupsRolesHandler(connectionString, realm + "_roles");
m_RoleMembership = new MySqlGroupsRoleMembershipHandler(connectionString, realm + "_rolemembership");
m_Invites = new MySqlGroupsInvitesHandler(connectionString, realm + "_invites");
m_Notices = new MySqlGroupsNoticesHandler(connectionString, realm + "_notices");
m_Principals = new MySqlGroupsPrincipalsHandler(connectionString, realm + "_principals");
}
#region groups table
public bool StoreGroup(GroupData data)
{
return m_Groups.Store(data);
}
public GroupData RetrieveGroup(UUID groupID)
{
GroupData[] groups = m_Groups.Get("GroupID", groupID.ToString());
if (groups.Length > 0)
return groups[0];
return null;
}
public GroupData RetrieveGroup(string name)
{
GroupData[] groups = m_Groups.Get("Name", name);
if (groups.Length > 0)
return groups[0];
return null;
}
public GroupData[] RetrieveGroups(string pattern)
{
if (string.IsNullOrEmpty(pattern))
pattern = "1";
else
pattern = string.Format("Name LIKE '%{0}%'", MySqlHelper.EscapeString(pattern));
return m_Groups.Get(string.Format("ShowInList=1 AND ({0}) ORDER BY Name LIMIT 100", pattern));
}
public bool DeleteGroup(UUID groupID)
{
return m_Groups.Delete("GroupID", groupID.ToString());
}
public int GroupsCount()
{
return (int)m_Groups.GetCount("Location=\"\"");
}
#endregion
#region membership table
public MembershipData[] RetrieveMembers(UUID groupID)
{
return m_Membership.Get("GroupID", groupID.ToString());
}
public MembershipData RetrieveMember(UUID groupID, string pricipalID)
{
MembershipData[] m = m_Membership.Get(new string[] { "GroupID", "PrincipalID" },
new string[] { groupID.ToString(), pricipalID });
if (m != null && m.Length > 0)
return m[0];
return null;
}
public MembershipData[] RetrieveMemberships(string pricipalID)
{
return m_Membership.Get("PrincipalID", pricipalID.ToString());
}
public bool StoreMember(MembershipData data)
{
return m_Membership.Store(data);
}
public bool DeleteMember(UUID groupID, string pricipalID)
{
return m_Membership.Delete(new string[] { "GroupID", "PrincipalID" },
new string[] { groupID.ToString(), pricipalID });
}
public int MemberCount(UUID groupID)
{
return (int)m_Membership.GetCount("GroupID", groupID.ToString());
}
#endregion
#region roles table
public bool StoreRole(RoleData data)
{
return m_Roles.Store(data);
}
public RoleData RetrieveRole(UUID groupID, UUID roleID)
{
RoleData[] data = m_Roles.Get(new string[] { "GroupID", "RoleID" },
new string[] { groupID.ToString(), roleID.ToString() });
if (data != null && data.Length > 0)
return data[0];
return null;
}
public RoleData[] RetrieveRoles(UUID groupID)
{
//return m_Roles.RetrieveRoles(groupID);
return m_Roles.Get("GroupID", groupID.ToString());
}
public bool DeleteRole(UUID groupID, UUID roleID)
{
return m_Roles.Delete(new string[] { "GroupID", "RoleID" },
new string[] { groupID.ToString(), roleID.ToString() });
}
public int RoleCount(UUID groupID)
{
return (int)m_Roles.GetCount("GroupID", groupID.ToString());
}
#endregion
#region rolememberhip table
public RoleMembershipData[] RetrieveRolesMembers(UUID groupID)
{
RoleMembershipData[] data = m_RoleMembership.Get("GroupID", groupID.ToString());
return data;
}
public RoleMembershipData[] RetrieveRoleMembers(UUID groupID, UUID roleID)
{
RoleMembershipData[] data = m_RoleMembership.Get(new string[] { "GroupID", "RoleID" },
new string[] { groupID.ToString(), roleID.ToString() });
return data;
}
public RoleMembershipData[] RetrieveMemberRoles(UUID groupID, string principalID)
{
RoleMembershipData[] data = m_RoleMembership.Get(new string[] { "GroupID", "PrincipalID" },
new string[] { groupID.ToString(), principalID.ToString() });
return data;
}
public RoleMembershipData RetrieveRoleMember(UUID groupID, UUID roleID, string principalID)
{
RoleMembershipData[] data = m_RoleMembership.Get(new string[] { "GroupID", "RoleID", "PrincipalID" },
new string[] { groupID.ToString(), roleID.ToString(), principalID.ToString() });
if (data != null && data.Length > 0)
return data[0];
return null;
}
public int RoleMemberCount(UUID groupID, UUID roleID)
{
return (int)m_RoleMembership.GetCount(new string[] { "GroupID", "RoleID" },
new string[] { groupID.ToString(), roleID.ToString() });
}
public bool StoreRoleMember(RoleMembershipData data)
{
return m_RoleMembership.Store(data);
}
public bool DeleteRoleMember(RoleMembershipData data)
{
return m_RoleMembership.Delete(new string[] { "GroupID", "RoleID", "PrincipalID"},
new string[] { data.GroupID.ToString(), data.RoleID.ToString(), data.PrincipalID });
}
public bool DeleteMemberAllRoles(UUID groupID, string principalID)
{
return m_RoleMembership.Delete(new string[] { "GroupID", "PrincipalID" },
new string[] { groupID.ToString(), principalID });
}
#endregion
#region principals table
public bool StorePrincipal(PrincipalData data)
{
return m_Principals.Store(data);
}
public PrincipalData RetrievePrincipal(string principalID)
{
PrincipalData[] p = m_Principals.Get("PrincipalID", principalID);
if (p != null && p.Length > 0)
return p[0];
return null;
}
public bool DeletePrincipal(string principalID)
{
return m_Principals.Delete("PrincipalID", principalID);
}
#endregion
#region invites table
public bool StoreInvitation(InvitationData data)
{
return m_Invites.Store(data);
}
public InvitationData RetrieveInvitation(UUID inviteID)
{
InvitationData[] invites = m_Invites.Get("InviteID", inviteID.ToString());
if (invites != null && invites.Length > 0)
return invites[0];
return null;
}
public InvitationData RetrieveInvitation(UUID groupID, string principalID)
{
InvitationData[] invites = m_Invites.Get(new string[] { "GroupID", "PrincipalID" },
new string[] { groupID.ToString(), principalID });
if (invites != null && invites.Length > 0)
return invites[0];
return null;
}
public bool DeleteInvite(UUID inviteID)
{
return m_Invites.Delete("InviteID", inviteID.ToString());
}
public void DeleteOldInvites()
{
m_Invites.DeleteOld();
}
#endregion
#region notices table
public bool StoreNotice(NoticeData data)
{
return m_Notices.Store(data);
}
public NoticeData RetrieveNotice(UUID noticeID)
{
NoticeData[] notices = m_Notices.Get("NoticeID", noticeID.ToString());
if (notices != null && notices.Length > 0)
return notices[0];
return null;
}
public NoticeData[] RetrieveNotices(UUID groupID)
{
NoticeData[] notices = m_Notices.Get("GroupID", groupID.ToString());
return notices;
}
public bool DeleteNotice(UUID noticeID)
{
return m_Notices.Delete("NoticeID", noticeID.ToString());
}
public void DeleteOldNotices()
{
m_Notices.DeleteOld();
}
#endregion
#region combinations
public MembershipData RetrievePrincipalGroupMembership(string principalID, UUID groupID)
{
// TODO
return null;
}
public MembershipData[] RetrievePrincipalGroupMemberships(string principalID)
{
// TODO
return null;
}
#endregion
}
public class MySqlGroupsGroupsHandler : MySQLGenericTableHandler<GroupData>
{
protected override Assembly Assembly
{
// WARNING! Moving migrations to this assembly!!!
get { return GetType().Assembly; }
}
public MySqlGroupsGroupsHandler(string connectionString, string realm, string store)
: base(connectionString, realm, store)
{
}
}
public class MySqlGroupsMembershipHandler : MySQLGenericTableHandler<MembershipData>
{
protected override Assembly Assembly
{
// WARNING! Moving migrations to this assembly!!!
get { return GetType().Assembly; }
}
public MySqlGroupsMembershipHandler(string connectionString, string realm)
: base(connectionString, realm, string.Empty)
{
}
}
public class MySqlGroupsRolesHandler : MySQLGenericTableHandler<RoleData>
{
protected override Assembly Assembly
{
// WARNING! Moving migrations to this assembly!!!
get { return GetType().Assembly; }
}
public MySqlGroupsRolesHandler(string connectionString, string realm)
: base(connectionString, realm, string.Empty)
{
}
}
public class MySqlGroupsRoleMembershipHandler : MySQLGenericTableHandler<RoleMembershipData>
{
protected override Assembly Assembly
{
// WARNING! Moving migrations to this assembly!!!
get { return GetType().Assembly; }
}
public MySqlGroupsRoleMembershipHandler(string connectionString, string realm)
: base(connectionString, realm, string.Empty)
{
}
}
public class MySqlGroupsInvitesHandler : MySQLGenericTableHandler<InvitationData>
{
protected override Assembly Assembly
{
// WARNING! Moving migrations to this assembly!!!
get { return GetType().Assembly; }
}
public MySqlGroupsInvitesHandler(string connectionString, string realm)
: base(connectionString, realm, string.Empty)
{
}
public void DeleteOld()
{
uint now = (uint)Util.UnixTimeSinceEpoch();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.CommandText = String.Format("delete from {0} where TMStamp < ?tstamp", m_Realm);
cmd.Parameters.AddWithValue("?tstamp", now - 14 * 24 * 60 * 60); // > 2 weeks old
ExecuteNonQuery(cmd);
}
}
}
public class MySqlGroupsNoticesHandler : MySQLGenericTableHandler<NoticeData>
{
protected override Assembly Assembly
{
// WARNING! Moving migrations to this assembly!!!
get { return GetType().Assembly; }
}
public MySqlGroupsNoticesHandler(string connectionString, string realm)
: base(connectionString, realm, string.Empty)
{
}
public void DeleteOld()
{
uint now = (uint)Util.UnixTimeSinceEpoch();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.CommandText = String.Format("delete from {0} where TMStamp < ?tstamp", m_Realm);
cmd.Parameters.AddWithValue("?tstamp", now - 14 * 24 * 60 * 60); // > 2 weeks old
ExecuteNonQuery(cmd);
}
}
}
public class MySqlGroupsPrincipalsHandler : MySQLGenericTableHandler<PrincipalData>
{
protected override Assembly Assembly
{
// WARNING! Moving migrations to this assembly!!!
get { return GetType().Assembly; }
}
public MySqlGroupsPrincipalsHandler(string connectionString, string realm)
: base(connectionString, realm, string.Empty)
{
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Parse.Infrastructure;
using Parse.Abstractions.Infrastructure;
using Parse.Infrastructure.Utilities;
using Parse.Platform.Objects;
using Parse.Platform.Users;
namespace Parse.Tests
{
[TestClass]
public class CurrentUserControllerTests
{
ParseClient Client { get; } = new ParseClient(new ServerConnectionData { Test = true });
[TestInitialize]
public void SetUp() => Client.AddValidClass<ParseUser>();
[TestCleanup]
public void TearDown() => (Client.Services as ServiceHub).Reset();
[TestMethod]
public void TestConstructor() => Assert.IsNull(new ParseCurrentUserController(new Mock<ICacheController> { }.Object, Client.ClassController, Client.Decoder).CurrentUser);
[TestMethod]
[AsyncStateMachine(typeof(CurrentUserControllerTests))]
public Task TestGetSetAsync()
{
#warning This method may need a fully custom ParseClient setup.
Mock<ICacheController> storageController = new Mock<ICacheController>(MockBehavior.Strict);
Mock<IDataCache<string, object>> mockedStorage = new Mock<IDataCache<string, object>>();
ParseCurrentUserController controller = new ParseCurrentUserController(storageController.Object, Client.ClassController, Client.Decoder);
ParseUser user = new ParseUser { }.Bind(Client) as ParseUser;
storageController.Setup(storage => storage.LoadAsync()).Returns(Task.FromResult(mockedStorage.Object));
return controller.SetAsync(user, CancellationToken.None).OnSuccess(_ =>
{
Assert.AreEqual(user, controller.CurrentUser);
object jsonObject = null;
#pragma warning disable IDE0039 // Use local function
Predicate<object> predicate = o =>
{
jsonObject = o;
return true;
};
#pragma warning restore IDE0039 // Use local function
mockedStorage.Verify(storage => storage.AddAsync("CurrentUser", Match.Create(predicate)));
mockedStorage.Setup(storage => storage.TryGetValue("CurrentUser", out jsonObject)).Returns(true);
return controller.GetAsync(Client, CancellationToken.None);
}).Unwrap().OnSuccess(task =>
{
Assert.AreEqual(user, controller.CurrentUser);
controller.ClearFromMemory();
Assert.AreNotEqual(user, controller.CurrentUser);
return controller.GetAsync(Client, CancellationToken.None);
}).Unwrap().OnSuccess(task =>
{
Assert.AreNotSame(user, controller.CurrentUser);
Assert.IsNotNull(controller.CurrentUser);
});
}
[TestMethod]
[AsyncStateMachine(typeof(CurrentUserControllerTests))]
public Task TestExistsAsync()
{
Mock<ICacheController> storageController = new Mock<ICacheController>();
Mock<IDataCache<string, object>> mockedStorage = new Mock<IDataCache<string, object>>();
ParseCurrentUserController controller = new ParseCurrentUserController(storageController.Object, Client.ClassController, Client.Decoder);
ParseUser user = new ParseUser { }.Bind(Client) as ParseUser;
storageController.Setup(c => c.LoadAsync()).Returns(Task.FromResult(mockedStorage.Object));
bool contains = false;
mockedStorage.Setup(storage => storage.AddAsync("CurrentUser", It.IsAny<object>())).Callback(() => contains = true).Returns(Task.FromResult<object>(null)).Verifiable();
mockedStorage.Setup(storage => storage.RemoveAsync("CurrentUser")).Callback(() => contains = false).Returns(Task.FromResult<object>(null)).Verifiable();
mockedStorage.Setup(storage => storage.ContainsKey("CurrentUser")).Returns(() => contains);
return controller.SetAsync(user, CancellationToken.None).OnSuccess(_ =>
{
Assert.AreEqual(user, controller.CurrentUser);
return controller.ExistsAsync(CancellationToken.None);
}).Unwrap().OnSuccess(task =>
{
Assert.IsTrue(task.Result);
controller.ClearFromMemory();
return controller.ExistsAsync(CancellationToken.None);
}).Unwrap().OnSuccess(task =>
{
Assert.IsTrue(task.Result);
controller.ClearFromDisk();
return controller.ExistsAsync(CancellationToken.None);
}).Unwrap().OnSuccess(task =>
{
Assert.IsFalse(task.Result);
mockedStorage.Verify();
});
}
[TestMethod]
[AsyncStateMachine(typeof(CurrentUserControllerTests))]
public Task TestIsCurrent()
{
Mock<ICacheController> storageController = new Mock<ICacheController>(MockBehavior.Strict);
ParseCurrentUserController controller = new ParseCurrentUserController(storageController.Object, Client.ClassController, Client.Decoder);
ParseUser user = new ParseUser { }.Bind(Client) as ParseUser;
ParseUser user2 = new ParseUser { }.Bind(Client) as ParseUser;
storageController.Setup(storage => storage.LoadAsync()).Returns(Task.FromResult(new Mock<IDataCache<string, object>>().Object));
return controller.SetAsync(user, CancellationToken.None).OnSuccess(task =>
{
Assert.IsTrue(controller.IsCurrent(user));
Assert.IsFalse(controller.IsCurrent(user2));
controller.ClearFromMemory();
Assert.IsFalse(controller.IsCurrent(user));
return controller.SetAsync(user, CancellationToken.None);
}).Unwrap().OnSuccess(task =>
{
Assert.IsTrue(controller.IsCurrent(user));
Assert.IsFalse(controller.IsCurrent(user2));
controller.ClearFromDisk();
Assert.IsFalse(controller.IsCurrent(user));
return controller.SetAsync(user2, CancellationToken.None);
}).Unwrap().OnSuccess(task =>
{
Assert.IsFalse(controller.IsCurrent(user));
Assert.IsTrue(controller.IsCurrent(user2));
});
}
[TestMethod]
[AsyncStateMachine(typeof(CurrentUserControllerTests))]
public Task TestCurrentSessionToken()
{
Mock<ICacheController> storageController = new Mock<ICacheController>();
Mock<IDataCache<string, object>> mockedStorage = new Mock<IDataCache<string, object>>();
ParseCurrentUserController controller = new ParseCurrentUserController(storageController.Object, Client.ClassController, Client.Decoder);
storageController.Setup(c => c.LoadAsync()).Returns(Task.FromResult(mockedStorage.Object));
return controller.GetCurrentSessionTokenAsync(Client, CancellationToken.None).OnSuccess(task =>
{
Assert.IsNull(task.Result);
// We should probably mock this.
ParseUser user = Client.CreateObjectWithoutData<ParseUser>(default);
user.HandleFetchResult(new MutableObjectState { ServerData = new Dictionary<string, object> { ["sessionToken"] = "randomString" } });
return controller.SetAsync(user, CancellationToken.None);
}).Unwrap().OnSuccess(_ => controller.GetCurrentSessionTokenAsync(Client, CancellationToken.None)).Unwrap().OnSuccess(task => Assert.AreEqual("randomString", task.Result));
}
public Task TestLogOut()
{
ParseCurrentUserController controller = new ParseCurrentUserController(new Mock<ICacheController>(MockBehavior.Strict).Object, Client.ClassController, Client.Decoder);
ParseUser user = new ParseUser { }.Bind(Client) as ParseUser;
return controller.SetAsync(user, CancellationToken.None).OnSuccess(_ =>
{
Assert.AreEqual(user, controller.CurrentUser);
return controller.ExistsAsync(CancellationToken.None);
}).Unwrap().OnSuccess(task =>
{
Assert.IsTrue(task.Result);
return controller.LogOutAsync(Client, CancellationToken.None);
}).Unwrap().OnSuccess(_ => controller.GetAsync(Client, CancellationToken.None)).Unwrap().OnSuccess(task =>
{
Assert.IsNull(task.Result);
return controller.ExistsAsync(CancellationToken.None);
}).Unwrap().OnSuccess(t => Assert.IsFalse(t.Result));
}
}
}
| |
using System;
using KabMan.Data;
using System.Data;
using System.Windows.Forms;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraEditors;
namespace KabMan.Forms
{
public partial class RackDetailManagerForm : DevExpress.XtraEditors.XtraForm
{
#region Properties
private object _RackID = null;
/// <summary>
/// Gets Rack ID which associated to this form
/// </summary>
public long RackID
{
get
{
if (_RackID != null)
{
return Convert.ToInt64(this._RackID);
}
return 0;
}
}
private object _SanGroupId;
public long SanGroupId
{
get
{
if (_SanGroupId != null)
{
return Convert.ToInt64(this._SanGroupId);
}
return 0;
}
}
#endregion
#region Constructor
public RackDetailManagerForm()
{
this.Icon = Resources.GetIcon("KabManIcon");
InitializeComponent();
}
public RackDetailManagerForm(object argRackID, Int64 sanGroupId)
{
this.Icon = Resources.GetIcon("KabManIcon");
this._RackID = argRackID;
this._SanGroupId = sanGroupId;
InitializeComponent();
}
public RackDetailManagerForm(object argRackID, string text, Int64 sanGroupId)
{
this._SanGroupId = sanGroupId;
this._RackID = argRackID;
InitializeComponent();
this.Text = text;
}
private void RackDetailManagerForm_Load(object sender, EventArgs e)
{
if (this.RackID > 0)
{
DataSet ds = DBAssistant.ExecProcedure(sproc.ServerDetail_Select_BySanGroupId, new object[] { "@ServerID", this.RackID, "@SanGroupId", this.SanGroupId });
CSan1Grid.DataSource = ds.Tables[0];
CSan2Grid.DataSource = ds.Tables[1];
setVTPortRepositoryDataSource();
setBlechRepositoryDataSource();
setLcUrmRepositoryDataSource();
}
}
#endregion
private void setVTPortRepositoryDataSource()
{
DataSet ds = DBAssistant.ExecProcedure(sproc.VTPort_For_Rack_BySanGroupId, new object[]{"@SanGroupId", SanGroupId});
repVtPortSan1.DataSource = ds.Tables[0];
repVtPortSan2.DataSource = ds.Tables[1];
}
private void setBlechRepositoryDataSource()
{
DataSet ds = DBAssistant.ExecProcedure(sproc.Blech_For_Rack, new object[] {});
repBlechSan1.DataSource = ds.Tables[0];
repBlechSan2.DataSource = ds.Tables[0];
}
private void setLcUrmRepositoryDataSource()
{
DataSet ds = DBAssistant.ExecProcedure(sproc.Cable_Select_Available_LcUrm_For_Rack_BySanGroupId, new object[] { "@RackID", this.RackID, "@SanGroupId", this.SanGroupId });
repLcUrmSan1.DataSource = ds.Tables[0];
repLcUrmSan2.DataSource = ds.Tables[1];
}
private void CSan2View_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
{
if (e.Column == gridColumn9)
{
DBAssistant.ExecProcedure(sproc.ServerDetail_Update_LcUrm, new object[] { "@LcUrmID", e.Value, "@ID", CSan2View.GetRowCellValue(e.RowHandle, "ID") });
repLcUrmSan2.DataSource = DBAssistant.ExecProcedure(sproc.Cable_Select_Available_LcUrm_For_Rack, new object[] { "@RackID", this.RackID, "@SanValue", 2 }).Tables[0].DefaultView;
}
else if (e.Column == gridColumn12)
{
string typeName = "VTPort";
object serverDetailId = CSan2View.GetRowCellValue(e.RowHandle, "ID");
object newVtPortId = e.Value;
DBAssistant.ExecProcedure(sproc.ServerDetail_Blech_VTPort_Update, new object[] { "@ServerDetailID", serverDetailId, "@TypeName", typeName, "@NewObjectId", newVtPortId });
setVTPortRepositoryDataSource();
}
else if (e.Column == gridColumn10)
{
string typeName = "Blech";
object serverDetailId = CSan2View.GetRowCellValue(e.RowHandle, "ID");
object newBlechId = e.Value;
DBAssistant.ExecProcedure(sproc.ServerDetail_Blech_VTPort_Update, new object[] { "@ServerDetailID", serverDetailId, "@TypeName", typeName, "@NewObjectId", newBlechId });
setBlechRepositoryDataSource();
}
}
private void CSan1View_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
{
if (e.Column == gridColumn2)
{
DBAssistant.ExecProcedure(sproc.ServerDetail_Update_LcUrm, new object[] { "@LcUrmID", e.Value, "@ID", CSan1View.GetRowCellValue(e.RowHandle, "ID") });
setLcUrmRepositoryDataSource();
}
else if (e.Column == gridColumn4)
{
string typeName = "VTPort";
object serverDetailId = CSan1View.GetRowCellValue(e.RowHandle, "ID");
object newVtPortId = e.Value;
DBAssistant.ExecProcedure(sproc.ServerDetail_Blech_VTPort_Update, new object[] { "@ServerDetailID", serverDetailId, "@TypeName", typeName, "@NewObjectId", newVtPortId });
setVTPortRepositoryDataSource();
}
else if (e.Column == gridColumn7)
{
string typeName = "Blech";
object serverDetailId = CSan1View.GetRowCellValue(e.RowHandle, "ID");
object newBlechId = e.Value;
DBAssistant.ExecProcedure(sproc.ServerDetail_Blech_VTPort_Update, new object[] { "@ServerDetailID", serverDetailId, "@TypeName", typeName, "@NewObjectId", newBlechId });
setBlechRepositoryDataSource();
}
}
private void repLcUrmSan1_Popup(object sender, EventArgs e)
{
DataView dv = ((DataTable)repLcUrmSan1.DataSource).DefaultView;
dv.RowFilter = "Connected = 'False'";
}
private void repLcUrmSan1_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
{
DataView dv = ((DataTable)repLcUrmSan1.DataSource).DefaultView;
dv.RowFilter = "";
}
private void repLcUrmSan2_Popup(object sender, EventArgs e)
{
DataView dv = ((DataTable)repLcUrmSan2.DataSource).DefaultView;
dv.RowFilter = "Connected = 'False'";
}
private void repLcUrmSan2_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
{
DataView dv = ((DataTable)repLcUrmSan2.DataSource).DefaultView;
dv.RowFilter = "";
}
private void repVtPortSan1_Popup(object sender, EventArgs e)
{
DataView view = ((DataTable)repVtPortSan1.DataSource).DefaultView;
view.RowFilter = "VTPortId=" + CSan1View.GetFocusedRowCellValue("VTPortId").ToString();
}
private void repVtPortSan1_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
{
DataView view = ((DataTable)repVtPortSan1.DataSource).DefaultView;
view.RowFilter = "";
}
private void repVtPortSan2_Popup(object sender, EventArgs e)
{
DataView view = ((DataTable)repVtPortSan2.DataSource).DefaultView;
view.RowFilter = "VTPortId=" + CSan2View.GetFocusedRowCellValue("VTPortId").ToString();
}
private void repVtPortSan2_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
{
DataView view = ((DataTable)repVtPortSan2.DataSource).DefaultView;
view.RowFilter = "";
}
private void repBlechSan1_Popup(object sender, EventArgs e)
{
DataView view = ((DataTable)repBlechSan1.DataSource).DefaultView;
view.RowFilter = "BlechId=" + CSan1View.GetFocusedRowCellValue("BlechId").ToString();
}
private void repBlechSan1_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
{
DataView view = ((DataTable)repBlechSan1.DataSource).DefaultView;
view.RowFilter = "";
}
private void repBlechSan2_Popup(object sender, EventArgs e)
{
DataView view = ((DataTable)repBlechSan2.DataSource).DefaultView;
view.RowFilter = "BlechId=" + CSan2View.GetFocusedRowCellValue("BlechId").ToString();
}
private void repBlechSan2_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
{
DataView view = ((DataTable)repBlechSan2.DataSource).DefaultView;
view.RowFilter = "";
}
private void CSan1View_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
{
//if (e.Column == gridColumn2 || e.Column == gridColumn4 || e.Column == gridColumn7)
//{
// if (MessageBox.Show("CSan1View", "Bla Bla", MessageBoxButtons.YesNo) != DialogResult.Yes)
// {
// return;
// }
//}
}
private void CSan1View_ShownEditor(object sender, EventArgs e)
{
GridView gridView = sender as GridView;
if (gridView.FocusedColumn == gridColumn2 || gridView.FocusedColumn == gridColumn4 || gridView.FocusedColumn == gridColumn7)
if (XtraMessageBox.Show("Do you wish to edit this row?", "Confirmation", MessageBoxButtons.YesNo) == DialogResult.No)
gridView.CloseEditor();
else
{
if(gridView.ActiveEditor!=null)
gridView.ActiveEditor.SelectAll();
}
}
private void CSan2View_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
{
//GridView gridView = sender as GridView;
//if (gridView.FocusedColumn == gridColumn9 || gridView.FocusedColumn == gridColumn12 || gridView.FocusedColumn == gridColumn10)
// if (XtraMessageBox.Show("Do you wish to edit this row?", "Confirmation", MessageBoxButtons.YesNo) == DialogResult.No)
// gridView.CloseEditor();
// else
// {
// if (gridView.ActiveEditor != null)
// gridView.ActiveEditor.SelectAll();
// }
}
}
}
| |
using UnityEngine;
using System;
using System.Collections;
namespace FourthSky
{
namespace Android
{
namespace Services
{
public class AndroidCursor : AndroidWrapper {
private string[] columnNames;
private AndroidCursor(AndroidJavaObject cursor)
{
mJavaObject = cursor;
}
protected override void Dispose(bool disposing) {
if (!this.disposed) {
if (disposing) {
if (mJavaObject != null) {
// First, close the cursor
mJavaObject.Call ("close");
// Now, release Java object
mJavaObject.Dispose();
mJavaObject = null;
}
}
}
this.disposed = true;
}
public int RowCount {
get {
return mJavaObject.Call<int>("getCount");
}
}
public string[] ColumnNames {
get {
if (columnNames == null)
{
columnNames = mJavaObject.Call<string[]>("getColumnNames");
}
return columnNames;
}
}
public int ColumnCount {
get {
return mJavaObject.Call<int>("getColumnCount");
}
}
public bool Closed {
get {
return mJavaObject.Call<bool>("isClosed");
}
}
public bool MoveToFirst ()
{
return mJavaObject.Call<bool> ("moveToFirst");
}
public bool MoveToNext ()
{
return mJavaObject.Call<bool> ("moveToNext");
}
public int GetColumnIndex (string columnName)
{
return mJavaObject.Call<int> ("getColumnIndex", columnName);
}
public ReturnType Get<ReturnType>(int columnIndex)
{
ReturnType result = default(ReturnType);
if (typeof(ReturnType).IsPrimitive)
{
if (typeof(ReturnType) == typeof(int))
{
result = mJavaObject.Call<ReturnType>("getInt", columnIndex);
}
else
{
if (typeof(ReturnType) == typeof(short))
{
result = mJavaObject.Call<ReturnType>("getShort", columnIndex);
}
else
{
if (typeof(ReturnType) == typeof(long))
{
result = mJavaObject.Call<ReturnType>("getLong", columnIndex);
}
else
{
if (typeof(ReturnType) == typeof(float))
{
result = mJavaObject.Call<ReturnType>("getFloat", columnIndex);
}
else
{
if (typeof(ReturnType) == typeof(double))
{
result = mJavaObject.Call<ReturnType>("getDouble", columnIndex);
}
else
{
result = default(ReturnType);
}
}
}
}
}
}
else
{
if (typeof(ReturnType) == typeof(string))
{
result = mJavaObject.Call<ReturnType>("getString", columnIndex);
}
else
{
if (typeof(ReturnType) == typeof(byte[]))
{
result = mJavaObject.Call<ReturnType>("getBlob", columnIndex);
}
}
}
return result;
}
public ReturnType Get<ReturnType>(string columnName) {
int idx = GetColumnIndex (columnName);
return Get<ReturnType> (idx);
}
/// <summary>
/// Opens the cursor.
/// </summary>
/// <returns>The cursor.</returns>
/// <param name="contentUri">Content URI.</param>
/// <param name="columns">List of columns for the result</param>
/// <param name="selection">Selection clause (WHERE clause)</param>
/// <param name="selectionArgs">Arguments for selection</param>
/// <param name="sortOrder">Sort order, by column and ASC or DESC</param>
public static AndroidCursor Open(string contentUri, string[] columns = null, string selection = "", string[] selectionArgs = null, string sortOrder = "")
{
// TODO if Uri is null or empty, throw error
if (string.IsNullOrEmpty(contentUri))
{
throw new System.ArgumentException("contentUri cannot be null");
}
// Uri of the file for the gallery
AndroidJavaObject uri = new AndroidJavaClass("android.net.Uri").CallStatic<AndroidJavaObject>("parse", contentUri);
return Open (uri, columns, selection, selectionArgs, sortOrder);
}
public static AndroidCursor Open(AndroidJavaObject contentUri, string[] columns, string selection = "", string[] selectionArgs = null, string sortOrder = "")
{
// TODO if Uri is null or empty, throw error
if (contentUri == null || contentUri.GetRawObject() == IntPtr.Zero)
{
throw new System.ArgumentException("contentUri cannot be null");
}
// Array of column names to get from database (array of java strings)
AndroidJavaObject proj = null;
if (columns != null && columns.Length > 0)
{
proj = AndroidSystem.ConstructJavaObjectFromPtr(AndroidJNI.NewObjectArray(columns.Length,
AndroidJNI.FindClass("java/lang/String"),
AndroidJNI.NewStringUTF("")));
for (int i = 0; i < columns.Length; i++)
AndroidJNI.SetObjectArrayElement(proj.GetRawObject(), i, AndroidJNI.NewStringUTF(columns[i]));
}
// Arguments for selection (array of java strings)
AndroidJavaObject args = null;
if (selectionArgs != null && selectionArgs.Length > 0)
{
args = AndroidSystem.ConstructJavaObjectFromPtr(AndroidJNIHelper.ConvertToJNIArray(selectionArgs));
}
AndroidJavaObject cursor = null;
if (AndroidSystem.Version > AndroidVersions.GINGERBREAD_MR1)
{
// This code is for Android 3.0 (SDK 11) and up
using (AndroidJavaObject loader = new AndroidJavaObject("android.content.CursorLoader",
AndroidSystem.UnityActivity))
{
loader.Call ("setUri", contentUri);
loader.Call ("setProjection", proj);
loader.Call ("setSelection", selection);
loader.Call ("setSelectionArgs", args);
loader.Call ("setSortOrder", sortOrder);
cursor = loader.Call<AndroidJavaObject>("loadInBackground");
}
}
else
{
// These two lines is for any Android version, but is deprecated for Android 3.0 and up
// Need to get method through AndroidJNI
IntPtr managedQueryMethod = AndroidJNIHelper.GetMethodID(AndroidSystem.UnityActivity.GetRawClass(), "query");
IntPtr cursorPtr = AndroidJNI.CallObjectMethod(AndroidSystem.UnityActivity.GetRawObject(),
managedQueryMethod,
AndroidJNIHelper.CreateJNIArgArray(new object[] {contentUri,
proj,
selection,
args,
sortOrder}));
cursor = AndroidSystem.ConstructJavaObjectFromPtr(cursorPtr);
}
return new AndroidCursor(cursor);
}
}
}
}
}
| |
// <file>
// <copyright see="prj:///doc/copyright.txt"/>
// <license see="prj:///doc/license.txt"/>
// <owner name="none" email=""/>
// <version>$Revision: 3662 $</version>
// </file>
using System;
using System.Collections.Generic;
using ICSharpCode.NRefactory.Ast;
namespace ICSharpCode.NRefactory.Visitors
{
public sealed class LocalLookupVariable
{
public readonly string Name;
public readonly TypeReference TypeRef;
public readonly Location StartPos;
public readonly Location EndPos;
public readonly bool IsConst;
public readonly bool IsLoopVariable;
public readonly Expression Initializer;
public readonly LambdaExpression ParentLambdaExpression;
public LocalLookupVariable(string name, TypeReference typeRef, Location startPos, Location endPos, bool isConst, bool isLoopVariable, Expression initializer, LambdaExpression parentLambdaExpression)
{
this.Name = name;
this.TypeRef = typeRef;
this.StartPos = startPos;
this.EndPos = endPos;
this.IsConst = isConst;
this.IsLoopVariable = isLoopVariable;
this.Initializer = initializer;
this.ParentLambdaExpression = parentLambdaExpression;
}
}
/// <summary>
/// Finds all local variable declarations.
/// </summary>
public sealed class LookupTableVisitor : AbstractAstVisitor
{
public bool IncludeParameters { get; set; }
Dictionary<string, List<LocalLookupVariable>> variables;
SupportedLanguage language;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public Dictionary<string, List<LocalLookupVariable>> Variables {
get {
return variables;
}
}
List<WithStatement> withStatements = new List<WithStatement>();
public List<WithStatement> WithStatements {
get {
return withStatements;
}
}
public LookupTableVisitor(SupportedLanguage language)
{
this.language = language;
if (language == SupportedLanguage.VBNet) {
variables = new Dictionary<string, List<LocalLookupVariable>>(StringComparer.InvariantCultureIgnoreCase);
} else {
variables = new Dictionary<string, List<LocalLookupVariable>>(StringComparer.InvariantCulture);
}
}
public void AddVariable(TypeReference typeRef, string name,
Location startPos, Location endPos, bool isConst,
bool isLoopVariable, Expression initializer,
LambdaExpression parentLambdaExpression)
{
if (name == null || name.Length == 0) {
return;
}
List<LocalLookupVariable> list;
if (!variables.ContainsKey(name)) {
variables[name] = list = new List<LocalLookupVariable>();
} else {
list = (List<LocalLookupVariable>)variables[name];
}
list.Add(new LocalLookupVariable(name, typeRef, startPos, endPos, isConst, isLoopVariable, initializer, parentLambdaExpression));
}
public override object VisitWithStatement(WithStatement withStatement, object data)
{
withStatements.Add(withStatement);
return base.VisitWithStatement(withStatement, data);
}
Stack<Location> endLocationStack = new Stack<Location>();
public LookupTableVisitor(SupportedLanguage language, bool includeParameters) : this(language)
{
IncludeParameters = includeParameters;
}
Location CurrentEndLocation {
get {
return (endLocationStack.Count == 0) ? Location.Empty : endLocationStack.Peek();
}
}
public override object VisitBlockStatement(BlockStatement blockStatement, object data)
{
endLocationStack.Push(blockStatement.EndLocation);
base.VisitBlockStatement(blockStatement, data);
endLocationStack.Pop();
return null;
}
public override object VisitLocalVariableDeclaration(LocalVariableDeclaration lvd, object data)
{
for (int i = 0; i < lvd.Variables.Count; ++i) {
VariableDeclaration varDecl = (VariableDeclaration)lvd.Variables[i];
AddVariable(lvd.GetTypeForVariable(i),
varDecl.Name,
lvd.StartLocation,
CurrentEndLocation,
(lvd.Modifier & Modifiers.Const) == Modifiers.Const,
false, varDecl.Initializer, null);
}
return base.VisitLocalVariableDeclaration(lvd, data);
}
public override object VisitAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression, object data)
{
foreach (ParameterDeclarationExpression p in anonymousMethodExpression.Parameters) {
AddVariable(p.TypeReference, p.ParameterName,
anonymousMethodExpression.StartLocation, anonymousMethodExpression.EndLocation,
false, false, null, null);
}
return base.VisitAnonymousMethodExpression(anonymousMethodExpression, data);
}
public override object VisitLambdaExpression(LambdaExpression lambdaExpression, object data)
{
foreach (ParameterDeclarationExpression p in lambdaExpression.Parameters) {
AddVariable(p.TypeReference, p.ParameterName,
lambdaExpression.StartLocation, lambdaExpression.ExtendedEndLocation,
false, false, null, lambdaExpression);
}
return base.VisitLambdaExpression(lambdaExpression, data);
}
public override object VisitQueryExpression(QueryExpression queryExpression, object data)
{
endLocationStack.Push(GetQueryVariableEndScope(queryExpression));
base.VisitQueryExpression(queryExpression, data);
endLocationStack.Pop();
return null;
}
Location GetQueryVariableEndScope(QueryExpression queryExpression)
{
return queryExpression.EndLocation;
}
public override object VisitQueryExpressionFromClause(QueryExpressionFromClause fromClause, object data)
{
AddVariable(fromClause.Type, fromClause.Identifier,
fromClause.StartLocation, CurrentEndLocation,
false, true, fromClause.InExpression, null);
return base.VisitQueryExpressionFromClause(fromClause, data);
}
public override object VisitQueryExpressionJoinClause(QueryExpressionJoinClause joinClause, object data)
{
if (string.IsNullOrEmpty(joinClause.IntoIdentifier)) {
AddVariable(joinClause.Type, joinClause.Identifier,
joinClause.StartLocation, CurrentEndLocation,
false, true, joinClause.InExpression, null);
} else {
AddVariable(joinClause.Type, joinClause.Identifier,
joinClause.StartLocation, joinClause.EndLocation,
false, true, joinClause.InExpression, null);
AddVariable(joinClause.Type, joinClause.IntoIdentifier,
joinClause.StartLocation, CurrentEndLocation,
false, false, joinClause.InExpression, null);
}
return base.VisitQueryExpressionJoinClause(joinClause, data);
}
public override object VisitQueryExpressionLetClause(QueryExpressionLetClause letClause, object data)
{
AddVariable(null, letClause.Identifier,
letClause.StartLocation, CurrentEndLocation,
false, false, letClause.Expression, null);
return base.VisitQueryExpressionLetClause(letClause, data);
}
public override object VisitForNextStatement(ForNextStatement forNextStatement, object data)
{
if (forNextStatement.EmbeddedStatement.EndLocation.IsEmpty) {
return base.VisitForNextStatement(forNextStatement, data);
} else {
endLocationStack.Push(forNextStatement.EmbeddedStatement.EndLocation);
AddVariable(forNextStatement.TypeReference,
forNextStatement.VariableName,
forNextStatement.StartLocation,
forNextStatement.EndLocation,
false, false,
forNextStatement.Start,
null);
base.VisitForNextStatement(forNextStatement, data);
endLocationStack.Pop();
return null;
}
}
public override object VisitFixedStatement(FixedStatement fixedStatement, object data)
{
// uses LocalVariableDeclaration, we just have to put the end location on the stack
if (fixedStatement.EmbeddedStatement.EndLocation.IsEmpty) {
return base.VisitFixedStatement(fixedStatement, data);
} else {
endLocationStack.Push(fixedStatement.EmbeddedStatement.EndLocation);
base.VisitFixedStatement(fixedStatement, data);
endLocationStack.Pop();
return null;
}
}
public override object VisitForStatement(ForStatement forStatement, object data)
{
// uses LocalVariableDeclaration, we just have to put the end location on the stack
if (forStatement.EmbeddedStatement.EndLocation.IsEmpty) {
return base.VisitForStatement(forStatement, data);
} else {
endLocationStack.Push(forStatement.EmbeddedStatement.EndLocation);
base.VisitForStatement(forStatement, data);
endLocationStack.Pop();
return null;
}
}
public override object VisitUsingStatement(UsingStatement usingStatement, object data)
{
// uses LocalVariableDeclaration, we just have to put the end location on the stack
if (usingStatement.EmbeddedStatement.EndLocation.IsEmpty) {
return base.VisitUsingStatement(usingStatement, data);
} else {
endLocationStack.Push(usingStatement.EmbeddedStatement.EndLocation);
base.VisitUsingStatement(usingStatement, data);
endLocationStack.Pop();
return null;
}
}
public override object VisitSwitchSection(SwitchSection switchSection, object data)
{
if (language == SupportedLanguage.VBNet) {
return VisitBlockStatement(switchSection, data);
} else {
return base.VisitSwitchSection(switchSection, data);
}
}
public override object VisitForeachStatement(ForeachStatement foreachStatement, object data)
{
AddVariable(foreachStatement.TypeReference,
foreachStatement.VariableName,
foreachStatement.StartLocation,
foreachStatement.EndLocation,
false, true,
foreachStatement.Expression,
null);
if (foreachStatement.Expression != null) {
foreachStatement.Expression.AcceptVisitor(this, data);
}
if (foreachStatement.EmbeddedStatement == null) {
return data;
}
return foreachStatement.EmbeddedStatement.AcceptVisitor(this, data);
}
public override object VisitTryCatchStatement(TryCatchStatement tryCatchStatement, object data)
{
if (tryCatchStatement == null) {
return data;
}
if (tryCatchStatement.StatementBlock != null) {
tryCatchStatement.StatementBlock.AcceptVisitor(this, data);
}
if (tryCatchStatement.CatchClauses != null) {
foreach (CatchClause catchClause in tryCatchStatement.CatchClauses) {
if (catchClause != null) {
if (catchClause.TypeReference != null && catchClause.VariableName != null) {
AddVariable(catchClause.TypeReference,
catchClause.VariableName,
catchClause.StatementBlock.StartLocation,
catchClause.StatementBlock.EndLocation,
false, false, NullExpression.Instance, null);
}
catchClause.StatementBlock.AcceptVisitor(this, data);
}
}
}
if (tryCatchStatement.FinallyBlock != null) {
return tryCatchStatement.FinallyBlock.AcceptVisitor(this, data);
}
return data;
}
public override object VisitParameterDeclarationExpression(ParameterDeclarationExpression parameterDeclarationExpression, object data)
{
if (IncludeParameters)
{
if (parameterDeclarationExpression == null)
return data;
AddVariable(parameterDeclarationExpression.TypeReference,
parameterDeclarationExpression.ParameterName,
parameterDeclarationExpression.StartLocation,
parameterDeclarationExpression.EndLocation,
false, false, NullExpression.Instance, null);
}
return base.VisitParameterDeclarationExpression(parameterDeclarationExpression, data);
}
}
}
| |
#region license
// Copyright (c) 2009 Rodrigo B. de Oliveira ([email protected])
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
//
// DO NOT EDIT THIS FILE!
//
// This file was generated automatically by astgen.boo.
//
namespace Boo.Lang.Compiler.Ast
{
using System.Collections;
using System.Runtime.Serialization;
[System.Serializable]
public partial class ExceptionHandler : Node
{
protected Declaration _declaration;
protected Expression _filterCondition;
protected ExceptionHandlerFlags _flags;
protected Block _block;
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public ExceptionHandler CloneNode()
{
return (ExceptionHandler)Clone();
}
/// <summary>
/// <see cref="Node.CleanClone"/>
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public ExceptionHandler CleanClone()
{
return (ExceptionHandler)base.CleanClone();
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public NodeType NodeType
{
get { return NodeType.ExceptionHandler; }
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public void Accept(IAstVisitor visitor)
{
visitor.OnExceptionHandler(this);
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Matches(Node node)
{
if (node == null) return false;
if (NodeType != node.NodeType) return false;
var other = ( ExceptionHandler)node;
if (!Node.Matches(_declaration, other._declaration)) return NoMatch("ExceptionHandler._declaration");
if (!Node.Matches(_filterCondition, other._filterCondition)) return NoMatch("ExceptionHandler._filterCondition");
if (_flags != other._flags) return NoMatch("ExceptionHandler._flags");
if (!Node.Matches(_block, other._block)) return NoMatch("ExceptionHandler._block");
return true;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Replace(Node existing, Node newNode)
{
if (base.Replace(existing, newNode))
{
return true;
}
if (_declaration == existing)
{
this.Declaration = (Declaration)newNode;
return true;
}
if (_filterCondition == existing)
{
this.FilterCondition = (Expression)newNode;
return true;
}
if (_block == existing)
{
this.Block = (Block)newNode;
return true;
}
return false;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public object Clone()
{
ExceptionHandler clone = (ExceptionHandler)FormatterServices.GetUninitializedObject(typeof(ExceptionHandler));
clone._lexicalInfo = _lexicalInfo;
clone._endSourceLocation = _endSourceLocation;
clone._documentation = _documentation;
clone._isSynthetic = _isSynthetic;
clone._entity = _entity;
if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone();
if (null != _declaration)
{
clone._declaration = _declaration.Clone() as Declaration;
clone._declaration.InitializeParent(clone);
}
if (null != _filterCondition)
{
clone._filterCondition = _filterCondition.Clone() as Expression;
clone._filterCondition.InitializeParent(clone);
}
clone._flags = _flags;
if (null != _block)
{
clone._block = _block.Clone() as Block;
clone._block.InitializeParent(clone);
}
return clone;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override internal void ClearTypeSystemBindings()
{
_annotations = null;
_entity = null;
if (null != _declaration)
{
_declaration.ClearTypeSystemBindings();
}
if (null != _filterCondition)
{
_filterCondition.ClearTypeSystemBindings();
}
if (null != _block)
{
_block.ClearTypeSystemBindings();
}
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public Declaration Declaration
{
get { return _declaration; }
set
{
if (_declaration != value)
{
_declaration = value;
if (null != _declaration)
{
_declaration.InitializeParent(this);
}
}
}
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public Expression FilterCondition
{
get { return _filterCondition; }
set
{
if (_filterCondition != value)
{
_filterCondition = value;
if (null != _filterCondition)
{
_filterCondition.InitializeParent(this);
}
}
}
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public ExceptionHandlerFlags Flags
{
get { return _flags; }
set { _flags = value; }
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public Block Block
{
get
{
if (_block == null)
{
_block = new Block();
_block.InitializeParent(this);
}
return _block;
}
set
{
if (_block != value)
{
_block = value;
if (null != _block)
{
_block.InitializeParent(this);
}
}
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Threading;
using System.Windows;
using StandUpTimer.Services;
using TestStack.White;
using TestStack.White.Factory;
using TestStack.White.UIItems;
using TestStack.White.UIItems.WindowItems;
namespace StandUpTimer.Specs.PageObjects
{
internal class StandUpTimer : IDisposable
{
private readonly Application application;
private Window window;
private StandUpTimer(Application application)
{
this.application = application;
}
private Window Window
{
get
{
return window ?? (window = application.Find(s => s.Contains("Stand-Up Timer"), InitializeOption.NoCache));
}
}
public static StandUpTimer Launch(string executable = "StandUpTimer.exe", int sittingWaitTime = 1200000, bool deleteCookies = true)
{
if (deleteCookies)
CookieContainerPersistance.DeleteCookiesFromDisk();
var processStartInfo = new ProcessStartInfo(executable,
$"--sit {sittingWaitTime} --stand 3600000 --noUpdate --baseUrl http://localhost:12346/");
return new StandUpTimer(Application.Launch(processStartInfo));
}
private T TryAction<T>(Func<T> action)
{
var tries = 0;
AutomationException lastException = null;
while (tries < 5)
{
try
{
var result = action();
return result;
}
catch (AutomationException e)
{
lastException = e;
window = null;
tries++;
}
}
throw lastException;
}
public void Dispose()
{
application.Dispose();
}
public string Title
{
get { return TryAction(() => Window.Title); }
}
public Image CurrentImage
{
get { return TryAction(() => Window.Get<Image>("CurrentImage")); }
}
public string CurrentImageFileName
{
get
{
var currentImageFileNameLabel = TryAction(() => Window.Get<Label>("CurrentImageFileName"));
return currentImageFileNameLabel?.Text;
}
}
public Button CloseButton
{
get { return TryAction(() => Window.Get<Button>("CloseButton")); }
}
public Button SkipButton
{
get { return TryAction(() => Window.Get<Button>("SkipButton")); }
}
public Button AttributionButton
{
get { return TryAction(() => Window.Get<Button>("AttributionButton")); }
}
public Button LoginButton
{
get { return TryAction(() => Window.Get<Button>("ChangeAuthenticationStateButton")); }
}
public string CurrentAuthenticationStatusFileName
{
get
{
var currentAuthenticationStatusFileNameLabel = TryAction(() => Window.Get<Label>("CurrentAuthenticationStatusFileName"));
return currentAuthenticationStatusFileNameLabel?.Text;
}
}
public Button OkButton
{
get { return TryAction(() => Window.Get<Button>("OkButton")); }
}
public ProgressBar ProgressBar
{
get { return TryAction(() => Window.Get<ProgressBar>("ProgressBar")); }
}
public string ProgressBarText
{
get
{
var progressBarTextLabel = TryAction(() => Window.Get<Label>("ProgressText"));
return progressBarTextLabel?.Text;
}
}
public bool IsFocussed
{
get { return TryAction(() => Window.IsFocussed); }
}
public Point Location => Window.Location;
public string VersionNumber
{
get
{
var versionNumberTextBox = TryAction(() => Window.Get<Label>("VersionNumber"));
return versionNumberTextBox?.Text;
}
}
public void WaitUntilProgressBarTextIs(string text)
{
WaitFor(() => ProgressBarText.Equals("60\nmin"));
}
private static void WaitFor(Func<bool> func)
{
var stopwatch = Stopwatch.StartNew();
while (stopwatch.Elapsed < TimeSpan.FromSeconds(5))
{
if (func())
return;
}
}
public bool TryGoToNextPosition(out string errorMessage)
{
var skipButton = SkipButton;
if (skipButton == null)
{
errorMessage = "cannot find the skip button";
return false;
}
skipButton.Click();
errorMessage = string.Empty;
return true;
}
public bool TryStopShaking(out string errorMessage)
{
var okButton = OkButton;
if (okButton == null)
{
errorMessage = "Cannot find the OK button.";
return false;
}
okButton.Click();
errorMessage = string.Empty;
return true;
}
public void OpenAttributionBox()
{
Window.Mouse.Location = AttributionButton.ClickablePoint;
// wait to show
Thread.Sleep(200);
}
public LoginDialog OpenLoginDialog(out string errorMessage)
{
var loginButton = LoginButton;
if (loginButton == null)
{
errorMessage = "Cannot find the login button.";
return null;
}
loginButton.Click();
errorMessage = string.Empty;
return FindLoginDialog();
}
public LoginDialog FindLoginDialog()
{
Window loginWindow = null;
WaitFor(() => (loginWindow = application.GetWindow("Login", InitializeOption.NoCache)) != null);
return new LoginDialog(loginWindow);
}
public void TakeScreenshot(string fileName)
{
Window.TakeScreenshot(fileName);
}
public void WaitUntilLoggedIn()
{
WaitFor(() => CurrentAuthenticationStatusFileName.Equals("..\\Images\\loggedInButton.png"));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Invio.Xunit;
using Xunit;
namespace Invio.Validation {
[UnitTest]
public class ValidationIssueTests {
[Fact]
public void Warning_NullMessage() {
// Act
var exception = Record.Exception(
() => ValidationIssue.Warning(null)
);
// Assert
Assert.IsType<ArgumentNullException>(exception);
}
[Fact]
public void Warning_WhiteSpaceMessage() {
// Act
var exception = Record.Exception(
() => ValidationIssue.Warning(" \t")
);
// Assert
Assert.IsType<ArgumentException>(exception);
}
[Fact]
public void Warning_WithJustCode() {
// Arrange
var message = "FooBar";
var code = "some-code";
// Act
var warning = ValidationIssue.Warning(message, code);
// Assert
Assert.Equal(message, warning.Message);
Assert.Equal(ValidationIssueLevel.Warning, warning.Level);
Assert.Equal(code, warning.Code);
Assert.Null(warning.MemberNames);
}
[Fact]
public void Warning_WithJustMemberNames() {
// Arrange
var message = "FooBar";
var memberNames = ImmutableHashSet.Create("foo", "bar");
// Act
var warning = ValidationIssue.Warning(message, memberNames);
// Assert
Assert.Equal(message, warning.Message);
Assert.Equal(ValidationIssueLevel.Warning, warning.Level);
Assert.Null(warning.Code);
Assert.Equal(memberNames, warning.MemberNames);
}
[Fact]
public void Warning_Valid() {
// Arrange
var message = "FooBar";
var code = "some-code";
var names = ImmutableHashSet.Create("Foo", "Bar");
// Act
var warning = ValidationIssue.Warning(
message,
code,
names
);
// Assert
Assert.Equal(message, warning.Message);
Assert.Equal(ValidationIssueLevel.Warning, warning.Level);
Assert.Equal(code, warning.Code);
Assert.Equal(names, warning.MemberNames);
}
[Fact]
public void Error_NullMessage() {
// Act
var exception = Record.Exception(
() => ValidationIssue.Error(null)
);
// Assert
Assert.IsType<ArgumentNullException>(exception);
}
[Fact]
public void Error_WhiteSpaceMessage() {
// Act
var exception = Record.Exception(
() => ValidationIssue.Error(" \t")
);
// Assert
Assert.IsType<ArgumentException>(exception);
}
[Fact]
public void Error_WithJustCode() {
// Arrange
var message = "FooBar";
var code = "some-code";
// Act
var warning = ValidationIssue.Error(message, code);
// Assert
Assert.Equal(message, warning.Message);
Assert.Equal(ValidationIssueLevel.Error, warning.Level);
Assert.Equal(code, warning.Code);
Assert.Null(warning.MemberNames);
}
[Fact]
public void Error_WithJustMemberNames() {
// Arrange
var message = "FooBar";
var memberNames = ImmutableHashSet.Create("foo", "bar");
// Act
var warning = ValidationIssue.Error(message, memberNames);
// Assert
Assert.Equal(message, warning.Message);
Assert.Equal(ValidationIssueLevel.Error, warning.Level);
Assert.Null(warning.Code);
Assert.Equal(memberNames, warning.MemberNames);
}
[Fact]
public void Error_Valid() {
// Arrange
var message = "FooBar";
var code = "bizz buzz barr";
var names = ImmutableHashSet.Create("Foo", "Bar");
// Act
var warning = ValidationIssue.Error(
message,
code,
names
);
// Assert
Assert.Equal(message, warning.Message);
Assert.Equal(ValidationIssueLevel.Error, warning.Level);
Assert.Equal(code, warning.Code);
Assert.Equal(names, warning.MemberNames);
}
[Fact]
public void Constructor_NullMessage() {
// Act
var exception = Record.Exception(
() => new ValidationIssue(null, ValidationIssueLevel.Warning)
);
// Assert
Assert.IsType<ArgumentNullException>(exception);
}
[Fact]
public void Constructor_WhiteSpaceMessage() {
// Act
var exception = Record.Exception(
() => new ValidationIssue(" \n", ValidationIssueLevel.Warning)
);
// Assert
Assert.IsType<ArgumentException>(exception);
}
[Fact]
public void Constructor_Valid() {
// Arrange
var message = "FooBar";
var code = "some-error-code";
var level = ValidationIssueLevel.Error;
var names = ImmutableHashSet.Create("Foo", "Bar");
// Act
var issue = new ValidationIssue(
message: message,
code: code,
level: level,
memberNames: names
);
// Assert
Assert.Equal(message, issue.Message);
Assert.Equal(code, issue.Code);
Assert.Equal(level, issue.Level);
Assert.Equal(names, issue.MemberNames);
}
[Fact]
public void SetMessage_NullMessage() {
// Arrange
var issue = ValidationIssue.Error("FooBar");
// Act
var exception = Record.Exception(
() => issue.SetMessage(null)
);
// Assert
Assert.IsType<ArgumentNullException>(exception);
}
[Fact]
public void SetMessage_WhiteSpaceMessage() {
// Arrange
var issue = ValidationIssue.Error("FooBar");
// Act
var exception = Record.Exception(
() => issue.SetMessage(" \n")
);
// Assert
Assert.IsType<ArgumentException>(exception);
}
[Fact]
public void SetMessage_Valid() {
// Arrange
var initial = ValidationIssue.Error("Foo");
// Act
var updated = initial.SetMessage("FooBar");
// Assert
Assert.Equal("Foo", initial.Message);
Assert.Equal("FooBar", updated.Message);
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
[InlineData("SomeCode")]
public void SetCode_AllStringsAreValid(string newCode) {
// Arrange
var initial = ValidationIssue.Warning("Bar", "Code?");
// Act
var updated = initial.SetCode(newCode);
// Assert
Assert.Equal(newCode, updated.Code);
}
[Fact]
public void SetLevel_Valid() {
// Arrange
var initial = ValidationIssue.Error("Foo");
// Act
var updated = initial.SetLevel(ValidationIssueLevel.Warning);
// Assert
Assert.Equal(ValidationIssueLevel.Error, initial.Level);
Assert.Equal(ValidationIssueLevel.Warning, updated.Level);
}
[Fact]
public void SetMemberNames_Valid() {
// Arrange
var names = ImmutableHashSet.Create("Foo", "Bar");
var initial = ValidationIssue.Error("Foo", memberNames: names);
// Act
var nextNames = names.Add("Name");
var updated = initial.SetMemberNames(nextNames);
// Assert
Assert.DoesNotContain("Name", initial.MemberNames);
Assert.Contains("Name", updated.MemberNames);
}
}
}
| |
#region Namespaces
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using System.IO;
#endregion
namespace FindImports
{
// a generic interface to report imported data found in a specific project.
interface IReportImportData
{
bool init(string projectName);
void startReportSection(string sectionName);
void logItem(string item);
void setWarning();
void done();
string getLogFileName();
}
class SimpleTextFileBasedReporter: IReportImportData
{
public SimpleTextFileBasedReporter()
{
}
public bool init(string projectFileName)
{
bool outcome = false;
m_currentSection = null;
m_warnUser = false;
if (0 != projectFileName.Length)
{
m_projectFileName = projectFileName;
}
else
{
m_projectFileName = "Default";
}
m_logFileName = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(m_projectFileName), System.IO.Path.GetFileNameWithoutExtension(m_projectFileName)) + "-ListOfImportedData.txt";
// construct log file name from projectFileName and try to open file. Project file name is assumed to be valid (expected to be called on an open doc)
try
{
m_outputFile = new StreamWriter(m_logFileName);
m_outputFile.WriteLine("List of imported CAD data in " + projectFileName);
outcome = true;
}
catch (System.UnauthorizedAccessException)
{
TaskDialog.Show("FindImports", "You are not authorized to create " + m_logFileName);
}
catch (System.ArgumentNullException) // oh, come on.
{
TaskDialog.Show("FindImports", "That's just not fair. Null argument for StreamWriter()");
}
catch (System.ArgumentException)
{
TaskDialog.Show("FindImports", "Failed to create " + m_logFileName);
}
catch (System.IO.DirectoryNotFoundException)
{
TaskDialog.Show("FindImports", "That's not supposed to happen: directory not found: " + System.IO.Path.GetDirectoryName(m_projectFileName));
}
catch (System.IO.PathTooLongException)
{
TaskDialog.Show("FindImports", "The OS thinks the file name " + m_logFileName + "is too long");
}
catch (System.IO.IOException)
{
TaskDialog.Show("FindImports", "An IO error has occurred while writing to " + m_logFileName);
}
catch (System.Security.SecurityException)
{
TaskDialog.Show("FindImports", "The OS thinks your access rights to" + System.IO.Path.GetDirectoryName(m_projectFileName) + "are insufficient");
}
return outcome;
}
public void startReportSection(string sectionName)
{
endReportSection();
m_outputFile.WriteLine();
m_outputFile.WriteLine(sectionName);
m_outputFile.WriteLine();
m_currentSection = sectionName;
}
public void logItem(string item)
{
m_outputFile.WriteLine(item);
}
public void setWarning()
{
m_warnUser = true;
}
public void done()
{
endReportSection();
m_outputFile.WriteLine();
m_outputFile.WriteLine("The End");
m_outputFile.WriteLine();
m_outputFile.Close();
// display "done" dialog, potentially open log file
TaskDialog doneMsg = null;
new TaskDialog("FindImports completed successfully");
if (m_warnUser)
{
doneMsg = new TaskDialog("Potential issues found. Please review the log file");
}
else
{
doneMsg = new TaskDialog("FindImports completed successfully");
}
doneMsg.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Review " + m_logFileName);
switch (doneMsg.Show())
{
default:
break;
case TaskDialogResult.CommandLink1:
// display the log file
Process.Start("notepad.exe", m_logFileName);
break;
}
}
public string getLogFileName()
{
return m_logFileName;
}
private void endReportSection()
{
if (null != m_currentSection)
{
m_outputFile.WriteLine();
m_outputFile.WriteLine("End of " + m_currentSection);
m_outputFile.WriteLine();
}
}
private string m_projectFileName;
private string m_logFileName;
private StreamWriter m_outputFile;
private string m_currentSection;
private bool m_warnUser; // tell the user to review the log file
}
[Transaction(TransactionMode.Manual)]
public class Command : IExternalCommand
{
public Result Execute(
ExternalCommandData commandData,
ref string message,
ElementSet elements)
{
UIApplication uiapp = commandData.Application;
UIDocument uidoc = uiapp.ActiveUIDocument;
Application app = uiapp.Application;
Document doc = uidoc.Document;
listImports(doc);
return Result.Succeeded;
}
private void listImports(Document doc)
{
FilteredElementCollector col = new FilteredElementCollector(doc).OfClass(typeof(ImportInstance));
NameValueCollection listOfViewSpecificImports = new NameValueCollection();
NameValueCollection listOfModelImports = new NameValueCollection();
NameValueCollection listOfUnidentifiedImports = new NameValueCollection();
foreach (Element e in col)
{
// collect all view-specific names
if (e.ViewSpecific)
{
string viewName = null;
try
{
Element viewElement = doc.GetElement(e.OwnerViewId);
viewName = viewElement.Name;
}
catch (Autodesk.Revit.Exceptions.ArgumentNullException) // just in case
{
viewName = String.Concat("Invalid View ID: ", e.OwnerViewId.ToString());
}
if (null != e.Category)
{
listOfViewSpecificImports.Add(importCategoryNameToFileName(e.Category.Name), viewName);
}
else
{
listOfUnidentifiedImports.Add(e.Id.ToString(), viewName);
}
}
else
{
listOfModelImports.Add(importCategoryNameToFileName(e.Category.Name), e.Name);
}
}
IReportImportData logOutput = new SimpleTextFileBasedReporter();
if (!logOutput.init(doc.PathName))
{
TaskDialog.Show("FindImports", "Unable to create report file");
}
else
{
if (listOfViewSpecificImports.HasKeys())
{
logOutput.startReportSection("View Specific Imports");
listResults(listOfViewSpecificImports, logOutput);
}
if (listOfModelImports.HasKeys())
{
logOutput.startReportSection("Model Imports");
listResults(listOfModelImports, logOutput);
}
if (listOfUnidentifiedImports.HasKeys())
{
logOutput.startReportSection("Unknown import instances");
listResults(listOfUnidentifiedImports, logOutput);
}
if (!sanityCheckViewSpecific(listOfViewSpecificImports, logOutput))
{
logOutput.setWarning();
//TaskDialog.Show("FindImportedData", "Possible issues found. Please review the log file");
}
logOutput.done();
}
}
// this is an import category. It is created from a CAD file name, with appropriate (number) added.
// we want to use the file name as a key for our list of import instances, so strip off the brackets
private string importCategoryNameToFileName(string catName)
{
string fileName = catName;
fileName = fileName.Trim();
if (fileName.EndsWith(")"))
{
int lastLeftBracket = fileName.LastIndexOf("(");
if (-1 != lastLeftBracket)
fileName = fileName.Remove(lastLeftBracket); // remove left bracket
}
return fileName.Trim();
}
private void listResults(NameValueCollection listOfImports, IReportImportData logFile)
{
foreach (String key in listOfImports.AllKeys)
{
logFile.logItem(key + ": " + listOfImports.Get(key));
}
}
// ran a few basic sanity checks on the list of view-specific imports. View-specific sanity is not the same as model sanity. Neither is necessarily sane.
// true means possibly sane, false means probably not
private bool sanityCheckViewSpecific(NameValueCollection listOfImports, IReportImportData logFile)
{
logFile.startReportSection("Sanity check report for view-specific imports");
bool status = true;
// count number of entities per key.
foreach (String key in listOfImports.AllKeys)
{
string[] levels = listOfImports.GetValues(key);
if (levels != null && levels.GetLength(0) > 1)
{
logFile.logItem("CAD data " + key + " appears to have been imported in Current View Only mode multiple times. It is present in views "+ listOfImports.Get(key));
status = false;
}
}
return status;
}
}
}
| |
// 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 CompareScalarUnorderedLessThanOrEqualBoolean()
{
var test = new BooleanBinaryOpTest__CompareScalarUnorderedLessThanOrEqualBoolean();
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();
if (Sse2.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 (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();
if (Sse2.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 (Sse2.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 (Sse2.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 (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class BooleanBinaryOpTest__CompareScalarUnorderedLessThanOrEqualBoolean
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private GCHandle inHandle1;
private GCHandle inHandle2;
private ulong alignment;
public DataTable(Double[] inArray1, Double[] inArray2, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Double> _fld1;
public Vector128<Double> _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>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
return testStruct;
}
public void RunStructFldScenario(BooleanBinaryOpTest__CompareScalarUnorderedLessThanOrEqualBoolean testClass)
{
var result = Sse2.CompareScalarUnorderedLessThanOrEqual(_fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, result);
}
public void RunStructFldScenario_Load(BooleanBinaryOpTest__CompareScalarUnorderedLessThanOrEqualBoolean testClass)
{
fixed (Vector128<Double>* pFld1 = &_fld1)
fixed (Vector128<Double>* pFld2 = &_fld2)
{
var result = Sse2.CompareScalarUnorderedLessThanOrEqual(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2))
);
testClass.ValidateResult(_fld1, _fld2, result);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Vector128<Double> _clsVar1;
private static Vector128<Double> _clsVar2;
private Vector128<Double> _fld1;
private Vector128<Double> _fld2;
private DataTable _dataTable;
static BooleanBinaryOpTest__CompareScalarUnorderedLessThanOrEqualBoolean()
{
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>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
}
public BooleanBinaryOpTest__CompareScalarUnorderedLessThanOrEqualBoolean()
{
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>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, _data2, LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.CompareScalarUnorderedLessThanOrEqual(
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.CompareScalarUnorderedLessThanOrEqual(
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.CompareScalarUnorderedLessThanOrEqual(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareScalarUnorderedLessThanOrEqual), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareScalarUnorderedLessThanOrEqual), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareScalarUnorderedLessThanOrEqual), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.CompareScalarUnorderedLessThanOrEqual(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Double>* pClsVar1 = &_clsVar1)
fixed (Vector128<Double>* pClsVar2 = &_clsVar2)
{
var result = Sse2.CompareScalarUnorderedLessThanOrEqual(
Sse2.LoadVector128((Double*)(pClsVar1)),
Sse2.LoadVector128((Double*)(pClsVar2))
);
ValidateResult(_clsVar1, _clsVar2, result);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr);
var result = Sse2.CompareScalarUnorderedLessThanOrEqual(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse2.CompareScalarUnorderedLessThanOrEqual(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse2.CompareScalarUnorderedLessThanOrEqual(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new BooleanBinaryOpTest__CompareScalarUnorderedLessThanOrEqualBoolean();
var result = Sse2.CompareScalarUnorderedLessThanOrEqual(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new BooleanBinaryOpTest__CompareScalarUnorderedLessThanOrEqualBoolean();
fixed (Vector128<Double>* pFld1 = &test._fld1)
fixed (Vector128<Double>* pFld2 = &test._fld2)
{
var result = Sse2.CompareScalarUnorderedLessThanOrEqual(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.CompareScalarUnorderedLessThanOrEqual(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Double>* pFld1 = &_fld1)
fixed (Vector128<Double>* pFld2 = &_fld2)
{
var result = Sse2.CompareScalarUnorderedLessThanOrEqual(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2))
);
ValidateResult(_fld1, _fld2, result);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.CompareScalarUnorderedLessThanOrEqual(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse2.CompareScalarUnorderedLessThanOrEqual(
Sse2.LoadVector128((Double*)(&test._fld1)),
Sse2.LoadVector128((Double*)(&test._fld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Double> op1, Vector128<Double> op2, bool result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(Double[] left, Double[] right, bool result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((left[0] <= right[0]) != result)
{
succeeded = false;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.CompareScalarUnorderedLessThanOrEqual)}<Boolean>(Vector128<Double>, Vector128<Double>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
#if WINDOWS_8 || IOS || ANDROID
#define NO_CODE_EMIT
#endif
using System;
using System.Collections.Generic;
using System.Reflection;
#if !NO_CODE_EMIT
using System.Reflection.Emit;
#endif
#if WpfDataUi
namespace WpfDataUi
#else
namespace FlatRedBall.Instructions.Reflection
#endif
{
public abstract class LateBinder
{
static Dictionary<Type, LateBinder> mLateBinders = new Dictionary<Type, LateBinder>();
public static LateBinder GetInstance(Type type)
{
if (!mLateBinders.ContainsKey(type))
{
Type t = typeof(LateBinder<>).MakeGenericType(
type);
object obj = Activator.CreateInstance(t);
mLateBinders.Add(type, obj as LateBinder);
}
return mLateBinders[type];
}
public static object GetValueStatic(object target, string name)
/// <summary>
/// Returns the value of the variable obtained by name. This named "Static"
/// because it is a static version of the GetValue variable on LateBinderinstances.
/// This can be used to obtain values without needing to first create an instance of a late binder.
/// </summary>
/// <param name="target">The object from which to get a value.</param>
/// <param name="name">The variable name.</param>
/// <returns></returns>
{
return GetInstance(target.GetType()).GetValue(target, name);
}
public static bool SetValueStatic(object target, string name, object value)
{
return GetInstance(target.GetType()).SetValue(target, name, value);
}
public static bool TryGetValueStatic(object target, string name, out object result)
{
return GetInstance(target.GetType()).TryGetValue(target, name, out result);
}
public abstract object GetValue(object target, string name);
public abstract bool IsReadOnly(string name);
public abstract bool IsWriteOnly(string name);
public abstract bool TryGetValue(object target, string name, out object result);
public abstract bool SetValue(object target, string name, object value);
}
/// <summary>
/// Provides a simple interface to late bind a class.
/// </summary>
/// <remarks>The first time you attempt to get or set a property, it will dynamically generate the get and/or set
/// methods and cache them internally. Subsequent gets uses the dynamic methods without having to query the type's
/// meta data.</remarks>
public sealed class LateBinder<T> : LateBinder
{
#region Fields
HashSet<string> mFieldsSet = new HashSet<string>();
HashSet<string> mPropertieSet = new HashSet<string>();
private Type mType;
private Dictionary<string, GetHandler> mPropertyGet;
private Dictionary<string, SetHandler> mPropertySet;
private Dictionary<Type, List<string>> mFields;
private T mTarget = default(T);
private static LateBinder<T> _instance;
#endregion
#region Properties
public static LateBinder<T> Instance
{
get { return _instance; }
}
/// <summary>
/// The instance that this binder operates on by default
/// </summary>
/// <remarks>This can be overridden by the caller explicitly passing a target to the indexer</remarks>
public T Target
{
get { return mTarget; }
set { mTarget = value; }
}
/// <summary>
/// Gets or Sets the supplied property on the contained <seealso cref="Instance"/>
/// </summary>
/// <exception cref="InvalidOperationException">Throws if the contained Instance is null.</exception>
public object this[string propertyName]
{
get
{
ValidateInstance();
return this[mTarget, propertyName];
}
set
{
ValidateInstance();
this[mTarget, propertyName] = value;
}
}
/// <summary>
/// Gets or Sets the supplied property on the supplied target
/// </summary>
public object this[T target, string propertyName]
{
get
{
ValidateGetter(ref propertyName);
return mPropertyGet[propertyName](target);
}
set
{
ValidateSetter(ref propertyName);
mPropertySet[propertyName](target, value);
}
}
#endregion
#region Methods
#region Constructors
static LateBinder()
{
_instance = new LateBinder<T>();
}
public LateBinder(T instance)
: this()
{
mTarget = instance;
}
public LateBinder()
{
mType = typeof(T);
mPropertyGet = new Dictionary<string, GetHandler>();
mPropertySet = new Dictionary<string, SetHandler>();
mFields = new Dictionary<Type, List<string>>();
}
#endregion
#endregion
#region Public Methods
public override object GetValue(object target, string name)
{
if (mFieldsSet.Contains(name))
{
return GetField(target, name);
}
else if (mPropertieSet.Contains(name))
{
return GetProperty(target, name);
}
else
{
#if UWP
if (mType.GetField(name) != null)
#else
GetFieldRecursive(mType, name, out FieldInfo fieldInfo, out Type throwaway);
if (fieldInfo != null)
#endif
{
mFieldsSet.Add(name);
return GetField(target, name);
}
else
{
mPropertieSet.Add(name);
return GetProperty(target, name);
}
}
}
private void GetFieldRecursive(Type type, string fieldName, out FieldInfo field, out Type ownerType)
{
#if UWP
field = type.GetField(fieldName);
#else
field = type.GetField(fieldName, mGetFieldBindingFlags);
#endif
ownerType = null;
if(field != null)
{
ownerType = type;
}
#if UWP
else if (field == null && type.GetTypeInfo().BaseType != null)
{
GetFieldRecursive(type.GetTypeInfo().BaseType, fieldName, out field, out ownerType);
}
#else
else if(field == null && type.BaseType != null)
{
GetFieldRecursive(type.BaseType, fieldName, out field, out ownerType);
}
#endif
}
public override bool IsReadOnly(string name)
{
FieldInfo fieldInfo;
PropertyInfo propertyInfo;
fieldInfo = mType.GetField(name);
if (fieldInfo != null)
{
return false; // need to adjust this eventually...assuming false now
}
else
{
propertyInfo = mType.GetProperty(name);
if (propertyInfo != null)
{
return propertyInfo.CanWrite == false;
}
}
return false;
}
public override bool IsWriteOnly(string name)
{
FieldInfo fieldInfo;
PropertyInfo propertyInfo;
fieldInfo = mType.GetField(name);
if (fieldInfo != null)
{
return false; // need to adjust this eventually...assuming false now
}
else
{
propertyInfo = mType.GetProperty(name);
if (propertyInfo != null)
{
return propertyInfo.CanRead == false;
}
}
return false;
}
public override bool TryGetValue(object target, string name, out object result)
{
if (mFieldsSet.Contains(name))
{
result = GetField(target, name);
return true;
}
else if (mPropertieSet.Contains(name))
{
result = GetProperty(target, name);
return true;
}
else
{
#if WINDOWS_8 || UWP
if (mType.GetField(name) != null)
#else
if (mType.GetField(name, mGetFieldBindingFlags) != null)
#endif
{
mFieldsSet.Add(name);
result = GetField(target, name);
return true;
}
else if (mType.GetProperty(name) != null)
{
mPropertieSet.Add(name);
result = GetProperty(target, name);
return true;
}
else
{
result = null;
return false;
}
}
}
public override bool SetValue(object target, string name, object value)
{
var wasSet = false;
if (mFieldsSet.Contains(name))
{
// do nothing currently
SetField(target, name, value);
wasSet = true;
}
else if (mPropertieSet.Contains(name))
{
SetProperty(target, name, value);
wasSet = true;
}
else
{
try
{
#if WINDOWS_8 || UWP
if (mType.GetField(name) != null)
#else
if (mType.GetField(name, mGetFieldBindingFlags) != null)
#endif
{
mFieldsSet.Add(name);
SetField(target, name, value);
wasSet = true;
}
else
{
mPropertieSet.Add(name);
SetProperty(target, name, value);
wasSet = true;
}
}
catch(InvalidCastException innerException)
{
throw new InvalidOperationException(
$"Error setting {name} to {value} (value type {value?.GetType()})", innerException);
}
}
return wasSet;
}
private void SetField(object target, string name, object value)
{
#if NO_CODE_EMIT
// If a field is
// set to a struct
// like Vector3, then
// the value that is set
// will be boxed if using
// SetValue. On the PC we
// use SetValueDirect, but that
// isn't available on the CompactFramework.
// I've asked a question about it here:
// http://stackoverflow.com/questions/11698172/how-to-set-a-field-of-a-struct-type-on-an-object-in-windows-phone-7
FieldInfo fieldInfo = target.GetType().GetField(
name);
fieldInfo.SetValue(target, value);
#else
FieldInfo fieldInfo = target.GetType().GetField(
name);
#if DEBUG
try
{
#endif
fieldInfo.SetValueDirect(
__makeref(target), value);
#if DEBUG
}
catch (Exception e)
{
if(fieldInfo == null)
{
throw new Exception("Could nto find field by the name " + name );
}
else
{
throw new Exception("Error trying to set field " + name + " which is of type " + fieldInfo.FieldType + ".\nTrying to set to " + value + " of type " + value.GetType());
}
}
#endif
#endif
}
/// <summary>
/// Sets the supplied property on the supplied target
/// </summary>
/// <typeparam name="K">the type of the value</typeparam>
public void SetProperty<K>(object target, string propertyName, K value)
{
#if NO_CODE_EMIT
// find out if this is a property or field
Type type = typeof(T);
PropertyInfo propertyInfo = type.GetProperty(propertyName);
if (propertyInfo != null)
{
propertyInfo.SetValue(target, value, null);
}
else
{
FieldInfo fieldInfo = type.GetField(propertyName);
if (fieldInfo != null)
{
fieldInfo.SetValue(target, value);
}
else
{
throw new ArgumentException("Cannot find property or field with the name " + propertyName);
}
}
#else
ValidateSetter(ref propertyName);
if (mPropertySet.ContainsKey(propertyName))
{
mPropertySet[propertyName](target, value);
}
else
{
// This is probably not a property so see if it is a field.
FieldInfo fieldInfo = mType.GetField(propertyName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);
if (fieldInfo == null)
{
string errorMessage =
$"LateBinder could not find a field or property by the name of {propertyName}" +
$" in the class {mType}. Check the name of the property to verify if it is correct.";
throw new System.MemberAccessException(errorMessage);
}
else
{
#if WINDOWS_8
fieldInfo.SetValue(target, value);
#else
// I don't know why we branch here....Can we not call SetValue on public values?
if (!fieldInfo.IsPublic)
{
fieldInfo.SetValue(target, value);
}
else
{
object[] args = { value };
mType.InvokeMember(propertyName, BindingFlags.SetField, null, target, args);
}
#endif
}
}
#endif
}
#if !UWP
static BindingFlags mGetFieldBindingFlags = BindingFlags.GetField | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public |
BindingFlags.NonPublic | BindingFlags.FlattenHierarchy;
#endif
public object GetField(object target, string fieldName)
{
if (target == null)
{
#if UWP
FieldInfo fieldInfo = mType.GetField(fieldName);
#else
FieldInfo fieldInfo = mType.GetField(fieldName, mGetFieldBindingFlags);
#endif
return fieldInfo.GetValue(null);
}
else
{
#if UWP
return mType.GetField(fieldName).GetValue(target);
#else
Binder binder = null;
object[] args = null;
// use this to get the recurisve type in case it's defined by base
GetFieldRecursive(mType, fieldName, out FieldInfo fieldInfo, out Type fieldOwner);
return fieldOwner.InvokeMember(
fieldName,
mGetFieldBindingFlags,
binder,
target,
args
);
#endif
}
}
public ReturnType GetField<ReturnType>(T target, string propertyName)
{
return (ReturnType)GetField(target, propertyName);
}
/// <summary>
/// Gets the supplied property on the supplied target
/// </summary>
/// <typeparam name="K">The type of the property being returned</typeparam>
public K GetProperty<K>(T target, string propertyName)
{
return (K)GetProperty(target, propertyName);
}
public object GetProperty(object target, string propertyName)
{
#if NO_CODE_EMIT
// SLOW, but still works
return GetPropertyThroughReflection(target, propertyName);
#else
// June 11, 2011
// Turns out that
// getters for value
// types don't work properly.
// I found this out by trying to
// get the X value on a System.Drawing.Rectangle
// which was 0, but it kept returning a value of
// 2 billion. Checking for value types and using
// regular reflection fixes this problem.
if (target == null || typeof(T).IsValueType)
{
// SLOW, but still works
return GetPropertyThroughReflection(target, propertyName);
}
else
{
ValidateGetter(ref propertyName);
GetHandler getHandler = mPropertyGet[propertyName];
// getter may throw an exception. We don't want the grid to blow up in that case, so we'll return null:
try
{
return getHandler(target);
}
catch
{
return null;
}
}
#endif
}
private static object GetPropertyThroughReflection(object target, string propertyName)
{
#if WINDOWS_8 || UWP
PropertyInfo pi = typeof(T).GetProperty(propertyName);
#else
PropertyInfo pi = typeof(T).GetProperty(propertyName, mGetterBindingFlags);
#endif
if (pi == null)
{
string message = "Could not find the property " + propertyName + "\n\nAvailableProperties:\n\n";
#if WINDOWS_8 || UWP
IEnumerable<PropertyInfo> properties = typeof(T).GetProperties();
#else
PropertyInfo[] properties = typeof(T).GetProperties(mGetterBindingFlags);
#endif
foreach (PropertyInfo containedProperty in properties)
{
message += containedProperty.Name + "\n";
}
throw new InvalidOperationException(message);
}
return pi.GetValue(target, null);
}
#endregion
#region Private Helpers
private void ValidateInstance()
{
if (mTarget == null)
{
throw new InvalidOperationException("Instance property must not be null");
}
}
private void ValidateSetter(ref string propertyName)
{
if (!mPropertySet.ContainsKey(propertyName))
{
#if WINDOWS_8 || UWP
PropertyInfo propertyInfo = mType.GetProperty(propertyName);
#else
BindingFlags bindingFlags =
BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.Instance | BindingFlags.Static;
PropertyInfo propertyInfo = mType.GetProperty(propertyName, bindingFlags);
#endif
if (propertyInfo != null && propertyInfo.CanWrite)
{
mPropertySet.Add(propertyName, DynamicMethodCompiler.CreateSetHandler(mType, propertyInfo));
}
}
}
#if !WINDOWS_8 && !UWP
static BindingFlags mGetterBindingFlags =
BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Static |
BindingFlags.FlattenHierarchy;
#endif
private void ValidateGetter(ref string propertyName)
{
if (!mPropertyGet.ContainsKey(propertyName))
{
Type type = mType;
#if WINDOWS_8 || UWP
PropertyInfo propertyInfo = mType.GetProperty(propertyName);
#else
PropertyInfo propertyInfo = mType.GetProperty(propertyName, mGetterBindingFlags);
var baseType = mType.BaseType;
while(baseType != null && propertyInfo == null)
{
propertyInfo = baseType.GetProperty(propertyName, mGetterBindingFlags);
if(propertyInfo != null)
{
type = baseType;
}
else
{
baseType = baseType.BaseType;
}
}
#endif
if (propertyInfo != null)
{
mPropertyGet.Add(propertyName, DynamicMethodCompiler.CreateGetHandler(type, propertyInfo));
}
}
}
#endregion
#region Contained Classes
internal delegate object GetHandler(object source);
internal delegate void SetHandler(object source, object value);
internal delegate object InstantiateObjectHandler();
/// <summary>
/// provides helper functions for late binding a class
/// </summary>
/// <remarks>
/// Class found here:
/// http://www.codeproject.com/useritems/Dynamic_Code_Generation.asp
/// </remarks>
internal sealed class DynamicMethodCompiler
{
// DynamicMethodCompiler
private DynamicMethodCompiler() { }
// CreateInstantiateObjectDelegate
internal static InstantiateObjectHandler CreateInstantiateObjectHandler(Type type)
{
#if !NO_CODE_EMIT
ConstructorInfo constructorInfo = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[0], null);
if (constructorInfo == null)
{
throw new ApplicationException(string.Format("The type {0} must declare an empty constructor (the constructor may be private, internal, protected, protected internal, or public).", type));
}
DynamicMethod dynamicMethod = new DynamicMethod("InstantiateObject", MethodAttributes.Static | MethodAttributes.Public, CallingConventions.Standard, typeof(object), null, type, true);
ILGenerator generator = dynamicMethod.GetILGenerator();
generator.Emit(OpCodes.Newobj, constructorInfo);
generator.Emit(OpCodes.Ret);
return (InstantiateObjectHandler)dynamicMethod.CreateDelegate(typeof(InstantiateObjectHandler));
#else
throw new NotSupportedException();
#endif
}
// CreateGetDelegate
internal static GetHandler CreateGetHandler(Type type, PropertyInfo propertyInfo)
{
#if !NO_CODE_EMIT
MethodInfo getMethodInfo = propertyInfo.GetGetMethod(true);
DynamicMethod dynamicGet = CreateGetDynamicMethod(type);
ILGenerator getGenerator = dynamicGet.GetILGenerator();
getGenerator.Emit(OpCodes.Ldarg_0);
getGenerator.Emit(OpCodes.Call, getMethodInfo);
BoxIfNeeded(getMethodInfo.ReturnType, getGenerator);
getGenerator.Emit(OpCodes.Ret);
return (GetHandler)dynamicGet.CreateDelegate(typeof(GetHandler));
#else
throw new NotSupportedException();
#endif
}
// CreateGetDelegate
internal static GetHandler CreateGetHandler(Type type, FieldInfo fieldInfo)
{
#if !NO_CODE_EMIT
DynamicMethod dynamicGet = CreateGetDynamicMethod(type);
ILGenerator getGenerator = dynamicGet.GetILGenerator();
getGenerator.Emit(OpCodes.Ldarg_0);
getGenerator.Emit(OpCodes.Ldfld, fieldInfo);
BoxIfNeeded(fieldInfo.FieldType, getGenerator);
getGenerator.Emit(OpCodes.Ret);
return (GetHandler)dynamicGet.CreateDelegate(typeof(GetHandler));
#else
throw new NotSupportedException();
#endif
}
// CreateSetDelegate
internal static SetHandler CreateSetHandler(Type type, PropertyInfo propertyInfo)
{
#if !NO_CODE_EMIT
MethodInfo setMethodInfo = propertyInfo.GetSetMethod(true);
DynamicMethod dynamicSet = CreateSetDynamicMethod(type);
ILGenerator setGenerator = dynamicSet.GetILGenerator();
setGenerator.Emit(OpCodes.Ldarg_0);
setGenerator.Emit(OpCodes.Ldarg_1);
UnboxIfNeeded(setMethodInfo.GetParameters()[0].ParameterType, setGenerator);
setGenerator.Emit(OpCodes.Call, setMethodInfo);
setGenerator.Emit(OpCodes.Ret);
return (SetHandler)dynamicSet.CreateDelegate(typeof(SetHandler));
#else
throw new NotSupportedException();
#endif
}
// CreateSetDelegate
internal static SetHandler CreateSetHandler(Type type, FieldInfo fieldInfo)
{
#if !NO_CODE_EMIT
DynamicMethod dynamicSet = CreateSetDynamicMethod(type);
ILGenerator setGenerator = dynamicSet.GetILGenerator();
setGenerator.Emit(OpCodes.Ldarg_0);
setGenerator.Emit(OpCodes.Ldarg_1);
UnboxIfNeeded(fieldInfo.FieldType, setGenerator);
setGenerator.Emit(OpCodes.Stfld, fieldInfo);
setGenerator.Emit(OpCodes.Ret);
return (SetHandler)dynamicSet.CreateDelegate(typeof(SetHandler));
#else
throw new NotSupportedException();
#endif
}
#if !NO_CODE_EMIT
// CreateGetDynamicMethod
private static DynamicMethod CreateGetDynamicMethod(Type type)
{
return new DynamicMethod("DynamicGet", typeof(object), new Type[] { typeof(object) }, type, true);
}
// CreateSetDynamicMethod
private static DynamicMethod CreateSetDynamicMethod(Type type)
{
return new DynamicMethod("DynamicSet", typeof(void), new Type[] { typeof(object), typeof(object) }, type, true);
}
// BoxIfNeeded
private static void BoxIfNeeded(Type type, ILGenerator generator)
{
if (type.IsValueType)
{
generator.Emit(OpCodes.Box, type);
}
}
// UnboxIfNeeded
private static void UnboxIfNeeded(Type type, ILGenerator generator)
{
if (type.IsValueType)
{
generator.Emit(OpCodes.Unbox_Any, type);
}
}
#endif
}
#endregion
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using OmniSharp.Models;
using OmniSharp.Options;
using OmniSharp.Roslyn.CSharp.Services.Intellisense;
using OmniSharp.Tests;
using Xunit;
namespace OmniSharp.Roslyn.CSharp.Tests
{
public class IntellisenseFacts
{
[Fact]
public async Task DisplayText_is_correct_for_property()
{
var source =
@"public class Class1 {
public int Foo { get; set; }
public Class1()
{
Foo$
}
}";
var request = CreateRequest(source);
request.WantSnippet = true;
var completions = await FindCompletionsAsync(source, request);
ContainsCompletions(completions.Select(c => c.DisplayText).Take(1), "Foo");
}
[Fact]
public async Task DisplayText_is_correct_for_variable()
{
var source =
@"public class Class1 {
public Class1()
{
var foo = 1;
foo$
}
}";
var request = CreateRequest(source);
request.WantSnippet = true;
var completions = await FindCompletionsAsync(source, request);
ContainsCompletions(completions.Select(c => c.DisplayText).Take(1), "foo");
}
[Fact]
public async Task DisplayText_matches_snippet_for_snippet_response()
{
var source =
@"public class Class1 {
public Class1()
{
Foo$
}
public void Foo(int bar = 1)
{
}
}";
var request = CreateRequest(source);
request.WantSnippet = true;
var completions = await FindCompletionsAsync(source, request);
ContainsCompletions(completions.Select(c => c.DisplayText).Take(2), "Foo()", "Foo(int bar = 1)");
}
[Fact]
public async Task DisplayText_matches_snippet_for_non_snippet_response()
{
var source =
@"public class Class1 {
public Class1()
{
Foo$
}
public void Foo(int bar = 1)
{
}
}";
var request = CreateRequest(source);
request.WantSnippet = false;
var completions = await FindCompletionsAsync(source, request);
ContainsCompletions(completions.Select(c => c.DisplayText).Take(1), "Foo(int bar = 1)");
}
[Fact]
public async Task Returns_camel_case_completions()
{
var source =
@"public class Class1 {
public Class1()
{
System.Guid.tp$
}
}";
var completions = await FindCompletionsAsync(source);
ContainsCompletions(completions.Select(c => c.CompletionText).Take(1), "TryParse");
}
[Fact]
public async Task Returns_sub_sequence_completions()
{
var source =
@"public class Class1 {
public Class1()
{
System.Guid.ng$
}
}";
var completions = await FindCompletionsAsync(source);
ContainsCompletions(completions.Select(c => c.CompletionText).Take(1), "NewGuid");
}
[Fact]
public async Task Returns_method_header()
{
var source =
@"public class Class1 {
public Class1()
{
System.Guid.ng$
}
}";
var completions = await FindCompletionsAsync(source);
ContainsCompletions(completions.Select(c => c.MethodHeader).Take(1), "NewGuid()");
}
[Fact]
public async Task Returns_variable_before_class()
{
var source =
@"public class MyClass1 {
public MyClass1()
{
var myvar = 1;
my$
}
}";
var completions = await FindCompletionsAsync(source);
ContainsCompletions(completions.Select(c => c.CompletionText), "myvar", "MyClass1");
}
[Fact]
public async Task Returns_class_before_variable()
{
var source =
@"public class MyClass1 {
public MyClass1()
{
var myvar = 1;
My$
}
}";
var completions = await FindCompletionsAsync(source);
ContainsCompletions(completions.Select(c => c.CompletionText), "MyClass1", "myvar");
}
private void ContainsCompletions(IEnumerable<string> completions, params string[] expected)
{
var same = completions.SequenceEqual(expected);
if (!same)
{
System.Console.Error.WriteLine("Expected");
System.Console.Error.WriteLine("--------");
foreach (var completion in expected)
{
System.Console.WriteLine(completion);
}
System.Console.Error.WriteLine();
System.Console.Error.WriteLine("Found");
System.Console.Error.WriteLine("-----");
foreach (var completion in completions)
{
System.Console.WriteLine(completion);
}
}
Assert.Equal(expected, completions.ToArray());
}
private async Task<IEnumerable<AutoCompleteResponse>> FindCompletionsAsync(string source, AutoCompleteRequest request = null)
{
var workspace = await TestHelpers.CreateSimpleWorkspace(source);
var controller = new IntellisenseService(workspace, new FormattingOptions());
if (request == null)
{
request = CreateRequest(source);
}
var response = await controller.Handle(request);
var completions = response as IEnumerable<AutoCompleteResponse>;
return completions;
}
private AutoCompleteRequest CreateRequest(string source, string fileName = "dummy.cs")
{
var lineColumn = TestHelpers.GetLineAndColumnFromDollar(source);
return new AutoCompleteRequest
{
Line = lineColumn.Line,
Column = lineColumn.Column,
FileName = fileName,
Buffer = source.Replace("$", ""),
WordToComplete = GetPartialWord(source),
WantMethodHeader = true
};
}
private static string GetPartialWord(string editorText)
{
MatchCollection matches = Regex.Matches(editorText, @"([a-zA-Z0-9_]*)\$");
return matches[0].Groups[1].ToString();
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="EditorPart.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.UI.WebControls.WebParts {
using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Security.Permissions;
using System.Web.UI;
using System.Web.UI.WebControls;
[
Bindable(false),
Designer("System.Web.UI.Design.WebControls.WebParts.EditorPartDesigner, " + AssemblyRef.SystemDesign),
]
public abstract class EditorPart : Part {
private WebPart _webPartToEdit;
private WebPartManager _webPartManager;
private EditorZoneBase _zone;
/// <devdoc>
/// Whether the editor part should be displayed to the user.
/// An editor part may decide that it should not be shown based on the state
/// or the type of web part it is associated with.
/// </devdoc>
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public virtual bool Display {
get {
// Always want EditorPart to be visible at design time (VSWhidbey 458247)
if (DesignMode) {
return true;
}
if (WebPartToEdit != null) {
// Do not display EditorParts for a ProxyWebPart, regardless of the value
// of AllowEdit, IsShared, and PersonalizationScope
if (WebPartToEdit is ProxyWebPart) {
return false;
}
if (!WebPartToEdit.AllowEdit &&
WebPartToEdit.IsShared &&
WebPartManager != null &&
WebPartManager.Personalization.Scope == PersonalizationScope.User) {
return false;
}
return true;
}
// If there is no WebPartToEdit, return false as a default case
return false;
}
}
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public string DisplayTitle {
get {
string displayTitle = Title;
if (String.IsNullOrEmpty(displayTitle)) {
displayTitle = SR.GetString(SR.Part_Untitled);
}
return displayTitle;
}
}
protected WebPartManager WebPartManager {
get {
return _webPartManager;
}
}
/// <devdoc>
/// The web part that is being edited by this editor part. Set by the EditorZoneBase after
/// the EditorPart is added to the zone's control collection.
/// </devdoc>
protected WebPart WebPartToEdit {
get {
return _webPartToEdit;
}
}
protected EditorZoneBase Zone {
get {
return _zone;
}
}
/// <devdoc>
/// Called by the Zone when the EditorPart should apply values to its associated control. True indicates
/// that the save was successful, false indicates that an error occurred.
/// </devdoc>
public abstract bool ApplyChanges();
// If custom errors are enabled, we do not want to render the exception message to the browser. (VSWhidbey 381646)
internal string CreateErrorMessage(string exceptionMessage) {
if (Context != null && Context.IsCustomErrorEnabled) {
return SR.GetString(SR.EditorPart_ErrorSettingProperty);
}
else {
return SR.GetString(SR.EditorPart_ErrorSettingPropertyWithExceptionMessage, exceptionMessage);
}
}
[SecurityPermission(SecurityAction.Demand, Unrestricted = true)]
protected override IDictionary GetDesignModeState() {
IDictionary state = new HybridDictionary(1);
state["Zone"] = Zone;
return state;
}
protected internal override void OnPreRender(EventArgs e) {
base.OnPreRender(e);
if (Zone == null) {
throw new InvalidOperationException(SR.GetString(SR.EditorPart_MustBeInZone, ID));
}
// Need to set Visible=false so postback is handled correctly for child controls
// i.e. CheckBox child controls will always be set to false after postback unless
// they are marked as not visible
if (Display == false) {
Visible = false;
}
}
private void RenderDisplayName(HtmlTextWriter writer, string displayName, string associatedClientID) {
if (Zone != null) {
Zone.LabelStyle.AddAttributesToRender(writer, this);
}
writer.AddAttribute(HtmlTextWriterAttribute.For, associatedClientID);
writer.RenderBeginTag(HtmlTextWriterTag.Label);
writer.WriteEncodedText(displayName);
writer.RenderEndTag(); // Label
}
internal void RenderPropertyEditors(HtmlTextWriter writer, string[] propertyDisplayNames, string[] propertyDescriptions,
WebControl[] propertyEditors, string[] errorMessages) {
Debug.Assert(propertyDisplayNames.Length == propertyEditors.Length);
Debug.Assert(propertyDisplayNames.Length == errorMessages.Length);
Debug.Assert(propertyDescriptions == null || (propertyDescriptions.Length == propertyDisplayNames.Length));
if (propertyDisplayNames.Length == 0) {
return;
}
writer.AddAttribute(HtmlTextWriterAttribute.Border, "0");
writer.AddAttribute(HtmlTextWriterAttribute.Cellspacing, "4");
writer.RenderBeginTag(HtmlTextWriterTag.Table);
for (int i = 0; i < propertyDisplayNames.Length; i++) {
WebControl editUIControl = propertyEditors[i];
if (Zone != null && !Zone.EditUIStyle.IsEmpty) {
editUIControl.ApplyStyle(Zone.EditUIStyle);
}
string propertyDescription = (propertyDescriptions != null) ? propertyDescriptions[i] : null;
if (!String.IsNullOrEmpty(propertyDescription)) {
writer.AddAttribute(HtmlTextWriterAttribute.Title, propertyDescription);
}
writer.RenderBeginTag(HtmlTextWriterTag.Tr);
writer.RenderBeginTag(HtmlTextWriterTag.Td);
if (editUIControl is CheckBox) {
editUIControl.RenderControl(writer);
writer.Write(" ");
RenderDisplayName(writer, propertyDisplayNames[i], editUIControl.ClientID);
}
else {
string associatedClientID;
CompositeControl compositeControl = editUIControl as CompositeControl;
if (compositeControl != null) {
// The <label for> tag should point to the first child control of the
// composite control. (VSWhidbey 372756)
associatedClientID = compositeControl.Controls[0].ClientID;
}
else {
// The <label for> tag should point to the editUIControl itself.
associatedClientID = editUIControl.ClientID;
}
RenderDisplayName(writer, propertyDisplayNames[i] + ":", associatedClientID);
writer.WriteBreak();
writer.WriteLine();
editUIControl.RenderControl(writer);
}
writer.WriteBreak();
writer.WriteLine();
string errorMessage = errorMessages[i];
if (!String.IsNullOrEmpty(errorMessage)) {
if (Zone != null && !Zone.ErrorStyle.IsEmpty) {
Zone.ErrorStyle.AddAttributesToRender(writer, this);
}
writer.RenderBeginTag(HtmlTextWriterTag.Span);
writer.WriteEncodedText(errorMessage);
writer.RenderEndTag(); // Span
writer.WriteBreak();
writer.WriteLine();
}
writer.RenderEndTag(); // Td
writer.RenderEndTag(); // Tr
}
writer.RenderEndTag(); // Table
}
[SecurityPermission(SecurityAction.Demand, Unrestricted = true)]
protected override void SetDesignModeState(IDictionary data) {
if (data != null) {
object o = data["Zone"];
if (o != null) {
SetZone((EditorZoneBase)o);
}
}
}
internal void SetWebPartToEdit(WebPart webPartToEdit) {
_webPartToEdit = webPartToEdit;
}
internal void SetWebPartManager(WebPartManager webPartManager) {
_webPartManager = webPartManager;
}
internal void SetZone(EditorZoneBase zone) {
_zone = zone;
}
/// <devdoc>
/// Called by the Zone when the EditorPart should [....] its values because other EditorParts
/// may have changed control properties. This is only called after all the ApplyChanges have returned.
/// </devdoc>
public abstract void SyncChanges();
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* [email protected]. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Modules;
using IronPython.Runtime.Types;
#if FEATURE_NUMERICS
using System.Numerics;
#else
using Microsoft.Scripting.Math;
using Complex = Microsoft.Scripting.Math.Complex64;
#endif
using SpecialNameAttribute = System.Runtime.CompilerServices.SpecialNameAttribute;
namespace IronPython.Runtime.Operations {
public static partial class Int32Ops {
private static object FastNew(CodeContext/*!*/ context, object o) {
Extensible<BigInteger> el;
if (o is string) return __new__(null, (string)o, 10);
if (o is double) return DoubleOps.__int__((double)o);
if (o is int) return o;
if (o is bool) return ((bool)o) ? 1 : 0;
if (o is BigInteger) {
int res;
if (((BigInteger)o).AsInt32(out res)) {
return ScriptingRuntimeHelpers.Int32ToObject(res);
}
return o;
}
if ((el = o as Extensible<BigInteger>) != null) {
int res;
if (el.Value.AsInt32(out res)) {
return ScriptingRuntimeHelpers.Int32ToObject(res);
}
return el.Value;
}
if (o is float) return DoubleOps.__int__((double)(float)o);
if (o is Complex) throw PythonOps.TypeError("can't convert complex to int; use int(abs(z))");
if (o is Int64) {
Int64 val = (Int64)o;
if (Int32.MinValue <= val && val <= Int32.MaxValue) {
return (Int32)val;
} else {
return (BigInteger)val;
}
} else if (o is UInt32) {
UInt32 val = (UInt32)o;
if (val <= Int32.MaxValue) {
return (Int32)val;
} else {
return (BigInteger)val;
}
} else if (o is UInt64) {
UInt64 val = (UInt64)o;
if (val <= Int32.MaxValue) {
return (Int32)val;
} else {
return (BigInteger)val;
}
} else if (o is Decimal) {
Decimal val = (Decimal)o;
if (Int32.MinValue <= val && val <= Int32.MaxValue) {
return (Int32)val;
} else {
return (BigInteger)val;
}
} else if (o is Enum) {
return ((IConvertible)o).ToInt32(null);
}
Extensible<string> es = o as Extensible<string>;
if (es != null) {
// __int__ takes precedence, call it if it's available...
object value;
if (PythonTypeOps.TryInvokeUnaryOperator(DefaultContext.Default, es, "__int__", out value)) {
return value;
}
// otherwise call __new__ on the string value
return __new__(null, es.Value, 10);
}
object result;
int intRes;
BigInteger bigintRes;
if (PythonTypeOps.TryInvokeUnaryOperator(context, o, "__int__", out result) &&
!Object.ReferenceEquals(result, NotImplementedType.Value)) {
if (result is int || result is BigInteger ||
result is Extensible<int> || result is Extensible<BigInteger>) {
return result;
} else {
throw PythonOps.TypeError("__int__ returned non-Integral (type {0})", PythonTypeOps.GetOldName(result));
}
} else if (PythonOps.TryGetBoundAttr(context, o, "__trunc__", out result)) {
result = PythonOps.CallWithContext(context, result);
if (result is int || result is BigInteger ||
result is Extensible<int> || result is Extensible<BigInteger>) {
return result;
} else if (Converter.TryConvertToInt32(result, out intRes)) {
return intRes;
} else if (Converter.TryConvertToBigInteger(result, out bigintRes)) {
return bigintRes;
} else {
throw PythonOps.TypeError("__trunc__ returned non-Integral (type {0})", PythonTypeOps.GetOldName(result));
}
}
if (o is OldInstance) {
throw PythonOps.AttributeError("{0} instance has no attribute '__trunc__'", PythonTypeOps.GetOldName((OldInstance)o));
} else {
throw PythonOps.TypeError("int() argument must be a string or a number, not '{0}'", PythonTypeOps.GetName(o));
}
}
[StaticExtensionMethod]
public static object __new__(CodeContext context, object o) {
return __new__(context, TypeCache.Int32, o);
}
[StaticExtensionMethod]
public static object __new__(CodeContext context, PythonType cls, Extensible<double> o) {
object value;
// always succeeds as float defines __int__
PythonTypeOps.TryInvokeUnaryOperator(context, o, "__int__", out value);
if (cls == TypeCache.Int32) {
return (int)value;
} else {
return cls.CreateInstance(context, value);
}
}
private static void ValidateType(PythonType cls) {
if (cls == TypeCache.Boolean)
throw PythonOps.TypeError("int.__new__(bool) is not safe, use bool.__new__()");
}
[StaticExtensionMethod]
public static object __new__(PythonType cls, string s, int @base) {
ValidateType(cls);
// radix 16/8/2 allows a 0x/0o/0b preceding it... We either need a whole new
// integer parser, or special case it here.
if (@base == 16 || @base == 8 || @base == 2) {
s = TrimRadix(s, @base);
}
return LiteralParser.ParseIntegerSign(s, @base);
}
[StaticExtensionMethod]
public static object __new__(CodeContext/*!*/ context, PythonType cls, IList<byte> s) {
object value;
IPythonObject po = s as IPythonObject;
if (po == null ||
!PythonTypeOps.TryInvokeUnaryOperator(DefaultContext.Default, po, "__int__", out value)) {
value = FastNew(context, s.MakeString());
}
if (cls == TypeCache.Int32) {
return value;
} else {
ValidateType(cls);
// derived int creation...
return cls.CreateInstance(context, value);
}
}
internal static string TrimRadix(string s, int radix) {
for (int i = 0; i < s.Length; i++) {
if (Char.IsWhiteSpace(s[i])) continue;
if (s[i] == '0' && i < s.Length - 1) {
switch(radix) {
case 16:
if (s[i + 1] == 'x' || s[i + 1] == 'X') {
s = s.Substring(i + 2);
}
break;
case 8:
if (s[i + 1] == 'o' || s[i + 1] == 'O') {
s = s.Substring(i + 2);
}
break;
case 2:
if (s[i + 1] == 'b' || s[i + 1] == 'B') {
s = s.Substring(i + 2);
}
break;
default:
break;
}
}
break;
}
return s;
}
[StaticExtensionMethod]
public static object __new__(CodeContext context, PythonType cls, object x) {
object value = FastNew(context, x);
if (cls == TypeCache.Int32) {
return value;
} else {
ValidateType(cls);
// derived int creation...
return cls.CreateInstance(context, value);
}
}
// "int()" calls ReflectedType.Call(), which calls "Activator.CreateInstance" and return directly.
// this is for derived int creation or direct calls to __new__...
[StaticExtensionMethod]
public static object __new__(CodeContext context, PythonType cls) {
if (cls == TypeCache.Int32) return 0;
return cls.CreateInstance(context);
}
#region Binary Operators
[SpecialName]
public static object FloorDivide(int x, int y) {
if (y == -1 && x == Int32.MinValue) {
return -(BigInteger)Int32.MinValue;
}
return ScriptingRuntimeHelpers.Int32ToObject(MathUtils.FloorDivideUnchecked(x, y));
}
[SpecialName]
public static int Mod(int x, int y) {
return MathUtils.FloorRemainder(x, y);
}
[SpecialName]
public static object Power(int x, BigInteger power, BigInteger qmod) {
return BigIntegerOps.Power((BigInteger)x, power, qmod);
}
[SpecialName]
public static object Power(int x, double power, double qmod) {
return NotImplementedType.Value;
}
[SpecialName]
public static object Power(int x, int power, int? qmod) {
if (qmod == null) return Power(x, power);
int mod = (int)qmod;
if (power < 0) throw PythonOps.TypeError("power", power, "power must be >= 0");
if (mod == 0) {
throw PythonOps.ZeroDivisionError();
}
// This is "exponentiation by squaring" (described in Applied Cryptography; a log-time algorithm)
long result = 1 % mod; // Handle special case of power=0, mod=1
long factor = x;
while (power != 0) {
if ((power & 1) != 0) result = (result * factor) % mod;
factor = (factor * factor) % mod;
power >>= 1;
}
// fix the sign for negative moduli or negative mantissas
if ((mod < 0 && result > 0) || (mod > 0 && result < 0)) {
result += mod;
}
return (int)result;
}
[SpecialName]
public static object Power(int x, int power) {
if (power == 0) return 1;
if (power < 0) {
if (x == 0)
throw PythonOps.ZeroDivisionError("0.0 cannot be raised to a negative power");
return DoubleOps.Power(x, power);
}
int factor = x;
int result = 1;
int savePower = power;
try {
checked {
while (power != 0) {
if ((power & 1) != 0) result = result * factor;
if (power == 1) break; // prevent overflow
factor = factor * factor;
power >>= 1;
}
return result;
}
} catch (OverflowException) {
return BigIntegerOps.Power((BigInteger)x, savePower);
}
}
[SpecialName]
public static object LeftShift(int x, int y) {
if (y < 0) {
throw PythonOps.ValueError("negative shift count");
}
if (y > 31 ||
(x > 0 && x > (Int32.MaxValue >> y)) ||
(x < 0 && x < (Int32.MinValue >> y))) {
return Int64Ops.LeftShift((long)x, y);
}
return ScriptingRuntimeHelpers.Int32ToObject(x << y);
}
[SpecialName]
public static int RightShift(int x, int y) {
if (y < 0) {
throw PythonOps.ValueError("negative shift count");
}
if (y > 31) {
return x >= 0 ? 0 : -1;
}
int q;
if (x >= 0) {
q = x >> y;
} else {
q = (x + ((1 << y) - 1)) >> y;
int r = x - (q << y);
if (r != 0) q--;
}
return q;
}
#endregion
public static PythonTuple __divmod__(int x, int y) {
return PythonTuple.MakeTuple(Divide(x, y), Mod(x, y));
}
[return: MaybeNotImplemented]
public static object __divmod__(int x, object y) {
return NotImplementedType.Value;
}
#region Unary Operators
public static string __oct__(int x) {
if (x == 0) {
return "0";
} else if (x > 0) {
return "0" + ((BigInteger)x).ToString(8);
} else {
return "-0" + ((BigInteger)(-x)).ToString(8);
}
}
public static string __hex__(int x) {
if (x < 0) {
return "-0x" + (-x).ToString("x");
} else {
return "0x" + x.ToString("x");
}
}
#endregion
public static object __getnewargs__(CodeContext context, int self) {
return PythonTuple.MakeTuple(Int32Ops.__new__(context, TypeCache.Int32, self));
}
public static object __rdivmod__(int x, int y) {
return __divmod__(y, x);
}
public static int __int__(int self) {
return self;
}
public static int __index__(int self) {
return self;
}
public static BigInteger __long__(int self) {
return (BigInteger)self;
}
public static double __float__(int self) {
return (double)self;
}
public static int __abs__(int self) {
return Math.Abs(self);
}
public static object __coerce__(CodeContext context, int x, object o) {
// called via builtin.coerce()
if (o is int) {
return PythonTuple.MakeTuple(ScriptingRuntimeHelpers.Int32ToObject(x), o);
}
return NotImplementedType.Value;
}
public static string __format__(CodeContext/*!*/ context, int self, [NotNull]string/*!*/ formatSpec) {
StringFormatSpec spec = StringFormatSpec.FromString(formatSpec);
if (spec.Precision != null) {
throw PythonOps.ValueError("Precision not allowed in integer format specifier");
}
string digits;
int width = 0;
switch (spec.Type) {
case 'n':
CultureInfo culture = PythonContext.GetContext(context).NumericCulture;
if (culture == CultureInfo.InvariantCulture) {
// invariant culture maps to CPython's C culture, which doesn't
// include any formatting info.
goto case 'd';
}
width = spec.Width ?? 0;
// If we're padding with leading zeros and we might be inserting
// culture sensitive number group separators. (i.e. commas)
// So use FormattingHelper.ToCultureString for that support.
if (spec.Fill.HasValue && spec.Fill.Value == '0' && width > 1) {
digits = FormattingHelper.ToCultureString(self, culture.NumberFormat, spec);
}
else {
digits = self.ToString("N0", culture);
}
break;
case null:
case 'd':
if (spec.ThousandsComma) {
width = spec.Width ?? 0;
// If we're inserting commas, and we're padding with leading zeros.
// AlignNumericText won't know where to place the commas,
// so use FormattingHelper.ToCultureString for that support.
if (spec.Fill.HasValue && spec.Fill.Value == '0' && width > 1) {
digits = FormattingHelper.ToCultureString(self, FormattingHelper.InvariantCommaNumberInfo, spec);
}
else {
digits = self.ToString("#,0", CultureInfo.InvariantCulture);
}
} else {
digits = self.ToString("D", CultureInfo.InvariantCulture);
}
break;
case '%':
if (spec.ThousandsComma) {
digits = self.ToString("#,0.000000%", CultureInfo.InvariantCulture);
} else {
digits = self.ToString("0.000000%", CultureInfo.InvariantCulture);
}
break;
case 'e':
if (spec.ThousandsComma) {
digits = self.ToString("#,0.000000e+00", CultureInfo.InvariantCulture);
} else {
digits = self.ToString("0.000000e+00", CultureInfo.InvariantCulture);
}
break;
case 'E':
if (spec.ThousandsComma) {
digits = self.ToString("#,0.000000E+00", CultureInfo.InvariantCulture);
} else {
digits = self.ToString("0.000000E+00", CultureInfo.InvariantCulture);
}
break;
case 'f':
case 'F':
if (spec.ThousandsComma) {
digits = self.ToString("#,########0.000000", CultureInfo.InvariantCulture);
} else {
digits = self.ToString("#########0.000000", CultureInfo.InvariantCulture);
}
break;
case 'g':
if (self >= 1000000 || self <= -1000000) {
digits = self.ToString("0.#####e+00", CultureInfo.InvariantCulture);
} else if (spec.ThousandsComma) {
// Handle the common case in 'd'.
goto case 'd';
} else {
digits = self.ToString(CultureInfo.InvariantCulture);
}
break;
case 'G':
if (self >= 1000000 || self <= -1000000) {
digits = self.ToString("0.#####E+00", CultureInfo.InvariantCulture);
} else if (spec.ThousandsComma) {
// Handle the common case in 'd'.
goto case 'd';
}
else {
digits = self.ToString(CultureInfo.InvariantCulture);
}
break;
case 'X':
digits = ToHex(self, false);
break;
case 'x':
digits = ToHex(self, true);
break;
case 'o': // octal
digits = ToOctal(self, true);
break;
case 'b': // binary
digits = ToBinary(self, false);
break;
case 'c': // single char
if (spec.Sign != null) {
throw PythonOps.ValueError("Sign not allowed with integer format specifier 'c'");
}
if (self < 0 || self > 0xFF) {
throw PythonOps.OverflowError("%c arg not in range(0x10000)");
}
digits = ScriptingRuntimeHelpers.CharToString((char)self);
break;
default:
throw PythonOps.ValueError("Unknown format code '{0}'", spec.Type.ToString());
}
if (self < 0 && digits[0] == '-') {
digits = digits.Substring(1);
}
return spec.AlignNumericText(digits, self == 0, self > 0);
}
public static string/*!*/ __repr__(int self) {
return self.ToString(CultureInfo.InvariantCulture);
}
private static string ToHex(int self, bool lowercase) {
string digits;
if (self != Int32.MinValue) {
int val = self;
if (self < 0) {
val = -self;
}
digits = val.ToString(lowercase ? "x" : "X", CultureInfo.InvariantCulture);
} else {
digits = "80000000";
}
return digits;
}
private static string ToOctal(int self, bool lowercase) {
string digits;
if (self == 0) {
digits = "0";
} else if (self != Int32.MinValue) {
int val = self;
if (self < 0) {
val = -self;
}
StringBuilder sbo = new StringBuilder();
for (int i = 30; i >= 0; i -= 3) {
char value = (char)('0' + (val >> i & 0x07));
if (value != '0' || sbo.Length > 0) {
sbo.Append(value);
}
}
digits = sbo.ToString();
} else {
digits = "20000000000";
}
return digits;
}
internal static string ToBinary(int self) {
if (self == Int32.MinValue) {
return "-0b10000000000000000000000000000000";
}
string res = ToBinary(self, true);
if (self < 0) {
res = "-" + res;
}
return res;
}
private static string ToBinary(int self, bool includeType) {
string digits;
if (self == 0) {
digits = "0";
} else if (self != Int32.MinValue) {
StringBuilder sbb = new StringBuilder();
int val = self;
if (self < 0) {
val = -self;
}
for (int i = 31; i >= 0; i--) {
if ((val & (1 << i)) != 0) {
sbb.Append('1');
} else if (sbb.Length != 0) {
sbb.Append('0');
}
}
digits = sbb.ToString();
} else {
digits = "10000000000000000000000000000000";
}
if (includeType) {
digits = "0b" + digits;
}
return digits;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Reflection;
using System.Threading;
using Microsoft.CodeAnalysis.Scripting.Hosting;
namespace Microsoft.CodeAnalysis.Scripting
{
using static ParameterValidationHelpers;
/// <summary>
/// Options for creating and running scripts.
/// </summary>
public sealed class ScriptOptions
{
public static readonly ScriptOptions Default = new ScriptOptions(
filePath: "",
references: ImmutableArray<MetadataReference>.Empty,
namespaces: ImmutableArray<string>.Empty,
metadataResolver: RuntimeMetadataReferenceResolver.Default,
sourceResolver: SourceFileResolver.Default);
/// <summary>
/// An array of <see cref="MetadataReference"/>s to be added to the script.
/// </summary>
/// <remarks>
/// The array may contain both resolved and unresolved references (<see cref="UnresolvedMetadataReference"/>).
/// Unresolved references are resolved when the script is about to be executed
/// (<see cref="Script.RunAsync(object, CancellationToken)"/>.
/// Any resolution errors are reported at that point through <see cref="CompilationErrorException"/>.
/// </remarks>
public ImmutableArray<MetadataReference> MetadataReferences { get; private set; }
/// <summary>
/// <see cref="MetadataReferenceResolver"/> to be used to resolve missing dependencies, unresolved metadata references and #r directives.
/// </summary>
public MetadataReferenceResolver MetadataResolver { get; private set; }
/// <summary>
/// <see cref="SourceReferenceResolver"/> to be used to resolve source of scripts referenced via #load directive.
/// </summary>
public SourceReferenceResolver SourceResolver { get; private set; }
/// <summary>
/// The namespaces, static classes and aliases imported by the script.
/// </summary>
public ImmutableArray<string> Imports { get; private set; }
/// <summary>
/// The path to the script source if it originated from a file, empty otherwise.
/// </summary>
public string FilePath { get; private set; }
internal ScriptOptions(
string filePath,
ImmutableArray<MetadataReference> references,
ImmutableArray<string> namespaces,
MetadataReferenceResolver metadataResolver,
SourceReferenceResolver sourceResolver)
{
Debug.Assert(filePath != null);
Debug.Assert(!references.IsDefault);
Debug.Assert(!namespaces.IsDefault);
Debug.Assert(metadataResolver != null);
Debug.Assert(sourceResolver != null);
FilePath = filePath;
MetadataReferences = references;
Imports = namespaces;
MetadataResolver = metadataResolver;
SourceResolver = sourceResolver;
}
private ScriptOptions(ScriptOptions other)
: this(filePath: other.FilePath,
references: other.MetadataReferences,
namespaces: other.Imports,
metadataResolver: other.MetadataResolver,
sourceResolver: other.SourceResolver)
{
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the <see cref="FilePath"/> changed.
/// </summary>
public ScriptOptions WithFilePath(string filePath) =>
(FilePath == filePath) ? this : new ScriptOptions(this) { FilePath = filePath ?? "" };
private static MetadataReference CreateUnresolvedReference(string reference) =>
new UnresolvedMetadataReference(reference, MetadataReferenceProperties.Assembly);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
private ScriptOptions WithReferences(ImmutableArray<MetadataReference> references) =>
MetadataReferences.Equals(references) ? this : new ScriptOptions(this) { MetadataReferences = CheckImmutableArray(references, nameof(references)) };
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions WithReferences(IEnumerable<MetadataReference> references) =>
WithReferences(ToImmutableArrayChecked(references, nameof(references)));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions WithReferences(params MetadataReference[] references) =>
WithReferences((IEnumerable<MetadataReference>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions AddReferences(IEnumerable<MetadataReference> references) =>
WithReferences(ConcatChecked(MetadataReferences, references, nameof(references)));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
public ScriptOptions AddReferences(params MetadataReference[] references) =>
AddReferences((IEnumerable<MetadataReference>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions WithReferences(IEnumerable<Assembly> references) =>
WithReferences(SelectChecked(references, nameof(references), MetadataReference.CreateFromAssemblyInternal));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions WithReferences(params Assembly[] references) =>
WithReferences((IEnumerable<Assembly>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions AddReferences(IEnumerable<Assembly> references) =>
AddReferences(SelectChecked(references, nameof(references), MetadataReference.CreateFromAssemblyInternal));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions AddReferences(params Assembly[] references) =>
AddReferences((IEnumerable<Assembly>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions WithReferences(IEnumerable<string> references) =>
WithReferences(SelectChecked(references, nameof(references), CreateUnresolvedReference));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions WithReferences(params string[] references) =>
WithReferences((IEnumerable<string>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions AddReferences(IEnumerable<string> references) =>
AddReferences(SelectChecked(references, nameof(references), CreateUnresolvedReference));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
public ScriptOptions AddReferences(params string[] references) =>
AddReferences((IEnumerable<string>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with specified <see cref="MetadataResolver"/>.
/// </summary>
public ScriptOptions WithMetadataResolver(MetadataReferenceResolver resolver) =>
MetadataResolver == resolver ? this : new ScriptOptions(this) { MetadataResolver = resolver };
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with specified <see cref="SourceResolver"/>.
/// </summary>
public ScriptOptions WithSourceResolver(SourceReferenceResolver resolver) =>
SourceResolver == resolver ? this : new ScriptOptions(this) { SourceResolver = resolver };
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the <see cref="Imports"/> changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception>
private ScriptOptions WithImports(ImmutableArray<string> imports) =>
Imports.Equals(imports) ? this : new ScriptOptions(this) { Imports = CheckImmutableArray(imports, nameof(imports)) };
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the <see cref="Imports"/> changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception>
public ScriptOptions WithImports(IEnumerable<string> imports) =>
WithImports(ToImmutableArrayChecked(imports, nameof(imports)));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the <see cref="Imports"/> changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception>
public ScriptOptions WithImports(params string[] imports) =>
WithImports((IEnumerable<string>)imports);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with <see cref="Imports"/> added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception>
public ScriptOptions AddImports(IEnumerable<string> imports) =>
WithImports(ConcatChecked(Imports, imports, nameof(imports)));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with <see cref="Imports"/> added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception>
public ScriptOptions AddImports(params string[] imports) =>
AddImports((IEnumerable<string>)imports);
}
}
| |
// dnlib: See LICENSE.txt for more info
using System;
using dnlib.IO;
using dnlib.PE;
using dnlib.Threading;
namespace dnlib.DotNet.MD {
/// <summary>
/// .NET metadata tables stream
/// </summary>
public sealed partial class TablesStream : DotNetStream {
bool initialized;
uint reserved1;
byte majorVersion;
byte minorVersion;
MDStreamFlags flags;
byte log2Rid;
ulong validMask;
ulong sortedMask;
uint extraData;
MDTable[] mdTables;
HotTableStream hotTableStream;
IColumnReader columnReader;
IRowReader<RawMethodRow> methodRowReader;
#pragma warning disable 1591 // XML doc comment
public MDTable ModuleTable { get; private set; }
public MDTable TypeRefTable { get; private set; }
public MDTable TypeDefTable { get; private set; }
public MDTable FieldPtrTable { get; private set; }
public MDTable FieldTable { get; private set; }
public MDTable MethodPtrTable { get; private set; }
public MDTable MethodTable { get; private set; }
public MDTable ParamPtrTable { get; private set; }
public MDTable ParamTable { get; private set; }
public MDTable InterfaceImplTable { get; private set; }
public MDTable MemberRefTable { get; private set; }
public MDTable ConstantTable { get; private set; }
public MDTable CustomAttributeTable { get; private set; }
public MDTable FieldMarshalTable { get; private set; }
public MDTable DeclSecurityTable { get; private set; }
public MDTable ClassLayoutTable { get; private set; }
public MDTable FieldLayoutTable { get; private set; }
public MDTable StandAloneSigTable { get; private set; }
public MDTable EventMapTable { get; private set; }
public MDTable EventPtrTable { get; private set; }
public MDTable EventTable { get; private set; }
public MDTable PropertyMapTable { get; private set; }
public MDTable PropertyPtrTable { get; private set; }
public MDTable PropertyTable { get; private set; }
public MDTable MethodSemanticsTable { get; private set; }
public MDTable MethodImplTable { get; private set; }
public MDTable ModuleRefTable { get; private set; }
public MDTable TypeSpecTable { get; private set; }
public MDTable ImplMapTable { get; private set; }
public MDTable FieldRVATable { get; private set; }
public MDTable ENCLogTable { get; private set; }
public MDTable ENCMapTable { get; private set; }
public MDTable AssemblyTable { get; private set; }
public MDTable AssemblyProcessorTable { get; private set; }
public MDTable AssemblyOSTable { get; private set; }
public MDTable AssemblyRefTable { get; private set; }
public MDTable AssemblyRefProcessorTable { get; private set; }
public MDTable AssemblyRefOSTable { get; private set; }
public MDTable FileTable { get; private set; }
public MDTable ExportedTypeTable { get; private set; }
public MDTable ManifestResourceTable { get; private set; }
public MDTable NestedClassTable { get; private set; }
public MDTable GenericParamTable { get; private set; }
public MDTable MethodSpecTable { get; private set; }
public MDTable GenericParamConstraintTable { get; private set; }
#pragma warning restore
#if THREAD_SAFE
internal readonly Lock theLock = Lock.Create();
#endif
internal HotTableStream HotTableStream {
set { hotTableStream = value; }
}
/// <summary>
/// Gets/sets the column reader
/// </summary>
public IColumnReader ColumnReader {
get { return columnReader; }
set { columnReader = value; }
}
/// <summary>
/// Gets/sets the <c>Method</c> table reader
/// </summary>
public IRowReader<RawMethodRow> MethodRowReader {
get { return methodRowReader; }
set { methodRowReader = value; }
}
/// <summary>
/// Gets the reserved field
/// </summary>
public uint Reserved1 {
get { return reserved1; }
}
/// <summary>
/// Gets the version. The major version is in the upper 8 bits, and the minor version
/// is in the lower 8 bits.
/// </summary>
public ushort Version {
get { return (ushort)((majorVersion << 8) | minorVersion); }
}
/// <summary>
/// Gets <see cref="MDStreamFlags"/>
/// </summary>
public MDStreamFlags Flags {
get { return flags; }
}
/// <summary>
/// Gets the reserved log2 rid field
/// </summary>
public byte Log2Rid {
get { return log2Rid; }
}
/// <summary>
/// Gets the valid mask
/// </summary>
public ulong ValidMask {
get { return validMask; }
}
/// <summary>
/// Gets the sorted mask
/// </summary>
public ulong SortedMask {
get { return sortedMask; }
}
/// <summary>
/// Gets the extra data
/// </summary>
public uint ExtraData {
get { return extraData; }
}
/// <summary>
/// Gets the MD tables
/// </summary>
public MDTable[] MDTables {
get { return mdTables; }
}
/// <summary>
/// Gets the <see cref="MDStreamFlags.BigStrings"/> bit
/// </summary>
public bool HasBigStrings {
get { return (flags & MDStreamFlags.BigStrings) != 0; }
}
/// <summary>
/// Gets the <see cref="MDStreamFlags.BigGUID"/> bit
/// </summary>
public bool HasBigGUID {
get { return (flags & MDStreamFlags.BigGUID) != 0; }
}
/// <summary>
/// Gets the <see cref="MDStreamFlags.BigBlob"/> bit
/// </summary>
public bool HasBigBlob {
get { return (flags & MDStreamFlags.BigBlob) != 0; }
}
/// <summary>
/// Gets the <see cref="MDStreamFlags.Padding"/> bit
/// </summary>
public bool HasPadding {
get { return (flags & MDStreamFlags.Padding) != 0; }
}
/// <summary>
/// Gets the <see cref="MDStreamFlags.DeltaOnly"/> bit
/// </summary>
public bool HasDeltaOnly {
get { return (flags & MDStreamFlags.DeltaOnly) != 0; }
}
/// <summary>
/// Gets the <see cref="MDStreamFlags.ExtraData"/> bit
/// </summary>
public bool HasExtraData {
get { return (flags & MDStreamFlags.ExtraData) != 0; }
}
/// <summary>
/// Gets the <see cref="MDStreamFlags.HasDelete"/> bit
/// </summary>
public bool HasDelete {
get { return (flags & MDStreamFlags.HasDelete) != 0; }
}
/// <inheritdoc/>
public TablesStream(IImageStream imageStream, StreamHeader streamHeader)
: base(imageStream, streamHeader) {
}
/// <summary>
/// Initializes MD tables
/// </summary>
/// <param name="peImage">The PEImage</param>
public void Initialize(IPEImage peImage) {
if (initialized)
throw new Exception("Initialize() has already been called");
initialized = true;
reserved1 = imageStream.ReadUInt32();
majorVersion = imageStream.ReadByte();
minorVersion = imageStream.ReadByte();
flags = (MDStreamFlags)imageStream.ReadByte();
log2Rid = imageStream.ReadByte();
validMask = imageStream.ReadUInt64();
sortedMask = imageStream.ReadUInt64();
int maxPresentTables;
var dnTableSizes = new DotNetTableSizes();
var tableInfos = dnTableSizes.CreateTables(majorVersion, minorVersion, out maxPresentTables);
mdTables = new MDTable[tableInfos.Length];
ulong valid = validMask;
var sizes = new uint[64];
for (int i = 0; i < 64; valid >>= 1, i++) {
uint rows = (valid & 1) == 0 ? 0 : imageStream.ReadUInt32();
if (i >= maxPresentTables)
rows = 0;
sizes[i] = rows;
if (i < mdTables.Length)
mdTables[i] = new MDTable((Table)i, rows, tableInfos[i]);
}
if (HasExtraData)
extraData = imageStream.ReadUInt32();
dnTableSizes.InitializeSizes(HasBigStrings, HasBigGUID, HasBigBlob, sizes);
var currentRva = peImage.ToRVA(imageStream.FileOffset) + (uint)imageStream.Position;
foreach (var mdTable in mdTables) {
var dataLen = (long)mdTable.TableInfo.RowSize * (long)mdTable.Rows;
mdTable.ImageStream = peImage.CreateStream(currentRva, dataLen);
var newRva = currentRva + (uint)dataLen;
if (newRva < currentRva)
throw new BadImageFormatException("Too big MD table");
currentRva = newRva;
}
InitializeTables();
}
void InitializeTables() {
ModuleTable = mdTables[(int)Table.Module];
TypeRefTable = mdTables[(int)Table.TypeRef];
TypeDefTable = mdTables[(int)Table.TypeDef];
FieldPtrTable = mdTables[(int)Table.FieldPtr];
FieldTable = mdTables[(int)Table.Field];
MethodPtrTable = mdTables[(int)Table.MethodPtr];
MethodTable = mdTables[(int)Table.Method];
ParamPtrTable = mdTables[(int)Table.ParamPtr];
ParamTable = mdTables[(int)Table.Param];
InterfaceImplTable = mdTables[(int)Table.InterfaceImpl];
MemberRefTable = mdTables[(int)Table.MemberRef];
ConstantTable = mdTables[(int)Table.Constant];
CustomAttributeTable = mdTables[(int)Table.CustomAttribute];
FieldMarshalTable = mdTables[(int)Table.FieldMarshal];
DeclSecurityTable = mdTables[(int)Table.DeclSecurity];
ClassLayoutTable = mdTables[(int)Table.ClassLayout];
FieldLayoutTable = mdTables[(int)Table.FieldLayout];
StandAloneSigTable = mdTables[(int)Table.StandAloneSig];
EventMapTable = mdTables[(int)Table.EventMap];
EventPtrTable = mdTables[(int)Table.EventPtr];
EventTable = mdTables[(int)Table.Event];
PropertyMapTable = mdTables[(int)Table.PropertyMap];
PropertyPtrTable = mdTables[(int)Table.PropertyPtr];
PropertyTable = mdTables[(int)Table.Property];
MethodSemanticsTable = mdTables[(int)Table.MethodSemantics];
MethodImplTable = mdTables[(int)Table.MethodImpl];
ModuleRefTable = mdTables[(int)Table.ModuleRef];
TypeSpecTable = mdTables[(int)Table.TypeSpec];
ImplMapTable = mdTables[(int)Table.ImplMap];
FieldRVATable = mdTables[(int)Table.FieldRVA];
ENCLogTable = mdTables[(int)Table.ENCLog];
ENCMapTable = mdTables[(int)Table.ENCMap];
AssemblyTable = mdTables[(int)Table.Assembly];
AssemblyProcessorTable = mdTables[(int)Table.AssemblyProcessor];
AssemblyOSTable = mdTables[(int)Table.AssemblyOS];
AssemblyRefTable = mdTables[(int)Table.AssemblyRef];
AssemblyRefProcessorTable = mdTables[(int)Table.AssemblyRefProcessor];
AssemblyRefOSTable = mdTables[(int)Table.AssemblyRefOS];
FileTable = mdTables[(int)Table.File];
ExportedTypeTable = mdTables[(int)Table.ExportedType];
ManifestResourceTable = mdTables[(int)Table.ManifestResource];
NestedClassTable = mdTables[(int)Table.NestedClass];
GenericParamTable = mdTables[(int)Table.GenericParam];
MethodSpecTable = mdTables[(int)Table.MethodSpec];
GenericParamConstraintTable = mdTables[(int)Table.GenericParamConstraint];
}
/// <inheritdoc/>
protected override void Dispose(bool disposing) {
if (disposing) {
var mt = mdTables;
if (mt != null) {
foreach (var mdTable in mt) {
if (mdTable != null)
mdTable.Dispose();
}
mdTables = null;
}
}
base.Dispose(disposing);
}
/// <summary>
/// Returns a MD table
/// </summary>
/// <param name="table">The table type</param>
/// <returns>A <see cref="MDTable"/> or <c>null</c> if table doesn't exist</returns>
public MDTable Get(Table table) {
int index = (int)table;
if ((uint)index >= (uint)mdTables.Length)
return null;
return mdTables[index];
}
/// <summary>
/// Checks whether a table exists
/// </summary>
/// <param name="table">The table type</param>
/// <returns><c>true</c> if the table exists</returns>
public bool HasTable(Table table) {
return (uint)table < (uint)mdTables.Length;
}
/// <summary>
/// Checks whether table <paramref name="table"/> is sorted
/// </summary>
/// <param name="table">The table</param>
public bool IsSorted(MDTable table) {
int index = (int)table.Table;
if ((uint)index >= 64)
return false;
return (sortedMask & (1UL << index)) != 0;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="DtdValidator.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Xml.Schema {
using System;
using System.Collections;
using System.Text;
using System.IO;
using System.Net;
using System.Diagnostics;
using System.Xml.Schema;
using System.Xml.XPath;
#pragma warning disable 618
internal sealed class DtdValidator : BaseValidator {
//required by ParseValue
class NamespaceManager : XmlNamespaceManager {
public override string LookupNamespace(string prefix) { return prefix; }
}
static NamespaceManager namespaceManager = new NamespaceManager();
const int STACK_INCREMENT = 10;
HWStack validationStack; // validaton contexts
Hashtable attPresence;
XmlQualifiedName name = XmlQualifiedName.Empty;
Hashtable IDs;
IdRefNode idRefListHead;
bool processIdentityConstraints;
internal DtdValidator(XmlValidatingReaderImpl reader, IValidationEventHandling eventHandling, bool processIdentityConstraints) : base(reader, null, eventHandling) {
this.processIdentityConstraints = processIdentityConstraints;
Init();
}
private void Init() {
Debug.Assert(reader != null);
validationStack = new HWStack(STACK_INCREMENT);
textValue = new StringBuilder();
name = XmlQualifiedName.Empty;
attPresence = new Hashtable();
schemaInfo = new SchemaInfo();
checkDatatype = false;
Push(name);
}
public override void Validate() {
if (schemaInfo.SchemaType == SchemaType.DTD) {
switch (reader.NodeType) {
case XmlNodeType.Element:
ValidateElement();
if (reader.IsEmptyElement) {
goto case XmlNodeType.EndElement;
}
break;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
if (MeetsStandAloneConstraint()) {
ValidateWhitespace();
}
break;
case XmlNodeType.ProcessingInstruction:
case XmlNodeType.Comment:
ValidatePIComment();
break;
case XmlNodeType.Text: // text inside a node
case XmlNodeType.CDATA: // <![CDATA[...]]>
ValidateText();
break;
case XmlNodeType.EntityReference:
if (!GenEntity( new XmlQualifiedName(reader.LocalName, reader.Prefix) ) ){
ValidateText();
}
break;
case XmlNodeType.EndElement:
ValidateEndElement();
break;
}
}
else {
if(reader.Depth == 0 &&
reader.NodeType == XmlNodeType.Element) {
SendValidationEvent(Res.Xml_NoDTDPresent, this.name.ToString(), XmlSeverityType.Warning);
}
}
}
private bool MeetsStandAloneConstraint() {
if (reader.StandAlone && // VC 1 - iv
context.ElementDecl != null &&
context.ElementDecl.IsDeclaredInExternal &&
context.ElementDecl.ContentValidator.ContentType == XmlSchemaContentType.ElementOnly) {
SendValidationEvent(Res.Sch_StandAlone);
return false;
}
return true;
}
private void ValidatePIComment() {
// When validating with a dtd, empty elements should be lexically empty.
if (context.NeedValidateChildren ) {
if (context.ElementDecl.ContentValidator == ContentValidator.Empty) {
SendValidationEvent(Res.Sch_InvalidPIComment);
}
}
}
private void ValidateElement() {
elementName.Init(reader.LocalName, reader.Prefix);
if ( (reader.Depth == 0) &&
(!schemaInfo.DocTypeName.IsEmpty) &&
(!schemaInfo.DocTypeName.Equals(elementName)) ){ //VC 1
SendValidationEvent(Res.Sch_RootMatchDocType);
}
else {
ValidateChildElement();
}
ProcessElement();
}
private void ValidateChildElement() {
Debug.Assert(reader.NodeType == XmlNodeType.Element);
if (context.NeedValidateChildren) { //i think i can get away with removing this if cond since won't make this call for documentelement
int errorCode = 0;
context.ElementDecl.ContentValidator.ValidateElement(elementName, context, out errorCode);
if (errorCode < 0) {
XmlSchemaValidator.ElementValidationError(elementName, context, EventHandler, reader, reader.BaseURI, PositionInfo.LineNumber, PositionInfo.LinePosition, null);
}
}
}
private void ValidateStartElement() {
if (context.ElementDecl != null) {
Reader.SchemaTypeObject = context.ElementDecl.SchemaType;
if (Reader.IsEmptyElement && context.ElementDecl.DefaultValueTyped != null) {
Reader.TypedValueObject = context.ElementDecl.DefaultValueTyped;
context.IsNill = true; // reusing IsNill - what is this flag later used for??
}
if ( context.ElementDecl.HasRequiredAttribute ) {
attPresence.Clear();
}
}
if (Reader.MoveToFirstAttribute()) {
do {
try {
reader.SchemaTypeObject = null;
SchemaAttDef attnDef = context.ElementDecl.GetAttDef( new XmlQualifiedName( reader.LocalName, reader.Prefix) );
if (attnDef != null) {
if (context.ElementDecl != null && context.ElementDecl.HasRequiredAttribute) {
attPresence.Add(attnDef.Name, attnDef);
}
Reader.SchemaTypeObject = attnDef.SchemaType;
if (attnDef.Datatype != null && !reader.IsDefault) { //Since XmlTextReader adds default attributes, do not check again
// set typed value
CheckValue(Reader.Value, attnDef);
}
}
else {
SendValidationEvent(Res.Sch_UndeclaredAttribute, reader.Name);
}
}
catch (XmlSchemaException e) {
e.SetSource(Reader.BaseURI, PositionInfo.LineNumber, PositionInfo.LinePosition);
SendValidationEvent(e);
}
} while(Reader.MoveToNextAttribute());
Reader.MoveToElement();
}
}
private void ValidateEndStartElement() {
if (context.ElementDecl.HasRequiredAttribute) {
try {
context.ElementDecl.CheckAttributes(attPresence, Reader.StandAlone);
}
catch (XmlSchemaException e) {
e.SetSource(Reader.BaseURI, PositionInfo.LineNumber, PositionInfo.LinePosition);
SendValidationEvent(e);
}
}
if (context.ElementDecl.Datatype != null) {
checkDatatype = true;
hasSibling = false;
textString = string.Empty;
textValue.Length = 0;
}
}
private void ProcessElement() {
SchemaElementDecl elementDecl = schemaInfo.GetElementDecl(elementName);
Push(elementName);
if (elementDecl != null) {
context.ElementDecl = elementDecl;
ValidateStartElement();
ValidateEndStartElement();
context.NeedValidateChildren = true;
elementDecl.ContentValidator.InitValidation( context );
}
else {
SendValidationEvent(Res.Sch_UndeclaredElement, XmlSchemaValidator.QNameString(context.LocalName, context.Namespace));
context.ElementDecl = null;
}
}
public override void CompleteValidation() {
if (schemaInfo.SchemaType == SchemaType.DTD) {
do {
ValidateEndElement();
} while (Pop());
CheckForwardRefs();
}
}
private void ValidateEndElement() {
if (context.ElementDecl != null) {
if (context.NeedValidateChildren) {
if(!context.ElementDecl.ContentValidator.CompleteValidation(context)) {
XmlSchemaValidator.CompleteValidationError(context, EventHandler, reader, reader.BaseURI, PositionInfo.LineNumber, PositionInfo.LinePosition, null);
}
}
if (checkDatatype) {
string stringValue = !hasSibling ? textString : textValue.ToString(); // only for identity-constraint exception reporting
CheckValue(stringValue, null);
checkDatatype = false;
textValue.Length = 0; // cleanup
textString = string.Empty;
}
}
Pop();
}
public override bool PreserveWhitespace {
get { return context.ElementDecl != null ? context.ElementDecl.ContentValidator.PreserveWhitespace : false; }
}
void ProcessTokenizedType(
XmlTokenizedType ttype,
string name
) {
switch(ttype) {
case XmlTokenizedType.ID:
if (processIdentityConstraints) {
if (FindId(name) != null) {
SendValidationEvent(Res.Sch_DupId, name);
}
else {
AddID(name, context.LocalName);
}
}
break;
case XmlTokenizedType.IDREF:
if (processIdentityConstraints) {
object p = FindId(name);
if (p == null) { // add it to linked list to check it later
idRefListHead = new IdRefNode(idRefListHead, name, this.PositionInfo.LineNumber, this.PositionInfo.LinePosition);
}
}
break;
case XmlTokenizedType.ENTITY:
ProcessEntity(schemaInfo, name, this, EventHandler, Reader.BaseURI, PositionInfo.LineNumber, PositionInfo.LinePosition);
break;
default:
break;
}
}
//check the contents of this attribute to ensure it is valid according to the specified attribute type.
private void CheckValue(string value, SchemaAttDef attdef) {
try {
reader.TypedValueObject = null;
bool isAttn = attdef != null;
XmlSchemaDatatype dtype = isAttn ? attdef.Datatype : context.ElementDecl.Datatype;
if (dtype == null) {
return; // no reason to check
}
if (dtype.TokenizedType != XmlTokenizedType.CDATA) {
value = value.Trim();
}
object typedValue = dtype.ParseValue(value, NameTable, namespaceManager);
reader.TypedValueObject = typedValue;
// Check special types
XmlTokenizedType ttype = dtype.TokenizedType;
if (ttype == XmlTokenizedType.ENTITY || ttype == XmlTokenizedType.ID || ttype == XmlTokenizedType.IDREF) {
if (dtype.Variety == XmlSchemaDatatypeVariety.List) {
string[] ss = (string[])typedValue;
for (int i = 0; i < ss.Length; ++i) {
ProcessTokenizedType(dtype.TokenizedType, ss[i]);
}
}
else {
ProcessTokenizedType(dtype.TokenizedType, (string)typedValue);
}
}
SchemaDeclBase decl = isAttn ? (SchemaDeclBase)attdef : (SchemaDeclBase)context.ElementDecl;
if (decl.Values != null && !decl.CheckEnumeration(typedValue)) {
if (dtype.TokenizedType == XmlTokenizedType.NOTATION) {
SendValidationEvent(Res.Sch_NotationValue, typedValue.ToString());
}
else {
SendValidationEvent(Res.Sch_EnumerationValue, typedValue.ToString());
}
}
if (!decl.CheckValue(typedValue)) {
if (isAttn) {
SendValidationEvent(Res.Sch_FixedAttributeValue, attdef.Name.ToString());
}
else {
SendValidationEvent(Res.Sch_FixedElementValue, XmlSchemaValidator.QNameString(context.LocalName, context.Namespace));
}
}
}
catch (XmlSchemaException) {
if (attdef != null) {
SendValidationEvent(Res.Sch_AttributeValueDataType, attdef.Name.ToString());
}
else {
SendValidationEvent(Res.Sch_ElementValueDataType, XmlSchemaValidator.QNameString(context.LocalName, context.Namespace));
}
}
}
internal void AddID(string name, object node) {
// Note: It used to be true that we only called this if _fValidate was true,
// but due to the fact that you can now dynamically type somethign as an ID
// that is no longer true.
if (IDs == null) {
IDs = new Hashtable();
}
IDs.Add(name, node);
}
public override object FindId(string name) {
return IDs == null ? null : IDs[name];
}
private bool GenEntity(XmlQualifiedName qname) {
string n = qname.Name;
if (n[0] == '#') { // char entity reference
return false;
}
else if (SchemaEntity.IsPredefinedEntity(n)) {
return false;
}
else {
SchemaEntity en = GetEntity(qname, false);
if (en == null) {
// well-formness error, see xml spec [68]
throw new XmlException(Res.Xml_UndeclaredEntity, n);
}
if (!en.NData.IsEmpty) {
// well-formness error, see xml spec [68]
throw new XmlException(Res.Xml_UnparsedEntityRef, n);
}
if (reader.StandAlone && en.DeclaredInExternal) {
SendValidationEvent(Res.Sch_StandAlone);
}
return true;
}
}
private SchemaEntity GetEntity(XmlQualifiedName qname, bool fParameterEntity) {
SchemaEntity entity;
if (fParameterEntity) {
if (schemaInfo.ParameterEntities.TryGetValue(qname, out entity)) {
return entity;
}
}
else {
if (schemaInfo.GeneralEntities.TryGetValue(qname, out entity)) {
return entity;
}
}
return null;
}
private void CheckForwardRefs() {
IdRefNode next = idRefListHead;
while (next != null) {
if(FindId(next.Id) == null) {
SendValidationEvent(new XmlSchemaException(Res.Sch_UndeclaredId, next.Id, reader.BaseURI, next.LineNo, next.LinePos));
}
IdRefNode ptr = next.Next;
next.Next = null; // unhook each object so it is cleaned up by Garbage Collector
next = ptr;
}
// not needed any more.
idRefListHead = null;
}
private void Push(XmlQualifiedName elementName) {
context = (ValidationState)validationStack.Push();
if (context == null) {
context = new ValidationState();
validationStack.AddToTop(context);
}
context.LocalName = elementName.Name;
context.Namespace = elementName.Namespace;
context.HasMatched = false;
context.IsNill = false;
context.NeedValidateChildren = false;
}
private bool Pop() {
if (validationStack.Length > 1) {
validationStack.Pop();
context = (ValidationState)validationStack.Peek();
return true;
}
return false;
}
public static void SetDefaultTypedValue(
SchemaAttDef attdef,
IDtdParserAdapter readerAdapter
) {
try {
string value = attdef.DefaultValueExpanded;
XmlSchemaDatatype dtype = attdef.Datatype;
if (dtype == null) {
return; // no reason to check
}
if (dtype.TokenizedType != XmlTokenizedType.CDATA) {
value = value.Trim();
}
attdef.DefaultValueTyped = dtype.ParseValue(value, readerAdapter.NameTable, readerAdapter.NamespaceResolver);
}
#if DEBUG
catch (XmlSchemaException ex) {
Debug.WriteLineIf(DiagnosticsSwitches.XmlSchema.TraceError, ex.Message);
#else
catch (Exception) {
#endif
IValidationEventHandling eventHandling = ((IDtdParserAdapterWithValidation)readerAdapter).ValidationEventHandling;
if (eventHandling != null) {
XmlSchemaException e = new XmlSchemaException(Res.Sch_AttributeDefaultDataType, attdef.Name.ToString());
eventHandling.SendEvent(e, XmlSeverityType.Error);
}
}
}
public static void CheckDefaultValue(
SchemaAttDef attdef,
SchemaInfo sinfo,
IValidationEventHandling eventHandling,
string baseUriStr
) {
try {
if (baseUriStr == null) {
baseUriStr = string.Empty;
}
XmlSchemaDatatype dtype = attdef.Datatype;
if (dtype == null) {
return; // no reason to check
}
object typedValue = attdef.DefaultValueTyped;
// Check special types
XmlTokenizedType ttype = dtype.TokenizedType;
if (ttype == XmlTokenizedType.ENTITY) {
if (dtype.Variety == XmlSchemaDatatypeVariety.List) {
string[] ss = (string[])typedValue;
for (int i = 0; i < ss.Length; ++i) {
ProcessEntity(sinfo, ss[i], eventHandling, baseUriStr, attdef.ValueLineNumber, attdef.ValueLinePosition);
}
}
else {
ProcessEntity(sinfo, (string)typedValue, eventHandling, baseUriStr, attdef.ValueLineNumber, attdef.ValueLinePosition);
}
}
else if (ttype == XmlTokenizedType.ENUMERATION) {
if (!attdef.CheckEnumeration(typedValue)) {
if (eventHandling != null) {
XmlSchemaException e = new XmlSchemaException(Res.Sch_EnumerationValue, typedValue.ToString(), baseUriStr, attdef.ValueLineNumber, attdef.ValueLinePosition);
eventHandling.SendEvent(e, XmlSeverityType.Error);
}
}
}
}
#if DEBUG
catch (XmlSchemaException ex) {
Debug.WriteLineIf(DiagnosticsSwitches.XmlSchema.TraceError, ex.Message);
#else
catch (Exception) {
#endif
if (eventHandling != null) {
XmlSchemaException e = new XmlSchemaException(Res.Sch_AttributeDefaultDataType, attdef.Name.ToString());
eventHandling.SendEvent(e, XmlSeverityType.Error);
}
}
}
}
#pragma warning restore 618
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
//using System.Collections.Generic;
using System.Timers;
using OpenMetaverse.Packets;
using OpenSim.Framework;
using OpenSim.Framework.Statistics;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Region.Framework.Scenes
{
public class SimStatsReporter
{
public delegate void SendStatResult(SimStats stats);
public delegate void YourStatsAreWrong();
public event SendStatResult OnSendStatsResult;
public event YourStatsAreWrong OnStatsIncorrect;
private SendStatResult handlerSendStatResult = null;
private YourStatsAreWrong handlerStatsIncorrect = null;
private enum Stats : uint
{
TimeDilation = 0,
SimFPS = 1,
PhysicsFPS = 2,
AgentUpdates = 3,
FrameMS = 4,
NetMS = 5,
OtherMS = 6,
PhysicsMS = 7,
AgentMS = 8,
ImageMS = 9,
ScriptMS = 10,
TotalPrim = 11,
ActivePrim = 12,
Agents = 13,
ChildAgents = 14,
ActiveScripts = 15,
ScriptLinesPerSecond = 16,
InPacketsPerSecond = 17,
OutPacketsPerSecond = 18,
PendingDownloads = 19,
PendingUploads = 20,
UnAckedBytes = 24,
}
// Sending a stats update every 3 seconds
private int statsUpdatesEveryMS = 3000;
private float statsUpdateFactor = 0;
private float m_timeDilation = 0;
private int m_fps = 0;
// saved last reported value so there is something available for llGetRegionFPS
private float lastReportedSimFPS = 0;
private float m_pfps = 0;
private int m_agentUpdates = 0;
private int m_frameMS = 0;
private int m_netMS = 0;
private int m_agentMS = 0;
private int m_physicsMS = 0;
private int m_imageMS = 0;
private int m_otherMS = 0;
//Ckrinke: (3-21-08) Comment out to remove a compiler warning. Bring back into play when needed.
//Ckrinke private int m_scriptMS = 0;
private int m_rootAgents = 0;
private int m_childAgents = 0;
private int m_numPrim = 0;
private int m_inPacketsPerSecond = 0;
private int m_outPacketsPerSecond = 0;
private int m_activePrim = 0;
private int m_unAckedBytes = 0;
private int m_pendingDownloads = 0;
private int m_pendingUploads = 0;
private int m_activeScripts = 0;
private int m_scriptLinesPerSecond = 0;
private int objectCapacity = RegionInfo.DEFAULT_REGION_PRIM_LIMIT;
private Scene m_scene;
private RegionInfo ReportingRegion;
private Timer m_report = new Timer();
private IEstateModule estateModule;
public SimStatsReporter(Scene scene)
{
statsUpdateFactor = (float)(statsUpdatesEveryMS / 1000);
m_scene = scene;
ReportingRegion = scene.RegionInfo;
m_report.AutoReset = true;
m_report.Interval = statsUpdatesEveryMS;
m_report.Elapsed += new ElapsedEventHandler(statsHeartBeat);
m_report.Enabled = true;
if (StatsManager.SimExtraStats != null)
OnSendStatsResult += StatsManager.SimExtraStats.ReceiveClassicSimStatsPacket;
}
public void SetUpdateMS(int ms)
{
statsUpdatesEveryMS = ms;
statsUpdateFactor = (float)(statsUpdatesEveryMS / 1000);
m_report.Interval = statsUpdatesEveryMS;
}
bool statsRunning = false;
private void statsHeartBeat(object sender, EventArgs e)
{
if (statsRunning) return;
try
{
statsRunning = true;
SimStatsPacket.StatBlock[] sb = new SimStatsPacket.StatBlock[21];
SimStatsPacket.RegionBlock rb = new SimStatsPacket.RegionBlock();
uint regionFlags = 0;
try
{
if (estateModule == null)
estateModule = m_scene.RequestModuleInterface<IEstateModule>();
regionFlags = estateModule != null ? estateModule.GetRegionFlags() : (uint)0;
}
catch (Exception)
{
// leave region flags at 0
}
float simfps = (int)m_fps;
// save the reported value so there is something available for llGetRegionFPS
lastReportedSimFPS = (float)simfps / statsUpdateFactor;
float physfps = m_pfps;
if (physfps < 0)
physfps = 0;
//Our time dilation is 0.91 when we're running a full speed,
// therefore to make sure we get an appropriate range,
// we have to factor in our error. (0.10f * statsUpdateFactor)
// multiplies the fix for the error times the amount of times it'll occur a second
// / 10 divides the value by the number of times the sim heartbeat runs (10fps)
// Then we divide the whole amount by the amount of seconds pass in between stats updates.
for (int i = 0; i < 21; i++)
{
sb[i] = new SimStatsPacket.StatBlock();
}
sb[0].StatID = (uint)Stats.TimeDilation;
sb[0].StatValue = (Single.IsNaN(m_timeDilation)) ? 0.1f : m_timeDilation; //((((m_timeDilation + (0.10f * statsUpdateFactor)) /10) / statsUpdateFactor));
sb[1].StatID = (uint)Stats.SimFPS;
sb[1].StatValue = simfps / statsUpdateFactor;
sb[2].StatID = (uint)Stats.PhysicsFPS;
sb[2].StatValue = physfps;
sb[3].StatID = (uint)Stats.AgentUpdates;
sb[3].StatValue = (m_agentUpdates / statsUpdateFactor);
sb[4].StatID = (uint)Stats.Agents;
sb[4].StatValue = m_rootAgents;
sb[5].StatID = (uint)Stats.ChildAgents;
sb[5].StatValue = m_childAgents;
sb[6].StatID = (uint)Stats.TotalPrim;
sb[6].StatValue = m_numPrim;
sb[7].StatID = (uint)Stats.ActivePrim;
sb[7].StatValue = m_activePrim;
sb[8].StatID = (uint)Stats.FrameMS;
sb[8].StatValue = m_frameMS / statsUpdateFactor;
sb[9].StatID = (uint)Stats.NetMS;
sb[9].StatValue = m_netMS / statsUpdateFactor;
sb[10].StatID = (uint)Stats.PhysicsMS;
sb[10].StatValue = m_physicsMS / statsUpdateFactor;
sb[11].StatID = (uint)Stats.ImageMS;
sb[11].StatValue = m_imageMS / statsUpdateFactor;
sb[12].StatID = (uint)Stats.OtherMS;
sb[12].StatValue = m_otherMS / statsUpdateFactor;
sb[13].StatID = (uint)Stats.InPacketsPerSecond;
sb[13].StatValue = (m_inPacketsPerSecond);
sb[14].StatID = (uint)Stats.OutPacketsPerSecond;
sb[14].StatValue = (m_outPacketsPerSecond / statsUpdateFactor);
sb[15].StatID = (uint)Stats.UnAckedBytes;
sb[15].StatValue = m_unAckedBytes;
sb[16].StatID = (uint)Stats.AgentMS;
sb[16].StatValue = m_agentMS / statsUpdateFactor;
sb[17].StatID = (uint)Stats.PendingDownloads;
sb[17].StatValue = m_pendingDownloads;
sb[18].StatID = (uint)Stats.PendingUploads;
sb[18].StatValue = m_pendingUploads;
sb[19].StatID = (uint)Stats.ActiveScripts;
sb[19].StatValue = m_activeScripts;
sb[20].StatID = (uint)Stats.ScriptLinesPerSecond;
sb[20].StatValue = m_scriptLinesPerSecond / statsUpdateFactor;
SimStats simStats
= new SimStats(
ReportingRegion.RegionLocX, ReportingRegion.RegionLocY, regionFlags, (uint)objectCapacity, rb, sb, m_scene.RegionInfo.originRegionID);
handlerSendStatResult = OnSendStatsResult;
if (handlerSendStatResult != null)
{
handlerSendStatResult(simStats);
}
resetvalues();
}
finally
{
statsRunning = false;
}
}
private void resetvalues()
{
m_timeDilation = 0;
m_fps = 0;
m_pfps = 0;
m_agentUpdates = 0;
m_inPacketsPerSecond = 0;
m_outPacketsPerSecond = 0;
m_unAckedBytes = 0;
m_scriptLinesPerSecond = 0;
m_frameMS = 0;
m_agentMS = 0;
m_netMS = 0;
m_physicsMS = 0;
m_imageMS = 0;
m_otherMS = 0;
//Ckrinke This variable is not used, so comment to remove compiler warning until it is used.
//Ckrinke m_scriptMS = 0;
}
# region methods called from Scene
// The majority of these functions are additive
// so that you can easily change the amount of
// seconds in between sim stats updates
public void AddTimeDilation(float td)
{
m_timeDilation = td;
}
public void SetRootAgents(int rootAgents)
{
m_rootAgents = rootAgents;
CheckStatSanity();
}
internal void CheckStatSanity()
{
if (m_rootAgents < 0 || m_childAgents < 0)
{
handlerStatsIncorrect = OnStatsIncorrect;
if (handlerStatsIncorrect != null)
{
handlerStatsIncorrect();
}
}
if (m_rootAgents == 0 && m_childAgents == 0)
{
m_unAckedBytes = 0;
}
}
public void SetChildAgents(int childAgents)
{
m_childAgents = childAgents;
CheckStatSanity();
}
public void SetObjects(int objects)
{
m_numPrim = objects;
}
public void SetActiveObjects(int objects)
{
m_activePrim = objects;
}
public void AddFPS(int frames)
{
m_fps += frames;
}
public void SetPhysicsFPS(float frames)
{
m_pfps = frames;
}
public void AddAgentUpdates(int numUpdates)
{
m_agentUpdates += numUpdates;
}
public void AddInPackets(int numPackets)
{
m_inPacketsPerSecond += numPackets;
}
public void AddOutPackets(int numPackets)
{
m_outPacketsPerSecond += numPackets;
}
public void AddunAckedBytes(int numBytes)
{
m_unAckedBytes += numBytes;
if (m_unAckedBytes < 0) m_unAckedBytes = 0;
}
public void addFrameMS(int ms)
{
m_frameMS += ms;
}
public void addNetMS(int ms)
{
m_netMS += ms;
}
public void addAgentMS(int ms)
{
m_agentMS += ms;
}
public void addPhysicsMS(int ms)
{
m_physicsMS += ms;
}
public void addImageMS(int ms)
{
m_imageMS += ms;
}
public void addOtherMS(int ms)
{
m_otherMS += ms;
}
// private static readonly log4net.ILog m_log
// = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public void AddPendingDownloads(int count)
{
m_pendingDownloads += count;
if (m_pendingDownloads < 0) m_pendingDownloads = 0;
//m_log.InfoFormat("[stats]: Adding {0} to pending downloads to make {1}", count, m_pendingDownloads);
}
public void addScriptLines(int count)
{
m_scriptLinesPerSecond += count;
}
public void SetActiveScripts(int count)
{
m_activeScripts = count;
}
public void SetObjectCapacity(int objects)
{
objectCapacity = objects;
}
/// <summary>
/// This is for llGetRegionFPS
/// </summary>
public float getLastReportedSimFPS()
{
return lastReportedSimFPS;
}
public void AddPacketsStats(int inPackets, int outPackets, int unAckedBytes)
{
AddInPackets(inPackets);
AddOutPackets(outPackets);
AddunAckedBytes(unAckedBytes);
}
public void AddAgentTime(int ms)
{
addFrameMS(ms);
addAgentMS(ms);
}
#endregion
}
}
| |
// 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.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml;
using OpenLiveWriter.CoreServices;
namespace OpenLiveWriter.PostEditor
{
/// <summary>
/// Speeds up lookups of wpost files by caching the blogid and postid of each file.
/// </summary>
public class PostEditorFileLookupCache
{
public delegate PostKey PostKeyGenerator(FileInfo file);
private readonly DirectoryInfo dir;
private readonly string cacheFilename;
private readonly PostKeyGenerator pkg;
private readonly string pattern;
protected PostEditorFileLookupCache(DirectoryInfo dir, string cacheFilename, PostKeyGenerator pkg, string pattern)
{
this.dir = dir;
this.cacheFilename = cacheFilename;
this.pkg = pkg;
this.pattern = pattern;
}
public static FileInfo Lookup(DirectoryInfo dir, string cacheFilename, PostKeyGenerator pkg, string pattern, string blogId, string postId)
{
return new PostEditorFileLookupCache(dir, cacheFilename, pkg, pattern).Lookup(blogId, postId);
}
protected FileInfo Lookup(string blogId, string postId)
{
if (string.IsNullOrEmpty(blogId) || string.IsNullOrEmpty(postId))
{
Debug.Fail("Doesn't make sense to lookup blogId or postId that is null/empty");
return null;
}
Dictionary<FileIdentity, PostKey> cache = GetCache();
foreach (KeyValuePair<FileIdentity, PostKey> pair in cache)
if (pair.Value.BlogId == blogId && pair.Value.PostId == postId)
return new FileInfo(Path.Combine(dir.FullName, pair.Key.Filename));
return null;
}
private Dictionary<FileIdentity, PostKey> GetCache()
{
// Ensure that the cache is fully up to date with respect to
// what's actually on disk.
Dictionary<FileIdentity, PostKey> filesInCache = LoadCache();
bool dirty = false;
// Read all files on disk--this is cheap since we don't actually look inside them
Dictionary<string, FileIdentity> filesOnDisk = new Dictionary<string, FileIdentity>();
foreach (FileInfo fi in dir.GetFiles(pattern, SearchOption.TopDirectoryOnly))
filesOnDisk.Add(fi.Name, new FileIdentity(fi));
// Remove any entries in the cache that are either no longer on disk or are
// stale (file on disk has changed, according to size or last modified).
// For any entries that are on disk and have an up-to-date copy in the cache,
// remove from filesOnDisk to ensure they get ignored for the next step.
// This step should also be cheap, no I/O involved.
foreach (FileIdentity fid in new List<FileIdentity>(filesInCache.Keys))
{
FileIdentity fidDisk;
if (!filesOnDisk.TryGetValue(fid.Filename, out fidDisk))
fidDisk = null;
if (fidDisk == null || !fidDisk.Equals(fid))
{
dirty = true;
filesInCache.Remove(fid);
}
else
filesOnDisk.Remove(fid.Filename);
}
// Anything left in filesOnDisk needs to be added to the cache, expensively.
if (filesOnDisk.Count > 0)
{
foreach (FileIdentity fid in filesOnDisk.Values)
{
PostKey postKey = pkg(new FileInfo(Path.Combine(dir.FullName, fid.Filename)));
if (postKey != null)
{
dirty = true;
filesInCache[fid] = postKey;
}
}
}
// Only persist if changes were made
if (dirty)
{
SaveCache(filesInCache);
}
return filesInCache;
}
private Dictionary<FileIdentity, PostKey> LoadCache()
{
string cacheFile = CacheFile;
if (File.Exists(cacheFile))
{
try
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(cacheFile);
Dictionary<FileIdentity, PostKey> result = new Dictionary<FileIdentity, PostKey>();
foreach (XmlElement el in xmlDoc.SelectNodes("/cache/file"))
{
string filename = el.GetAttribute("name");
DateTime lastModified = new DateTime(long.Parse(el.GetAttribute("ticks"), CultureInfo.InvariantCulture), DateTimeKind.Utc);
long size = long.Parse(el.GetAttribute("size"), CultureInfo.InvariantCulture);
string blogId = el.GetAttribute("blogId");
string postId = el.GetAttribute("postId");
if (string.IsNullOrEmpty(filename))
{
Trace.Fail("Corrupted entry in cache");
continue;
}
result.Add(new FileIdentity(filename, lastModified, size), new PostKey(blogId, postId));
}
return result;
}
catch (Exception e)
{
Trace.WriteLine("Failed to load post cache file " + cacheFile + ": " + e.ToString());
}
}
return new Dictionary<FileIdentity, PostKey>();
}
private string CacheFile
{
get { return Path.Combine(dir.FullName, cacheFilename); }
}
private void SaveCache(Dictionary<FileIdentity, PostKey> cache)
{
XmlDocument xmlDoc = new XmlDocument();
XmlElement cacheEl = xmlDoc.CreateElement("cache");
xmlDoc.AppendChild(cacheEl);
foreach (KeyValuePair<FileIdentity, PostKey> pair in cache)
{
XmlElement fileEl = xmlDoc.CreateElement("file");
fileEl.SetAttribute("name", pair.Key.Filename);
fileEl.SetAttribute("ticks", pair.Key.LastModified.Ticks.ToString(CultureInfo.InvariantCulture));
fileEl.SetAttribute("size", pair.Key.Size.ToString(CultureInfo.InvariantCulture));
fileEl.SetAttribute("blogId", pair.Value.BlogId);
fileEl.SetAttribute("postId", pair.Value.PostId);
cacheEl.AppendChild(fileEl);
}
xmlDoc.Save(CacheFile);
}
public class PostKey : IEquatable<PostKey>
{
private readonly string blogId;
private readonly string postId;
public PostKey(string blogId, string postId)
{
this.blogId = blogId ?? "";
this.postId = postId ?? "";
}
public string BlogId
{
get { return blogId; }
}
public string PostId
{
get { return postId; }
}
public bool Equals(PostKey postKey)
{
if (postKey == null) return false;
return Equals(blogId, postKey.blogId) && Equals(postId, postKey.postId);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(this, obj)) return true;
return Equals(obj as PostKey);
}
public override int GetHashCode()
{
return (blogId != null ? blogId.GetHashCode() : 0) + 29*(postId != null ? postId.GetHashCode() : 0);
}
}
public class FileIdentity : IEquatable<FileIdentity>
{
private readonly string filename;
private readonly DateTime lastModified;
private readonly long size;
public FileIdentity(string filename, DateTime lastModified, long size)
{
this.filename = filename;
this.lastModified = lastModified;
this.size = size;
}
public FileIdentity(FileInfo fi)
{
filename = fi.Name;
lastModified = fi.LastWriteTimeUtc;
size = fi.Length;
}
public string Filename
{
get { return filename; }
}
public DateTime LastModified
{
get { return lastModified; }
}
public long Size
{
get { return size; }
}
public bool Equals(FileIdentity fileIdentity)
{
if (fileIdentity == null) return false;
if (!Equals(filename, fileIdentity.filename)) return false;
if (!Equals(lastModified, fileIdentity.lastModified)) return false;
if (size != fileIdentity.size) return false;
return true;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(this, obj)) return true;
return Equals(obj as FileIdentity);
}
public override int GetHashCode()
{
int result = filename.GetHashCode();
result = 29*result + lastModified.GetHashCode();
result = 29*result + (int) size;
return result;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using Votter.Services.Areas.HelpPage.ModelDescriptions;
using Votter.Services.Areas.HelpPage.Models;
namespace Votter.Services.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
//---------------------------------------------------------------------------------------------
// Torque Game Builder
// Copyright (C) GarageGames.com, Inc.
//---------------------------------------------------------------------------------------------
$Gui::fontCacheDirectory = expandFilename("~/data/fonts");
//---------------------------------------------------------------------------------------------
// GuiDefaultProfile is a special profile that all other profiles inherit defaults from. It
// must exist.
//---------------------------------------------------------------------------------------------
if(!isObject(GuiDefaultProfile)) new GuiControlProfile (GuiDefaultProfile)
{
tab = false;
canKeyFocus = false;
hasBitmapArray = false;
mouseOverSelected = false;
// fill color
opaque = false;
fillColor = "211 211 211";
fillColorHL = "244 244 244";
fillColorNA = "244 244 244";
// border color
border = 1;
borderColor = "40 40 40 100";
borderColorHL = "128 128 128";
borderColorNA = "64 64 64";
// font
fontType = "Arial";
fontSize = 14;
fontColor = "0 0 0";
fontColorHL = "32 100 100";
fontColorNA = "0 0 0";
fontColorSEL= "200 200 200";
// bitmap information
bitmap = "./images/window";
bitmapBase = "";
textOffset = "0 0";
// used by guiTextControl
modal = true;
justify = "left";
autoSizeWidth = false;
autoSizeHeight = false;
returnTab = false;
numbersOnly = false;
cursorColor = "0 0 0 255";
// sounds
soundButtonDown = "";
soundButtonOver = "";
};
if(!isObject(GuiSolidDefaultProfile)) new GuiControlProfile (GuiSolidDefaultProfile)
{
opaque = true;
border = true;
};
if(!isObject(GuiTransparentProfile)) new GuiControlProfile (GuiTransparentProfile)
{
opaque = false;
border = false;
};
if(!isObject(GuiToolTipProfile)) new GuiControlProfile (GuiToolTipProfile)
{
// fill color
fillColor = "239 237 222";
// border color
borderColor = "138 134 122";
// font
fontType = "Arial";
fontSize = 14;
fontColor = "0 0 0";
};
if(!isObject(GuiModelessDialogProfile)) new GuiControlProfile("GuiModelessDialogProfile")
{
modal = false;
};
if(!isObject(GuiFrameSetProfile)) new GuiControlProfile (GuiFrameSetProfile)
{
fillColor = "239 237 222";
borderColor = "138 134 122";
opaque = true;
border = true;
};
if(!isObject(GuiWindowProfile)) new GuiControlProfile (GuiWindowProfile)
{
opaque = true;
border = 1;
fillColor = "211 211 211";
fillColorHL = "190 255 255";
fillColorNA = "255 255 255";
fontColor = "0 0 0";
fontColorHL = "200 200 200";
text = "untitled";
bitmap = "./images/window";
textOffset = "5 5";
hasBitmapArray = true;
justify = "center";
};
if(!isObject(GuiContentProfile)) new GuiControlProfile (GuiContentProfile)
{
opaque = true;
fillColor = "255 255 255";
};
if(!isObject(GuiBlackContentProfile)) new GuiControlProfile (GuiBlackContentProfile)
{
opaque = true;
fillColor = "0 0 0";
};
if(!isObject(GuiInputCtrlProfile)) new GuiControlProfile( GuiInputCtrlProfile )
{
tab = true;
canKeyFocus = true;
};
if(!isObject(GuiTextProfile)) new GuiControlProfile (GuiTextProfile)
{
fontColor = "0 0 0";
};
if(!isObject(GuiMediumTextProfile)) new GuiControlProfile (GuiMediumTextProfile : GuiTextProfile)
{
fontSize = 24;
};
if(!isObject(GuiBigTextProfile)) new GuiControlProfile (GuiBigTextProfile : GuiTextProfile)
{
fontSize = 36;
};
if(!isObject(GuiMLTextProfile)) new GuiControlProfile ("GuiMLTextProfile")
{
fontColorLink = "255 96 96";
fontColorLinkHL = "0 0 255";
autoSizeWidth = true;
autoSizeHeight = true;
border = false;
};
if(!isObject(GuiTextArrayProfile)) new GuiControlProfile (GuiTextArrayProfile : GuiTextProfile)
{
fontColorHL = "32 100 100";
fillColorHL = "200 200 200";
};
if(!isObject(GuiTextListProfile)) new GuiControlProfile (GuiTextListProfile : GuiTextProfile)
{
tab = true;
canKeyFocus = true;
};
if(!isObject(GuiTextEditProfile)) new GuiControlProfile (GuiTextEditProfile)
{
opaque = true;
fillColor = "255 255 255";
fillColorHL = "128 128 128";
border = -2;
bitmap = "./images/textEdit";
borderColor = "40 40 40 100";
fontColor = "0 0 0";
fontColorHL = "255 255 255";
fontColorNA = "128 128 128";
textOffset = "4 2";
autoSizeWidth = false;
autoSizeHeight = true;
tab = true;
canKeyFocus = true;
};
if(!isObject(GuiProgressProfile)) new GuiControlProfile ("GuiProgressProfile")
{
opaque = false;
fillColor = "44 152 162 100";
border = true;
borderColor = "78 88 120";
};
if(!isObject(GuiProgressTextProfile)) new GuiControlProfile ("GuiProgressTextProfile")
{
fontColor = "0 0 0";
justify = "center";
};
if(!isObject(GuiButtonProfile)) new GuiControlProfile (GuiButtonProfile)
{
opaque = true;
border = -1;
fontColor = "0 0 0";
fontColorHL = "32 100 100";
fixedExtent = true;
justify = "center";
canKeyFocus = false;
bitmap = "./images/button";
};
if(!isObject(GuiCheckBoxProfile)) new GuiControlProfile (GuiCheckBoxProfile)
{
opaque = false;
fillColor = "232 232 232";
border = false;
borderColor = "0 0 0";
fontSize = 14;
fontColor = "0 0 0";
fontColorHL = "32 100 100";
fixedExtent = true;
justify = "left";
bitmap = "./images/checkBox";
hasBitmapArray = true;
};
if(!isObject(GuiRadioProfile)) new GuiControlProfile (GuiRadioProfile)
{
fontSize = 14;
fillColor = "232 232 232";
fontColorHL = "32 100 100";
fixedExtent = true;
bitmap = "./images/radioButton";
hasBitmapArray = true;
};
if(!isObject(GuiScrollProfile)) new GuiControlProfile (GuiScrollProfile)
{
opaque = true;
fillColor = "255 255 255";
border = 1;
borderThickness = 2;
bitmap = "./images/scrollBar";
hasBitmapArray = true;
};
if(!isObject(GuiTransparentScrollProfile)) new GuiControlProfile (GuiTransparentScrollProfile)
{
opaque = false;
fillColor = "255 255 255";
border = false;
borderThickness = 2;
borderColor = "0 0 0";
bitmap = "./images/scrollBar";
hasBitmapArray = true;
};
if(!isObject(GuiSliderProfile)) new GuiControlProfile (GuiSliderProfile)
{
bitmap = "./images/slider";
};
if(!isObject(GuiPaneProfile)) new GuiControlProfile(GuiPaneProfile)
{
bitmap = "./images/popupMenu";
hasBitmapArray = true;
};
if(!isObject(GuiPopupMenuItemBorder)) new GuiControlProfile ( GuiPopupMenuItemBorder : GuiButtonProfile )
{
borderColor = "51 51 53 200";
borderColorHL = "51 51 53 200";
};
if(!isObject(GuiPopUpMenu)) new GuiControlProfile (GuiPopUpMenuDefault : GuiDefaultProfile )
{
opaque = true;
mouseOverSelected = true;
textOffset = "3 3";
border = 4;
borderThickness = 2;
fixedExtent = true;
bitmap = "./images/scrollBar";
hasBitmapArray = true;
profileForChildren = GuiPopupMenuItemBorder;
fillColor = "255 255 255 200";
fontColorHL = "128 128 128";
borderColor = "151 151 153 175";
borderColorHL = "151 151 153 175";
};
if(!isObject(GuiPopUpMenuProfile)) new GuiControlProfile (GuiPopUpMenuProfile : GuiPopUpMenuDefault)
{
textOffset = "6 3";
bitmap = "./images/dropDown";
hasBitmapArray = true;
border = -3;
profileForChildren = GuiPopUpMenuDefault;
};
if(!isObject(GuiPopUpMenuEditProfile)) new GuiControlProfile (GuiPopUpMenuEditProfile : GuiPopUpMenuDefault)
{
textOffset = "6 3";
canKeyFocus = true;
bitmap = "./images/dropDown";
hasBitmapArray = true;
border = -3;
profileForChildren = GuiPopUpMenuDefault;
};
if(!isObject(GuiListBoxProfile)) new GuiControlProfile (GuiListBoxProfile)
{
tab = true;
canKeyFocus = true;
};
if(!isObject(GuiTabBookProfile)) new GuiControlProfile (GuiTabBookProfile)
{
fillColor = "255 255 255";
fillColorHL = "64 150 150";
fillColorNA = "150 150 150";
fontColor = "30 30 30";
fontColorHL = "32 100 100";
fontColorNA = "0 0 0";
fontType = "Arial Bold";
fontSize = 14;
justify = "center";
bitmap = "./images/tab";
tabWidth = 64;
tabHeight = 24;
tabPosition = "Top";
tabRotation = "Horizontal";
textOffset = "0 -2";
tab = true;
cankeyfocus = true;
};
if(!isObject(GuiTabPageProfile)) new GuiControlProfile (GuiTabPageProfile : GuiTransparentProfile )
{
fillColor = "255 255 255";
opaque = true;
};
if(!isObject(GuiMenuBarProfile)) new GuiControlProfile (GuiMenuBarProfile)
{
fontType = "Arial";
fontSize = 15;
opaque = true;
fillColor = "239 237 222";
fillColorHL = "102 153 204";
borderColor = "138 134 122";
borderColorHL = "0 51 153";
border = 5;
fontColor = "0 0 0";
fontColorHL = "255 255 255";
fontColorNA = "128 128 128";
fixedExtent = true;
justify = "center";
canKeyFocus = false;
mouseOverSelected = true;
bitmap = "./images/menu";
hasBitmapArray = true;
};
if(!isObject(GuiConsoleProfile)) new GuiControlProfile (GuiConsoleProfile)
{
fontType = ($platform $= "macos") ? "Monaco" : "Lucida Console";
fontSize = ($platform $= "macos") ? 13 : 12;
fontColor = "0 0 0";
fontColorHL = "130 130 130";
fontColorNA = "255 0 0";
fontColors[6] = "50 50 50";
fontColors[7] = "50 50 0";
fontColors[8] = "0 0 50";
fontColors[9] = "0 50 0";
};
if(!isObject(GuiConsoleTextEditProfile)) new GuiControlProfile (GuiConsoleTextEditProfile : GuiTextEditProfile)
{
fontType = ($platform $= "macos") ? "Monaco" : "Lucida Console";
fontSize = ($platform $= "macos") ? 13 : 12;
};
if (!isObject(GuiTreeViewProfile)) new GuiControlProfile (GuiTreeViewProfile)
{
fillColorHL = "0 60 150";
fontSize = 14;
fontColor = "0 0 0";
fontColorHL = "64 150 150";
fontColorNA = "240 240 240";
fontColorSEL= "250 250 250";
bitmap = "./images/treeView";
canKeyFocus = true;
autoSizeHeight = true;
};
//*** DAW:
if(!isObject(GuiText24Profile)) new GuiControlProfile (GuiText24Profile : GuiTextProfile)
{
fontSize = 24;
};
if(!isObject(GuiRSSFeedMLTextProfile)) new GuiControlProfile ("GuiRSSFeedMLTextProfile")
{
fontColorLink = "55 55 255";
fontColorLinkHL = "255 55 55";
};
| |
using System;
using System.Threading;
using MonoBrick;
using System.Diagnostics;
using System.Collections.Generic;
namespace MonoBrick.NXT
{
#region Base Sensor
/// <summary>
/// Sensor ports
/// </summary>
public enum SensorPort {
#pragma warning disable
In1 = 0, In2 = 1, In3 = 2, In4 = 3
#pragma warning restore
};
/// <summary>
/// Sensor types
/// </summary>
public enum SensorType {
#pragma warning disable
NoSensor = 0x00, Touch = 0x01, Temperature = 0x02, Reflection = 0x03, Angle = 0x04, LightActive = 0x05,
LightInactive = 0x06, SoundDB = 0x07, SoundDBA = 0x08, Custom = 0x09,LowSpeed = 0x0A, LowSpeed9V = 0x0B,
HighSpeed = 0x0C, ColorFull = 0x0D, ColorRed = 0x0E, ColorGreen = 0x0F, ColorBlue = 0x10, ColorNone = 0x11,
ColorExit = 0x12
#pragma warning restore
};
/// <summary>
/// Sensor modes
/// </summary>
public enum SensorMode {
#pragma warning disable
Raw = 0x00, Bool = 0x20, Transition = 0x40, Period = 0x60, Percent = 0x80,
Celsius = 0xA0, Fahrenheit = 0xc0, Angle = 0xe0
#pragma warning restore
};
internal class SensorReadings{
public UInt16 Raw;//device dependent
public UInt16 Normalized;//type dependent
public Int16 Scaled;//mode dependent
//public Int32 Calibrated;//not used
}
/// <summary>
/// Analog Sensor class. Works as base class for all NXT sensors
/// </summary>
public class Sensor : ISensor
{
/// <summary>
/// The sensor port to use
/// </summary>
protected SensorPort port;
/// <summary>
/// The connection to use for communication
/// </summary>
protected Connection<Command,Reply> connection = null;
/// <summary>
/// The sensor mode to use
/// </summary>
protected SensorMode Mode{get;private set;}
/// <summary>
/// The sensor type to use
/// </summary>
protected SensorType Type{get;private set;}
/// <summary>
/// True if sensor has been initialized
/// </summary>
protected bool hasInit;
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.NXT.Sensor"/> class with no sensor as type.
/// </summary>
public Sensor()
{
Mode = SensorMode.Raw;
Type = SensorType.NoSensor;
}
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.NXT.Sensor"/> class.
/// </summary>
/// <param name='sensorType'>
/// Sensor type
/// </param>
/// <param name='sensorMode'>
/// Sensor mode
/// </param>
public Sensor(SensorType sensorType, SensorMode sensorMode)
{
Mode = sensorMode;
Type = sensorType;
}
/// <summary>
/// Resets the scaled value.
/// </summary>
protected void ResetScaledValue(){
ResetScaledValue(false);
}
/// <summary>
/// Resets the scaled value.
/// </summary>
/// <param name='reply'>
/// If set to <c>true</c> brick will send a reply
/// </param>
protected void ResetScaledValue(bool reply){
var command = new Command(CommandType.DirecCommand, CommandByte.ResetInputScaledValue, reply);
command.Append((byte)port);
connection.Send(command);
if (reply) {
var brickReply = connection.Receive();
Error.CheckForError(brickReply, 3);
}
}
/// <summary>
/// Updates the sensor type and mode.
/// </summary>
/// <param name='sensorType'>
/// Sensor type.
/// </param>
/// <param name='sensorMode'>
/// Sensor mode.
/// </param>
protected void UpdateTypeAndMode(SensorType sensorType, SensorMode sensorMode){
Type = sensorType;
Mode = sensorMode;
var command = new Command(CommandType.DirecCommand, CommandByte.SetInputMode, true);
command.Append((byte)port);
command.Append((byte)Type);
command.Append((byte)Mode);
connection.Send(command);
var reply = connection.Receive();
Error.CheckForError(reply, 3);
}
internal SensorPort Port{
get{ return port;}
set{ port = value;}
}
internal Connection<Command,Reply> Connection{
get{ return connection;}
set{ connection = value;}
}
internal SensorReadings GetSensorReadings()
{
if (!hasInit)
{
Initialize();
}
SensorReadings sensorReadings = new SensorReadings();
var command = new Command(CommandType.DirecCommand,CommandByte.GetInputValues, true);
command.Append((byte) port);
var reply = connection.SendAndReceive(command);
Error.CheckForError(reply, 16);
sensorReadings.Raw = reply.GetUInt16(8);
sensorReadings.Normalized = reply.GetUInt16(10);
sensorReadings.Scaled = reply.GetInt16(12);
return sensorReadings;
}
/// <summary>
/// Read mode dependent sensor value
/// </summary>
/// <returns>
/// The scaled value
/// </returns>
protected Int16 GetScaledValue()
{
return GetSensorReadings().Scaled;
}
/// <summary>
/// Read device dependent sensor value
/// </summary>
/// <returns>
/// The raw value.
/// </returns>
protected UInt16 GetRawValue()
{
return GetSensorReadings().Raw;
}
/// <summary>
/// Read type dependent sensor value
/// </summary>
/// <returns>
/// The normalized value.
/// </returns>
protected UInt16 GetNormalizedValue()
{
return GetSensorReadings().Normalized;
}
/*protected Int32 CalibratedValue(){
return GetSensorValues().Scaled;
}*/
/// <summary>
/// Initialize this sensor
/// </summary>
virtual public void Initialize()
{
//Console.WriteLine("Sensor " + Port + " init");
if (connection != null && connection.IsConnected)
{
UpdateTypeAndMode(Type, Mode);
Thread.Sleep(100);
ResetScaledValue();
Thread.Sleep(100);
UpdateTypeAndMode(Type, Mode);
hasInit = true;
}
else
{
hasInit = false;
}
}
/// <summary>
/// Reset the sensor
/// </summary>
/// <param name='reply'>
/// If set to <c>true</c> the brick will send a reply
/// </param>
virtual public void Reset(bool reply) {
ResetScaledValue(reply);
}
/// <summary>
/// Reads the sensor value as a string.
/// </summary>
/// <returns>
/// The value as a string
/// </returns>
virtual public string ReadAsString()
{
return GetScaledValue().ToString();
}
/// <summary>
/// Gets a value indicating whether the sensor has been initialized.
/// </summary>
/// <value>
/// <c>true</c> if the sensor is initialized; otherwise, <c>false</c>.
/// </value>
public bool IsInitialized{get{return hasInit;}}
/// <summary>
/// Gets a dictionary of sensors that has been implemented. Can be use in a combobox or simular
/// </summary>
/// <value>The sensor dictionary.</value>
public static Dictionary<string,Sensor> SensorDictionary{
get{
Dictionary<string,Sensor> dictionary = new Dictionary<string, Sensor>();
dictionary.Add("None" , new NoSensor());
dictionary.Add("HiTechnic Color",new HiTecColor());
dictionary.Add("HiTechnic Compass", new HiTecCompass());
dictionary.Add("HiTechnic Gyro", new HiTecGyro(0));
dictionary.Add("HiTechnic Tilt", new HiTecTilt());
dictionary.Add("NXT Color", new NXTColorSensor());
dictionary.Add("NXT Color Reflection Pct", new NXTColorSensor(SensorMode.Percent));
dictionary.Add("NXT Color Reflection Raw", new NXTColorSensor(SensorMode.Raw));
dictionary.Add("NXT Color Inactive Pct", new NXTColorSensor(ColorMode.None,SensorMode.Percent));
dictionary.Add("NXT Color Inactive Raw", new NXTColorSensor(ColorMode.None,SensorMode.Raw));
dictionary.Add("NXT Light Active Pct", new NXTLightSensor(LightMode.On,SensorMode.Percent));
dictionary.Add("NXT Light Active Raw", new NXTLightSensor(LightMode.On,SensorMode.Raw));
dictionary.Add("NXT Light Inactive Pct", new NXTLightSensor(LightMode.Off,SensorMode.Percent));
dictionary.Add("NXT Light Inactive Raw", new NXTLightSensor(LightMode.Off,SensorMode.Raw));
dictionary.Add("NXT Sonar Inch", new Sonar(SonarMode.CentiInch));
dictionary.Add("NXT Sonar Metric", new Sonar(SonarMode.Centimeter));
dictionary.Add("NXT Sound dBA",new NXTSoundSensor(SoundMode.SoundDBA));
dictionary.Add("NXT Sound dB", new NXTSoundSensor(SoundMode.SoundDB));
dictionary.Add("NXT/RCX Touch Bool", new TouchSensor(SensorMode.Bool));
dictionary.Add("NXT/RCX Touch Raw", new TouchSensor(SensorMode.Raw));
dictionary.Add("RCX Angle", new RCXRotationSensor());
dictionary.Add("RCX Light Pct", new RCXLightSensor(SensorMode.Percent));
dictionary.Add("RCX Light Raw", new RCXLightSensor(SensorMode.Raw));
dictionary.Add("RCX Temp Celcius", new RCXTemperatureSensor(TemperatureMode.Celsius));
dictionary.Add("RCX Temp Fahrenheit", new RCXTemperatureSensor(TemperatureMode.Fahrenheit));
return dictionary;
}
}
}
#endregion //Sensor
#region No Sensor
/// <summary>
/// When a sensor is not connected use the class to minimize power consumption
/// </summary>
public class NoSensor: Sensor {
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.NXT.NoSensor"/> class.
/// </summary>
public NoSensor(): base (SensorType.NoSensor, SensorMode.Raw) {
}
}
#endregion
#region No Sensor
/// <summary>
/// When a sensor analog sensor is connected
/// </summary>
public class CustomSensor: Sensor {
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.NXT.CustomSensor"/> class using custom sensor type and raw mode
/// </summary>
public CustomSensor(): base (SensorType.Custom, SensorMode.Percent) {
}
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.NXT.CustomSensor"/> class.
/// </summary>
/// <param name='type'>
/// Sensor type
/// </param>
/// <param name='mode'>
/// Sensor mode
/// </param>
public CustomSensor(SensorType type, SensorMode mode): base (type, mode) {
}
/// <summary>
/// Read the sensor value
/// </summary>
public virtual int Read()
{
return GetScaledValue();
}
}
#endregion
#region NXT 2.0 Color sensor
/// <summary>
/// Sensor modes when using a NXT 2.0 color sensor
/// </summary>
public enum ColorMode {
#pragma warning disable
Full = SensorType.ColorFull, Red = SensorType.ColorRed, Green = SensorType.ColorGreen,
Blue = SensorType.ColorBlue, None = SensorType.ColorNone
#pragma warning restore
};
/// <summary>
/// Colors that can be read from the NXT 2.0 color sensor
/// </summary>
public enum Color {
#pragma warning disable
Black = 0x01, Blue = 0x02, Green = 0x03,
Yellow = 0x04, Red = 0x05, White = 0x06
#pragma warning restore
};
/// <summary>
/// NXT 2.0 color sensor.
/// </summary>
public class NXTColorSensor : Sensor {
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.NXT.NXTColorSensor"/> class as a color sensor.
/// </summary>
public NXTColorSensor() : base ((SensorType)ColorMode.Full,SensorMode.Raw){
}
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.NXT.NXTColorSensor"/> class as a light sensor.
/// </summary>
public NXTColorSensor(SensorMode mode) : base ((SensorType)ColorMode.Red,mode){
}
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.NXT.NXTColorSensor"/> class.
/// </summary>
/// <param name="colorMode">The color mode to use</param>
/// <param name="mode">The sensor mode to use</param>
public NXTColorSensor(ColorMode colorMode, SensorMode mode) : base ((SensorType)colorMode,mode){
}
/// <summary>
/// Set the sensor to be used as a color sensor
/// </summary>
public void UseAsColorSensor(){
UpdateTypeAndMode(SensorType.ColorFull,SensorMode.Raw);
}
/// <summary>
/// Set the sensor to be used as a light sensor
/// </summary>
public void UseAsLightSensor(SensorMode mode = SensorMode.Percent){
UpdateTypeAndMode(SensorType.ColorRed,mode);
}
/// <summary>
/// Gets or sets the light mode.
/// </summary>
/// <value>
/// The light mode
/// </value>
public ColorMode ColorMode
{
set{
UpdateTypeAndMode((SensorType)value, Mode);
}
get{
return (ColorMode) Type;
}
}
/// <summary>
/// Gets or sets the sensor mode.
/// </summary>
/// <value>
/// The sensor mode.
/// </value>
public SensorMode SensorMode
{
get{
return Mode;
}
set{
UpdateTypeAndMode(Type,value);
}
}
/// <summary>
/// Read the intensity of the reflected light
/// </summary>
public int ReadLightLevel()
{
return GetScaledValue();
}
/// <summary>
/// Reads the color value
/// </summary>
/// <returns>The color read from the sensor</returns>
public Color ReadColor(){
Color color = Color.Black;
try{
color = (Color) (GetScaledValue());
}
catch(InvalidCastException){
}
return color;
}
/// <summary>
/// Reads the sensor value as a string.
/// </summary>
/// <returns>The value as a string</returns>
public override string ReadAsString(){
if(Type == SensorType.ColorFull && Mode == SensorMode.Raw){
return ReadColor().ToString();
}
return ReadLightLevel().ToString();
}
}
#endregion
#region NXT Light Sensor
/// <summary>
/// Sensor modes when using a light sensor
/// </summary>
public enum LightMode {
#pragma warning disable
Off = SensorType.LightInactive, On = SensorType.LightActive
#pragma warning restore
};
/// <summary>
/// NXT light sensor.
/// </summary>
public class NXTLightSensor : Sensor {
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.NXT.NXTLightSensor"/> class with active light.
/// </summary>
public NXTLightSensor() : base ((SensorType)LightMode.On,SensorMode.Percent){
}
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.NXT.NXTLightSensor"/> class.
/// </summary>
/// <param name='lightMode'>
/// Light sensor mode
/// </param>
public NXTLightSensor(LightMode lightMode) : base ((SensorType)lightMode, SensorMode.Percent){
}
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.NXT.NXTLightSensor"/> class.
/// </summary>
/// <param name='lightMode'>
/// Light sensor mode
/// </param>
/// <param name='sensorMode'>
/// Sensor mode. Raw, bool, percent...
/// </param>
public NXTLightSensor(LightMode lightMode, SensorMode sensorMode) : base ((SensorType)lightMode, sensorMode){
}
/// <summary>
/// Gets or sets the light mode.
/// </summary>
/// <value>
/// The light mode
/// </value>
public LightMode LightMode
{
set{
UpdateTypeAndMode((SensorType)value, Mode);
}
get{
return (LightMode) Type;
}
}
/// <summary>
/// Gets or sets the sensor mode.
/// </summary>
/// <value>
/// The sensor mode.
/// </value>
public SensorMode SensorMode
{
get{
return Mode;
}
set{
UpdateTypeAndMode(Type,value);
}
}
/// <summary>
/// Read the intensity of the reflected light
/// </summary>
public int ReadLightLevel()
{
return GetScaledValue();
}
}
#endregion
#region RCX Light Sensor
/// <summary>
/// RCX light sensor.
/// </summary>
public class RCXLightSensor : Sensor {
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.NXT.RCXLightSensor"/> class.
/// </summary>
public RCXLightSensor() : base(SensorType.Reflection, SensorMode.Percent) {}
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.NXT.RCXLightSensor"/> class.
/// </summary>
/// <param name='sensorMode'>
/// Sensor mode. Raw, bool, percent...
/// </param>
public RCXLightSensor(SensorMode sensorMode) : base(SensorType.Reflection, sensorMode) {}
/// <summary>
/// Gets or sets the sensor mode.
/// </summary>
/// <value>
/// The sensor mode.
/// </value>
public SensorMode SensorMode
{
get{
return Mode;
}
set{
UpdateTypeAndMode(Type,value);
}
}
/// <summary>
/// Read the intensity of the reflected light
/// </summary>
public int ReadLightLevel()
{
return GetScaledValue();
}
}
#endregion
#region RCX Rotation Sensor
/// <summary>
/// RCX rotation sensor.
/// </summary>
public class RCXRotationSensor : Sensor {
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.NXT.RCXRotationSensor"/> class.
/// </summary>
public RCXRotationSensor() : base(SensorType.Angle, SensorMode.Angle) { }
/// <summary>
/// Read the rotation count
/// </summary>
public int ReadCount()
{
return GetScaledValue();
}
}
#endregion
#region RCX Temperature Sensor
/// <summary>
/// Sensor mode when using a temperature sensor
/// </summary>
public enum TemperatureMode {
/// <summary>
/// Result is in celsius
/// </summary>
Celsius = SensorMode.Celsius,
/// <summary>
/// Result is in fahrenheit.
/// </summary>
Fahrenheit = SensorMode.Fahrenheit
};
/// <summary>
/// RCX temperature sensor.
/// </summary>
public class RCXTemperatureSensor : Sensor {
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.NXT.RCXTemperatureSensor"/> class as celsius
/// </summary>
public RCXTemperatureSensor() : base(SensorType.Temperature, (SensorMode)TemperatureMode.Celsius) {
}
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.NXT.RCXTemperatureSensor"/> class.
/// </summary>
/// <param name='temperatureMode'>
/// Temperature mode
/// </param>
public RCXTemperatureSensor(TemperatureMode temperatureMode) : base(SensorType.Temperature, (SensorMode)temperatureMode) { }
/// <summary>
/// Gets or sets the temperature mode.
/// </summary>
/// <value>
/// The temperature mode.
/// </value>
public TemperatureMode TemperatureMode{
get{return (TemperatureMode) Mode;}
set
{
UpdateTypeAndMode(Type,(SensorMode)value);
}
}
/// <summary>
/// Read the temperature
/// </summary>
public int ReadTemperature()
{
return GetScaledValue();
}
}
#endregion
#region NXT Sound Sensor
/// <summary>
/// Sensor mode when using a sound sensor
/// </summary>
public enum SoundMode {
/// <summary>
/// The sound level is measured in A-weighting decibel
/// </summary>
SoundDBA = SensorType.SoundDBA,
/// <summary>
/// The sound level is measured in decibel
/// </summary>
SoundDB = SensorType.SoundDB };
/// <summary>
/// NXT sound sensor.
/// </summary>
public class NXTSoundSensor : Sensor {
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.NXT.NXTSoundSensor"/> class in DBA mode.
/// </summary>
public NXTSoundSensor() : base((SensorType)SoundMode.SoundDBA, SensorMode.Percent) { }
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.NXT.NXTSoundSensor"/> class.
/// </summary>
/// <param name='soundMode'>
/// Sound mode
/// </param>
public NXTSoundSensor(SoundMode soundMode) : base((SensorType)soundMode, SensorMode.Percent) { }
/// <summary>
/// Gets or sets the sound mode.
/// </summary>
/// <value>
/// The sound mode.
/// </value>
public SoundMode SoundMode{
get{return (SoundMode) Type;}
set
{
UpdateTypeAndMode((SensorType)value,Mode);
}
}
/// <summary>
/// Read the sound level
/// </summary>
public int ReadSoundLevel()
{
return GetScaledValue();
}
}
#endregion
#region Touch Sensor
/// <summary>
/// Touch sensor.
/// </summary>
public class TouchSensor : CustomSensor {
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.NXT.TouchSensor"/> class in bool mode
/// </summary>
public TouchSensor() : base(SensorType.Touch, SensorMode.Bool) { }
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.NXT.TouchSensor"/> class.
/// </summary>
/// <param name='sensorMode'>
/// Sensor mode. Raw, bool, percent...
/// </param>
public TouchSensor(SensorMode sensorMode) : base(SensorType.Touch, sensorMode) { }
/// <summary>
/// Gets or sets the sensor mode.
/// </summary>
/// <value>
/// The sensor mode.
/// </value>
public SensorMode SensorMode
{
get{
return Mode;
}
set{
UpdateTypeAndMode(Type,value);
}
}
}
#endregion
#region HiTechnic gyro sensor
/// <summary>
/// HiTechnic gyro sensor
/// </summary>
public class HiTecGyro : Sensor {
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.NXT.HiTecGyro"/> class without offset
/// </summary>
public HiTecGyro() : base(SensorType.Custom , SensorMode.Raw) {
Offset = 0;
}
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrick.NXT.HiTecGyro"/> class.
/// </summary>
/// <param name='offset'>
/// Offset
/// </param>
public HiTecGyro(int offset) : base(SensorType.Custom , SensorMode.Raw) {
Offset = offset;
}
/// <summary>
/// Read angular acceleration
/// </summary>
public int ReadAngularAcceleration()
{
return GetRawValue()-Offset;
}
/// <summary>
/// Reads the angular acceleration as a string.
/// </summary>
/// <returns>
/// The value as a string.
/// </returns>
public override string ReadAsString()
{
return this.ReadAngularAcceleration().ToString() + " deg/sec";
}
/// <summary>
/// Gets or sets the offset.
/// </summary>
/// <value>
/// The offset.
/// </value>
public int Offset{get;set;}
}
#endregion
}
| |
using AngleSharp.Css.Dom;
using AngleSharp.Css.Parser;
namespace AngleSharp.Css.Tests.Declarations
{
using AngleSharp.Dom;
using NUnit.Framework;
using static CssConstructionFunctions;
[TestFixture]
public class CssBorderPropertyTests
{
[Test]
public void CssBorderSpacingLengthLegal()
{
var snippet = "border-spacing: 20px";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border-spacing", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("20px", property.Value);
}
[Test]
public void CssBorderSpacingZeroLegal()
{
var snippet = "border-spacing: 0";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border-spacing", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("0", property.Value);
}
[Test]
public void CssBorderSpacingLengthLengthLegal()
{
var snippet = "border-spacing: 15px 3em";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border-spacing", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("15px 3em", property.Value);
}
[Test]
public void CssBorderSpacingLengthZeroLegal()
{
var snippet = "border-spacing: 15px 0";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border-spacing", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("15px 0", property.Value);
}
[Test]
public void CssBorderSpacingPercentIllegal()
{
var snippet = "border-spacing: 15%";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border-spacing", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsTrue(property.IsInherited);
Assert.IsFalse(property.HasValue);
}
[Test]
public void CssBorderBottomColorRedLegal()
{
var snippet = "border-bottom-color: red";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border-bottom-color", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("rgba(255, 0, 0, 1)", property.Value);
}
[Test]
public void CssBorderTopColorHexLegal()
{
var snippet = "border-top-color: #0F0";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border-top-color", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("rgba(0, 255, 0, 1)", property.Value);
}
[Test]
public void CssBorderRightColorRgbaLegal()
{
var snippet = "border-right-color: rgba(1, 1, 1, 0)";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border-right-color", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("rgba(1, 1, 1, 0)", property.Value);
}
[Test]
public void CssBorderLeftColorRgbLegal()
{
var snippet = "border-left-color: rgb(1, 255, 100) !important";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border-left-color", property.Name);
Assert.IsTrue(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("rgba(1, 255, 100, 1)", property.Value);
}
[Test]
public void CssBorderColorTransparentLegal()
{
var snippet = "border-color: transparent";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border-color", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("rgba(0, 0, 0, 0)", property.Value);
}
[Test]
public void CssBorderColorRedGreenLegal()
{
var snippet = "border-color: red green";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border-color", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("rgba(255, 0, 0, 1) rgba(0, 128, 0, 1)", property.Value);
}
[Test]
public void CssBorderColorRedRgbLegal()
{
var snippet = "border-color: red rgb(0,0,0)";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border-color", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("rgba(255, 0, 0, 1) rgba(0, 0, 0, 1)", property.Value);
}
[Test]
public void CssBorderColorRedBlueGreenLegal()
{
var snippet = "border-color: red blue green";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border-color", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("rgba(255, 0, 0, 1) rgba(0, 0, 255, 1) rgba(0, 128, 0, 1)", property.Value);
}
[Test]
public void CssBorderColorRedBlueGreenBlackLegal()
{
var snippet = "border-color: red blue green BLACK";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border-color", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("rgba(255, 0, 0, 1) rgba(0, 0, 255, 1) rgba(0, 128, 0, 1) rgba(0, 0, 0, 1)", property.Value);
}
[Test]
public void CssBorderColorRedBlueGreenBlackTransparentIllegal()
{
var snippet = "border-color: red blue green black transparent";
var property = ParseDeclaration(snippet);
Assert.IsFalse(property.HasValue);
}
[Test]
public void CssBorderStyleDottedLegal()
{
var snippet = "border-style: dotted";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border-style", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("dotted", property.Value);
}
[Test]
public void CssBorderStyleInsetOutsetUpperLegal()
{
var snippet = "border-style: INSET OUTset";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border-style", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("inset outset", property.Value);
}
[Test]
public void CssBorderStyleDoubleGrooveLegal()
{
var snippet = "border-style: double groove";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border-style", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("double groove", property.Value);
}
[Test]
public void CssBorderStyleRidgeSolidDashedLegal()
{
var snippet = "border-style: ridge solid dashed";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border-style", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("ridge solid dashed", property.Value);
}
[Test]
public void CssBorderStyleHiddenDottedNoneNoneLegal()
{
var snippet = "border-style : hidden dotted NONE nONe";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border-style", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("hidden dotted none none", property.Value);
}
[Test]
public void CssBorderStyleMultipleExpandCorrectly_Issue34()
{
var source = @"<!DOCTYPE html>
<html>
<head><title></title></head>
<body style=""border-style: hidden double dashed;""></body>
</html>";
var document = source.ToHtmlDocument(Configuration.Default.WithCss());
var styleDeclaration = document.Body.ComputeCurrentStyle();
Assert.AreEqual("hidden", styleDeclaration.GetBorderTopStyle());
Assert.AreEqual("double", styleDeclaration.GetBorderLeftStyle());
Assert.AreEqual("double", styleDeclaration.GetBorderRightStyle());
Assert.AreEqual("dashed", styleDeclaration.GetBorderBottomStyle());
}
[Test]
public void CssBorderStyleWavyIllegal()
{
var snippet = "border-style: wavy";
var property = ParseDeclaration(snippet);
Assert.IsFalse(property.HasValue);
}
[Test]
public void CssBorderBottomStyleGrooveLegal()
{
var snippet = "border-bottom-style: GROOVE";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border-bottom-style", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("groove", property.Value);
}
[Test]
public void CssBorderTopStyleNoneLegal()
{
var snippet = "border-top-style:none";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border-top-style", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("none", property.Value);
}
[Test]
public void CssBorderRightStyleDoubleLegal()
{
var snippet = "border-right-style:double";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border-right-style", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("double", property.Value);
}
[Test]
public void CssBorderLeftStyleHiddenLegal()
{
var snippet = "border-left-style: hidden !important";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border-left-style", property.Name);
Assert.IsTrue(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("hidden", property.Value);
}
[Test]
public void CssBorderBottomWidthThinLegal()
{
var snippet = "border-bottom-width: THIN";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border-bottom-width", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("1px", property.Value);
}
[Test]
public void CssBorderTopWidthZeroLegal()
{
var snippet = "border-top-width: 0";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border-top-width", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("0", property.Value);
}
[Test]
public void CssBorderRightWidthEmLegal()
{
var snippet = "border-right-width: 3em";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border-right-width", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("3em", property.Value);
}
[Test]
public void CssBorderLeftWidthThickLegal()
{
var snippet = "border-left-width: thick !important";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border-left-width", property.Name);
Assert.IsTrue(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("5px", property.Value);
}
[Test]
public void CssBorderWidthMediumLegal()
{
var snippet = "border-width: medium";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border-width", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("3px", property.Value);
}
[Test]
public void CssBorderWidthLengthZeroLegal()
{
var snippet = "border-width: 3px 0";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border-width", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("3px 0", property.Value);
}
[Test]
public void CssBorderWidthThinLengthLegal()
{
var snippet = "border-width: THIN 1px";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border-width", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("1px", property.Value);
}
[Test]
public void CssBorderWidthMediumThinThickLegal()
{
var snippet = "border-width: medium thin thick";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border-width", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("3px 1px 5px", property.Value);
}
[Test]
public void CssBorderWidthLengthLengthLengthLengthLegal()
{
var snippet = "border-width: 1px 2px 3px 4px !important ";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border-width", property.Name);
Assert.IsTrue(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("1px 2px 3px 4px", property.Value);
}
[Test]
public void CssBorderWidthLengthInEmZeroLegal()
{
var snippet = "border-width: 0.3em 0 ";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border-width", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("0.3em 0", property.Value);
}
[Test]
public void CssBorderWidthMediumZeroLengthThickLegal()
{
var snippet = "border-width: medium 0 1px thick ";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border-width", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("3px 0 1px 5px", property.Value);
}
[Test]
public void CssBorderWidthZerosIllegal()
{
var snippet = "border-width: 0 0 0 0 0";
var property = ParseDeclaration(snippet);
Assert.IsFalse(property.HasValue);
}
[Test]
public void CssBorderLeftZeroLegal()
{
var snippet = "border-left: 0 ";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border-left", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("0", property.Value);
}
[Test]
public void CssBorderRightLineStyleLegal()
{
var snippet = "border-right : dotted ";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border-right", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("dotted", property.Value);
}
[Test]
public void CssBorderTopLengthRedLegal()
{
var snippet = "border-top : 2px red ";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border-top", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("2px rgba(255, 0, 0, 1)", property.Value);
}
[Test]
public void CssBorderBottomRgbLegal()
{
var snippet = "border-bottom : rgb(255, 100, 0) ";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border-bottom", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("rgba(255, 100, 0, 1)", property.Value);
}
[Test]
public void CssBorderGrooveRgbLegal()
{
var snippet = "border : GROOVE rgb(255, 100, 0) ";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
}
[Test]
public void CssBorderInsetGreenLengthLegal()
{
var snippet = "border : inset green 3em ";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("3em inset rgba(0, 128, 0, 1)", property.Value);
}
[Test]
public void CssBorderRedSolidLengthLegal()
{
var snippet = "border : red SOLID 1px ";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
}
[Test]
public void CssBorderLengthBlackDoubleLegal()
{
var snippet = "border : 0.5px black double ";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("0.5px double rgba(0, 0, 0, 1)", property.Value);
}
[Test]
public void CssBorderOutSetCurrentColor()
{
var snippet = "border: 1px outset currentColor";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("1px outset currentColor", property.Value);
}
[Test]
public void CssBorderOutSetWithNoColor()
{
var snippet = "border: 1px outset";
var property = ParseDeclaration(snippet);
Assert.AreEqual("border", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("1px outset", property.Value);
}
[Test]
public void CssBorderAggregation()
{
var expectedCss = "border: 1px solid rgba(0, 0, 0, 1)";
var context = BrowsingContext.New(Configuration.Default.WithCss());
var style = new CssStyleDeclaration(context);
style.SetBorderWidth("1px");
style.SetBorderStyle("solid");
style.SetBorderColor("black");
Assert.AreEqual(expectedCss, style.CssText);
}
}
}
| |
// 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.V8.Enums;
using gagvr = Google.Ads.GoogleAds.V8.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.V8.Services;
namespace Google.Ads.GoogleAds.Tests.V8.Services
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedSharedSetServiceClientTest
{
[Category("Autogenerated")][Test]
public void GetSharedSetRequestObject()
{
moq::Mock<SharedSetService.SharedSetServiceClient> mockGrpcClient = new moq::Mock<SharedSetService.SharedSetServiceClient>(moq::MockBehavior.Strict);
GetSharedSetRequest request = new GetSharedSetRequest
{
ResourceNameAsSharedSetName = gagvr::SharedSetName.FromCustomerSharedSet("[CUSTOMER_ID]", "[SHARED_SET_ID]"),
};
gagvr::SharedSet expectedResponse = new gagvr::SharedSet
{
ResourceNameAsSharedSetName = gagvr::SharedSetName.FromCustomerSharedSet("[CUSTOMER_ID]", "[SHARED_SET_ID]"),
Type = gagve::SharedSetTypeEnum.Types.SharedSetType.NegativePlacements,
Status = gagve::SharedSetStatusEnum.Types.SharedSetStatus.Enabled,
Id = -6774108720365892680L,
SharedSetName = gagvr::SharedSetName.FromCustomerSharedSet("[CUSTOMER_ID]", "[SHARED_SET_ID]"),
MemberCount = -5151590354343439845L,
ReferenceCount = -8440758895662409664L,
};
mockGrpcClient.Setup(x => x.GetSharedSet(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SharedSetServiceClient client = new SharedSetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::SharedSet response = client.GetSharedSet(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetSharedSetRequestObjectAsync()
{
moq::Mock<SharedSetService.SharedSetServiceClient> mockGrpcClient = new moq::Mock<SharedSetService.SharedSetServiceClient>(moq::MockBehavior.Strict);
GetSharedSetRequest request = new GetSharedSetRequest
{
ResourceNameAsSharedSetName = gagvr::SharedSetName.FromCustomerSharedSet("[CUSTOMER_ID]", "[SHARED_SET_ID]"),
};
gagvr::SharedSet expectedResponse = new gagvr::SharedSet
{
ResourceNameAsSharedSetName = gagvr::SharedSetName.FromCustomerSharedSet("[CUSTOMER_ID]", "[SHARED_SET_ID]"),
Type = gagve::SharedSetTypeEnum.Types.SharedSetType.NegativePlacements,
Status = gagve::SharedSetStatusEnum.Types.SharedSetStatus.Enabled,
Id = -6774108720365892680L,
SharedSetName = gagvr::SharedSetName.FromCustomerSharedSet("[CUSTOMER_ID]", "[SHARED_SET_ID]"),
MemberCount = -5151590354343439845L,
ReferenceCount = -8440758895662409664L,
};
mockGrpcClient.Setup(x => x.GetSharedSetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::SharedSet>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SharedSetServiceClient client = new SharedSetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::SharedSet responseCallSettings = await client.GetSharedSetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::SharedSet responseCancellationToken = await client.GetSharedSetAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetSharedSet()
{
moq::Mock<SharedSetService.SharedSetServiceClient> mockGrpcClient = new moq::Mock<SharedSetService.SharedSetServiceClient>(moq::MockBehavior.Strict);
GetSharedSetRequest request = new GetSharedSetRequest
{
ResourceNameAsSharedSetName = gagvr::SharedSetName.FromCustomerSharedSet("[CUSTOMER_ID]", "[SHARED_SET_ID]"),
};
gagvr::SharedSet expectedResponse = new gagvr::SharedSet
{
ResourceNameAsSharedSetName = gagvr::SharedSetName.FromCustomerSharedSet("[CUSTOMER_ID]", "[SHARED_SET_ID]"),
Type = gagve::SharedSetTypeEnum.Types.SharedSetType.NegativePlacements,
Status = gagve::SharedSetStatusEnum.Types.SharedSetStatus.Enabled,
Id = -6774108720365892680L,
SharedSetName = gagvr::SharedSetName.FromCustomerSharedSet("[CUSTOMER_ID]", "[SHARED_SET_ID]"),
MemberCount = -5151590354343439845L,
ReferenceCount = -8440758895662409664L,
};
mockGrpcClient.Setup(x => x.GetSharedSet(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SharedSetServiceClient client = new SharedSetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::SharedSet response = client.GetSharedSet(request.ResourceName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetSharedSetAsync()
{
moq::Mock<SharedSetService.SharedSetServiceClient> mockGrpcClient = new moq::Mock<SharedSetService.SharedSetServiceClient>(moq::MockBehavior.Strict);
GetSharedSetRequest request = new GetSharedSetRequest
{
ResourceNameAsSharedSetName = gagvr::SharedSetName.FromCustomerSharedSet("[CUSTOMER_ID]", "[SHARED_SET_ID]"),
};
gagvr::SharedSet expectedResponse = new gagvr::SharedSet
{
ResourceNameAsSharedSetName = gagvr::SharedSetName.FromCustomerSharedSet("[CUSTOMER_ID]", "[SHARED_SET_ID]"),
Type = gagve::SharedSetTypeEnum.Types.SharedSetType.NegativePlacements,
Status = gagve::SharedSetStatusEnum.Types.SharedSetStatus.Enabled,
Id = -6774108720365892680L,
SharedSetName = gagvr::SharedSetName.FromCustomerSharedSet("[CUSTOMER_ID]", "[SHARED_SET_ID]"),
MemberCount = -5151590354343439845L,
ReferenceCount = -8440758895662409664L,
};
mockGrpcClient.Setup(x => x.GetSharedSetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::SharedSet>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SharedSetServiceClient client = new SharedSetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::SharedSet responseCallSettings = await client.GetSharedSetAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::SharedSet responseCancellationToken = await client.GetSharedSetAsync(request.ResourceName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetSharedSetResourceNames()
{
moq::Mock<SharedSetService.SharedSetServiceClient> mockGrpcClient = new moq::Mock<SharedSetService.SharedSetServiceClient>(moq::MockBehavior.Strict);
GetSharedSetRequest request = new GetSharedSetRequest
{
ResourceNameAsSharedSetName = gagvr::SharedSetName.FromCustomerSharedSet("[CUSTOMER_ID]", "[SHARED_SET_ID]"),
};
gagvr::SharedSet expectedResponse = new gagvr::SharedSet
{
ResourceNameAsSharedSetName = gagvr::SharedSetName.FromCustomerSharedSet("[CUSTOMER_ID]", "[SHARED_SET_ID]"),
Type = gagve::SharedSetTypeEnum.Types.SharedSetType.NegativePlacements,
Status = gagve::SharedSetStatusEnum.Types.SharedSetStatus.Enabled,
Id = -6774108720365892680L,
SharedSetName = gagvr::SharedSetName.FromCustomerSharedSet("[CUSTOMER_ID]", "[SHARED_SET_ID]"),
MemberCount = -5151590354343439845L,
ReferenceCount = -8440758895662409664L,
};
mockGrpcClient.Setup(x => x.GetSharedSet(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SharedSetServiceClient client = new SharedSetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::SharedSet response = client.GetSharedSet(request.ResourceNameAsSharedSetName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetSharedSetResourceNamesAsync()
{
moq::Mock<SharedSetService.SharedSetServiceClient> mockGrpcClient = new moq::Mock<SharedSetService.SharedSetServiceClient>(moq::MockBehavior.Strict);
GetSharedSetRequest request = new GetSharedSetRequest
{
ResourceNameAsSharedSetName = gagvr::SharedSetName.FromCustomerSharedSet("[CUSTOMER_ID]", "[SHARED_SET_ID]"),
};
gagvr::SharedSet expectedResponse = new gagvr::SharedSet
{
ResourceNameAsSharedSetName = gagvr::SharedSetName.FromCustomerSharedSet("[CUSTOMER_ID]", "[SHARED_SET_ID]"),
Type = gagve::SharedSetTypeEnum.Types.SharedSetType.NegativePlacements,
Status = gagve::SharedSetStatusEnum.Types.SharedSetStatus.Enabled,
Id = -6774108720365892680L,
SharedSetName = gagvr::SharedSetName.FromCustomerSharedSet("[CUSTOMER_ID]", "[SHARED_SET_ID]"),
MemberCount = -5151590354343439845L,
ReferenceCount = -8440758895662409664L,
};
mockGrpcClient.Setup(x => x.GetSharedSetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::SharedSet>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SharedSetServiceClient client = new SharedSetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::SharedSet responseCallSettings = await client.GetSharedSetAsync(request.ResourceNameAsSharedSetName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::SharedSet responseCancellationToken = await client.GetSharedSetAsync(request.ResourceNameAsSharedSetName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateSharedSetsRequestObject()
{
moq::Mock<SharedSetService.SharedSetServiceClient> mockGrpcClient = new moq::Mock<SharedSetService.SharedSetServiceClient>(moq::MockBehavior.Strict);
MutateSharedSetsRequest request = new MutateSharedSetsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new SharedSetOperation(),
},
PartialFailure = false,
ValidateOnly = true,
ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly,
};
MutateSharedSetsResponse expectedResponse = new MutateSharedSetsResponse
{
Results =
{
new MutateSharedSetResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateSharedSets(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SharedSetServiceClient client = new SharedSetServiceClientImpl(mockGrpcClient.Object, null);
MutateSharedSetsResponse response = client.MutateSharedSets(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateSharedSetsRequestObjectAsync()
{
moq::Mock<SharedSetService.SharedSetServiceClient> mockGrpcClient = new moq::Mock<SharedSetService.SharedSetServiceClient>(moq::MockBehavior.Strict);
MutateSharedSetsRequest request = new MutateSharedSetsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new SharedSetOperation(),
},
PartialFailure = false,
ValidateOnly = true,
ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly,
};
MutateSharedSetsResponse expectedResponse = new MutateSharedSetsResponse
{
Results =
{
new MutateSharedSetResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateSharedSetsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateSharedSetsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SharedSetServiceClient client = new SharedSetServiceClientImpl(mockGrpcClient.Object, null);
MutateSharedSetsResponse responseCallSettings = await client.MutateSharedSetsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateSharedSetsResponse responseCancellationToken = await client.MutateSharedSetsAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateSharedSets()
{
moq::Mock<SharedSetService.SharedSetServiceClient> mockGrpcClient = new moq::Mock<SharedSetService.SharedSetServiceClient>(moq::MockBehavior.Strict);
MutateSharedSetsRequest request = new MutateSharedSetsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new SharedSetOperation(),
},
};
MutateSharedSetsResponse expectedResponse = new MutateSharedSetsResponse
{
Results =
{
new MutateSharedSetResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateSharedSets(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SharedSetServiceClient client = new SharedSetServiceClientImpl(mockGrpcClient.Object, null);
MutateSharedSetsResponse response = client.MutateSharedSets(request.CustomerId, request.Operations);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateSharedSetsAsync()
{
moq::Mock<SharedSetService.SharedSetServiceClient> mockGrpcClient = new moq::Mock<SharedSetService.SharedSetServiceClient>(moq::MockBehavior.Strict);
MutateSharedSetsRequest request = new MutateSharedSetsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new SharedSetOperation(),
},
};
MutateSharedSetsResponse expectedResponse = new MutateSharedSetsResponse
{
Results =
{
new MutateSharedSetResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateSharedSetsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateSharedSetsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SharedSetServiceClient client = new SharedSetServiceClientImpl(mockGrpcClient.Object, null);
MutateSharedSetsResponse responseCallSettings = await client.MutateSharedSetsAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateSharedSetsResponse responseCancellationToken = await client.MutateSharedSetsAsync(request.CustomerId, request.Operations, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// 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.Xml;
using System.Runtime.Serialization;
using System.Globalization;
namespace System.Runtime.Serialization.Json
{
internal class JsonReaderDelegator : XmlReaderDelegator
{
private DateTimeFormat _dateTimeFormat;
private DateTimeArrayJsonHelperWithString _dateTimeArrayHelper;
public JsonReaderDelegator(XmlReader reader)
: base(reader)
{
}
public JsonReaderDelegator(XmlReader reader, DateTimeFormat dateTimeFormat)
: this(reader)
{
_dateTimeFormat = dateTimeFormat;
}
internal XmlDictionaryReaderQuotas ReaderQuotas
{
get
{
if (this.dictionaryReader == null)
{
return null;
}
else
{
return dictionaryReader.Quotas;
}
}
}
private DateTimeArrayJsonHelperWithString DateTimeArrayHelper
{
get
{
if (_dateTimeArrayHelper == null)
{
_dateTimeArrayHelper = new DateTimeArrayJsonHelperWithString(_dateTimeFormat);
}
return _dateTimeArrayHelper;
}
}
internal static XmlQualifiedName ParseQualifiedName(string qname)
{
string name, ns;
if (string.IsNullOrEmpty(qname))
{
name = ns = String.Empty;
}
else
{
qname = qname.Trim();
int colon = qname.IndexOf(':');
if (colon >= 0)
{
name = qname.Substring(0, colon);
ns = qname.Substring(colon + 1);
}
else
{
name = qname;
ns = string.Empty;
}
}
return new XmlQualifiedName(name, ns);
}
internal char ReadContentAsChar()
{
return XmlConvert.ToChar(ReadContentAsString());
}
internal override XmlQualifiedName ReadContentAsQName()
{
return ParseQualifiedName(ReadContentAsString());
}
internal override char ReadElementContentAsChar()
{
return XmlConvert.ToChar(ReadElementContentAsString());
}
public byte[] ReadContentAsBase64()
{
if (isEndOfEmptyElement)
return Array.Empty<byte>();
byte[] buffer;
if (dictionaryReader == null)
{
XmlDictionaryReader tempDictionaryReader = XmlDictionaryReader.CreateDictionaryReader(reader);
buffer = ByteArrayHelperWithString.Instance.ReadArray(tempDictionaryReader, JsonGlobals.itemString, string.Empty, tempDictionaryReader.Quotas.MaxArrayLength);
}
else
{
buffer = ByteArrayHelperWithString.Instance.ReadArray(dictionaryReader, JsonGlobals.itemString, string.Empty, dictionaryReader.Quotas.MaxArrayLength);
}
return buffer;
}
internal override byte[] ReadElementContentAsBase64()
{
if (isEndOfEmptyElement)
{
throw new XmlException(SR.Format(SR.XmlStartElementExpected, "EndElement"));
}
bool isEmptyElement = reader.IsStartElement() && reader.IsEmptyElement;
byte[] buffer;
if (isEmptyElement)
{
reader.Read();
buffer = Array.Empty<byte>();
}
else
{
reader.ReadStartElement();
buffer = ReadContentAsBase64();
reader.ReadEndElement();
}
return buffer;
}
internal DateTime ReadContentAsDateTime()
{
return ParseJsonDate(ReadContentAsString(), _dateTimeFormat);
}
internal static DateTime ParseJsonDate(string originalDateTimeValue, DateTimeFormat dateTimeFormat)
{
if (dateTimeFormat == null)
{
return ParseJsonDateInDefaultFormat(originalDateTimeValue);
}
else
{
return DateTime.ParseExact(originalDateTimeValue, dateTimeFormat.FormatString, dateTimeFormat.FormatProvider, dateTimeFormat.DateTimeStyles);
}
}
internal static DateTime ParseJsonDateInDefaultFormat(string originalDateTimeValue)
{
// Dates are represented in JSON as "\/Date(number of ticks)\/".
// The number of ticks is the number of milliseconds since January 1, 1970.
string dateTimeValue;
if (!string.IsNullOrEmpty(originalDateTimeValue))
{
dateTimeValue = originalDateTimeValue.Trim();
}
else
{
dateTimeValue = originalDateTimeValue;
}
if (string.IsNullOrEmpty(dateTimeValue) ||
!dateTimeValue.StartsWith(JsonGlobals.DateTimeStartGuardReader, StringComparison.Ordinal) ||
!dateTimeValue.EndsWith(JsonGlobals.DateTimeEndGuardReader, StringComparison.Ordinal))
{
throw new FormatException(SR.Format(SR.JsonInvalidDateTimeString, originalDateTimeValue, JsonGlobals.DateTimeStartGuardWriter, JsonGlobals.DateTimeEndGuardWriter));
}
string ticksvalue = dateTimeValue.Substring(6, dateTimeValue.Length - 8);
long millisecondsSinceUnixEpoch;
DateTimeKind dateTimeKind = DateTimeKind.Utc;
int indexOfTimeZoneOffset = ticksvalue.IndexOf('+', 1);
if (indexOfTimeZoneOffset == -1)
{
indexOfTimeZoneOffset = ticksvalue.IndexOf('-', 1);
}
if (indexOfTimeZoneOffset != -1)
{
dateTimeKind = DateTimeKind.Local;
ticksvalue = ticksvalue.Substring(0, indexOfTimeZoneOffset);
}
try
{
millisecondsSinceUnixEpoch = Int64.Parse(ticksvalue, CultureInfo.InvariantCulture);
}
catch (ArgumentException exception)
{
throw XmlExceptionHelper.CreateConversionException(ticksvalue, "Int64", exception);
}
catch (FormatException exception)
{
throw XmlExceptionHelper.CreateConversionException(ticksvalue, "Int64", exception);
}
catch (OverflowException exception)
{
throw XmlExceptionHelper.CreateConversionException(ticksvalue, "Int64", exception);
}
// Convert from # millseconds since epoch to # of 100-nanosecond units, which is what DateTime understands
long ticks = millisecondsSinceUnixEpoch * 10000 + JsonGlobals.unixEpochTicks;
try
{
DateTime dateTime = new DateTime(ticks, DateTimeKind.Utc);
switch (dateTimeKind)
{
case DateTimeKind.Local:
return dateTime.ToLocalTime();
case DateTimeKind.Unspecified:
return DateTime.SpecifyKind(dateTime.ToLocalTime(), DateTimeKind.Unspecified);
case DateTimeKind.Utc:
default:
return dateTime;
}
}
catch (ArgumentException exception)
{
throw XmlExceptionHelper.CreateConversionException(ticksvalue, "DateTime", exception);
}
}
internal override DateTime ReadElementContentAsDateTime()
{
return ParseJsonDate(ReadElementContentAsString(), _dateTimeFormat);
}
internal bool TryReadJsonDateTimeArray(XmlObjectSerializerReadContext context,
XmlDictionaryString itemName, XmlDictionaryString itemNamespace,
int arrayLength, out DateTime[] array)
{
if ((dictionaryReader == null) || (arrayLength != -1))
{
array = null;
return false;
}
array = this.DateTimeArrayHelper.ReadArray(dictionaryReader, XmlDictionaryString.GetString(itemName), XmlDictionaryString.GetString(itemNamespace), GetArrayLengthQuota(context));
context.IncrementItemCount(array.Length);
return true;
}
private class DateTimeArrayJsonHelperWithString : ArrayHelper<string, DateTime>
{
private DateTimeFormat _dateTimeFormat;
public DateTimeArrayJsonHelperWithString(DateTimeFormat dateTimeFormat)
{
_dateTimeFormat = dateTimeFormat;
}
protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, DateTime[] array, int offset, int count)
{
XmlJsonReader.CheckArray(array, offset, count);
int actual = 0;
while (actual < count && reader.IsStartElement(JsonGlobals.itemString, string.Empty))
{
array[offset + actual] = JsonReaderDelegator.ParseJsonDate(reader.ReadElementContentAsString(), _dateTimeFormat);
actual++;
}
return actual;
}
protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, DateTime[] array, int offset, int count)
{
throw NotImplemented.ByDesign;
}
}
// Overridden because base reader relies on XmlConvert.ToUInt64 for conversion to ulong
internal ulong ReadContentAsUnsignedLong()
{
string value = reader.ReadContentAsString();
if (value == null || value.Length == 0)
{
throw new XmlException(XmlObjectSerializer.TryAddLineInfo(this, SR.Format(SR.XmlInvalidConversion, value, "UInt64")));
}
try
{
return ulong.Parse(value, NumberStyles.Float, NumberFormatInfo.InvariantInfo);
}
catch (ArgumentException exception)
{
throw XmlExceptionHelper.CreateConversionException(value, "UInt64", exception);
}
catch (FormatException exception)
{
throw XmlExceptionHelper.CreateConversionException(value, "UInt64", exception);
}
catch (OverflowException exception)
{
throw XmlExceptionHelper.CreateConversionException(value, "UInt64", exception);
}
}
// Overridden because base reader relies on XmlConvert.ToUInt64 for conversion to ulong
internal override UInt64 ReadElementContentAsUnsignedLong()
{
if (isEndOfEmptyElement)
{
throw new XmlException(SR.Format(SR.XmlStartElementExpected, "EndElement"));
}
string value = reader.ReadElementContentAsString();
if (value == null || value.Length == 0)
{
throw new XmlException(XmlObjectSerializer.TryAddLineInfo(this, SR.Format(SR.XmlInvalidConversion, value, "UInt64")));
}
try
{
return ulong.Parse(value, NumberStyles.Float, NumberFormatInfo.InvariantInfo);
}
catch (ArgumentException exception)
{
throw XmlExceptionHelper.CreateConversionException(value, "UInt64", exception);
}
catch (FormatException exception)
{
throw XmlExceptionHelper.CreateConversionException(value, "UInt64", exception);
}
catch (OverflowException exception)
{
throw XmlExceptionHelper.CreateConversionException(value, "UInt64", exception);
}
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the cloudformation-2010-05-15.normal.json service model.
*/
using System;
using System.IO;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Amazon.CloudFormation;
using Amazon.CloudFormation.Model;
using Amazon.CloudFormation.Model.Internal.MarshallTransformations;
using Amazon.Runtime.Internal.Transform;
using ServiceClientGenerator;
using AWSSDK_DotNet35.UnitTests.TestTools;
namespace AWSSDK_DotNet35.UnitTests.Marshalling
{
[TestClass]
public class CloudFormationMarshallingTests
{
static readonly ServiceModel service_model = Utils.LoadServiceModel("cloudformation-2010-05-15.normal.json", "cloudformation.customizations.json");
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("CloudFormation")]
public void CancelUpdateStackMarshallTest()
{
var operation = service_model.FindOperation("CancelUpdateStack");
var request = InstantiateClassGenerator.Execute<CancelUpdateStackRequest>();
var marshaller = new CancelUpdateStackRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("CloudFormation")]
public void CreateStackMarshallTest()
{
var operation = service_model.FindOperation("CreateStack");
var request = InstantiateClassGenerator.Execute<CreateStackRequest>();
var marshaller = new CreateStackRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = CreateStackResponseUnmarshaller.Instance.Unmarshall(context)
as CreateStackResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("CloudFormation")]
public void DeleteStackMarshallTest()
{
var operation = service_model.FindOperation("DeleteStack");
var request = InstantiateClassGenerator.Execute<DeleteStackRequest>();
var marshaller = new DeleteStackRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("CloudFormation")]
public void DescribeAccountLimitsMarshallTest()
{
var operation = service_model.FindOperation("DescribeAccountLimits");
var request = InstantiateClassGenerator.Execute<DescribeAccountLimitsRequest>();
var marshaller = new DescribeAccountLimitsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = DescribeAccountLimitsResponseUnmarshaller.Instance.Unmarshall(context)
as DescribeAccountLimitsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("CloudFormation")]
public void DescribeStackEventsMarshallTest()
{
var operation = service_model.FindOperation("DescribeStackEvents");
var request = InstantiateClassGenerator.Execute<DescribeStackEventsRequest>();
var marshaller = new DescribeStackEventsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = DescribeStackEventsResponseUnmarshaller.Instance.Unmarshall(context)
as DescribeStackEventsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("CloudFormation")]
public void DescribeStackResourceMarshallTest()
{
var operation = service_model.FindOperation("DescribeStackResource");
var request = InstantiateClassGenerator.Execute<DescribeStackResourceRequest>();
var marshaller = new DescribeStackResourceRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = DescribeStackResourceResponseUnmarshaller.Instance.Unmarshall(context)
as DescribeStackResourceResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("CloudFormation")]
public void DescribeStackResourcesMarshallTest()
{
var operation = service_model.FindOperation("DescribeStackResources");
var request = InstantiateClassGenerator.Execute<DescribeStackResourcesRequest>();
var marshaller = new DescribeStackResourcesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = DescribeStackResourcesResponseUnmarshaller.Instance.Unmarshall(context)
as DescribeStackResourcesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("CloudFormation")]
public void DescribeStacksMarshallTest()
{
var operation = service_model.FindOperation("DescribeStacks");
var request = InstantiateClassGenerator.Execute<DescribeStacksRequest>();
var marshaller = new DescribeStacksRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = DescribeStacksResponseUnmarshaller.Instance.Unmarshall(context)
as DescribeStacksResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("CloudFormation")]
public void EstimateTemplateCostMarshallTest()
{
var operation = service_model.FindOperation("EstimateTemplateCost");
var request = InstantiateClassGenerator.Execute<EstimateTemplateCostRequest>();
var marshaller = new EstimateTemplateCostRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = EstimateTemplateCostResponseUnmarshaller.Instance.Unmarshall(context)
as EstimateTemplateCostResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("CloudFormation")]
public void GetStackPolicyMarshallTest()
{
var operation = service_model.FindOperation("GetStackPolicy");
var request = InstantiateClassGenerator.Execute<GetStackPolicyRequest>();
var marshaller = new GetStackPolicyRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = GetStackPolicyResponseUnmarshaller.Instance.Unmarshall(context)
as GetStackPolicyResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("CloudFormation")]
public void GetTemplateMarshallTest()
{
var operation = service_model.FindOperation("GetTemplate");
var request = InstantiateClassGenerator.Execute<GetTemplateRequest>();
var marshaller = new GetTemplateRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = GetTemplateResponseUnmarshaller.Instance.Unmarshall(context)
as GetTemplateResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("CloudFormation")]
public void GetTemplateSummaryMarshallTest()
{
var operation = service_model.FindOperation("GetTemplateSummary");
var request = InstantiateClassGenerator.Execute<GetTemplateSummaryRequest>();
var marshaller = new GetTemplateSummaryRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = GetTemplateSummaryResponseUnmarshaller.Instance.Unmarshall(context)
as GetTemplateSummaryResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("CloudFormation")]
public void ListStackResourcesMarshallTest()
{
var operation = service_model.FindOperation("ListStackResources");
var request = InstantiateClassGenerator.Execute<ListStackResourcesRequest>();
var marshaller = new ListStackResourcesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = ListStackResourcesResponseUnmarshaller.Instance.Unmarshall(context)
as ListStackResourcesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("CloudFormation")]
public void ListStacksMarshallTest()
{
var operation = service_model.FindOperation("ListStacks");
var request = InstantiateClassGenerator.Execute<ListStacksRequest>();
var marshaller = new ListStacksRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = ListStacksResponseUnmarshaller.Instance.Unmarshall(context)
as ListStacksResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("CloudFormation")]
public void SetStackPolicyMarshallTest()
{
var operation = service_model.FindOperation("SetStackPolicy");
var request = InstantiateClassGenerator.Execute<SetStackPolicyRequest>();
var marshaller = new SetStackPolicyRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("CloudFormation")]
public void SignalResourceMarshallTest()
{
var operation = service_model.FindOperation("SignalResource");
var request = InstantiateClassGenerator.Execute<SignalResourceRequest>();
var marshaller = new SignalResourceRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("CloudFormation")]
public void UpdateStackMarshallTest()
{
var operation = service_model.FindOperation("UpdateStack");
var request = InstantiateClassGenerator.Execute<UpdateStackRequest>();
var marshaller = new UpdateStackRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = UpdateStackResponseUnmarshaller.Instance.Unmarshall(context)
as UpdateStackResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Query")]
[TestCategory("CloudFormation")]
public void ValidateTemplateMarshallTest()
{
var operation = service_model.FindOperation("ValidateTemplate");
var request = InstantiateClassGenerator.Execute<ValidateTemplateRequest>();
var marshaller = new ValidateTemplateRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation);
validator.Validate();
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null);
var response = ValidateTemplateResponseUnmarshaller.Instance.Unmarshall(context)
as ValidateTemplateResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Asn1 {
public static class AsnIO {
public static byte[] FindDER(byte[] buf)
{
return FindBER(buf, true);
}
public static byte[] FindBER(byte[] buf)
{
return FindBER(buf, false);
}
/*
* Find a BER/DER object in the provided buffer. If the data is
* not already in the right format, conversion to string then
* Base64 decoding is attempted; in the latter case, PEM headers
* are detected and skipped. In any case, the returned buffer
* must begin with a well-formed tag and length, corresponding to
* the object length.
*
* If 'strictDER' is true, then the function furthermore insists
* on the object to use a defined DER length.
*
* The returned buffer may be the source buffer itself, or a newly
* allocated buffer.
*
* On error, null is returned.
*/
public static byte[] FindBER(byte[] buf, bool strictDER)
{
/*
* If it is already (from the outside) a BER object,
* return it.
*/
if (LooksLikeBER(buf, strictDER)) {
return buf;
}
/*
* Convert the blob to a string. We support UTF-16 with
* and without a BOM, UTF-8 with and without a BOM, and
* ASCII-compatible encodings. Non-ASCII characters get
* truncated.
*/
if (buf.Length < 3) {
return null;
}
string str = null;
if ((buf.Length & 1) == 0) {
if (buf[0] == 0xFE && buf[1] == 0xFF) {
// Starts with big-endian UTF-16 BOM
str = ConvertBi(buf, 2, true);
} else if (buf[0] == 0xFF && buf[1] == 0xFE) {
// Starts with little-endian UTF-16 BOM
str = ConvertBi(buf, 2, false);
} else if (buf[0] == 0) {
// First byte is 0 -> big-endian UTF-16
str = ConvertBi(buf, 0, true);
} else if (buf[1] == 0) {
// Second byte is 0 -> little-endian UTF-16
str = ConvertBi(buf, 0, false);
}
}
if (str == null) {
if (buf[0] == 0xEF
&& buf[1] == 0xBB
&& buf[2] == 0xBF)
{
// Starts with UTF-8 BOM
str = ConvertMono(buf, 3);
} else {
// Assumed ASCII-compatible mono-byte encoding
str = ConvertMono(buf, 0);
}
}
if (str == null) {
return null;
}
/*
* Try to detect a PEM header and footer; if we find both
* then we remove both, keeping only the characters that
* occur in between.
*/
int p = str.IndexOf("-----BEGIN");
int q = str.IndexOf("-----END");
if (p >= 0 && q >= 0) {
int r = str.IndexOf((char)10, p) + 1;
if (r > 0 && r <= q) {
str = str.Substring(r, q - r);
}
}
/*
* Convert from Base64.
*/
try {
buf = Convert.FromBase64String(str);
if (LooksLikeBER(buf, strictDER)) {
return buf;
}
} catch {
// ignored: not Base64
}
/*
* Decoding failed.
*/
return null;
}
/* =============================================================== */
/*
* Decode a tag; returned value is true on success, false otherwise.
* On success, 'off' is updated to point to the first byte after
* the tag.
*/
static bool DecodeTag(byte[] buf, int lim, ref int off)
{
int p = off;
if (p >= lim) {
return false;
}
int v = buf[p ++];
if ((v & 0x1F) == 0x1F) {
do {
if (p >= lim) {
return false;
}
v = buf[p ++];
} while ((v & 0x80) != 0);
}
off = p;
return true;
}
/*
* Decode a BER length. Returned value is:
* -2 no decodable length
* -1 indefinite length
* 0+ definite length
* If a definite or indefinite length could be decoded, then 'off'
* is updated to point to the first byte after the length.
*/
static int DecodeLength(byte[] buf, int lim, ref int off)
{
int p = off;
if (p >= lim) {
return -2;
}
int v = buf[p ++];
if (v < 0x80) {
off = p;
return v;
} else if (v == 0x80) {
off = p;
return -1;
}
v &= 0x7F;
if ((lim - p) < v) {
return -2;
}
int acc = 0;
while (v -- > 0) {
if (acc > 0x7FFFFF) {
return -2;
}
acc = (acc << 8) + buf[p ++];
}
off = p;
return acc;
}
/*
* Get the length, in bytes, of the object in the provided
* buffer. The object begins at offset 'off' but does not extend
* farther than offset 'lim'. If no such BER object can be
* decoded, then -1 is returned. The returned length includes
* that of the tag and length fields.
*/
static int BERLength(byte[] buf, int lim, int off)
{
int orig = off;
if (!DecodeTag(buf, lim, ref off)) {
return -1;
}
int len = DecodeLength(buf, lim, ref off);
if (len >= 0) {
if (len > (lim - off)) {
return -1;
}
return off + len - orig;
} else if (len < -1) {
return -1;
}
/*
* Indefinite length: we must do some recursive exploration.
* End of structure is marked by a "null tag": object has
* total length 2 and its tag byte is 0.
*/
for (;;) {
int slen = BERLength(buf, lim, off);
if (slen < 0) {
return -1;
}
off += slen;
if (slen == 2 && buf[off] == 0) {
return off - orig;
}
}
}
static bool LooksLikeBER(byte[] buf, bool strictDER)
{
return LooksLikeBER(buf, 0, buf.Length, strictDER);
}
static bool LooksLikeBER(byte[] buf, int off, int len, bool strictDER)
{
int lim = off + len;
int objLen = BERLength(buf, lim, off);
if (objLen != len) {
return false;
}
if (strictDER) {
DecodeTag(buf, lim, ref off);
return DecodeLength(buf, lim, ref off) >= 0;
} else {
return true;
}
}
static string ConvertMono(byte[] buf, int off)
{
int len = buf.Length - off;
char[] tc = new char[len];
for (int i = 0; i < len; i ++) {
int v = buf[off + i];
if (v < 1 || v > 126) {
v = '?';
}
tc[i] = (char)v;
}
return new string(tc);
}
static string ConvertBi(byte[] buf, int off, bool be)
{
int len = buf.Length - off;
if ((len & 1) != 0) {
return null;
}
len >>= 1;
char[] tc = new char[len];
for (int i = 0; i < len; i ++) {
int b0 = buf[off + (i << 1) + 0];
int b1 = buf[off + (i << 1) + 1];
int v = be ? ((b0 << 8) + b1) : (b0 + (b1 << 8));
if (v < 1 || v > 126) {
v = '?';
}
tc[i] = (char)v;
}
return new string(tc);
}
}
}
| |
// 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;
using System.Globalization;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Microsoft.Win32.SafeHandles;
namespace Internal.Cryptography.Pal
{
internal sealed class OpenSslX509CertificateReader : ICertificatePal
{
private static DateTimeFormatInfo s_validityDateTimeFormatInfo;
private SafeX509Handle _cert;
private SafeEvpPKeyHandle _privateKey;
private X500DistinguishedName _subjectName;
private X500DistinguishedName _issuerName;
internal OpenSslX509CertificateReader(SafeX509Handle handle)
{
// X509_check_purpose has the effect of populating the sha1_hash value,
// and other "initialize" type things.
bool init = Interop.Crypto.X509CheckPurpose(handle, -1, 0);
if (!init)
{
throw Interop.Crypto.CreateOpenSslCryptographicException();
}
_cert = handle;
}
public bool HasPrivateKey
{
get { return _privateKey != null; }
}
public IntPtr Handle
{
get { return _cert == null ? IntPtr.Zero : _cert.DangerousGetHandle(); }
}
internal SafeX509Handle SafeHandle
{
get { return _cert; }
}
public string Issuer
{
get { return IssuerName.Name; }
}
public string Subject
{
get { return SubjectName.Name; }
}
public byte[] Thumbprint
{
get
{
return Interop.Crypto.GetX509Thumbprint(_cert);
}
}
public string KeyAlgorithm
{
get
{
IntPtr oidPtr = Interop.Crypto.GetX509PublicKeyAlgorithm(_cert);
return Interop.Crypto.GetOidValue(oidPtr);
}
}
public byte[] KeyAlgorithmParameters
{
get
{
return Interop.Crypto.GetX509PublicKeyParameterBytes(_cert);
}
}
public byte[] PublicKeyValue
{
get
{
IntPtr keyBytesPtr = Interop.Crypto.GetX509PublicKeyBytes(_cert);
return Interop.Crypto.GetAsn1StringBytes(keyBytesPtr);
}
}
public byte[] SerialNumber
{
get
{
using (SafeSharedAsn1IntegerHandle serialNumber = Interop.Crypto.X509GetSerialNumber(_cert))
{
byte[] serial = Interop.Crypto.GetAsn1IntegerBytes(serialNumber);
// Windows returns this in BigInteger Little-Endian,
// OpenSSL returns this in BigInteger Big-Endian.
Array.Reverse(serial);
return serial;
}
}
}
public string SignatureAlgorithm
{
get
{
IntPtr oidPtr = Interop.Crypto.GetX509SignatureAlgorithm(_cert);
return Interop.Crypto.GetOidValue(oidPtr);
}
}
public DateTime NotAfter
{
get
{
return ExtractValidityDateTime(Interop.Crypto.GetX509NotAfter(_cert));
}
}
public DateTime NotBefore
{
get
{
return ExtractValidityDateTime(Interop.Crypto.GetX509NotBefore(_cert));
}
}
public byte[] RawData
{
get
{
return Interop.Crypto.OpenSslEncode(
x => Interop.Crypto.GetX509DerSize(x),
(x, buf) => Interop.Crypto.EncodeX509(x, buf),
_cert);
}
}
public int Version
{
get
{
int version = Interop.Crypto.GetX509Version(_cert);
if (version < 0)
{
throw new CryptographicException();
}
// The file encoding is v1(0), v2(1), v3(2).
// The .NET answers are 1, 2, 3.
return version + 1;
}
}
public bool Archived
{
get { return false; }
set
{
throw new PlatformNotSupportedException(
SR.Format(SR.Cryptography_Unix_X509_PropertyNotSettable, "Archived"));
}
}
public string FriendlyName
{
get { return ""; }
set
{
throw new PlatformNotSupportedException(
SR.Format(SR.Cryptography_Unix_X509_PropertyNotSettable, "FriendlyName"));
}
}
public X500DistinguishedName SubjectName
{
get
{
if (_subjectName == null)
{
_subjectName = Interop.Crypto.LoadX500Name(Interop.Crypto.X509GetSubjectName(_cert));
}
return _subjectName;
}
}
public X500DistinguishedName IssuerName
{
get
{
if (_issuerName == null)
{
_issuerName = Interop.Crypto.LoadX500Name(Interop.Crypto.X509GetIssuerName(_cert));
}
return _issuerName;
}
}
public IEnumerable<X509Extension> Extensions
{
get
{
int extensionCount = Interop.Crypto.X509GetExtCount(_cert);
X509Extension[] extensions = new X509Extension[extensionCount];
for (int i = 0; i < extensionCount; i++)
{
IntPtr ext = Interop.Crypto.X509GetExt(_cert, i);
Interop.Crypto.CheckValidOpenSslHandle(ext);
IntPtr oidPtr = Interop.Crypto.X509ExtensionGetOid(ext);
Interop.Crypto.CheckValidOpenSslHandle(oidPtr);
string oidValue = Interop.Crypto.GetOidValue(oidPtr);
Oid oid = new Oid(oidValue);
IntPtr dataPtr = Interop.Crypto.X509ExtensionGetData(ext);
Interop.Crypto.CheckValidOpenSslHandle(dataPtr);
byte[] extData = Interop.Crypto.GetAsn1StringBytes(dataPtr);
bool critical = Interop.Crypto.X509ExtensionGetCritical(ext);
extensions[i] = new X509Extension(oid, extData, critical);
}
return extensions;
}
}
internal void SetPrivateKey(SafeEvpPKeyHandle privateKey)
{
_privateKey = privateKey;
}
internal SafeEvpPKeyHandle PrivateKeyHandle
{
get { return _privateKey; }
}
public RSA GetRSAPrivateKey()
{
if (_privateKey == null || _privateKey.IsInvalid)
{
return null;
}
return new RSAOpenSsl(_privateKey);
}
public ECDsa GetECDsaPublicKey()
{
using (SafeEvpPKeyHandle publicKeyHandle = Interop.Crypto.GetX509EvpPublicKey(_cert))
{
Interop.Crypto.CheckValidOpenSslHandle(publicKeyHandle);
return new ECDsaOpenSsl(publicKeyHandle);
}
}
public ECDsa GetECDsaPrivateKey()
{
if (_privateKey == null || _privateKey.IsInvalid)
{
return null;
}
return new ECDsaOpenSsl(_privateKey);
}
public string GetNameInfo(X509NameType nameType, bool forIssuer)
{
using (SafeBioHandle bioHandle = Interop.Crypto.GetX509NameInfo(_cert, (int)nameType, forIssuer))
{
if (bioHandle.IsInvalid)
{
return "";
}
int bioSize = Interop.Crypto.GetMemoryBioSize(bioHandle);
// Ensure space for the trailing \0
var buf = new byte[bioSize + 1];
int read = Interop.Crypto.BioGets(bioHandle, buf, buf.Length);
if (read < 0)
{
throw Interop.Crypto.CreateOpenSslCryptographicException();
}
return Encoding.UTF8.GetString(buf, 0, read);
}
}
public void AppendPrivateKeyInfo(StringBuilder sb)
{
if (!HasPrivateKey)
{
return;
}
// There's nothing really to say about the key, just acknowledge there is one.
sb.AppendLine();
sb.AppendLine();
sb.AppendLine("[Private Key]");
}
public void Dispose()
{
if (_privateKey != null)
{
_privateKey.Dispose();
_privateKey = null;
}
if (_cert != null)
{
_cert.Dispose();
_cert = null;
}
}
internal OpenSslX509CertificateReader DuplicateHandles()
{
SafeX509Handle certHandle = Interop.Crypto.X509UpRef(_cert);
OpenSslX509CertificateReader duplicate = new OpenSslX509CertificateReader(certHandle);
if (_privateKey != null)
{
SafeEvpPKeyHandle keyHandle = _privateKey.DuplicateHandle();
duplicate.SetPrivateKey(keyHandle);
}
return duplicate;
}
internal static DateTime ExtractValidityDateTime(IntPtr validityDatePtr)
{
byte[] bytes = Interop.Crypto.GetAsn1StringBytes(validityDatePtr);
// RFC 5280 (X509v3 - https://tools.ietf.org/html/rfc5280)
// states that the validity times are either UTCTime:YYMMDDHHMMSSZ (13 bytes)
// or GeneralizedTime:YYYYMMDDHHMMSSZ (15 bytes).
// Technically, both UTCTime and GeneralizedTime can have more complicated
// representations, but X509 restricts them to only the one form each.
//
// Furthermore, the UTCTime year values are to be interpreted as 1950-2049.
//
// No mention is made in RFC 5280 of different rules for v1 or v2 certificates.
Debug.Assert(bytes != null);
Debug.Assert(
bytes.Length == 13 || bytes.Length == 15,
"DateTime value should be UTCTime (13 bytes) or GeneralizedTime (15 bytes)");
Debug.Assert(
bytes[bytes.Length - 1] == 'Z',
"DateTime value should end with Z marker");
if (bytes == null || bytes.Length < 1 || bytes[bytes.Length - 1] != 'Z')
{
throw new CryptographicException();
}
string dateString = Encoding.ASCII.GetString(bytes);
if (s_validityDateTimeFormatInfo == null)
{
DateTimeFormatInfo validityFormatInfo =
(DateTimeFormatInfo)CultureInfo.InvariantCulture.DateTimeFormat.Clone();
// Two-digit years are 1950-2049
validityFormatInfo.Calendar.TwoDigitYearMax = 2049;
s_validityDateTimeFormatInfo = validityFormatInfo;
}
if (bytes.Length == 13)
{
DateTime utcTime;
if (!DateTime.TryParseExact(
dateString,
"yyMMddHHmmss'Z'",
s_validityDateTimeFormatInfo,
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal,
out utcTime))
{
throw new CryptographicException();
}
return utcTime.ToLocalTime();
}
if (bytes.Length == 15)
{
DateTime generalizedTime;
if (!DateTime.TryParseExact(
dateString,
"yyyyMMddHHmmss'Z'",
s_validityDateTimeFormatInfo,
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal,
out generalizedTime))
{
throw new CryptographicException();
}
return generalizedTime.ToLocalTime();
}
throw new CryptographicException();
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Cluster
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Events;
using Apache.Ignite.Core.Messaging;
using Apache.Ignite.Core.Services;
/// <summary>
/// Defines grid projection which represents a common functionality over a group of nodes.
/// Grid projection allows to group Ignite nodes into various subgroups to perform distributed
/// operations on them. All ForXXX(...)' methods will create a child grid projection
/// from existing projection. If you create a new projection from current one, then the resulting
/// projection will include a subset of nodes from current projection. The following code snippet
/// shows how to create grid projections:
/// <code>
/// var g = Ignition.GetIgnite();
///
/// // Projection over remote nodes.
/// var remoteNodes = g.ForRemotes();
///
/// // Projection over random remote node.
/// var randomNode = g.ForRandom();
///
/// // Projection over all nodes with cache named "myCache" enabled.
/// var cacheNodes = g.ForCacheNodes("myCache");
///
/// // Projection over all nodes that have user attribute "group" set to value "worker".
/// var workerNodes = g.ForAttribute("group", "worker");
/// </code>
/// Grid projection provides functionality for executing tasks and closures over
/// nodes in this projection using <see cref="GetCompute"/>.
/// <para/>
/// All members are thread-safe and may be used concurrently from multiple threads.
/// </summary>
public interface IClusterGroup
{
/// <summary>
/// Instance of Ignite.
/// </summary>
IIgnite Ignite { get; }
/// <summary>
/// Gets compute functionality over this grid projection. All operations
/// on the returned ICompute instance will only include nodes from
/// this projection.
/// </summary>
/// <returns>Compute instance over this grid projection.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Semantics.")]
ICompute GetCompute();
/// <summary>
/// Creates a grid projection over a given set of nodes.
/// </summary>
/// <param name="nodes">Collection of nodes to create a projection from.</param>
/// <returns>Projection over provided Ignite nodes.</returns>
IClusterGroup ForNodes(IEnumerable<IClusterNode> nodes);
/// <summary>
/// Creates a grid projection over a given set of nodes.
/// </summary>
/// <param name="nodes">Collection of nodes to create a projection from.</param>
/// <returns>Projection over provided Ignite nodes.</returns>
IClusterGroup ForNodes(params IClusterNode[] nodes);
/// <summary>
/// Creates a grid projection over a given set of node IDs.
/// </summary>
/// <param name="ids">Collection of node IDs to create a projection from.</param>
/// <returns>Projection over provided Ignite node IDs.</returns>
IClusterGroup ForNodeIds(IEnumerable<Guid> ids);
/// <summary>
/// Creates a grid projection over a given set of node IDs.
/// </summary>
/// <param name="ids">Collection of node IDs to create a projection from.</param>
/// <returns>Projection over provided Ignite node IDs.</returns>
IClusterGroup ForNodeIds(params Guid[] ids);
/// <summary>
/// Creates a grid projection which includes all nodes that pass the given predicate filter.
/// </summary>
/// <param name="p">Predicate filter for nodes to include into this projection.</param>
/// <returns>Grid projection for nodes that passed the predicate filter.</returns>
IClusterGroup ForPredicate(Func<IClusterNode, bool> p);
/// <summary>
/// Creates projection for nodes containing given name and value
/// specified in user attributes.
/// </summary>
/// <param name="name">Name of the attribute.</param>
/// <param name="val">Optional attribute value to match.</param>
/// <returns>Grid projection for nodes containing specified attribute.</returns>
IClusterGroup ForAttribute(string name, string val);
/// <summary>
/// Creates projection for all nodes that have cache with specified name running.
/// </summary>
/// <param name="name">Cache name to include into projection.</param>
/// <returns>Projection over nodes that have specified cache running.</returns>
IClusterGroup ForCacheNodes(string name);
/// <summary>
/// Creates projection for all nodes that have cache with specified name running
/// and cache distribution mode is PARTITIONED_ONLY or NEAR_PARTITIONED.
/// </summary>
/// <param name="name">Cache name to include into projection.</param>
/// <returns>Projection over nodes that have specified cache running.</returns>
IClusterGroup ForDataNodes(string name);
/// <summary>
/// Creates projection for all nodes that have cache with specified name running
/// and cache distribution mode is CLIENT_ONLY or NEAR_ONLY.
/// </summary>
/// <param name="name">Cache name to include into projection.</param>
/// <returns>Projection over nodes that have specified cache running.</returns>
IClusterGroup ForClientNodes(string name);
/// <summary>
/// Gets grid projection consisting from the nodes in this projection excluding the local node.
/// </summary>
/// <returns>Grid projection consisting from the nodes in this projection excluding the local node.</returns>
IClusterGroup ForRemotes();
/// <summary>
/// Gets a cluster group consisting of the daemon nodes.
/// <para />
/// Daemon nodes are the usual grid nodes that participate in topology but not visible on the main APIs,
/// i.e. they are not part of any cluster group. The only way to see daemon nodes is to use this method.
/// <para />
/// Daemon nodes are used primarily for management and monitoring functionality that
/// is build on Ignite and needs to participate in the topology, but also needs to be
/// excluded from the "normal" topology, so that it won't participate in the task execution
/// or in-memory data grid storage.
/// </summary>
/// <returns>Cluster group consisting of the daemon nodes.</returns>
IClusterGroup ForDaemons();
/// <summary>
/// Gets grid projection consisting from the nodes in this projection residing on the
/// same host as given node.
/// </summary>
/// <param name="node">Node residing on the host for which projection is created.</param>
/// <returns>Projection for nodes residing on the same host as passed in node.</returns>
IClusterGroup ForHost(IClusterNode node);
/// <summary>
/// Creates grid projection with one random node from current projection.
/// </summary>
/// <returns>Grid projection with one random node from current projection.</returns>
IClusterGroup ForRandom();
/// <summary>
/// Creates grid projection with one oldest node in the current projection.
/// The resulting projection is dynamic and will always pick the next oldest
/// node if the previous one leaves topology even after the projection has
/// been created.
/// </summary>
/// <returns>Grid projection with one oldest node from the current projection.</returns>
IClusterGroup ForOldest();
/// <summary>
/// Creates grid projection with one youngest node in the current projection.
/// The resulting projection is dynamic and will always pick the newest
/// node in the topology, even if more nodes entered after the projection
/// has been created.
/// </summary>
/// <returns>Grid projection with one youngest node from the current projection.</returns>
IClusterGroup ForYoungest();
/// <summary>
/// Creates grid projection for nodes supporting .Net, i.e. for nodes started with Apache.Ignite.exe.
/// </summary>
/// <returns>Grid projection for nodes supporting .Net.</returns>
IClusterGroup ForDotNet();
/// <summary>
/// Creates a cluster group of nodes started in server mode (<see cref="IgniteConfiguration.ClientMode"/>).
/// </summary>
/// <returns>Cluster group of nodes started in server mode.</returns>
IClusterGroup ForServers();
/// <summary>
/// Gets read-only collections of nodes in this projection.
/// </summary>
/// <returns>All nodes in this projection.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Semantics.")]
ICollection<IClusterNode> GetNodes();
/// <summary>
/// Gets a node for given ID from this grid projection.
/// </summary>
/// <param name="id">Node ID.</param>
/// <returns>Node with given ID from this projection or null if such node does not
/// exist in this projection.</returns>
IClusterNode GetNode(Guid id);
/// <summary>
/// Gets first node from the list of nodes in this projection.
/// </summary>
/// <returns>Node.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Semantics.")]
IClusterNode GetNode();
/// <summary>
/// Gets a metrics snapshot for this projection
/// </summary>
/// <returns>Grid projection metrics snapshot.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Semantics.")]
IClusterMetrics GetMetrics();
/// <summary>
/// Gets messaging facade over nodes within this cluster group. All operations on the returned
/// <see cref="IMessaging"/>> instance will only include nodes from current cluster group.
/// </summary>
/// <returns>Messaging instance over this cluster group.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Semantics.")]
IMessaging GetMessaging();
/// <summary>
/// Gets events facade over nodes within this cluster group. All operations on the returned
/// <see cref="IEvents"/>> instance will only include nodes from current cluster group.
/// </summary>
/// <returns>Events instance over this cluster group.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Semantics.")]
IEvents GetEvents();
/// <summary>
/// Gets services facade over nodes within this cluster group. All operations on the returned
/// <see cref="IServices"/>> instance will only include nodes from current cluster group.
/// </summary>
/// <returns>Services instance over this cluster group.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Semantics.")]
IServices GetServices();
/// <summary>
/// Sets statistics enabled flag globally for the caches
/// </summary>
/// <param name="cacheNames">Collection of cache names to set the flag</param>
/// <param name="enabled">Enabled flag</param>
void EnableStatistics(IEnumerable<string> cacheNames, bool enabled);
/// <summary>
/// Clears statistics for caches cluster wide.
/// </summary>
/// <param name="caches">Collection of cache names.</param>
void ClearStatistics(IEnumerable<string> caches);
}
}
| |
/**
* 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
*
* 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.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using NUnit.Framework;
using Avro.Specific;
namespace Avro.Test
{
[TestFixture]
class CodeGenTest
{
[Test]
public void TestGetNullableTypeException()
{
Assert.Throws<ArgumentNullException>(() => CodeGen.GetNullableType(null));
}
#if !NETCOREAPP // System.CodeDom compilation not supported in .NET Core: https://github.com/dotnet/corefx/issues/12180
[TestCase(@"{
""type"" : ""record"",
""name"" : ""ClassKeywords"",
""namespace"" : ""com.base"",
""fields"" :
[
{ ""name"" : ""int"", ""type"" : ""int"" },
{ ""name"" : ""base"", ""type"" : ""long"" },
{ ""name"" : ""event"", ""type"" : ""boolean"" },
{ ""name"" : ""foreach"", ""type"" : ""double"" },
{ ""name"" : ""bool"", ""type"" : ""float"" },
{ ""name"" : ""internal"", ""type"" : ""bytes"" },
{ ""name"" : ""while"", ""type"" : ""string"" },
{ ""name"" : ""return"", ""type"" : ""null"" },
{ ""name"" : ""enum"", ""type"" : { ""type"" : ""enum"", ""name"" : ""class"", ""symbols"" : [ ""Unknown"", ""A"", ""B"" ], ""default"" : ""Unknown"" } },
{ ""name"" : ""string"", ""type"" : { ""type"": ""fixed"", ""size"": 16, ""name"": ""static"" } }
]
}
", new object[] {"com.base.ClassKeywords", typeof(int), typeof(long), typeof(bool), typeof(double), typeof(float), typeof(byte[]), typeof(string),typeof(object),"com.base.class", "com.base.static"}, TestName = "TestCodeGen0")]
[TestCase(@"{
""type"" : ""record"",
""name"" : ""AvroNamespaceType"",
""namespace"" : ""My.Avro"",
""fields"" :
[
{ ""name"" : ""justenum"", ""type"" : { ""type"" : ""enum"", ""name"" : ""justenumEnum"", ""symbols"" : [ ""One"", ""Two"" ] } },
]
}
", new object[] {"My.Avro.AvroNamespaceType", "My.Avro.justenumEnum"}, TestName = "TestCodeGen3 - Avro namespace conflict")]
[TestCase(@"{
""type"" : ""record"",
""name"" : ""SchemaObject"",
""namespace"" : ""schematest"",
""fields"" :
[
{ ""name"" : ""myobject"", ""type"" :
[
""null"",
{""type"" : ""array"", ""items"" : [ ""null"",
{ ""type"" : ""enum"", ""name"" : ""MyEnum"", ""symbols"" : [ ""A"", ""B"" ] },
{ ""type"": ""fixed"", ""size"": 16, ""name"": ""MyFixed"" }
]
}
]
}
]
}
", new object[] { "schematest.SchemaObject", typeof(IList<object>) }, TestName = "TestCodeGen1")]
[TestCase(@"{
""type"" : ""record"",
""name"" : ""LogicalTypes"",
""namespace"" : ""schematest"",
""fields"" :
[
{ ""name"" : ""nullibleguid"", ""type"" : [""null"", {""type"": ""string"", ""logicalType"": ""uuid"" } ]},
{ ""name"" : ""guid"", ""type"" : {""type"": ""string"", ""logicalType"": ""uuid"" } },
{ ""name"" : ""nullibletimestampmillis"", ""type"" : [""null"", {""type"": ""long"", ""logicalType"": ""timestamp-millis""}] },
{ ""name"" : ""timestampmillis"", ""type"" : {""type"": ""long"", ""logicalType"": ""timestamp-millis""} },
{ ""name"" : ""nullibiletimestampmicros"", ""type"" : [""null"", {""type"": ""long"", ""logicalType"": ""timestamp-micros""}] },
{ ""name"" : ""timestampmicros"", ""type"" : {""type"": ""long"", ""logicalType"": ""timestamp-micros""} },
{ ""name"" : ""nullibiletimemicros"", ""type"" : [""null"", {""type"": ""long"", ""logicalType"": ""time-micros""}] },
{ ""name"" : ""timemicros"", ""type"" : {""type"": ""long"", ""logicalType"": ""time-micros""} },
{ ""name"" : ""nullibiletimemillis"", ""type"" : [""null"", {""type"": ""int"", ""logicalType"": ""time-millis""}] },
{ ""name"" : ""timemillis"", ""type"" : {""type"": ""int"", ""logicalType"": ""time-millis""} },
{ ""name"" : ""nullibledecimal"", ""type"" : [""null"", {""type"": ""bytes"", ""logicalType"": ""decimal"", ""precision"": 4, ""scale"": 2}] },
{ ""name"" : ""decimal"", ""type"" : {""type"": ""bytes"", ""logicalType"": ""decimal"", ""precision"": 4, ""scale"": 2} }
]
}
", new object[] { "schematest.LogicalTypes", typeof(Guid?), typeof(Guid), typeof(DateTime?), typeof(DateTime), typeof(DateTime?), typeof(DateTime), typeof(TimeSpan?), typeof(TimeSpan), typeof(TimeSpan?), typeof(TimeSpan), typeof(AvroDecimal?), typeof(AvroDecimal) }, TestName = "TestCodeGen2 - Logical Types")]
public static void TestCodeGen(string str, object[] result)
{
Schema schema = Schema.Parse(str);
CompilerResults compres = GenerateSchema(schema);
// instantiate object
ISpecificRecord rec = compres.CompiledAssembly.CreateInstance((string)result[0]) as ISpecificRecord;
Assert.IsNotNull(rec);
// test type of each fields
for (int i = 1; i < result.Length; ++i)
{
object field = rec.Get(i - 1);
Type stype;
if (result[i].GetType() == typeof(string))
{
object obj = compres.CompiledAssembly.CreateInstance((string)result[i]);
Assert.IsNotNull(obj);
stype = obj.GetType();
}
else
stype = (Type)result[i];
if (!stype.IsValueType)
Assert.IsNull(field); // can't test reference type, it will be null
else if (stype.IsValueType && field == null)
Assert.IsNull(field); // nullable value type, so we can't get the type using GetType
else
Assert.AreEqual(stype, field.GetType());
}
}
[TestCase(@"{
""type"": ""fixed"",
""namespace"": ""com.base"",
""name"": ""MD5"",
""size"": 16
}", null, null, "com.base")]
[TestCase(@"{
""type"": ""fixed"",
""namespace"": ""com.base"",
""name"": ""MD5"",
""size"": 16
}", "com.base", "SchemaTest", "SchemaTest")]
[TestCase(@"{
""type"": ""fixed"",
""namespace"": ""com.base"",
""name"": ""MD5"",
""size"": 16
}", "miss", "SchemaTest", "com.base")]
public void TestCodeGenNamespaceMapping(string str, string avroNamespace, string csharpNamespace,
string expectedNamespace)
{
Schema schema = Schema.Parse(str);
var codegen = new CodeGen();
codegen.AddSchema(schema);
if (avroNamespace != null && csharpNamespace != null)
{
codegen.NamespaceMapping[avroNamespace] = csharpNamespace;
}
var results = GenerateAssembly(codegen);
foreach(var type in results.CompiledAssembly.GetTypes())
{
Assert.AreEqual(expectedNamespace, type.Namespace);
}
}
private static CompilerResults GenerateSchema(Schema schema)
{
var codegen = new CodeGen();
codegen.AddSchema(schema);
return GenerateAssembly(codegen);
}
private static CompilerResults GenerateAssembly(CodeGen schema)
{
var compileUnit = schema.GenerateCode();
var comparam = new CompilerParameters(new string[] { "netstandard.dll" });
comparam.ReferencedAssemblies.Add("System.dll");
comparam.ReferencedAssemblies.Add(Path.Combine(TestContext.CurrentContext.TestDirectory, "Avro.dll"));
comparam.GenerateInMemory = true;
var ccp = new CSharpCodeProvider();
var units = new[] { compileUnit };
var compres = ccp.CompileAssemblyFromDom(comparam, units);
if (compres.Errors.Count > 0)
{
for (int i = 0; i < compres.Errors.Count; i++)
Console.WriteLine(compres.Errors[i]);
}
Assert.AreEqual(0, compres.Errors.Count);
return compres;
}
#endif
[TestFixture]
public class CodeGenTestClass : CodeGen
{
[Test]
public void TestGenerateNamesException()
{
Protocol protocol = null;
Assert.Throws<ArgumentNullException>(() => this.GenerateNames(protocol));
}
}
}
}
| |
//------------------------------------------------------------------------------
// <license file="NativeGlobal.cs">
//
// The use and distribution terms for this software are contained in the file
// named 'LICENSE', which can be found in the resources directory of this
// distribution.
//
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// </license>
//------------------------------------------------------------------------------
using System;
using EcmaScript.NET.Types.E4X;
namespace EcmaScript.NET.Types
{
/// <summary> This class implements the global native object (function and value
/// properties only).
///
/// See ECMA 15.1.[12].
///
/// </summary>
public class BuiltinGlobal : IIdFunctionCall
{
public static void Init (Context cx, IScriptable scope, bool zealed)
{
BuiltinGlobal obj = new BuiltinGlobal ();
for (int id = 1; id <= LAST_SCOPE_FUNCTION_ID; ++id) {
string name;
int arity = 1;
switch (id) {
case Id_decodeURI:
name = "decodeURI";
break;
case Id_decodeURIComponent:
name = "decodeURIComponent";
break;
case Id_encodeURI:
name = "encodeURI";
break;
case Id_encodeURIComponent:
name = "encodeURIComponent";
break;
case Id_escape:
name = "escape";
break;
case Id_eval:
name = "eval";
break;
case Id_isFinite:
name = "isFinite";
break;
case Id_isNaN:
name = "isNaN";
break;
case Id_isXMLName:
name = "isXMLName";
break;
case Id_parseFloat:
name = "parseFloat";
break;
case Id_parseInt:
name = "parseInt";
arity = 2;
break;
case Id_unescape:
name = "unescape";
break;
case Id_uneval:
name = "uneval";
break;
default:
throw Context.CodeBug ();
}
IdFunctionObject f = new IdFunctionObject (obj, FTAG, id, name, arity, scope);
if (zealed) {
f.SealObject ();
}
f.ExportAsScopeProperty ();
}
ScriptableObject.DefineProperty (scope, "NaN", (object)double.NaN, ScriptableObject.DONTENUM);
ScriptableObject.DefineProperty (scope, "Infinity", (System.Double.PositiveInfinity), ScriptableObject.DONTENUM);
ScriptableObject.DefineProperty (scope, "undefined", Undefined.Value, ScriptableObject.DONTENUM);
string [] errorMethods = new string [] {
"ConversionError",
"EvalError",
"RangeError",
"ReferenceError",
"SyntaxError",
"TypeError",
"URIError",
"InternalError",
"JavaException"
};
/*
Each error constructor gets its own Error object as a prototype,
with the 'name' property set to the name of the error.
*/
for (int i = 0; i < errorMethods.Length; i++) {
string name = errorMethods [i];
IScriptable errorProto = ScriptRuntime.NewObject (cx, scope, "Error", ScriptRuntime.EmptyArgs);
errorProto.Put ("name", errorProto, name);
if (zealed) {
if (errorProto is ScriptableObject) {
((ScriptableObject)errorProto).SealObject ();
}
}
IdFunctionObject ctor = new IdFunctionObject (obj, FTAG, Id_new_CommonError, name, 1, scope);
ctor.MarkAsConstructor (errorProto);
if (zealed) {
ctor.SealObject ();
}
ctor.ExportAsScopeProperty ();
}
}
public virtual object ExecIdCall (IdFunctionObject f, Context cx, IScriptable scope, IScriptable thisObj, object [] args)
{
if (f.HasTag (FTAG)) {
int methodId = f.MethodId;
switch (methodId) {
case Id_decodeURI:
case Id_decodeURIComponent: {
string str = ScriptConvert.ToString (args, 0);
return decode (str, methodId == Id_decodeURI);
}
case Id_encodeURI:
case Id_encodeURIComponent: {
string str = ScriptConvert.ToString (args, 0);
return encode (str, methodId == Id_encodeURI);
}
case Id_escape:
return js_escape (args);
case Id_eval:
return ImplEval (cx, scope, thisObj, args);
case Id_isFinite: {
bool result;
if (args.Length < 1) {
result = false;
}
else {
double d = ScriptConvert.ToNumber (args [0]);
result = (!double.IsNaN (d) && d != System.Double.PositiveInfinity && d != System.Double.NegativeInfinity);
}
return result;
}
case Id_isNaN: {
// The global method isNaN, as per ECMA-262 15.1.2.6.
bool result;
if (args.Length < 1) {
result = true;
}
else {
double d = ScriptConvert.ToNumber (args [0]);
result = (double.IsNaN (d));
}
return result;
}
case Id_isXMLName: {
object name = (args.Length == 0) ? Undefined.Value : args [0];
XMLLib xmlLib = XMLLib.ExtractFromScope (scope);
return xmlLib.IsXMLName (cx, name);
}
case Id_parseFloat:
return js_parseFloat (args);
case Id_parseInt:
return js_parseInt (args);
case Id_unescape:
return js_unescape (args);
case Id_uneval: {
object value = (args.Length != 0) ? args [0] : Undefined.Value;
return ScriptRuntime.uneval (cx, scope, value);
}
case Id_new_CommonError:
// The implementation of all the ECMA error constructors
// (SyntaxError, TypeError, etc.)
return BuiltinError.make (cx, scope, f, args);
}
}
throw f.Unknown ();
}
/// <summary> The global method parseInt, as per ECMA-262 15.1.2.2.</summary>
private object js_parseInt (object [] args)
{
string s = ScriptConvert.ToString (args, 0);
int radix = ScriptConvert.ToInt32 (args, 1);
int len = s.Length;
if (len == 0)
return double.NaN;
bool negative = false;
int start = 0;
char c;
do {
c = s [start];
if (!char.IsWhiteSpace (c))
break;
start++;
}
while (start < len);
if (c == '+' || (negative = (c == '-')))
start++;
const int NO_RADIX = -1;
if (radix == 0) {
radix = NO_RADIX;
}
else if (radix < 2 || radix > 36) {
return double.NaN;
}
else if (radix == 16 && len - start > 1 && s [start] == '0') {
c = s [start + 1];
if (c == 'x' || c == 'X')
start += 2;
}
if (radix == NO_RADIX) {
radix = 10;
if (len - start > 1 && s [start] == '0') {
c = s [start + 1];
if (c == 'x' || c == 'X') {
radix = 16;
start += 2;
}
else if ('0' <= c && c <= '9') {
radix = 8;
start++;
}
}
}
double d = ScriptConvert.ToNumber (s, start, radix);
return (negative ? -d : d);
}
/// <summary> The global method parseFloat, as per ECMA-262 15.1.2.3.
///
/// </summary>
/// <param name="cx">unused
/// </param>
/// <param name="thisObj">unused
/// </param>
/// <param name="args">the arguments to parseFloat, ignoring args[>=1]
/// </param>
/// <param name="funObj">unused
/// </param>
private object js_parseFloat (object [] args)
{
if (args.Length < 1)
return double.NaN;
string s = ScriptConvert.ToString (args [0]);
int len = s.Length;
int start = 0;
// Scan forward to skip whitespace
char c;
for (; ; ) {
if (start == len) {
return double.NaN;
}
c = s [start];
if (!TokenStream.isJSSpace (c)) {
break;
}
++start;
}
int i = start;
if (c == '+' || c == '-') {
++i;
if (i == len) {
return double.NaN;
}
c = s [i];
}
if (c == 'I') {
// check for "Infinity"
if (i + 8 <= len && String.Compare (s, i, "Infinity", 0, 8) == 0) {
double d;
if (s [start] == '-') {
d = System.Double.NegativeInfinity;
}
else {
d = System.Double.PositiveInfinity;
}
return (d);
}
return double.NaN;
}
// Find the end of the legal bit
int dec = -1;
int exponent = -1;
for (; i < len; i++) {
switch (s [i]) {
case '.':
if (dec != -1)
// Only allow a single decimal point.
break;
dec = i;
continue;
case 'e':
case 'E':
if (exponent != -1)
break;
exponent = i;
continue;
case '+':
case '-':
// Only allow '+' or '-' after 'e' or 'E'
if (exponent != i - 1)
break;
continue;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
continue;
default:
break;
}
break;
}
s = s.Substring (start, (i) - (start));
try {
return System.Double.Parse (s, BuiltinNumber.NumberFormatter);
}
catch (OverflowException) {
// HACK
if (s [0] == '-')
return double.NegativeInfinity;
else
return double.PositiveInfinity;
}
catch (Exception) {
return double.NaN;
}
}
/// <summary> The global method escape, as per ECMA-262 15.1.2.4.
/// Includes code for the 'mask' argument supported by the C escape
/// method, which used to be part of the browser imbedding. Blame
/// for the strange constant names should be directed there.
/// </summary>
private object js_escape (object [] args)
{
const int URL_XALPHAS = 1;
const int URL_XPALPHAS = 2;
const int URL_PATH = 4;
string s = ScriptConvert.ToString (args, 0);
int mask = URL_XALPHAS | URL_XPALPHAS | URL_PATH;
if (args.Length > 1) {
// the 'mask' argument. Non-ECMA.
double d = ScriptConvert.ToNumber (args [1]);
if (double.IsNaN (d) || ((mask = (int)d) != d) || 0 != (mask & ~(URL_XALPHAS | URL_XPALPHAS | URL_PATH))) {
throw Context.ReportRuntimeErrorById ("msg.bad.esc.mask");
}
}
System.Text.StringBuilder sb = null;
for (int k = 0, L = s.Length; k != L; ++k) {
int c = s [k];
if (mask != 0 && ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '@' || c == '*' || c == '_' || c == '-' || c == '.' || (0 != (mask & URL_PATH) && (c == '/' || c == '+')))) {
if (sb != null) {
sb.Append ((char)c);
}
}
else {
if (sb == null) {
sb = new System.Text.StringBuilder (L + 3);
sb.Append (s);
sb.Length = k;
}
int hexSize;
if (c < 256) {
if (c == ' ' && mask == URL_XPALPHAS) {
sb.Append ('+');
continue;
}
sb.Append ('%');
hexSize = 2;
}
else {
sb.Append ('%');
sb.Append ('u');
hexSize = 4;
}
// append hexadecimal form of c left-padded with 0
for (int shift = (hexSize - 1) * 4; shift >= 0; shift -= 4) {
int digit = 0xf & (c >> shift);
int hc = (digit < 10) ? '0' + digit : 'A' - 10 + digit;
sb.Append ((char)hc);
}
}
}
return (sb == null) ? s : sb.ToString ();
}
/// <summary> The global unescape method, as per ECMA-262 15.1.2.5.</summary>
private object js_unescape (object [] args)
{
string s = ScriptConvert.ToString (args, 0);
int firstEscapePos = s.IndexOf ((char)'%');
if (firstEscapePos >= 0) {
int L = s.Length;
char [] buf = s.ToCharArray ();
int destination = firstEscapePos;
for (int k = firstEscapePos; k != L; ) {
char c = buf [k];
++k;
if (c == '%' && k != L) {
int end, start;
if (buf [k] == 'u') {
start = k + 1;
end = k + 5;
}
else {
start = k;
end = k + 2;
}
if (end <= L) {
int x = 0;
for (int i = start; i != end; ++i) {
x = ScriptConvert.XDigitToInt (buf [i], x);
}
if (x >= 0) {
c = (char)x;
k = end;
}
}
}
buf [destination] = c;
++destination;
}
s = new string (buf, 0, destination);
}
return s;
}
private object ImplEval (Context cx, IScriptable scope, IScriptable thisObj, object [] args)
{
if (cx.Version == Context.Versions.JS1_4) {
Context.ReportWarningById ("msg.cant.call.indirect", "eval");
return ScriptRuntime.evalSpecial (cx, scope, thisObj, args, string.Empty, 0);
}
throw ScriptRuntime.ConstructError ("EvalError", ScriptRuntime.GetMessage ("msg.cant.call.indirect", "eval"));
}
internal static bool isEvalFunction (object functionObj)
{
if (functionObj is IdFunctionObject) {
IdFunctionObject function = (IdFunctionObject)functionObj;
if (function.HasTag (FTAG) && function.MethodId == Id_eval) {
return true;
}
}
return false;
}
/*
* ECMA 3, 15.1.3 URI Handling Function Properties
*
* The following are implementations of the algorithms
* given in the ECMA specification for the hidden functions
* 'Encode' and 'Decode'.
*/
private static string encode (string str, bool fullUri)
{
sbyte [] utf8buf = null;
System.Text.StringBuilder sb = null;
for (int k = 0, length = str.Length; k != length; ++k) {
char C = str [k];
if (encodeUnescaped (C, fullUri)) {
if (sb != null) {
sb.Append (C);
}
}
else {
if (sb == null) {
sb = new System.Text.StringBuilder (length + 3);
sb.Append (str);
sb.Length = k;
utf8buf = new sbyte [6];
}
if (0xDC00 <= C && C <= 0xDFFF) {
throw Context.ReportRuntimeErrorById ("msg.bad.uri");
}
int V;
if (C < 0xD800 || 0xDBFF < C) {
V = C;
}
else {
k++;
if (k == length) {
throw Context.ReportRuntimeErrorById ("msg.bad.uri");
}
char C2 = str [k];
if (!(0xDC00 <= C2 && C2 <= 0xDFFF)) {
throw Context.ReportRuntimeErrorById ("msg.bad.uri");
}
V = ((C - 0xD800) << 10) + (C2 - 0xDC00) + 0x10000;
}
int L = oneUcs4ToUtf8Char (utf8buf, V);
for (int j = 0; j < L; j++) {
int d = 0xff & utf8buf [j];
sb.Append ('%');
sb.Append (toHexChar ((int)((uint)d >> 4)));
sb.Append (toHexChar (d & 0xf));
}
}
}
return (sb == null) ? str : sb.ToString ();
}
private static char toHexChar (int i)
{
if (i >> 4 != 0)
Context.CodeBug ();
return (char)((i < 10) ? i + '0' : i - 10 + 'a');
}
private static int unHex (char c)
{
if ('A' <= c && c <= 'F') {
return c - 'A' + 10;
}
else if ('a' <= c && c <= 'f') {
return c - 'a' + 10;
}
else if ('0' <= c && c <= '9') {
return c - '0';
}
else {
return -1;
}
}
private static int unHex (char c1, char c2)
{
int i1 = unHex (c1);
int i2 = unHex (c2);
if (i1 >= 0 && i2 >= 0) {
return (i1 << 4) | i2;
}
return -1;
}
private static string decode (string str, bool fullUri)
{
char [] buf = null;
int bufTop = 0;
for (int k = 0, length = str.Length; k != length; ) {
char C = str [k];
if (C != '%') {
if (buf != null) {
buf [bufTop++] = C;
}
++k;
}
else {
if (buf == null) {
// decode always compress so result can not be bigger then
// str.length()
buf = new char [length];
str.ToCharArray (0, k).CopyTo (buf, 0);
bufTop = k;
}
int start = k;
if (k + 3 > length)
throw Context.ReportRuntimeErrorById ("msg.bad.uri");
int B = unHex (str [k + 1], str [k + 2]);
if (B < 0)
throw Context.ReportRuntimeErrorById ("msg.bad.uri");
k += 3;
if ((B & 0x80) == 0) {
C = (char)B;
}
else {
// Decode UTF-8 sequence into ucs4Char and encode it into
// UTF-16
int utf8Tail, ucs4Char, minUcs4Char;
if ((B & 0xC0) == 0x80) {
// First UTF-8 should be ouside 0x80..0xBF
throw Context.ReportRuntimeErrorById ("msg.bad.uri");
}
else if ((B & 0x20) == 0) {
utf8Tail = 1;
ucs4Char = B & 0x1F;
minUcs4Char = 0x80;
}
else if ((B & 0x10) == 0) {
utf8Tail = 2;
ucs4Char = B & 0x0F;
minUcs4Char = 0x800;
}
else if ((B & 0x08) == 0) {
utf8Tail = 3;
ucs4Char = B & 0x07;
minUcs4Char = 0x10000;
}
else if ((B & 0x04) == 0) {
utf8Tail = 4;
ucs4Char = B & 0x03;
minUcs4Char = 0x200000;
}
else if ((B & 0x02) == 0) {
utf8Tail = 5;
ucs4Char = B & 0x01;
minUcs4Char = 0x4000000;
}
else {
// First UTF-8 can not be 0xFF or 0xFE
throw Context.ReportRuntimeErrorById ("msg.bad.uri");
}
if (k + 3 * utf8Tail > length)
throw Context.ReportRuntimeErrorById ("msg.bad.uri");
for (int j = 0; j != utf8Tail; j++) {
if (str [k] != '%')
throw Context.ReportRuntimeErrorById ("msg.bad.uri");
B = unHex (str [k + 1], str [k + 2]);
if (B < 0 || (B & 0xC0) != 0x80)
throw Context.ReportRuntimeErrorById ("msg.bad.uri");
ucs4Char = (ucs4Char << 6) | (B & 0x3F);
k += 3;
}
// Check for overlongs and other should-not-present codes
if (ucs4Char < minUcs4Char || ucs4Char == 0xFFFE || ucs4Char == 0xFFFF) {
ucs4Char = 0xFFFD;
}
if (ucs4Char >= 0x10000) {
ucs4Char -= 0x10000;
if (ucs4Char > 0xFFFFF)
throw Context.ReportRuntimeErrorById ("msg.bad.uri");
char H = (char)(((int)((uint)ucs4Char >> 10)) + 0xD800);
C = (char)((ucs4Char & 0x3FF) + 0xDC00);
buf [bufTop++] = H;
}
else {
C = (char)ucs4Char;
}
}
if (fullUri && URI_DECODE_RESERVED.IndexOf ((char)C) >= 0) {
for (int x = start; x != k; x++) {
buf [bufTop++] = str [x];
}
}
else {
buf [bufTop++] = C;
}
}
}
return (buf == null) ? str : new string (buf, 0, bufTop);
}
private static bool encodeUnescaped (char c, bool fullUri)
{
if (('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z') || ('0' <= c && c <= '9')) {
return true;
}
if ("-_.!~*'()".IndexOf ((char)c) >= 0)
return true;
if (fullUri) {
return URI_DECODE_RESERVED.IndexOf ((char)c) >= 0;
}
return false;
}
private const string URI_DECODE_RESERVED = ";/?:@&=+$,#";
/* Convert one UCS-4 char and write it into a UTF-8 buffer, which must be
* at least 6 bytes long. Return the number of UTF-8 bytes of data written.
*/
private static int oneUcs4ToUtf8Char (sbyte [] utf8Buffer, int ucs4Char)
{
int utf8Length = 1;
//JS_ASSERT(ucs4Char <= 0x7FFFFFFF);
if ((ucs4Char & ~0x7F) == 0)
utf8Buffer [0] = (sbyte)ucs4Char;
else {
int i;
int a = (int)((uint)ucs4Char >> 11);
utf8Length = 2;
while (a != 0) {
a = (int)((uint)a >> 5);
utf8Length++;
}
i = utf8Length;
while (--i > 0) {
utf8Buffer [i] = (sbyte)((ucs4Char & 0x3F) | 0x80);
ucs4Char = (int)((uint)ucs4Char >> 6);
}
utf8Buffer [0] = (sbyte)(0x100 - (1 << (8 - utf8Length)) + ucs4Char);
}
return utf8Length;
}
private static readonly object FTAG = new object ();
#region PrototypeIds
private const int Id_decodeURI = 1;
private const int Id_decodeURIComponent = 2;
private const int Id_encodeURI = 3;
private const int Id_encodeURIComponent = 4;
private const int Id_escape = 5;
private const int Id_eval = 6;
private const int Id_isFinite = 7;
private const int Id_isNaN = 8;
private const int Id_isXMLName = 9;
private const int Id_parseFloat = 10;
private const int Id_parseInt = 11;
private const int Id_unescape = 12;
private const int Id_uneval = 13;
private const int LAST_SCOPE_FUNCTION_ID = 13;
private const int Id_new_CommonError = 14;
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Globalization;
namespace ICSimulator
{
public class Stats
{
public int N;
ulong m_finishtime;
public AccumStat cycle;
//micro13 rebuttal stat
public AccumStat bridge0Count;
public AccumStat bridge1Count;
public AccumStat bridge2Count;
public AccumStat bridge3Count;
public AccumStat bridge4Count;
public AccumStat bridge5Count;
public AccumStat bridge6Count;
public AccumStat bridge7Count;
//processor stats
public AccumStat[] active_cycles;
public AccumStat[] idle_cycles;
public AccumStat[] active_cycles_alone;
public ConstAccumStat[] skipped_insns_persrc;
public ConstAccumStat[] warming_insns_persrc;
public AccumStat[] insns_persrc;
public AccumStat[] every_insns_persrc;
public AccumStat[] opp_buff_preventable_stalls_persrc;
//public EnumStat<StallSources>[] front_stalls_persrc;
//public EnumStat<StallSources>[] back_stalls_persrc;
//public EnumStat<StallSources>[] mem_back_stalls_persrc;
//public EnumStat<StallSources>[] nonmem_back_stalls_persrc;
public enum StallSources
{
MEMORY,
LACK_OF_MSHRS,
NOTHING_TO_RETIRE,
ADDR_PACKET,
DATA_PACKET,
MC_ADDR_PACKET,
MC_DATA_PACKET,
INJ_ADDR_PACKET,
INJ_DATA_PACKET,
INJ_MC_ADDR_PACKET,
INJ_MC_DATA_PACKET
};
//network stalls: packetOffset + (2*(int)p.packetType) + 1 if in injectionQueue
public AccumStat[] cold_accesses_persrc;
public AccumStat[] L1_accesses_persrc;
public AccumStat[] L1_hits_persrc;
public AccumStat[] L1_misses_persrc;
public AccumStat[] L1_upgr_persrc;
public AccumStat[] L1_c2c_persrc;
public AccumStat[] L1_evicts_persrc;
public AccumStat[] L1_writebacks_persrc;
public AccumStat[] L2_accesses_persrc;
public AccumStat[] L2_hits_persrc;
public AccumStat[] L2_misses_persrc;
public AccumStat[] L2_evicts_persrc;
public AccumStat[] L2_writebacks_persrc;
public AccumStat l1_warmblocks, l1_totblocks; // L1 warming stats
public AccumStat l2_warmblocks, l2_totblocks; // L2 warming stats
public SampledStat deadline;
public SampledStat req_rtt;
// network-level stats
public AccumStat inject_flit, eject_flit, inject_flit_head;
public AccumStat[] inject_flit_bysrc, eject_flit_bydest;
// throttling stats
public AccumStat[] throttled_counts_persrc;
public AccumStat[] not_throttled_counts_persrc;
public SampledStat total_th_off;
public SampledStat[] mpki_bysrc;
public SampledStat allowed_sum_mpki;
public SampledStat total_sum_mpki;
public SampledStat total_th_rate;
//ipc difference b/w free-injecting and throttled interval for each app
//In the uniform controller, each app is put into a cluster, so that
//the interference is minimized.
public SampledStat[] ipc_diff_bysrc;
public AccumStat[] low_cluster;
public AccumStat[] rr_cluster;
public AccumStat[] high_cluster;
//public AccumStat[,] inject_flit_srcdest;
public AccumStat[] inject_flit_req;
public SampledStat flit_traversals, deflect_flit, unprod_flit;
public SampledStat[] deflect_flit_byinc, unprod_flit_byinc;
public SampledStat[] deflect_perflit_byreq;
public AccumStat[] deflect_flit_bysrc, deflect_flit_byloc,deflect_flit_byreq;
public AccumStat[] unprod_flit_bysrc, unprod_flit_byloc;
public AccumStat starve_flit;
public AccumStat[] starve_flit_bysrc;
public SampledStat[] starve_interval_bysrc;
public SampledStat net_decisionLevel;
//public AccumStat [] intdefl_bysrc;
//public SampledStat send_buf, rcv_buf;
//public SampledStat [] send_buf_bysrc, rcv_buf_bydest;
public SampledStat net_latency, total_latency;
public SampledStat[] net_latency_bysrc, total_latency_bysrc;
public SampledStat[] net_latency_bydest, total_latency_bydest;
//public SampledStat[,] net_latency_srcdest, total_latency_srcdest;
//In HighOther state
public AccumStat[] throttle_time_bysrc;
//In AlwaysThrottled state
public AccumStat[] always_throttle_time_bysrc;
public SampledStat[] flit_inj_latency_byapp, flit_net_latency_byapp, flit_total_latency_byapp;
public SampledStat flit_inj_latency, flit_net_latency, flit_total_latency;
public SampledStat hoq_latency;
public SampledStat[] hoq_latency_bysrc;
public SampledStat golden_pernode; // golden flits per node, per cycle (0, 1, 2, 3, 4)
public AccumStat[] golden_bycount; // histogram of the above
public AccumStat[] traversals_pernode;
//public AccumStat[,] traversals_pernode_bysrc;
public AccumStat flow_open, flow_close, flow_retx;
//public SampledStat [] flit_head_latency_byapp;
//public SampledStat flit_head_latency;
public SampledStat netutil;
// AFC -- buffer power
public AccumStat afc_buf_enabled, afc_buf_write, afc_buf_read, afc_xbar;
public AccumStat[] afc_buf_enabled_bysrc, afc_buf_write_bysrc, afc_buf_read_bysrc, afc_xbar_bysrc;
// AFC -- switching stats
public AccumStat afc_switch, afc_switch_bless, afc_switch_buf;
public AccumStat[] afc_switch_bysrc, afc_switch_bless_bysrc, afc_switch_buf_bysrc;
public AccumStat afc_buffered, afc_bless, afc_gossip;
public AccumStat[] afc_buffered_bysrc, afc_bless_bysrc, afc_gossip_bysrc;
public SampledStat afc_avg;
public SampledStat[] afc_avg_bysrc;
public SampledStat afc_buf_occupancy;
public SampledStat[] afc_buf_occupancy_bysrc;
public AccumStat[] afc_vnet;
public AccumStat afc_bufferBypass;
public SampledStat stretch;
public SampledStat[] stretch_bysrc, stretch_bydest;
//public SampledStat[,] stretch_srcdest;
public SampledStat minpath;
public SampledStat[] minpath_bysrc;
//public SampledStat [] netslow_bysrc;
//public SampledStat [] fairness_ie, fairness_ic;
//public SampledStat [] fairness_slowdown, fairness_texcess;
//public SampledStat [] fairness_ie_perpkt, fairness_ic_perpkt;
//public SampledStat [] injqueue_bysrc;
//public SampledStat injqueue;
public SampledStat[] fairness_ie_starve_perpkt, fairness_ie_defl_perpkt;
// ---- SCARAB impl
public AccumStat drop;
public AccumStat[] drop_by_src;
public AccumStat nack_unavail;
public AccumStat[] nack_unavail_by_src;
private static List<StatsObject> m_subobjects = new List<StatsObject>();
// energy stats
// TODO
public SampledStat[] tier1_unstarve;
public DictSampledStat[] compute_episode_persrc;
public DictSampledStat[] network_episode_persrc;
public DictSampledStat[] memory_episode_persrc;
public DictSampledStat[] nonmemory_episode_persrc;
// Memory Stats
//public AccumStat[,] bank_access_persrc;
//public AccumStat[,] bank_rowhits_persrc;
//public SampledStat[,] bank_queuedepth_persrc;
public SampledStat[] bank_queuedepth;
// ---- Live/Deadlock paper
public AccumStat[] reflect_flit_bysrc;
public AccumStat reflect_flit;
public SampledStat[] buf_usage_bysrc;
//Router prioritization counters
public PeriodicAccumStat[] L1_misses_persrc_period;
public PeriodicAccumStat[] insns_persrc_period;
public PeriodicAccumStat[] outstandingReq_persrc_period;
public PeriodicAccumStat[] weightedOutstandingReq_persrc_period;
public PeriodicAccumStat[] cycles_persrc_period;
public AccumStat[] cpu_sync_memdep, cpu_sync_lock, cpu_sync_barrier;
public AccumStat[] cpu_stall, cpu_stall_mem;
public AccumStat[] promise_wait;
public SampledStat[] promises_local, promises_local_queued;
//public SampledStat[,] promises_remote_wait, promises_remote_surplus;
public AccumStat livelock; // one event counted if we stop due to livelock
public AccumStat retx_once; // Retransmit-Once retx
public SampledStat retx_once_slots;
// slack stats
public SampledStat[] all_slack_persrc;
public SampledStat[] net_slack_persrc;
public SampledStat[] mem_slack_persrc;
public SampledStat all_slack;
public SampledStat net_slack;
public SampledStat mem_slack;
// stall stats
public SampledStat[] all_stall_persrc;
public SampledStat[] net_stall_persrc;
public SampledStat[] mem_stall_persrc;
public SampledStat all_stall;
public SampledStat net_stall;
public SampledStat mem_stall;
public SampledStat[] deflect_perdist;
public SampledStat[] mshrs_persrc;
public SampledStat mshrs;
//RingCLustered
/* public AccumStat[,] nodeRouterAccess;
public AccumStat[,] connectRouterAccess;
public AccumStat[,] connectRouter_deflected;
public AccumStat[,] connectRouter_traversed;
public AccumStat[,] connectRouter_nonproductive;
public SampledStat[,] bufferDepth;*/
public AccumStat bypassConnect;
public AccumStat crossXConnect;
public AccumStat crossYConnect;
public SampledStat timeInTheSourceRing;
public SampledStat timeInTheTransitionRing;
public SampledStat timeInTheDestRing;
public SampledStat timeWaitToInject;
public SampledStat timeInBuffer1hop;
public SampledStat timeInBuffer2hop;
public SampledStat netLatency_local;
public SampledStat netLatency_1hop;
public SampledStat netLatency_2hop;
public AccumStat flitLocal;
public AccumStat flitL1Global;
public AccumStat flit1hop;
public AccumStat flit2hop;
public SampledStat local_net_util;
public SampledStat global_net_util;
public SampledStat g1_net_util;
public SampledStat g2_net_util;
public SampledStat timeInGR1hop;
public SampledStat timeInGR2hop;
public AccumStat[] flitsTryToEject;
public SampledStat ejectsFromSamePacket;
public SampledStat ejectTrial;
public SampledStat minNetLatency;
public SampledStat destDeflectedNetLatency;
public SampledStat destDeflectedMinLatency;
public AccumStat multiEjectTrialFlits;
public AccumStat singleEjectTrialFlits;
public AccumStat starveTriggered;
public AccumStat observerTriggered;
public AccumStat allNodeThrottled;
public AccumStat injStarvation;
public AccumStat flitsToRouter;
public AccumStat flitsToHRnode;
public AccumStat flitsToHRbridge;
public AccumStat flitsPassBy;
public AccumStat LdeflectedFlit;
public AccumStat GdeflectedFlit;
public AccumStat G2LcrossFlit;
public AccumStat L2GcrossFlit;
public AccumStat G2LBufferBypass;
public AccumStat L2GBufferBypass;
// Buffered Ring stats
public AccumStat totalBufferEnqCount;
public SampledStat avgBufferDepth;
public AccumStat bufrings_nic_enqueue, bufrings_nic_dequeue;
public AccumStat bufrings_nic_inject, bufrings_nic_eject;
public AccumStat bufrings_nic_starve;
public AccumStat[] bufrings_iri_enqueue_g, bufrings_iri_dequeue_g;
public AccumStat[] bufrings_iri_enqueue_l, bufrings_iri_dequeue_l;
public AccumStat[] bufrings_iri_enqueue_gl, bufrings_iri_dequeue_gl;
public AccumStat[] bufrings_iri_enqueue_lg, bufrings_iri_dequeue_lg;
public AccumStat[] bufrings_link_traverse;
public SampledStat[] bufrings_iri_occupancy_g;
public SampledStat[] bufrings_iri_occupancy_l;
public SampledStat[] bufrings_iri_occupancy_gl;
public SampledStat[] bufrings_iri_occupancy_lg;
public SampledStat bufrings_nic_occupancy;
public SampledStat[] bufrings_ring_util;
public AccumStat bufrings_nuke;
AccumStat newAccumStat()
{
AccumStat ret = new AccumStat();
return ret;
}
AccumStat[] newAccumStatArray()
{
AccumStat[] ret = new AccumStat[N];
for (int i = 0; i < N; i++)
ret[i] = new AccumStat();
return ret;
}
ConstAccumStat[] newConstAccumStatArray()
{
ConstAccumStat[] ret = new ConstAccumStat[N];
for (int i = 0; i < N; i++)
ret[i] = new ConstAccumStat();
return ret;
}
AccumStat[,] newAccumStatArray2D()
{
AccumStat[,] ret = new AccumStat[N, N];
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
ret[i, j] = new AccumStat();
return ret;
}
const int NumBins = 2500; // arbitrary
SampledStat newSampledStat()
{
SampledStat ret = new SampledStat(NumBins, 0, NumBins);
return ret;
}
SampledStat[] newSampledStatArray()
{
return newSampledStatArray(false);
}
SampledStat[] newSampledStatArray(bool bins)
{
SampledStat[] ret = new SampledStat[N];
for (int i = 0; i < N; i++)
{
if (!bins)
ret[i] = new SampledStat();
else
ret[i] = new SampledStat(NumBins, 0, NumBins);
}
return ret;
}
DictSampledStat[] newDictSampledStatArray()
{
DictSampledStat[] ret = new DictSampledStat[N];
for (int i = 0; i < N; i++)
ret[i] = new DictSampledStat();
return ret;
}
/*
EnumStat<StallSources>[] newEnumSampledStatArray(int binSize)
{
EnumStat<StallSources>[] ret = new EnumStat<StallSources>[N];
for (int i = 0; i < N; i++)
{
ret[i] = new EnumStat<StallSources>();
}
return ret;
}
*/
SampledStat[,] newSampledStatArray2D()
{
SampledStat[,] ret = new SampledStat[N, N];
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
{
ret[i, j] = new SampledStat(); // no bins for arrays
}
return ret;
}
PeriodicAccumStat[] newPeriodicAccumStatArray()
{
PeriodicAccumStat[] ret = new PeriodicAccumStat[N];
for (int i = 0; i < N; i++)
ret[i] = new PeriodicAccumStat();
return ret;
}
public Stats(int nrNodes)
{
Init(nrNodes);
}
public void Init(int nrNodes)
{
N = nrNodes;
m_subobjects = new List<StatsObject>();
//First, do the non standard constructors
//front_stalls_persrc = newEnumSampledStatArray(Enum.GetValues(typeof(StallSources)).Length);
//back_stalls_persrc = newEnumSampledStatArray(Enum.GetValues(typeof(StallSources)).Length);
//mem_back_stalls_persrc = newEnumSampledStatArray(Enum.GetValues(typeof(StallSources)).Length);
//nonmem_back_stalls_persrc = newEnumSampledStatArray(Enum.GetValues(typeof(StallSources)).Length);
//bank_access_persrc = new AccumStat[Config.memory.bank_max_per_mem * Config.memory.mem_max, N];
//bank_rowhits_persrc = new AccumStat[Config.memory.bank_max_per_mem * Config.memory.mem_max, N];
//Console.WriteLine(Config.memory.bank_max_per_mem.ToString() + '\t' + Config.memory.mem_max.ToString());
//bank_queuedepth_persrc = new SampledStat[Config.memory.bank_max_per_mem * Config.memory.mem_max, N];
bank_queuedepth = new SampledStat[Config.memory.bank_max_per_mem * Config.memory.mem_max];
for (int i = 0; i < Config.memory.bank_max_per_mem * Config.memory.mem_max; i++)
{
bank_queuedepth[i] = new SampledStat();
for (int j = 0; j < N; j++)
{
//bank_access_persrc[i, j] = new AccumStat();
//bank_rowhits_persrc[i, j] = new AccumStat();
//bank_queuedepth_persrc[i, j] = new SampledStat();
}
}
//Fill each other field with the default constructor
foreach (FieldInfo fi in GetType().GetFields())
{
if (fi.GetValue(this) != null)
continue;
Type t = fi.FieldType;
if (t == typeof(DictSampledStat[]))
fi.SetValue(this, newDictSampledStatArray());
else if (t == typeof(PeriodicAccumStat[]))
fi.SetValue(this, newPeriodicAccumStatArray());
else if (t == typeof(AccumStat))
fi.SetValue(this, newAccumStat());
else if (t == typeof(AccumStat[]))
fi.SetValue(this, newAccumStatArray());
else if (t == typeof(AccumStat[,]))
fi.SetValue(this, newAccumStatArray2D());
else if (t == typeof(ConstAccumStat[]))
fi.SetValue(this, newConstAccumStatArray());
else if (t == typeof(SampledStat))
fi.SetValue(this, newSampledStat());
else if (t == typeof(SampledStat[]))
fi.SetValue(this, newSampledStatArray());
else if (t == typeof(SampledStat[,]))
fi.SetValue(this, newSampledStatArray2D());
}
}
public void Reset()
{
foreach (StatsObject s in m_subobjects)
s.Reset();
}
public void DumpJSON(TextWriter tw)
{
tw.WriteLine("{");
bool first = true;
foreach (FieldInfo fi in GetType().GetFields())
{
object o = fi.GetValue(this);
if (o is StatsObject || o is object[] || o is object[,])
{
if (!first)
tw.WriteLine(",");
else
first = false;
tw.Write("\"{0}\":", fi.Name);
DumpJSON(tw, o);
}
else
Console.WriteLine("not dumping "+fi.Name);
}
tw.WriteLine("}");
}
public void DumpJSON(TextWriter tw, object o)
{
if (o is StatsObject)
((StatsObject)o).DumpJSON(tw);
if (o is ulong)
tw.Write("{0}", (ulong)o);
if (o is object[])
{
bool first = true;
tw.Write("[");
foreach (object elem in (object[])o)
{
if (first) first = false;
else tw.Write(",");
DumpJSON(tw, elem);
}
tw.Write("]");
}
if (o is object[,])
{
object[,] arr2D = (object[,])o;
int dim0 = arr2D.GetUpperBound(0) + 1, dim1 = arr2D.GetUpperBound(1) + 1;
object[][] arr = new object[dim0][];
for (int i = 0; i < dim0; i++)
{
arr[i] = new object[dim1];
for (int j = 0; j < dim1; j++)
arr[i][j] = arr2D[i, j];
}
DumpJSON(tw, arr);
}
}
public void DumpMATLAB(TextWriter tw)
{
tw.WriteLine("dimX = {0}; dimY = {1};", Config.network_nrX, Config.network_nrY);
tw.WriteLine("cycles = {0};", m_finishtime);
foreach (FieldInfo fi in GetType().GetFields())
{
object o = fi.GetValue(this);
if (o is AccumStat || o is SampledStat)
{
object[,] arr = new object[1, 1] { { o } };
DumpMATLAB(tw, fi.Name, arr);
}
if (o is object[])
{
object[] a = (object[])o;
object[,] arr = new object[1, a.Length];
for (int i = 0; i < a.Length; i++)
arr[0, i] = a[i];
DumpMATLAB(tw, fi.Name, arr);
}
if (o is object[,])
DumpMATLAB(tw, fi.Name, (object[,])o);
}
}
void DumpMATLAB(TextWriter tw, double val)
{
if (val == Double.PositiveInfinity)
tw.Write("inf,");
else if (val == Double.NegativeInfinity)
tw.Write("-inf,");
else
tw.Write("{0},", val);
}
void DumpMATLAB(TextWriter tw, string name, object[,] o)
{
int dim0 = o.GetUpperBound(0) + 1, dim1 = o.GetUpperBound(1) + 1;
if (o[0, 0] is AccumStat)
{
tw.WriteLine("{0} = [", name);
for (int x = 0; x < dim0; x++)
{
for (int y = 0; y < dim1; y++)
{
tw.Write("{0},", ((AccumStat)o[x, y]).Count);
}
tw.WriteLine();
}
tw.WriteLine("];");
}
else if (o[0, 0] is SampledStat)
{
tw.WriteLine("{0}_avg = [", name);
for (int x = 0; x < dim0; x++)
{
for (int y = 0; y < dim1; y++)
{
DumpMATLAB(tw, ((SampledStat)o[x, y]).Avg);
}
tw.WriteLine();
}
tw.WriteLine("];");
tw.WriteLine("{0}_min = [", name);
for (int x = 0; x < dim0; x++)
{
for (int y = 0; y < dim1; y++)
{
DumpMATLAB(tw, ((SampledStat)o[x, y]).Min);
}
tw.WriteLine();
}
tw.WriteLine("];");
tw.WriteLine("{0}_max = [", name);
for (int x = 0; x < dim0; x++)
{
for (int y = 0; y < dim1; y++)
{
DumpMATLAB(tw, ((SampledStat)o[x, y]).Max);
}
tw.WriteLine();
}
tw.WriteLine("];");
tw.WriteLine("{0}_count = [", name);
for (int x = 0; x < dim0; x++)
{
for (int y = 0; y < dim1; y++)
{
tw.Write("{0},", ((SampledStat)o[x, y]).Count);
}
tw.WriteLine();
}
tw.WriteLine("];");
if (dim0 == 1 && dim1 == 1)
{
ulong[] bins = ((SampledStat)o[0, 0]).Hist;
tw.WriteLine("{0}_hist = [", name);
for (int i = 0; i < bins.Length; i++)
tw.Write("{0},", bins[i]);
tw.WriteLine("];");
}
}
}
public void Finish()
{
m_finishtime = Simulator.CurrentRound; // -Config.WarmingDuration;
/*
foreach (AccumStat st in m_accum)
st.Finish(m_finishtime);*/
foreach (StatsObject so in m_subobjects)
if (so is AccumStat)
((AccumStat)so).Finish(m_finishtime);
}
public void Report(TextWriter tw)
{
tw.WriteLine();
tw.WriteLine("--- Overall");
tw.WriteLine(" cycles: {0}", m_finishtime);
tw.WriteLine(" injections: {0} (rate {1:0.0000})", inject_flit.Count, inject_flit.Rate);
tw.WriteLine(" head flits: {0} (fraction {1:0.0000} of total)", inject_flit_head.Count,
(double)inject_flit_head.Count / inject_flit.Count);
//tw.WriteLine(" deflections: {0} (rate {1:0.0000} per cycle, {2:0.0000} per flit",
// deflect_flit.Count, deflect_flit.Rate, deflect_flit.Rate / inject_flit.Rate);
tw.WriteLine(" starvations: {0} (rate {1:0.0000} per cycle, {2:0.0000} per flit",
starve_flit.Count, starve_flit.Rate, starve_flit.Rate / inject_flit.Rate);
tw.WriteLine(" net latency: {0}", net_latency);
tw.WriteLine(" tot latency: {0}", total_latency);
tw.WriteLine(" stretch: {0}", stretch);
// tw.WriteLine(" interference: {0} (rate {1:0.0000} per cycle, {2:0.0000} per flit",
// interference.Count, interference.Rate, interference.Rate / inject_flit.Rate);
for (int i = 0; i < N; i++)
{
Coord c = new Coord(i);
int x = c.x, y = c.y;
tw.WriteLine("--- Application at ({0},{1}) (config: {2})", x, y,
"NOTIMPLEMENTED");
//String.Join(" ", Simulator.sources.spec.GetSpec(x, y).ToArray()));
tw.WriteLine(" injections: {0} (rate {1:0.0000})", inject_flit_bysrc[i].Count,
inject_flit_bysrc[i].Rate);
tw.WriteLine(" deflections by source: {0} (rate {1:0.0000} per cycle, {2:0.0000} per flit",
deflect_flit_bysrc[i].Count, deflect_flit_bysrc[i].Rate,
deflect_flit_bysrc[i].Rate / inject_flit_bysrc[i].Rate);
tw.WriteLine(" deflections by requester: {0} (rate {1:0.0000} per cycle, {2:0.0000} per flit",
deflect_flit_byreq[i].Count, deflect_flit_byreq[i].Rate,
deflect_flit_byreq[i].Rate / inject_flit_bysrc[i].Rate);
tw.WriteLine(" starvations: {0} (rate {1:0.0000} per cycle, {2:0.0000} per flit",
starve_flit_bysrc[i].Count, starve_flit_bysrc[i].Rate,
starve_flit_bysrc[i].Rate / inject_flit_bysrc[i].Rate);
tw.WriteLine(" net latency: {0}", net_latency_bysrc[i]);
tw.WriteLine(" tot latency: {0}", total_latency_bysrc[i]);
tw.WriteLine(" stretch: {0}", stretch_bysrc[i]);
// tw.WriteLine(" ic: {0}", ic_bysrc[i]);
// tw.WriteLine(" ie: {0}", ie_bysrc[i]);
tw.WriteLine();
/*foreach (Node n in Simulator.network.nodes)
n.cpu.output(tw);*/
}
}
public static void addStat(StatsObject so)
{
m_subobjects.Add(so);
}
}
public class StatsObject
{
public StatsObject()
{
Stats.addStat(this);
}
public virtual void Reset()
{
throw new Exception();
}
public virtual void DumpJSON(TextWriter tw)
{
throw new Exception();
}
}
// a SampledStat consists of samples of some value (latency,
// packets in network, ...) from which we can extract a
// distribution, an average and standard deviation, a min and max,
// etc.
public class DictSampledStat : SampledStat
{
Dictionary<double, ulong> d;
public DictSampledStat()
{
d = new Dictionary<double, ulong>();
}
public override void Add(double val)
{
base.Add(val);
if (d.ContainsKey(val))
d[val]++;
else
d[val] = 1;
}
public override void Reset()
{
base.Reset();
if (d != null)
d.Clear();
}
public override void DumpJSON(TextWriter tw)
{
tw.Write("{{\"avg\":{0},\"min\":{1},\"max\":{2},\"count\":{3},\"total\":{4},\"bins\":",
Avg, Min, Max, Count, Total);
tw.Write("{");
bool first = true;
foreach (KeyValuePair<double, ulong> pair in d)
{
if (first) first = false;
else tw.Write(",");
tw.Write("\"{0}\":{1}", pair.Key, pair.Value);
}
tw.Write("}}");
}
}
public class EnumStat<T> : StatsObject where T : IConvertible
{
private double[] m_bins;
public EnumStat()
{
Reset();
}
public override void Reset()
{
m_bins = new double[Enum.GetValues(typeof(T)).Length];
}
public override void DumpJSON(TextWriter tw)
{
tw.Write("{");
bool first = true;
foreach (T value in Enum.GetValues(typeof(T)))
{
tw.Write("{0}\"{1}\":{2}", (first ? "" : ","), Enum.GetName(typeof(T), value), m_bins[value.ToInt32(NumberFormatInfo.InvariantInfo)]);
first = false;
}
tw.Write("}");
}
public void Add(int index, double d) //TODO: can we pass value of type enum T?
{
m_bins[index] += d;
}
public void Add(double[] d)
{
for (int i = 0; i < m_bins.Length; i++)
m_bins[i] += d[i];
}
}
public class SampledStat : StatsObject
{
private double m_total, m_sqtotal, m_min, m_max;
private ulong m_count;
private ulong[] m_bins;
private int m_bincount;
private double m_binmin, m_binmax;
public SampledStat(int bins, double binmin, double binmax)
{
m_bincount = bins;
m_binmin = binmin;
m_binmax = binmax;
Reset();
}
public SampledStat()
{
m_bincount = 0;
m_binmin = 0;
m_binmax = 0;
Reset();
}
public virtual void Add(double val)
{
m_total += val;
m_sqtotal += val * val;
m_count++;
if (val < m_min) m_min = val;
if (val > m_max) m_max = val;
if (m_bincount > 0)
{
int bin = (int)Math.Round((val - m_binmin) /
(m_binmax - m_binmin) * m_bincount);
if (bin > m_bincount) bin = m_bincount;
if (bin < 0) bin = 0;
m_bins[bin]++;
}
}
public override void Reset()
{
m_count = 0;
m_total = 0;
m_sqtotal = 0;
m_min = Double.MaxValue;
m_max = Double.MinValue;
m_bins = new ulong[m_bincount + 1];
}
public override string ToString()
{
return String.Format("mean {0}, min {1}, max {2}, var {3}, total {4} ({5} samples)",
Avg, Min, Max, Variance, Total, Count);
}
public double Total
{ get { return m_total; } }
public double Variance
{ get { return AvgSq - Avg * Avg; } }
public double Min
{ get { return m_count > 0 ? m_min : 0.0; } }
public double Max
{ get { return m_count > 0 ? m_max : 0.0; } }
public double Avg
{ get { return (m_count > 0) ? (m_total / m_count) : 0; } }
public double AvgSq
{ get { return (m_count > 0) ? (m_sqtotal / m_count) : 0; } }
public ulong Count
{ get { return m_count; } }
public ulong[] Hist
{ get { return m_bins; } }
public override void DumpJSON(TextWriter tw)
{
tw.Write("{{\"avg\":{0},\"min\":{1},\"max\":{2},\"std\":{3},\"count\":{4},\"binmin\":{5},\"binmax\":{6}",
Avg, Min, Max, Math.Sqrt(Variance), Count, m_binmin, m_binmax);
if (Config.histogram_bins)
{
tw.Write(",\"bins\":");
tw.Write("[");
bool first = true;
foreach (ulong i in m_bins)
{
if (first) first = false;
else tw.Write(",");
tw.Write("{0}", i);
}
tw.Write("]");
}
tw.Write("}");
}
}
// an AccumStat is a statistic that counts discrete events (flit
// deflections, ...) and from which we can extract a rate
// (events/time).
public class AccumStat : StatsObject
{
protected ulong m_count;
private ulong m_endtime;
public AccumStat()
{
Reset();
}
public void Add()
{
m_count++;
}
public void Add(ulong addee)
{
m_count += addee;
}
// USE WITH CARE. (e.g., canceling an event that didn't actually happen...)
public void Sub()
{
m_count--;
}
public void Sub(ulong subtrahend) // I've always wanted to use that word...
{
m_count -= subtrahend;
}
public override void Reset()
{
m_count = 0;
m_endtime = 0;
}
public void Finish(ulong time)
{
m_endtime = time;
}
public override void DumpJSON(TextWriter tw)
{
tw.Write("{0}", m_count);
}
public ulong Count
{ get { return m_count; } }
public double Rate // events per time unit
{ get { return (double)Count / (double)m_endtime; } }
}
public class ConstAccumStat : AccumStat
{
public override void Reset() {} //can't be reset
}
//this metric
public class PeriodicAccumStat : AccumStat
{
private List<ulong> history = new List<ulong>();
public override void Reset()
{
base.Reset();
history.Clear();
}
public ulong EndPeriod()
{
ulong lastPeriodValue = m_count;
history.Add(m_count);
m_count = 0;
return lastPeriodValue;
}
public override void DumpJSON(TextWriter tw)
{
tw.Write("[");
foreach (ulong i in history)
tw.Write("{0},", i);
tw.Write("{0}]", m_count);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using Excel.Core;
using Excel.Core.BinaryFormat;
using Excel.Log;
namespace Excel
{
/// <summary>
/// ExcelDataReader Class
/// </summary>
public class ExcelBinaryReader : IExcelDataReader
{
#region Members
private Stream m_file;
private XlsHeader m_hdr;
private List<XlsWorksheet> m_sheets;
private XlsBiffStream m_stream;
private DataSet m_workbookData;
private XlsWorkbookGlobals m_globals;
private ushort m_version;
private bool m_ConvertOADate;
private Encoding m_encoding;
private bool m_isValid;
private bool m_isClosed;
private readonly Encoding m_Default_Encoding = Encoding.UTF8;
private string m_exceptionMessage;
private object[] m_cellsValues;
private uint[] m_dbCellAddrs;
private int m_dbCellAddrsIndex;
private bool m_canRead;
private int m_SheetIndex;
private int m_depth;
private int m_cellOffset;
private int m_maxCol;
private int m_maxRow;
private bool m_noIndex;
private XlsBiffRow m_currentRowRecord;
private readonly ReadOption m_ReadOption = ReadOption.Strict;
private bool m_IsFirstRead;
private bool _isFirstRowAsColumnNames;
private const string WORKBOOK = "Workbook";
private const string BOOK = "Book";
private const string COLUMN = "Column";
private bool disposed;
#region Fields for batch support
private DataSet _schema = null;
private int _batchSize = 1000;
private int _sheetIndex = -1;
private string _sheetName = string.Empty;
private int _skipRows = -1;
private DataTable _dtBatch = null;
#endregion
#endregion
internal ExcelBinaryReader()
{
m_encoding = m_Default_Encoding;
m_version = 0x0600;
m_isValid = true;
m_SheetIndex = -1;
m_IsFirstRead = true;
}
internal ExcelBinaryReader(ReadOption readOption) : this()
{
m_ReadOption = readOption;
}
#region IDisposable Members
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if (!this.disposed)
{
if (disposing)
{
if (m_workbookData != null) m_workbookData.Dispose();
if (m_sheets != null) m_sheets.Clear();
}
m_workbookData = null;
m_sheets = null;
m_stream = null;
m_globals = null;
m_encoding = null;
m_hdr = null;
disposed = true;
}
}
~ExcelBinaryReader()
{
Dispose(false);
}
#endregion
#region Private methods
private int findFirstDataCellOffset(int startOffset)
{
//seek to the first dbcell record
var record = m_stream.ReadAt(startOffset);
while (!(record is XlsBiffDbCell))
{
if (m_stream.Position >= m_stream.Size)
return -1;
if (record is XlsBiffEOF)
return -1;
record = m_stream.Read();
}
XlsBiffDbCell startCell = (XlsBiffDbCell)record;
XlsBiffRow row = null;
int offs = startCell.RowAddress;
do
{
row = m_stream.ReadAt(offs) as XlsBiffRow;
if (row == null) break;
offs += row.Size;
} while (null != row);
return offs;
}
private void readWorkBookGlobals()
{
//Read Header
try
{
m_hdr = XlsHeader.ReadHeader(m_file);
}
catch (Exceptions.HeaderException ex)
{
fail(ex.Message);
return;
}
catch (FormatException ex)
{
fail(ex.Message);
return;
}
XlsRootDirectory dir = new XlsRootDirectory(m_hdr);
XlsDirectoryEntry workbookEntry = dir.FindEntry(WORKBOOK) ?? dir.FindEntry(BOOK);
if (workbookEntry == null)
{ fail(Errors.ErrorStreamWorkbookNotFound); return; }
if (workbookEntry.EntryType != STGTY.STGTY_STREAM)
{ fail(Errors.ErrorWorkbookIsNotStream); return; }
m_stream = new XlsBiffStream(m_hdr, workbookEntry.StreamFirstSector, workbookEntry.IsEntryMiniStream, dir, this);
m_globals = new XlsWorkbookGlobals();
m_stream.Seek(0, SeekOrigin.Begin);
XlsBiffRecord rec = m_stream.Read();
XlsBiffBOF bof = rec as XlsBiffBOF;
if (bof == null || bof.Type != BIFFTYPE.WorkbookGlobals)
{ fail(Errors.ErrorWorkbookGlobalsInvalidData); return; }
bool sst = false;
m_version = bof.Version;
m_sheets = new List<XlsWorksheet>();
while (null != (rec = m_stream.Read()))
{
switch (rec.ID)
{
case BIFFRECORDTYPE.INTERFACEHDR:
m_globals.InterfaceHdr = (XlsBiffInterfaceHdr)rec;
break;
case BIFFRECORDTYPE.BOUNDSHEET:
XlsBiffBoundSheet sheet = (XlsBiffBoundSheet)rec;
if (sheet.Type != XlsBiffBoundSheet.SheetType.Worksheet) break;
sheet.IsV8 = isV8();
sheet.UseEncoding = m_encoding;
LogManager.Log(this).Debug("BOUNDSHEET IsV8={0}", sheet.IsV8);
m_sheets.Add(new XlsWorksheet(m_globals.Sheets.Count, sheet));
m_globals.Sheets.Add(sheet);
break;
case BIFFRECORDTYPE.MMS:
m_globals.MMS = rec;
break;
case BIFFRECORDTYPE.COUNTRY:
m_globals.Country = rec;
break;
case BIFFRECORDTYPE.CODEPAGE:
m_globals.CodePage = (XlsBiffSimpleValueRecord)rec;
try
{
m_encoding = Encoding.GetEncoding(m_globals.CodePage.Value);
}
catch (ArgumentException)
{
// Warning - Password protection
// TODO: Attach to ILog
}
break;
case BIFFRECORDTYPE.FONT:
case BIFFRECORDTYPE.FONT_V34:
m_globals.Fonts.Add(rec);
break;
case BIFFRECORDTYPE.FORMAT_V23:
{
var fmt = (XlsBiffFormatString) rec;
fmt.UseEncoding = m_encoding;
m_globals.Formats.Add((ushort) m_globals.Formats.Count, fmt);
}
break;
case BIFFRECORDTYPE.FORMAT:
{
var fmt = (XlsBiffFormatString) rec;
m_globals.Formats.Add(fmt.Index, fmt);
}
break;
case BIFFRECORDTYPE.XF:
case BIFFRECORDTYPE.XF_V4:
case BIFFRECORDTYPE.XF_V3:
case BIFFRECORDTYPE.XF_V2:
m_globals.ExtendedFormats.Add(rec);
break;
case BIFFRECORDTYPE.SST:
m_globals.SST = (XlsBiffSST)rec;
sst = true;
break;
case BIFFRECORDTYPE.CONTINUE:
if (!sst) break;
XlsBiffContinue contSST = (XlsBiffContinue)rec;
m_globals.SST.Append(contSST);
break;
case BIFFRECORDTYPE.EXTSST:
m_globals.ExtSST = rec;
sst = false;
break;
case BIFFRECORDTYPE.PROTECT:
case BIFFRECORDTYPE.PASSWORD:
case BIFFRECORDTYPE.PROT4REVPASSWORD:
//IsProtected
break;
case BIFFRECORDTYPE.EOF:
if (m_globals.SST != null)
m_globals.SST.ReadStrings();
return;
default:
continue;
}
}
}
private bool readWorkSheetGlobals(XlsWorksheet sheet, out XlsBiffIndex idx, out XlsBiffRow row)
{
idx = null;
row = null;
m_stream.Seek((int)sheet.DataOffset, SeekOrigin.Begin);
XlsBiffBOF bof = m_stream.Read() as XlsBiffBOF;
if (bof == null || bof.Type != BIFFTYPE.Worksheet) return false;
//DumpBiffRecords();
XlsBiffRecord rec = m_stream.Read();
if (rec == null) return false;
if (rec is XlsBiffIndex)
{
idx = rec as XlsBiffIndex;
}
else if (rec is XlsBiffUncalced)
{
// Sometimes this come before the index...
idx = m_stream.Read() as XlsBiffIndex;
}
//if (null == idx)
//{
// // There is a record before the index! Chech his type and see the MS Biff Documentation
// return false;
//}
if (idx != null)
{
idx.IsV8 = isV8();
LogManager.Log(this).Debug("INDEX IsV8={0}", idx.IsV8);
}
XlsBiffRecord trec;
XlsBiffDimensions dims = null;
do
{
trec = m_stream.Read();
if (trec.ID == BIFFRECORDTYPE.DIMENSIONS)
{
dims = (XlsBiffDimensions)trec;
break;
}
} while (trec != null && trec.ID != BIFFRECORDTYPE.ROW);
//if we are already on row record then set that as the row, otherwise step forward till we get to a row record
if (trec.ID == BIFFRECORDTYPE.ROW)
row = (XlsBiffRow)trec;
XlsBiffRow rowRecord = null;
while (rowRecord == null)
{
if (m_stream.Position >= m_stream.Size)
break;
var thisRec = m_stream.Read();
LogManager.Log(this).Debug("finding rowRecord offset {0}, rec: {1}", thisRec.Offset, thisRec.ID);
if (thisRec is XlsBiffEOF)
break;
rowRecord = thisRec as XlsBiffRow;
}
if (rowRecord != null)
LogManager.Log(this).Debug("Got row {0}, rec: id={1},rowindex={2}, rowColumnStart={3}, rowColumnEnd={4}", rowRecord.Offset, rowRecord.ID, rowRecord.RowIndex, rowRecord.FirstDefinedColumn, rowRecord.LastDefinedColumn);
row = rowRecord;
if (dims != null) {
dims.IsV8 = isV8();
LogManager.Log(this).Debug("dims IsV8={0}", dims.IsV8);
m_maxCol = dims.LastColumn - 1;
//handle case where sheet reports last column is 1 but there are actually more
if (m_maxCol <= 0 && rowRecord != null)
{
m_maxCol = rowRecord.LastDefinedColumn;
}
m_maxRow = (int)dims.LastRow;
sheet.Dimensions = dims;
} else {
m_maxCol = 256;
m_maxRow = (int)idx.LastExistingRow;
}
if (idx != null && idx.LastExistingRow <= idx.FirstExistingRow)
{
return false;
}
else if (row == null)
{
return false;
}
m_depth = 0;
return true;
}
private void DumpBiffRecords()
{
XlsBiffRecord rec = null;
var startPos = m_stream.Position;
do
{
rec = m_stream.Read();
LogManager.Log(this).Debug(rec.ID.ToString());
} while (rec != null && m_stream.Position < m_stream.Size);
m_stream.Seek(startPos, SeekOrigin.Begin);
}
private bool readWorkSheetRow()
{
m_cellsValues = new object[m_maxCol];
while (m_cellOffset < m_stream.Size)
{
XlsBiffRecord rec = m_stream.ReadAt(m_cellOffset);
m_cellOffset += rec.Size;
if ((rec is XlsBiffDbCell)) { break; };//break;
if (rec is XlsBiffEOF) { return false; };
XlsBiffBlankCell cell = rec as XlsBiffBlankCell;
if ((null == cell) || (cell.ColumnIndex >= m_maxCol)) continue;
if (cell.RowIndex != m_depth) { m_cellOffset -= rec.Size; break; };
pushCellValue(cell);
}
m_depth++;
return m_depth < m_maxRow;
}
private DataTable readWholeWorkSheet(XlsWorksheet sheet)
{
XlsBiffIndex idx;
if (!readWorkSheetGlobals(sheet, out idx, out m_currentRowRecord)) return null;
DataTable table = new DataTable(sheet.Name);
bool triggerCreateColumns = true;
if (idx != null)
readWholeWorkSheetWithIndex(idx, triggerCreateColumns, table);
else
readWholeWorkSheetNoIndex(triggerCreateColumns, table);
table.EndLoadData();
return table;
}
//TODO: quite a bit of duplication with the noindex version
private void readWholeWorkSheetWithIndex(XlsBiffIndex idx, bool triggerCreateColumns, DataTable table)
{
m_dbCellAddrs = idx.DbCellAddresses;
for (int index = 0; index < m_dbCellAddrs.Length; index++)
{
if (m_depth == m_maxRow) break;
// init reading data
m_cellOffset = findFirstDataCellOffset((int) m_dbCellAddrs[index]);
if (m_cellOffset < 0)
return;
//DataTable columns
if (triggerCreateColumns)
{
if (_isFirstRowAsColumnNames && readWorkSheetRow() || (_isFirstRowAsColumnNames && m_maxRow == 1))
{
for (int i = 0; i < m_maxCol; i++)
{
if (m_cellsValues[i] != null && m_cellsValues[i].ToString().Length > 0)
Helpers.AddColumnHandleDuplicate(table, m_cellsValues[i].ToString());
else
Helpers.AddColumnHandleDuplicate(table, string.Concat(COLUMN, i));
}
}
else
{
for (int i = 0; i < m_maxCol; i++)
{
table.Columns.Add(null, typeof (Object));
}
}
triggerCreateColumns = false;
table.BeginLoadData();
}
while (readWorkSheetRow())
{
table.Rows.Add(m_cellsValues);
}
//add the row
if (m_depth > 0 && !(_isFirstRowAsColumnNames && m_maxRow == 1))
{
table.Rows.Add(m_cellsValues);
}
}
}
private void readWholeWorkSheetNoIndex(bool triggerCreateColumns, DataTable table)
{
while (Read())
{
if (m_depth == m_maxRow) break;
bool justAddedColumns = false;
//DataTable columns
if (triggerCreateColumns)
{
if (_isFirstRowAsColumnNames || (_isFirstRowAsColumnNames && m_maxRow == 1))
{
for (int i = 0; i < m_maxCol; i++)
{
if (m_cellsValues[i] != null && m_cellsValues[i].ToString().Length > 0)
Helpers.AddColumnHandleDuplicate(table, m_cellsValues[i].ToString());
else
Helpers.AddColumnHandleDuplicate(table, string.Concat(COLUMN, i));
}
}
else
{
for (int i = 0; i < m_maxCol; i++)
{
table.Columns.Add(null, typeof(Object));
}
}
triggerCreateColumns = false;
justAddedColumns = true;
table.BeginLoadData();
}
if (!justAddedColumns && m_depth > 0 && !(_isFirstRowAsColumnNames && m_maxRow == 1))
{
table.Rows.Add(m_cellsValues);
}
}
if (m_depth > 0 && !(_isFirstRowAsColumnNames && m_maxRow == 1))
{
table.Rows.Add(m_cellsValues);
}
}
private void pushCellValue(XlsBiffBlankCell cell)
{
double _dValue;
LogManager.Log(this).Debug("pushCellValue {0}", cell.ID);
switch (cell.ID)
{
case BIFFRECORDTYPE.BOOLERR:
if (cell.ReadByte(7) == 0)
m_cellsValues[cell.ColumnIndex] = cell.ReadByte(6) != 0;
break;
case BIFFRECORDTYPE.BOOLERR_OLD:
if (cell.ReadByte(8) == 0)
m_cellsValues[cell.ColumnIndex] = cell.ReadByte(7) != 0;
break;
case BIFFRECORDTYPE.INTEGER:
case BIFFRECORDTYPE.INTEGER_OLD:
m_cellsValues[cell.ColumnIndex] = ((XlsBiffIntegerCell)cell).Value;
break;
case BIFFRECORDTYPE.NUMBER:
case BIFFRECORDTYPE.NUMBER_OLD:
_dValue = ((XlsBiffNumberCell)cell).Value;
m_cellsValues[cell.ColumnIndex] = !ConvertOaDate ?
_dValue : tryConvertOADateTime(_dValue, cell.XFormat);
LogManager.Log(this).Debug("VALUE: {0}", _dValue);
break;
case BIFFRECORDTYPE.LABEL:
case BIFFRECORDTYPE.LABEL_OLD:
case BIFFRECORDTYPE.RSTRING:
m_cellsValues[cell.ColumnIndex] = ((XlsBiffLabelCell)cell).Value;
LogManager.Log(this).Debug("VALUE: {0}", m_cellsValues[cell.ColumnIndex]);
break;
case BIFFRECORDTYPE.LABELSST:
string tmp = m_globals.SST.GetString(((XlsBiffLabelSSTCell)cell).SSTIndex);
LogManager.Log(this).Debug("VALUE: {0}", tmp);
m_cellsValues[cell.ColumnIndex] = tmp;
break;
case BIFFRECORDTYPE.RK:
_dValue = ((XlsBiffRKCell)cell).Value;
m_cellsValues[cell.ColumnIndex] = !ConvertOaDate ?
_dValue : tryConvertOADateTime(_dValue, cell.XFormat);
LogManager.Log(this).Debug("VALUE: {0}", _dValue);
break;
case BIFFRECORDTYPE.MULRK:
XlsBiffMulRKCell _rkCell = (XlsBiffMulRKCell)cell;
for (ushort j = cell.ColumnIndex; j <= _rkCell.LastColumnIndex; j++)
{
_dValue = _rkCell.GetValue(j);
LogManager.Log(this).Debug("VALUE[{1}]: {0}", _dValue, j);
m_cellsValues[j] = !ConvertOaDate ? _dValue : tryConvertOADateTime(_dValue, _rkCell.GetXF(j));
}
break;
case BIFFRECORDTYPE.BLANK:
case BIFFRECORDTYPE.BLANK_OLD:
case BIFFRECORDTYPE.MULBLANK:
// Skip blank cells
break;
case BIFFRECORDTYPE.FORMULA:
case BIFFRECORDTYPE.FORMULA_OLD:
object _oValue = ((XlsBiffFormulaCell)cell).Value;
if (null != _oValue && _oValue is FORMULAERROR)
{
_oValue = null;
}
else
{
m_cellsValues[cell.ColumnIndex] = !ConvertOaDate ?
_oValue : tryConvertOADateTime(_oValue, (ushort)(cell.XFormat));//date time offset
}
break;
default:
break;
}
}
private bool moveToNextRecord()
{
//if sheet has no index
if (m_noIndex)
{
LogManager.Log(this).Debug("No index");
return moveToNextRecordNoIndex();
}
//if sheet has index
if (null == m_dbCellAddrs ||
m_dbCellAddrsIndex == m_dbCellAddrs.Length ||
m_depth == m_maxRow) return false;
m_canRead = readWorkSheetRow();
//read last row
if (!m_canRead && m_depth > 0) m_canRead = true;
if (!m_canRead && m_dbCellAddrsIndex < (m_dbCellAddrs.Length - 1))
{
m_dbCellAddrsIndex++;
m_cellOffset = findFirstDataCellOffset((int)m_dbCellAddrs[m_dbCellAddrsIndex]);
if (m_cellOffset < 0)
return false;
m_canRead = readWorkSheetRow();
}
return m_canRead;
}
private bool moveToNextRecordNoIndex()
{
//seek from current row record to start of cell data where that cell relates to the next row record
XlsBiffRow rowRecord = m_currentRowRecord;
if (rowRecord == null)
return false;
if (rowRecord.RowIndex < m_depth)
{
m_stream.Seek(rowRecord.Offset + rowRecord.Size, SeekOrigin.Begin);
do
{
if (m_stream.Position >= m_stream.Size)
return false;
var record = m_stream.Read();
if (record is XlsBiffEOF)
return false;
rowRecord = record as XlsBiffRow;
} while (rowRecord == null || rowRecord.RowIndex < m_depth);
}
m_currentRowRecord = rowRecord;
//m_depth = m_currentRowRecord.RowIndex;
//we have now found the row record for the new row, the we need to seek forward to the first cell record
XlsBiffBlankCell cell = null;
do
{
if (m_stream.Position >= m_stream.Size)
return false;
var record = m_stream.Read();
if (record is XlsBiffEOF)
return false;
if (record.IsCell)
{
var candidateCell = record as XlsBiffBlankCell;
if (candidateCell != null)
{
if (candidateCell.RowIndex == m_currentRowRecord.RowIndex)
cell = candidateCell;
}
}
} while (cell == null);
m_cellOffset = cell.Offset;
m_canRead = readWorkSheetRow();
//read last row
//if (!m_canRead && m_depth > 0) m_canRead = true;
//if (!m_canRead && m_dbCellAddrsIndex < (m_dbCellAddrs.Length - 1))
//{
// m_dbCellAddrsIndex++;
// m_cellOffset = findFirstDataCellOffset((int)m_dbCellAddrs[m_dbCellAddrsIndex]);
// m_canRead = readWorkSheetRow();
//}
return m_canRead;
}
private void initializeSheetRead()
{
if (m_SheetIndex == ResultsCount) return;
m_dbCellAddrs = null;
m_IsFirstRead = false;
if (m_SheetIndex == -1) m_SheetIndex = 0;
XlsBiffIndex idx;
if (!readWorkSheetGlobals(m_sheets[m_SheetIndex], out idx, out m_currentRowRecord))
{
//read next sheet
m_SheetIndex++;
initializeSheetRead();
return;
};
if (idx == null)
{
//no index, but should have the first row record
m_noIndex = true;
}
else
{
m_dbCellAddrs = idx.DbCellAddresses;
m_dbCellAddrsIndex = 0;
m_cellOffset = findFirstDataCellOffset((int)m_dbCellAddrs[m_dbCellAddrsIndex]);
if (m_cellOffset < 0)
{
fail("Badly formed binary file. Has INDEX but no DBCELL");
return;
}
}
}
private void fail(string message)
{
m_exceptionMessage = message;
m_isValid = false;
m_file.Close();
m_isClosed = true;
m_workbookData = null;
m_sheets = null;
m_stream = null;
m_globals = null;
m_encoding = null;
m_hdr = null;
}
private object tryConvertOADateTime(double value, ushort XFormat)
{
ushort format = 0;
if (XFormat >= 0 && XFormat < m_globals.ExtendedFormats.Count)
{
var rec = m_globals.ExtendedFormats[XFormat];
switch (rec.ID)
{
case BIFFRECORDTYPE.XF_V2:
format = (ushort) (rec.ReadByte(2) & 0x3F);
break;
case BIFFRECORDTYPE.XF_V3:
if ((rec.ReadByte(3) & 4) == 0)
return value;
format = rec.ReadByte(1);
break;
case BIFFRECORDTYPE.XF_V4:
if ((rec.ReadByte(5) & 4) == 0)
return value;
format = rec.ReadByte(1);
break;
default:
if ((rec.ReadByte(m_globals.Sheets[m_globals.Sheets.Count-1].IsV8 ? 9 : 7) & 4) == 0)
return value;
format = rec.ReadUInt16(2);
break;
}
}
else
{
format = XFormat;
}
switch (format)
{
// numeric built in formats
case 0: //"General";
case 1: //"0";
case 2: //"0.00";
case 3: //"#,##0";
case 4: //"#,##0.00";
case 5: //"\"$\"#,##0_);(\"$\"#,##0)";
case 6: //"\"$\"#,##0_);[Red](\"$\"#,##0)";
case 7: //"\"$\"#,##0.00_);(\"$\"#,##0.00)";
case 8: //"\"$\"#,##0.00_);[Red](\"$\"#,##0.00)";
case 9: //"0%";
case 10: //"0.00%";
case 11: //"0.00E+00";
case 12: //"# ?/?";
case 13: //"# ??/??";
case 0x30:// "##0.0E+0";
case 0x25:// "_(#,##0_);(#,##0)";
case 0x26:// "_(#,##0_);[Red](#,##0)";
case 0x27:// "_(#,##0.00_);(#,##0.00)";
case 40:// "_(#,##0.00_);[Red](#,##0.00)";
case 0x29:// "_(\"$\"* #,##0_);_(\"$\"* (#,##0);_(\"$\"* \"-\"_);_(@_)";
case 0x2a:// "_(\"$\"* #,##0_);_(\"$\"* (#,##0);_(\"$\"* \"-\"_);_(@_)";
case 0x2b:// "_(\"$\"* #,##0.00_);_(\"$\"* (#,##0.00);_(\"$\"* \"-\"??_);_(@_)";
case 0x2c:// "_(* #,##0.00_);_(* (#,##0.00);_(* \"-\"??_);_(@_)";
return value;
// date formats
case 14: //this.GetDefaultDateFormat();
case 15: //"D-MM-YY";
case 0x10: // "D-MMM";
case 0x11: // "MMM-YY";
case 0x12: // "h:mm AM/PM";
case 0x13: // "h:mm:ss AM/PM";
case 20: // "h:mm";
case 0x15: // "h:mm:ss";
case 0x16: // string.Format("{0} {1}", this.GetDefaultDateFormat(), this.GetDefaultTimeFormat());
case 0x2d: // "mm:ss";
case 0x2e: // "[h]:mm:ss";
case 0x2f: // "mm:ss.0";
return Helpers.ConvertFromOATime(value);
case 0x31:// "@";
return value.ToString();
default:
XlsBiffFormatString fmtString;
if (m_globals.Formats.TryGetValue(format, out fmtString) )
{
var fmt = fmtString.Value;
var formatReader = new FormatReader() {FormatString = fmt};
if (formatReader.IsDateFormatString())
return Helpers.ConvertFromOATime(value);
}
return value;
}
}
private object tryConvertOADateTime(object value, ushort XFormat)
{
double _dValue;
if (double.TryParse(value.ToString(), out _dValue))
return tryConvertOADateTime(_dValue, XFormat);
return value;
}
public bool isV8()
{
return m_version >= 0x600;
}
#endregion
#region IExcelDataReader Members
public void Initialize(Stream fileStream)
{
m_file = fileStream;
readWorkBookGlobals();
// set the sheet index to the index of the first sheet.. this is so that properties such as Name which use m_sheetIndex reflect the first sheet in the file without having to perform a read() operation
m_SheetIndex = 0;
}
public DataSet AsDataSet()
{
return AsDataSet(false);
}
public DataSet AsDataSet(bool convertOADateTime)
{
if (!m_isValid) return null;
if (m_isClosed) return m_workbookData;
ConvertOaDate = convertOADateTime;
m_workbookData = new DataSet();
for (int index = 0; index < ResultsCount; index++)
{
DataTable table = readWholeWorkSheet(m_sheets[index]);
if (null != table)
{
table.ExtendedProperties.Add("visiblestate", m_sheets[index].VisibleState);
m_workbookData.Tables.Add(table);
}
}
m_file.Close();
m_isClosed = true;
m_workbookData.AcceptChanges();
Helpers.FixDataTypes(m_workbookData);
return m_workbookData;
}
public string ExceptionMessage
{
get { return m_exceptionMessage; }
}
public string Name
{
get
{
if (null != m_sheets && m_sheets.Count > 0)
return m_sheets[m_SheetIndex].Name;
else
return null;
}
}
public string VisibleState
{
get
{
if (null != m_sheets && m_sheets.Count > 0)
return m_sheets[m_SheetIndex].VisibleState;
else
return null;
}
}
public bool IsValid
{
get { return m_isValid; }
}
public void Close()
{
m_file.Close();
m_isClosed = true;
}
public int Depth
{
get { return m_depth; }
}
public int ResultsCount
{
get { return m_globals.Sheets.Count; }
}
public bool IsClosed
{
get { return m_isClosed; }
}
public bool NextResult()
{
if (m_SheetIndex >= (this.ResultsCount - 1)) return false;
m_SheetIndex++;
m_IsFirstRead = true;
return true;
}
public bool Read()
{
if (!m_isValid) return false;
if (m_IsFirstRead) initializeSheetRead();
return moveToNextRecord();
}
public int FieldCount
{
get { return m_maxCol; }
}
public bool GetBoolean(int i)
{
if (IsDBNull(i)) return false;
return Boolean.Parse(m_cellsValues[i].ToString());
}
public DateTime GetDateTime(int i)
{
if (IsDBNull(i)) return DateTime.MinValue;
// requested change: 3
object val = m_cellsValues[i];
if (val is DateTime)
{
// if the value is already a datetime.. return it without further conversion
return (DateTime)val;
}
// otherwise proceed with conversion attempts
string valString = val.ToString();
double dVal;
try
{
dVal = double.Parse(valString);
}
catch (FormatException)
{
return DateTime.Parse(valString);
}
return DateTime.FromOADate(dVal);
}
public decimal GetDecimal(int i)
{
if (IsDBNull(i)) return decimal.MinValue;
return decimal.Parse(m_cellsValues[i].ToString());
}
public double GetDouble(int i)
{
if (IsDBNull(i)) return double.MinValue;
return double.Parse(m_cellsValues[i].ToString());
}
public float GetFloat(int i)
{
if (IsDBNull(i)) return float.MinValue;
return float.Parse(m_cellsValues[i].ToString());
}
public short GetInt16(int i)
{
if (IsDBNull(i)) return short.MinValue;
return short.Parse(m_cellsValues[i].ToString());
}
public int GetInt32(int i)
{
if (IsDBNull(i)) return int.MinValue;
return int.Parse(m_cellsValues[i].ToString());
}
public long GetInt64(int i)
{
if (IsDBNull(i)) return long.MinValue;
return long.Parse(m_cellsValues[i].ToString());
}
public string GetString(int i)
{
if (IsDBNull(i)) return null;
return m_cellsValues[i].ToString();
}
public object GetValue(int i)
{
return m_cellsValues[i];
}
public bool IsDBNull(int i)
{
return (null == m_cellsValues[i]) || (DBNull.Value == m_cellsValues[i]);
}
public object this[int i]
{
get { return m_cellsValues[i]; }
}
#region Methods for batch support
private DataTable CreateTableSchema(int sheetIndex)
{
XlsWorksheet worksheet = m_sheets[sheetIndex];
DataTable dataTable = new DataTable(worksheet.Name);
dataTable.ExtendedProperties.Add("visiblestate", worksheet.VisibleState);
dataTable.ExtendedProperties.Add("SkipRows", _skipRows);
dataTable.ExtendedProperties.Add("IsFirstRowAsColumnNames", _isFirstRowAsColumnNames);
//DataTable columns
if (!_isFirstRowAsColumnNames)
{
for (int i = 0; i < m_maxCol; i++)
{
dataTable.Columns.Add(null, typeof(Object));
}
}
else if (m_cellsValues != null)
{
for (int i = 0; i < m_cellsValues.Length; i++)
{
object cellValues = m_cellsValues[i];
if (cellValues != null && cellValues.ToString().Length > 0)
Helpers.AddColumnHandleDuplicate(dataTable, cellValues.ToString());
else
Helpers.AddColumnHandleDuplicate(dataTable, string.Concat(COLUMN, i));
}
}
return dataTable;
}
private bool IsSheetIndexValid(int sheetIndex)
{
return (_sheetIndex >= 0 && _sheetIndex < m_sheets.Count);
}
private bool ValidateSheetParameters()
{
if (string.IsNullOrEmpty(_sheetName)) { throw new Exception("Sheet name property of IExcelDataReader is not set."); }
else { _sheetIndex = m_sheets.FindIndex(s => s.Name.ToLower() == _sheetName.ToLower()); }
if (!IsSheetIndexValid(_sheetIndex)) { throw new Exception(string.Format(@"Sheet '{0}' not found in excel.", _sheetName)); }
return true;
}
private bool InitializeSheetBatchRead()
{
if (ResultsCount <= 0) return false;
XlsWorksheet worksheet = m_sheets[_sheetIndex];
XlsBiffIndex idx;
if (!readWorkSheetGlobals(worksheet, out idx, out m_currentRowRecord)) return false;
if (worksheet.Dimensions == null) return false;
if (_skipRows >= worksheet.Dimensions.LastRow) { throw new Exception(string.Format(@"Sheet '{0}' contains less rows than SkipRows property of IExcelDataReader.", _sheetName)); }
if (idx == null)
{
//no index, but should have the first row record
m_noIndex = true;
}
else
{
m_dbCellAddrs = idx.DbCellAddresses;
m_dbCellAddrsIndex = 0;
if (m_dbCellAddrs.Length > 0) { m_cellOffset = findFirstDataCellOffset((int)m_dbCellAddrs[m_dbCellAddrsIndex]); }
if (m_cellOffset < 0)
{
fail("Badly formed binary file. Has INDEX but no DBCELL");
return false;
}
}
m_depth = 0;
// m_emptyRowCount = 0;
if (_skipRows > 0) { for (int i = 0; i < _skipRows; i++) { moveToNextRecordBatch(); } }
if (_isFirstRowAsColumnNames) { moveToNextRecordBatch(); }
m_IsFirstRead = false;
return true;
}
private bool moveToNextRecordBatch()
{
//if sheet has no index
if (m_noIndex)
{
LogManager.Log(this).Debug("No index");
return moveToNextRecordNoIndexBatch();
}
//if sheet has index
if (null == m_dbCellAddrs ||
m_dbCellAddrsIndex == m_dbCellAddrs.Length ||
m_depth == m_maxRow) return false;
m_canRead = ReadWorkSheetBatchRow();
return m_canRead;
}
private bool moveToNextRecordNoIndexBatch()
{
//seek from current row record to start of cell data where that cell relates to the next row record
XlsBiffRow rowRecord = m_currentRowRecord;
if (rowRecord == null)
return false;
if (rowRecord.RowIndex < m_depth)
{
m_stream.Seek(rowRecord.Offset + rowRecord.Size, SeekOrigin.Begin);
do
{
if (m_stream.Position >= m_stream.Size)
return false;
var record = m_stream.Read();
if (record is XlsBiffEOF)
return false;
rowRecord = record as XlsBiffRow;
} while (rowRecord == null || rowRecord.RowIndex < m_depth);
}
m_currentRowRecord = rowRecord;
//m_depth = m_currentRowRecord.RowIndex;
//we have now found the row record for the new row, the we need to seek forward to the first cell record
XlsBiffBlankCell cell = null;
do
{
if (m_stream.Position >= m_stream.Size)
return false;
var record = m_stream.Read();
if (record is XlsBiffEOF)
return false;
if (record.IsCell)
{
var candidateCell = record as XlsBiffBlankCell;
if (candidateCell != null)
{
if (candidateCell.RowIndex == m_currentRowRecord.RowIndex)
cell = candidateCell;
}
}
} while (cell == null);
m_cellOffset = cell.Offset;
m_canRead = ReadWorkSheetBatchRow();
return m_canRead;
}
private bool ReadWorkSheetBatchRow()
{
m_cellsValues = new object[m_maxCol];
while (m_cellOffset < m_stream.Size)
{
XlsBiffRecord rec = m_stream.ReadAt(m_cellOffset);
m_cellOffset += rec.Size;
if ((rec is XlsBiffDbCell)) { break; };//break;
if (rec is XlsBiffEOF) { return false; };
XlsBiffBlankCell cell = rec as XlsBiffBlankCell;
if ((null == cell) || (cell.ColumnIndex >= m_maxCol)) continue;
if (cell.RowIndex != m_depth) { m_cellOffset -= rec.Size; break; };
pushCellValue(cell);
}
m_depth++;
return m_depth <= m_maxRow;
}
private bool ReadBatchForSchema()
{
if (!m_isValid) { return false; }
if (m_IsFirstRead)
{
if (!ValidateSheetParameters()) { return false; }
if (!InitializeSheetBatchRead()) { return false; }
}
_dtBatch = CreateTableSchema(_sheetIndex);
var workSheet = m_sheets[_sheetIndex];
_dtBatch.BeginLoadData();
int currentRowIndexInBatch = 0;
while (currentRowIndexInBatch < _batchSize)
{
if (moveToNextRecordBatch())
{
_dtBatch.LoadDataRow(m_cellsValues, false);
currentRowIndexInBatch++;
}
else { break; }
}
_dtBatch.EndLoadData();
if (currentRowIndexInBatch == 0) { SheetName = string.Empty; return false; }
return true;
}
public int BatchSize
{
get
{
return _batchSize;
}
set
{
_batchSize = value;
}
}
public int SheetIndex
{
get
{
return _sheetIndex;
}
set
{
_sheetIndex = value;
m_SheetIndex = _sheetIndex;
_dtBatch = null;
m_IsFirstRead = true;
// _savedCellsValues = null;
}
}
public string SheetName
{
get
{
return _sheetName;
}
set
{
_sheetName = value;
_dtBatch = null;
m_IsFirstRead = true;
//_savedCellsValues = null;
}
}
public int SkipRows
{
get
{
return _skipRows;
}
set
{
_skipRows = value;
}
}
public List<string> GetSheetNames()
{
List<string> sheetNames = new List<string>();
foreach (var sheet in m_sheets) { sheetNames.Add(sheet.Name); }
return sheetNames;
}
public DataSet GetSchema(bool isFirstRowAsColumnNames = true, int skipRows = 0)
{
if (!m_isValid) return null;
DataSet dataset = new DataSet();
foreach (var sheet in m_sheets)
{
SheetName = sheet.Name;
SkipRows = skipRows;
IsFirstRowAsColumnNames = isFirstRowAsColumnNames;
if (ReadBatchForSchema()) { dataset.Tables.Add(GetCurrentBatch()); }
}
if (dataset.Tables.Count > 0)
{
Helpers.FixDataTypes(dataset);
dataset.Clear();
_schema = dataset.Clone();
}
return dataset;
}
public DataSet GetSchema(List<SheetParameters> sheetParametersList)
{
if (!m_isValid) return null;
if (sheetParametersList == null || sheetParametersList.Count == 0) return null;
DataSet dataset = new DataSet();
foreach (SheetParameters param in sheetParametersList)
{
SheetName = param.SheetName;
SkipRows = param.SkipRows;
IsFirstRowAsColumnNames = param.IsFirstRowAsColumnNames;
if (ReadBatchForSchema()) { dataset.Tables.Add(GetCurrentBatch()); }
}
if (dataset.Tables.Count > 0)
{
Helpers.FixDataTypes(dataset);
dataset.Clear();
_schema = dataset.Clone();
}
return dataset;
}
public DataTable GetSchema(SheetParameters sheetParameters)
{
if (!m_isValid) return null;
DataTable dataTable = new DataTable();
SheetName = sheetParameters.SheetName;
SkipRows = sheetParameters.SkipRows;
IsFirstRowAsColumnNames = sheetParameters.IsFirstRowAsColumnNames;
if (ReadBatchForSchema()) { dataTable = GetCurrentBatch(); }
if (dataTable.Rows.Count > 0)
{
dataTable = Helpers.FixDataTypes(dataTable);
dataTable.Clear();
_schema = new DataSet();
_schema.Tables.Add(dataTable.Clone());
}
return dataTable;
}
public bool ReadBatch()
{
if (!m_isValid) { return false; }
if (m_IsFirstRead)
{
if (!ValidateSheetParameters()) { return false; }
if (_schema == null || _schema.Tables[_sheetName] == null)
{ GetSchema(new SheetParameters(SheetName, IsFirstRowAsColumnNames, SkipRows)); }
if (_schema == null || _schema.Tables[_sheetName] == null) { return false; }
if (!InitializeSheetBatchRead()) { return false; }
_dtBatch = _schema.Tables[_sheetName].Clone();
}
_dtBatch.Clear();
int currentRowIndexInBatch = 0;
_dtBatch.BeginLoadData();
var workSheet = m_sheets[_sheetIndex];
while (currentRowIndexInBatch < _batchSize)
{
if (moveToNextRecordBatch())
{
_dtBatch.LoadDataRow(m_cellsValues, false);
currentRowIndexInBatch++;
}
else { break; }
}
_dtBatch.EndLoadData();
if (currentRowIndexInBatch == 0) { SheetName = string.Empty; return false; }
return true;
}
public DataTable GetCurrentBatch()
{
return _dtBatch;
}
public DataTable GetTopRows(int rowCount, SheetParameters sheetParameters)
{
if (!m_isValid) return null;
DataSet dataset = new DataSet();
DataTable datatable = null;
SheetName = sheetParameters.SheetName;
SkipRows = sheetParameters.SkipRows;
IsFirstRowAsColumnNames = sheetParameters.IsFirstRowAsColumnNames;
int originalBatchSize = _batchSize;
_batchSize = rowCount;
if (ReadBatchForSchema()) { dataset.Tables.Add(GetCurrentBatch()); }
_batchSize = originalBatchSize;
if (dataset.Tables.Count > 0)
{
Helpers.FixDataTypes(dataset);
datatable = dataset.Tables[0];
}
return datatable;
}
#endregion
#endregion
#region Not Supported IDataReader Members
public DataTable GetSchemaTable()
{
throw new NotSupportedException();
}
public int RecordsAffected
{
get { throw new NotSupportedException(); }
}
#endregion
#region Not Supported IDataRecord Members
public byte GetByte(int i)
{
throw new NotSupportedException();
}
public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length)
{
throw new NotSupportedException();
}
public char GetChar(int i)
{
throw new NotSupportedException();
}
public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length)
{
throw new NotSupportedException();
}
public IDataReader GetData(int i)
{
throw new NotSupportedException();
}
public string GetDataTypeName(int i)
{
throw new NotSupportedException();
}
public Type GetFieldType(int i)
{
throw new NotSupportedException();
}
public Guid GetGuid(int i)
{
throw new NotSupportedException();
}
public string GetName(int i)
{
throw new NotSupportedException();
}
public int GetOrdinal(string name)
{
throw new NotSupportedException();
}
public int GetValues(object[] values)
{
throw new NotSupportedException();
}
public object this[string name]
{
get { throw new NotSupportedException(); }
}
#endregion
#region IExcelDataReader Members
public bool IsFirstRowAsColumnNames
{
get
{
return _isFirstRowAsColumnNames;
}
set
{
_isFirstRowAsColumnNames = value;
}
}
public bool ConvertOaDate
{
get { return m_ConvertOADate; }
set { m_ConvertOADate = value; }
}
public ReadOption ReadOption
{
get { return m_ReadOption; }
}
#endregion
}
/// <summary>
/// Strict is as normal, Loose is more forgiving and will not cause an exception if a record size takes it beyond the end of the file. It will be trunacted in this case (SQl Reporting Services)
/// </summary>
public enum ReadOption
{
Strict,
Loose
}
}
| |
// 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.Runtime.CompilerServices;
using System.Threading;
using Debug = System.Diagnostics.Debug;
namespace Internal.TypeSystem
{
/// <summary>
/// A hash table which is lock free for readers and up to 1 writer at a time.
/// It must be possible to compute the key's hashcode from a value.
/// All values must convertable to/from an IntPtr.
/// It must be possible to perform an equality check between a key and a value.
/// It must be possible to perform an equality check between a value and a value.
/// A LockFreeReaderKeyValueComparer must be provided to perform these operations.
/// </summary>
abstract public class LockFreeReaderHashtableOfPointers<TKey, TValue>
{
private const int _initialSize = 16;
private const int _fillPercentageBeforeResize = 60;
/// <summary>
/// _hashtable is the currently visible underlying array for the hashtable
/// Any modifications to this array must be additive only, and there must
/// never be a situation where the visible _hashtable has less data than
/// it did at an earlier time. This value is initialized to an array of size
/// 1. (That array is never mutated as any additions will trigger an Expand
/// operation, but we don't use an empty array as the
/// initial step, as this approach allows the TryGetValue logic to always
/// succeed without needing any length or null checks.)
/// </summary>
private volatile IntPtr[] _hashtable = new IntPtr[_initialSize];
/// <summary>
/// Tracks the hashtable being used by expansion. Used as a sentinel
/// to threads trying to add to the old hashtable that an expansion is
/// in progress.
/// </summary>
private volatile IntPtr[] _newHashTable;
/// <summary>
/// _count represents the current count of elements in the hashtable
/// _count is used in combination with _resizeCount to control when the
/// hashtable should expand
/// </summary>
private volatile int _count = 0;
/// <summary>
/// Represents _count plus the number of potential adds currently happening.
/// If this reaches _hashTable.Length-1, an expansion is required (because
/// one slot must always be null for seeks to complete).
/// </summary>
private int _reserve = 0;
/// <summary>
/// _resizeCount represents the size at which the hashtable should resize.
/// While this doesn't strictly need to be volatile, having threads read stale values
/// triggers a lot of unneeded attempts to expand.
/// </summary>
private volatile int _resizeCount = _initialSize * _fillPercentageBeforeResize / 100;
/// <summary>
/// Get the underlying array for the hashtable at this time.
/// </summary>
private IntPtr[] GetCurrentHashtable()
{
return _hashtable;
}
/// <summary>
/// Set the newly visible hashtable underlying array. Used by writers after
/// the new array is fully constructed. The volatile write is used to ensure
/// that all writes to the contents of hashtable are completed before _hashtable
/// is visible to readers.
/// </summary>
private void SetCurrentHashtable(IntPtr[] hashtable)
{
_hashtable = hashtable;
}
/// <summary>
/// Used to ensure that the hashtable can function with
/// fairly poor initial hash codes.
/// </summary>
public static int HashInt1(int key)
{
unchecked
{
int a = (int)0x9e3779b9 + key;
int b = (int)0x9e3779b9;
int c = 16777619;
a -= b; a -= c; a ^= (c >> 13);
b -= c; b -= a; b ^= (a << 8);
c -= a; c -= b; c ^= (b >> 13);
a -= b; a -= c; a ^= (c >> 12);
b -= c; b -= a; b ^= (a << 16);
c -= a; c -= b; c ^= (b >> 5);
a -= b; a -= c; a ^= (c >> 3);
b -= c; b -= a; b ^= (a << 10);
c -= a; c -= b; c ^= (b >> 15);
return c;
}
}
/// <summary>
/// Generate a somewhat independent hash value from another integer. This is used
/// as part of a double hashing scheme. By being relatively prime with powers of 2
/// this hash function can be reliably used as part of a double hashing scheme as it
/// is guaranteed to eventually probe every slot in the table. (Table sizes are
/// constrained to be a power of two)
/// </summary>
public static int HashInt2(int key)
{
unchecked
{
int hash = unchecked((int)0xB1635D64) + key;
hash += (hash << 3);
hash ^= (hash >> 11);
hash += (hash << 15);
hash |= 0x00000001; // To make sure that this is relatively prime with power of 2
return hash;
}
}
/// <summary>
/// Create the LockFreeReaderHashtable. This hash table is designed for GetOrCreateValue
/// to be a generally lock free api (unless an add is necessary)
/// </summary>
public LockFreeReaderHashtableOfPointers()
{
#if DEBUG
// Ensure the initial value is a power of 2
bool foundAOne = false;
for (int i = 0; i < 32; i++)
{
int lastBit = _initialSize >> i;
if ((lastBit & 0x1) == 0x1)
{
Debug.Assert(!foundAOne);
foundAOne = true;
}
}
#endif // DEBUG
_newHashTable = _hashtable;
}
/// <summary>
/// The current count of elements in the hashtable
/// </summary>
public int Count { get { return _count; } }
/// <summary>
/// Gets the value associated with the specified key.
/// </summary>
/// <param name="key">The key of the value to get.</param>
/// <param name="value">When this method returns, contains the value associated with
/// the specified key, if the key is found; otherwise, the default value for the type
/// of the value parameter. This parameter is passed uninitialized. This function is threadsafe,
/// and wait-free</param>
/// <returns>true if a value was found</returns>
public bool TryGetValue(TKey key, out TValue value)
{
IntPtr[] hashTableLocal = GetCurrentHashtable();
Debug.Assert(hashTableLocal.Length > 0);
int mask = hashTableLocal.Length - 1;
int hashCode = GetKeyHashCode(key);
int tableIndex = HashInt1(hashCode) & mask;
if (hashTableLocal[tableIndex] == IntPtr.Zero)
{
value = default(TValue);
return false;
}
TValue valTemp = ConvertIntPtrToValue(hashTableLocal[tableIndex]);
if (CompareKeyToValue(key, valTemp))
{
value = valTemp;
return true;
}
int hash2 = HashInt2(hashCode);
tableIndex = (tableIndex + hash2) & mask;
while (hashTableLocal[tableIndex] != IntPtr.Zero)
{
valTemp = ConvertIntPtrToValue(hashTableLocal[tableIndex]);
if (CompareKeyToValue(key, valTemp))
{
value = valTemp;
return true;
}
tableIndex = (tableIndex + hash2) & mask;
}
value = default(TValue);
return false;
}
/// <summary>
/// Make the underlying array of the hashtable bigger. This function
/// does not change the contents of the hashtable. This entire function locks.
/// </summary>
private void Expand(IntPtr[] oldHashtable)
{
lock(this)
{
// If somebody else already resized, don't try to do it based on an old table
if(oldHashtable != _hashtable)
{
return;
}
// The checked statement here protects against both the hashTable size and _reserve overflowing. That does mean
// the maximum size of _hashTable is 0x70000000
int newSize = checked(oldHashtable.Length * 2);
// The hashtable only functions well when it has a certain minimum size
const int minimumUsefulSize = 16;
if (newSize < minimumUsefulSize)
newSize = minimumUsefulSize;
IntPtr[] newHashTable = new IntPtr[newSize];
_newHashTable = newHashTable;
int mask = newHashTable.Length - 1;
foreach (IntPtr ptrValue in _hashtable)
{
if (ptrValue == IntPtr.Zero)
continue;
TValue value = ConvertIntPtrToValue(ptrValue);
// If there's a deadlock at this point, GetValueHashCode is re-entering Add, which it must not do.
int hashCode = GetValueHashCode(value);
int tableIndex = HashInt1(hashCode) & mask;
// Initial probe into hashtable found empty spot
if (newHashTable[tableIndex] == IntPtr.Zero)
{
// Add to hash
newHashTable[tableIndex] = ptrValue;
continue;
}
int hash2 = HashInt2(hashCode);
tableIndex = (tableIndex + hash2) & mask;
while (newHashTable[tableIndex] != IntPtr.Zero)
{
tableIndex = (tableIndex + hash2) & mask;
}
// We've probed to find an empty spot
// Add to hash
newHashTable[tableIndex] = ptrValue;
}
_resizeCount = checked((newSize * _fillPercentageBeforeResize) / 100);
SetCurrentHashtable(newHashTable);
}
}
/// <summary>
/// Grow the hashtable so that storing into the hashtable does not require any allocation
/// operations.
/// </summary>
/// <param name="size"></param>
public void Reserve(int size)
{
while (size >= _resizeCount)
Expand(_hashtable);
}
/// <summary>
/// Adds a value to the hashtable if it is not already present.
/// Note that the key is not specified as it is implicit in the value. This function is thread-safe,
/// but must only take locks around internal operations and GetValueHashCode.
/// </summary>
/// <param name="value">Value to attempt to add to the hashtable, must not be null</param>
/// <returns>True if the value was added. False if it was already present.</returns>
public bool TryAdd(TValue value)
{
bool addedValue;
AddOrGetExistingInner(value, out addedValue);
return addedValue;
}
/// <summary>
/// Add a value to the hashtable, or find a value which is already present in the hashtable.
/// Note that the key is not specified as it is implicit in the value. This function is thread-safe,
/// but must only take locks around internal operations and GetValueHashCode.
/// </summary>
/// <param name="value">Value to attempt to add to the hashtable, its conversion to IntPtr must not result in IntPtr.Zero</param>
/// <returns>Newly added value, or a value which was already present in the hashtable which is equal to it.</returns>
public TValue AddOrGetExisting(TValue value)
{
bool unused;
return AddOrGetExistingInner(value, out unused);
}
private TValue AddOrGetExistingInner(TValue value, out bool addedValue)
{
IntPtr ptrValue = ConvertValueToIntPtr(value);
if (ptrValue == IntPtr.Zero)
throw new ArgumentNullException();
// Optimistically check to see if adding this value may require an expansion. If so, expand
// the table now. This isn't required to ensure space for the write, but helps keep
// the ratio in a good range.
if (_count >= _resizeCount)
{
Expand(_hashtable);
}
TValue result = default(TValue);
bool success;
do
{
success = TryAddOrGetExisting(value, out addedValue, ref result);
} while (!success);
return result;
}
/// <summary>
/// Attemps to add a value to the hashtable, or find a value which is already present in the hashtable.
/// In some cases, this will fail due to contention with other additions and must be retried.
/// Note that the key is not specified as it is implicit in the value. This function is thread-safe,
/// but must only take locks around internal operations and GetValueHashCode.
/// </summary>
/// <param name="value">Value to attempt to add to the hashtable, must not be null</param>
/// <param name="addedValue">Set to true if <paramref name="value"/> was added to the table. False if the value
/// was already present. Not defined if adding was attempted but failed.</param>
/// <param name="valueInHashtable">Newly added value if adding succeds, a value which was already present in the hashtable which is equal to it,
/// or an undefined value if adding fails and must be retried.</param>
/// <returns>True if the operation succeeded (either because the value was added or the value was already present).</returns>
private bool TryAddOrGetExisting(TValue value, out bool addedValue, ref TValue valueInHashtable)
{
// The table must be captured into a local to ensure reads/writes
// don't get torn by expansions
IntPtr[] hashTableLocal = _hashtable;
addedValue = true;
int mask = hashTableLocal.Length - 1;
int hashCode = GetValueHashCode(value);
int tableIndex = HashInt1(hashCode) & mask;
// Find an empty spot, starting with the initial tableIndex
if (hashTableLocal[tableIndex] != IntPtr.Zero)
{
TValue valTmp = ConvertIntPtrToValue(hashTableLocal[tableIndex]);
if (CompareValueToValue(value, valTmp))
{
// Value is already present in hash, do not add
addedValue = false;
valueInHashtable = valTmp;
return true;
}
int hash2 = HashInt2(hashCode);
tableIndex = (tableIndex + hash2) & mask;
while (hashTableLocal[tableIndex] != IntPtr.Zero)
{
valTmp = ConvertIntPtrToValue(hashTableLocal[tableIndex]);
if (CompareValueToValue(value, valTmp))
{
// Value is already present in hash, do not add
addedValue = false;
valueInHashtable = valTmp;
return true;
}
tableIndex = (tableIndex + hash2) & mask;
}
}
// Ensure there's enough space for at least one null slot after this write
if (Interlocked.Increment(ref _reserve) >= hashTableLocal.Length - 1)
{
Interlocked.Decrement(ref _reserve);
Expand(hashTableLocal);
// Since we expanded, our index won't work, restart
return false;
}
// We've probed to find an empty spot, add to hash
IntPtr ptrValue = ConvertValueToIntPtr(value);
if (!TryWriteValueToLocation(ptrValue, hashTableLocal, tableIndex))
{
Interlocked.Decrement(ref _reserve);
return false;
}
// Now that we've written to the local array, find out if that array has been
// replaced by expansion. If it has, we need to restart and write to the new array.
if (_newHashTable != hashTableLocal)
{
// Pulse the lock so we don't spin during an expansion
lock(this) { }
Interlocked.Decrement(ref _reserve);
return false;
}
// If the write succeeded, increment _count
Interlocked.Increment(ref _count);
valueInHashtable = value;
return true;
}
/// <summary>
/// Attampts to write a value into the table. May fail if another value has been added.
/// </summary>
/// <returns>True if the value was successfully written</returns>
private bool TryWriteValueToLocation(IntPtr value, IntPtr[] hashTableLocal, int tableIndex)
{
// Add to hash, use a volatile write to ensure that
// the contents of the value are fully published to all
// threads before adding to the hashtable
if (Interlocked.CompareExchange(ref hashTableLocal[tableIndex], value, IntPtr.Zero) == IntPtr.Zero)
{
return true;
}
return false;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private TValue CreateValueAndEnsureValueIsInTable(TKey key)
{
TValue newValue = CreateValueFromKey(key);
Debug.Assert(GetValueHashCode(newValue) == GetKeyHashCode(key));
return AddOrGetExisting(newValue);
}
/// <summary>
/// Get the value associated with a key. If value is not present in dictionary, use the creator delegate passed in
/// at object construction time to create the value, and attempt to add it to the table. (Create the value while not
/// under the lock, but add it to the table while under the lock. This may result in a throw away object being constructed)
/// This function is thread-safe, but will take a lock to perform its operations.
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TValue GetOrCreateValue(TKey key)
{
TValue existingValue;
if (TryGetValue(key, out existingValue))
return existingValue;
return CreateValueAndEnsureValueIsInTable(key);
}
/// <summary>
/// Determine if this collection contains a value associated with a key. This function is thread-safe, and wait-free.
/// </summary>
public bool Contains(TKey key)
{
TValue dummyExistingValue;
return TryGetValue(key, out dummyExistingValue);
}
/// <summary>
/// Determine if this collection contains a given value, and returns the value in the hashtable if found. This function is thread-safe, and wait-free.
/// </summary>
/// <param name="value">Value to search for in the hashtable, must not be null</param>
/// <returns>Value from the hashtable if found, otherwise null.</returns>
public TValue GetValueIfExists(TValue value)
{
if (value == null)
throw new ArgumentNullException();
IntPtr[] hashTableLocal = GetCurrentHashtable();
Debug.Assert(hashTableLocal.Length > 0);
int mask = hashTableLocal.Length - 1;
int hashCode = GetValueHashCode(value);
int tableIndex = HashInt1(hashCode) & mask;
if (hashTableLocal[tableIndex] == IntPtr.Zero)
return default(TValue);
TValue valTmp = ConvertIntPtrToValue(hashTableLocal[tableIndex]);
if (CompareValueToValue(value, valTmp))
return valTmp;
int hash2 = HashInt2(hashCode);
tableIndex = (tableIndex + hash2) & mask;
while (hashTableLocal[tableIndex] != IntPtr.Zero)
{
valTmp = ConvertIntPtrToValue(hashTableLocal[tableIndex]);
if (CompareValueToValue(value, valTmp))
return valTmp;
tableIndex = (tableIndex + hash2) & mask;
}
return default(TValue);
}
/// <summary>
/// Enumerator type for the LockFreeReaderHashtable
/// This is threadsafe, but is not garaunteed to avoid torn state.
/// In particular, the enumerator may report some newly added values
/// but not others. All values in the hashtable as of enumerator
/// creation will always be enumerated.
/// </summary>
public struct Enumerator : IEnumerator<TValue>
{
LockFreeReaderHashtableOfPointers<TKey, TValue> _hashtable;
private IntPtr[] _hashtableContentsToEnumerate;
private int _index;
private TValue _current;
/// <summary>
/// Use this to get an enumerable collection from a LockFreeReaderHashtable.
/// Used instead of a GetEnumerator method on the LockFreeReaderHashtable to
/// reduce excess type creation. (By moving the method here, the generic dictionary for
/// LockFreeReaderHashtable does not need to contain a reference to the
/// enumerator type.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Enumerator Get(LockFreeReaderHashtableOfPointers<TKey, TValue> hashtable)
{
return new Enumerator(hashtable);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Enumerator GetEnumerator()
{
return this;
}
internal Enumerator(LockFreeReaderHashtableOfPointers<TKey, TValue> hashtable)
{
_hashtable = hashtable;
_hashtableContentsToEnumerate = hashtable._hashtable;
_index = 0;
_current = default(TValue);
}
public bool MoveNext()
{
if ((_hashtableContentsToEnumerate != null) && (_index < _hashtableContentsToEnumerate.Length))
{
for (; _index < _hashtableContentsToEnumerate.Length; _index++)
{
if (_hashtableContentsToEnumerate[_index] != IntPtr.Zero)
{
_current = _hashtable.ConvertIntPtrToValue(_hashtableContentsToEnumerate[_index]);
_index++;
return true;
}
}
}
_current = default(TValue);
return false;
}
public void Dispose()
{
}
public void Reset()
{
throw new NotSupportedException();
}
public TValue Current
{
get
{
return _current;
}
}
object IEnumerator.Current
{
get
{
throw new NotSupportedException();
}
}
}
/// <summary>
/// Given a key, compute a hash code. This function must be thread safe.
/// </summary>
protected abstract int GetKeyHashCode(TKey key);
/// <summary>
/// Given a value, compute a hash code which would be identical to the hash code
/// for a key which should look up this value. This function must be thread safe.
/// This function must also not cause additional hashtable adds.
/// </summary>
protected abstract int GetValueHashCode(TValue value);
/// <summary>
/// Compare a key and value. If the key refers to this value, return true.
/// This function must be thread safe.
/// </summary>
protected abstract bool CompareKeyToValue(TKey key, TValue value);
/// <summary>
/// Compare a value with another value. Return true if values are equal.
/// This function must be thread safe.
/// </summary>
protected abstract bool CompareValueToValue(TValue value1, TValue value2);
/// <summary>
/// Create a new value from a key. Must be threadsafe. Value may or may not be added
/// to collection. Return value must not be null.
/// </summary>
protected abstract TValue CreateValueFromKey(TKey key);
/// <summary>
/// Convert a value to an IntPtr for storage into the hashtable
/// </summary>
protected abstract IntPtr ConvertValueToIntPtr(TValue value);
/// <summary>
/// Convert an IntPtr into a value for comparisions, or for returning.
/// </summary>
protected abstract TValue ConvertIntPtrToValue(IntPtr pointer);
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.IO;
using NUnit.Framework;
using WhitespaceAnalyzer = Lucene.Net.Analysis.WhitespaceAnalyzer;
using Document = Lucene.Net.Documents.Document;
using Field = Lucene.Net.Documents.Field;
using IndexReader = Lucene.Net.Index.IndexReader;
using IndexWriter = Lucene.Net.Index.IndexWriter;
using IndexSearcher = Lucene.Net.Search.IndexSearcher;
using English = Lucene.Net.Util.English;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
namespace Lucene.Net.Store
{
/// <summary> JUnit testcase to test RAMDirectory. RAMDirectory itself is used in many testcases,
/// but not one of them uses an different constructor other than the default constructor.
///
///
/// </summary>
/// <version> $Id: RAMDirectory.java 150537 2004-09-28 22:45:26 +0200 (Di, 28 Sep 2004) cutting $
/// </version>
[TestFixture]
public class TestRAMDirectory:LuceneTestCase
{
private class AnonymousClassThread:SupportClass.ThreadClass
{
public AnonymousClassThread(int num, Lucene.Net.Index.IndexWriter writer, Lucene.Net.Store.MockRAMDirectory ramDir, TestRAMDirectory enclosingInstance)
{
InitBlock(num, writer, ramDir, enclosingInstance);
}
private void InitBlock(int num, Lucene.Net.Index.IndexWriter writer, Lucene.Net.Store.MockRAMDirectory ramDir, TestRAMDirectory enclosingInstance)
{
this.num = num;
this.writer = writer;
this.ramDir = ramDir;
this.enclosingInstance = enclosingInstance;
}
private int num;
private Lucene.Net.Index.IndexWriter writer;
private Lucene.Net.Store.MockRAMDirectory ramDir;
private TestRAMDirectory enclosingInstance;
public TestRAMDirectory Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
override public void Run()
{
for (int j = 1; j < Enclosing_Instance.docsPerThread; j++)
{
Document doc = new Document();
doc.Add(new Field("sizeContent", English.IntToEnglish(num * Enclosing_Instance.docsPerThread + j).Trim(), Field.Store.YES, Field.Index.NOT_ANALYZED));
try
{
writer.AddDocument(doc);
}
catch (System.IO.IOException e)
{
throw new System.SystemException("", e);
}
}
}
}
private System.IO.FileInfo indexDir = null;
// add enough document so that the index will be larger than RAMDirectory.READ_BUFFER_SIZE
private int docsToAdd = 500;
// setup the index
[SetUp]
public override void SetUp()
{
base.SetUp();
System.String tempDir = System.IO.Path.GetTempPath();
if (tempDir == null)
throw new System.IO.IOException("java.io.tmpdir undefined, cannot run test");
indexDir = new System.IO.FileInfo(Path.Combine(tempDir, "RAMDirIndex"));
IndexWriter writer = new IndexWriter(indexDir, new WhitespaceAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);
// add some documents
Document doc = null;
for (int i = 0; i < docsToAdd; i++)
{
doc = new Document();
doc.Add(new Field("content", English.IntToEnglish(i).Trim(), Field.Store.YES, Field.Index.NOT_ANALYZED));
writer.AddDocument(doc);
}
Assert.AreEqual(docsToAdd, writer.DocCount());
writer.Close();
}
[Test]
public virtual void TestRAMDirectory_Renamed()
{
Directory dir = FSDirectory.Open(indexDir);
MockRAMDirectory ramDir = new MockRAMDirectory(dir);
// close the underlaying directory
dir.Close();
// Check size
Assert.AreEqual(ramDir.SizeInBytes(), ramDir.GetRecomputedSizeInBytes());
// open reader to test document count
IndexReader reader = IndexReader.Open(ramDir);
Assert.AreEqual(docsToAdd, reader.NumDocs());
// open search zo check if all doc's are there
IndexSearcher searcher = new IndexSearcher(reader);
// search for all documents
for (int i = 0; i < docsToAdd; i++)
{
Document doc = searcher.Doc(i);
Assert.IsTrue(doc.GetField("content") != null);
}
// cleanup
reader.Close();
searcher.Close();
}
[Test]
public virtual void TestRAMDirectoryFile()
{
MockRAMDirectory ramDir = new MockRAMDirectory(indexDir);
// Check size
Assert.AreEqual(ramDir.SizeInBytes(), ramDir.GetRecomputedSizeInBytes());
// open reader to test document count
IndexReader reader = IndexReader.Open(ramDir);
Assert.AreEqual(docsToAdd, reader.NumDocs());
// open search zo check if all doc's are there
IndexSearcher searcher = new IndexSearcher(reader);
// search for all documents
for (int i = 0; i < docsToAdd; i++)
{
Document doc = searcher.Doc(i);
Assert.IsTrue(doc.GetField("content") != null);
}
// cleanup
reader.Close();
searcher.Close();
}
[Test]
public virtual void TestRAMDirectoryString()
{
MockRAMDirectory ramDir = new MockRAMDirectory(indexDir.FullName);
// Check size
Assert.AreEqual(ramDir.SizeInBytes(), ramDir.GetRecomputedSizeInBytes());
// open reader to test document count
IndexReader reader = IndexReader.Open(ramDir);
Assert.AreEqual(docsToAdd, reader.NumDocs());
// open search zo check if all doc's are there
IndexSearcher searcher = new IndexSearcher(reader);
// search for all documents
for (int i = 0; i < docsToAdd; i++)
{
Document doc = searcher.Doc(i);
Assert.IsTrue(doc.GetField("content") != null);
}
// cleanup
reader.Close();
searcher.Close();
}
private int numThreads = 10;
private int docsPerThread = 40;
[Test]
public virtual void TestRAMDirectorySize()
{
MockRAMDirectory ramDir = new MockRAMDirectory(indexDir.FullName);
IndexWriter writer = new IndexWriter(ramDir, new WhitespaceAnalyzer(), false, IndexWriter.MaxFieldLength.LIMITED);
writer.Optimize();
Assert.AreEqual(ramDir.SizeInBytes(), ramDir.GetRecomputedSizeInBytes());
SupportClass.ThreadClass[] threads = new SupportClass.ThreadClass[numThreads];
for (int i = 0; i < numThreads; i++)
{
int num = i;
threads[i] = new AnonymousClassThread(num, writer, ramDir, this);
}
for (int i = 0; i < numThreads; i++)
threads[i].Start();
for (int i = 0; i < numThreads; i++)
threads[i].Join();
writer.Optimize();
Assert.AreEqual(ramDir.SizeInBytes(), ramDir.GetRecomputedSizeInBytes());
writer.Close();
}
[Test]
public virtual void TestSerializable()
{
Directory dir = new RAMDirectory();
System.IO.MemoryStream bos = new System.IO.MemoryStream(1024);
Assert.AreEqual(0, bos.Length, "initially empty");
System.IO.BinaryWriter out_Renamed = new System.IO.BinaryWriter(bos);
long headerSize = bos.Length;
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
formatter.Serialize(out_Renamed.BaseStream, dir);
out_Renamed.Flush(); // In Java, this is Close(), but we can't do this in .NET, and the Close() is moved to after the validation check
Assert.IsTrue(headerSize < bos.Length, "contains more then just header");
out_Renamed.Close();
}
[TearDown]
public override void TearDown()
{
base.TearDown();
// cleanup
if(System.IO.Directory.Exists(indexDir.FullName))
{
System.IO.Directory.Delete(indexDir.FullName, true);
}
}
// LUCENE-1196
[Test]
public virtual void TestIllegalEOF()
{
RAMDirectory dir = new RAMDirectory();
IndexOutput o = dir.CreateOutput("out");
byte[] b = new byte[1024];
o.WriteBytes(b, 0, 1024);
o.Close();
IndexInput i = dir.OpenInput("out");
i.Seek(1024);
i.Close();
dir.Close();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Fadd;
#if DEBUG
using HttpServer.Rendering.Haml;
using Xunit;
#endif
namespace HttpServer.Rendering
{
/// <summary>
/// Purpose if this class is to take template objects and keep them in
/// memory. It will also take a filename and the code generator to use
/// if when the template have been changed on disk.
/// </summary>
public class TemplateManager
{
private readonly Dictionary<string, TemplateInfoImp> _compiledTemplates = new Dictionary<string, TemplateInfoImp>();
private readonly Dictionary<string, ITemplateGenerator> _generators = new Dictionary<string, ITemplateGenerator>();
private readonly List<Type> _includedTypes = new List<Type>();
private readonly List<ITemplateLoader> _templateLoaders = new List<ITemplateLoader>();
//TODO: Create a path/template index (to avoid unnecessary IO).
/// <summary>
/// Initializes a new instance of the <see cref="TemplateManager"/> class.
/// </summary>
/// <param name="loaders">
/// Template loaders used to load templates from any source.
/// The loaders will be invoked in the order they are given, that is the first loader will always be asked to give a template
/// first.
/// </param>
public TemplateManager(params ITemplateLoader[] loaders)
{
Check.Require(loaders.Length, "Parameter loaders must contain at least one ITemplateLoader.");
_templateLoaders.AddRange(loaders);
}
/// <summary>
/// Initializes a new instance of the <see cref="TemplateManager"/> class.
/// </summary>
/// <remarks>Uses the file template loader.</remarks>
public TemplateManager()
{
_templateLoaders.Add(new FileTemplateLoader());
}
/// <summary>
/// Add a template generator
/// </summary>
/// <param name="fileExtension">File extension without the dot.</param>
/// <param name="generator">Generator to handle the extension</param>
/// <exception cref="InvalidOperationException">If the generator already exists.</exception>
/// <exception cref="ArgumentException">If file extension is incorrect</exception>
/// <exception cref="ArgumentNullException">If generator is not specified.</exception>
/// <example>
/// <code>
/// cache.Add("haml", new HamlGenerator());
/// </code>
/// </example>
public void Add(string fileExtension, ITemplateGenerator generator)
{
if (string.IsNullOrEmpty(fileExtension) || fileExtension.Contains("."))
throw new ArgumentException("Invalid file extension.");
if (generator == null)
throw new ArgumentNullException("generator");
if (_generators.ContainsKey(fileExtension))
throw new InvalidOperationException("A generator already exists for " + fileExtension);
_generators.Add(fileExtension, generator);
}
/// <summary>
/// This type should be included, so it may be called from the scripts (name space and assembly).
/// </summary>
/// <param name="type"></param>
public void AddType(Type type)
{
bool assemblyExists = false;
bool nsExists = false;
foreach (Type includedType in _includedTypes)
{
if (includedType.Namespace == type.Namespace)
nsExists = true;
if (includedType.Assembly == type.Assembly)
assemblyExists = true;
if (nsExists && assemblyExists)
break;
}
if (!assemblyExists || !nsExists)
_includedTypes.Add(type);
}
/// <summary>
/// Checks the template.
/// </summary>
/// <param name="info">Template information, filename must be set.</param>
/// <returns>true if template exists and have been compiled.</returns>
private bool CheckTemplate(ITemplateInfo info)
{
if (info == null)
return false;
foreach (ITemplateLoader loader in _templateLoaders)
if (loader.HasTemplate(info.Filename))
return loader.CheckTemplate(info);
return false;
}
/// <summary>
/// Compiles the specified code.
/// </summary>
/// <param name="fileName">Name of template.</param>
/// <param name="code">c# code generated from a template.</param>
/// <param name="arguments">Arguments as in name, value, name, value, name, value</param>
/// <param name="templateId">
/// An id to specify the exact instance of a template. Made from joining the 'TemplateClass' with the hashcode of the filename
/// and the hashcode of the supplied arguments
/// </param>
/// <returns>Template</returns>
/// <exception cref="TemplateException">If compilation fails</exception>
protected ITinyTemplate Compile(string fileName, string code, TemplateArguments arguments, string templateId)
{
if (string.IsNullOrEmpty(code))
throw new ArgumentException("Code is not specified.");
TemplateCompiler compiler = new TemplateCompiler();
foreach (Type type in _includedTypes)
compiler.Add(type);
try
{
return compiler.Compile(arguments, code, templateId);
}
catch(CompilerException err)
{
throw new TemplateException(fileName, err);
}
}
/// <summary>
/// Will generate code from the template.
/// Next step is to compile the code.
/// </summary>
/// <param name="path">Path and filename to template.</param>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="InvalidOperationException">If no template generator exists for the specified extension.</exception>
/// <exception cref="CodeGeneratorException">If parsing/compiling fails</exception>
/// <see cref="Render(string, TemplateArguments)"/>
private string GenerateCode(ref string path)
{
if (string.IsNullOrEmpty(path))
throw new ArgumentException("No filename was specified.");
int pos = path.LastIndexOf('.');
if (pos == -1)
throw new ArgumentException("Filename do not contain a file extension.");
if (pos == path.Length - 1)
throw new ArgumentException("Invalid filename '" + path + "', should not end with a dot.");
string extension = path.Substring(pos + 1);
lock (_generators)
{
ITemplateGenerator generator = null;
if (extension == "*")
generator = GetGeneratorForWildCard(ref path);
else
{
if (_generators.ContainsKey(extension))
generator = _generators[extension];
}
if (generator == null)
throw new InvalidOperationException("No template generator exists for '" + path + "'.");
TextReader reader = null;
try
{
foreach (ITemplateLoader loader in _templateLoaders)
{
reader = loader.LoadTemplate(path);
if (reader != null)
break;
}
if (reader == null)
throw new FileNotFoundException("Did not find template: " + path);
generator.Parse(reader);
reader.Close();
}
finally
{
if (reader != null)
reader.Dispose();
}
StringBuilder sb = new StringBuilder();
using (TextWriter writer = new StringWriter(sb))
{
generator.GenerateCode(writer);
return sb.ToString();
}
}
}
/// <summary>
/// Find a template using wildcards in filename.
/// </summary>
/// <param name="filePath">Full path (including wildcards in filename) to where we should find a template.</param>
/// <returns>First found generator if an extension was matched; otherwise null.</returns>
/// <remarks>method is not thread safe</remarks>
private ITemplateGenerator GetGeneratorForWildCard(ref string filePath)
{
int pos = filePath.LastIndexOf('\\');
if (pos == -1)
throw new InvalidOperationException("Failed to find path in filename.");
string path = filePath.Substring(0, pos);
string filename = filePath.Substring(pos + 1);
List<string> files = new List<string>();
foreach (ITemplateLoader loader in _templateLoaders)
files.AddRange(loader.GetFiles(path, filename));
for (int i = 0; i < files.Count; ++i)
{
pos = files[i].LastIndexOf('.');
string extension = files[i].Substring(pos + 1);
if (!_generators.ContainsKey(extension))
continue;
if(filePath.EndsWith("*"))
filePath = filePath.TrimEnd('*') + extension;
return _generators[extension] ;
}
return null;
}
#if DEBUG
[Fact]
private void TestGetGeneratorForWildCard()
{
string resource = "rendering\\resourcetest.*";
Add("haml", new HamlGenerator());
Add("tiny", new Tiny.TinyGenerator());
_templateLoaders.Clear();
ResourceTemplateLoader loader = new ResourceTemplateLoader();
loader.LoadTemplates("rendering/", loader.GetType().Assembly, "HttpServer.Rendering");
_templateLoaders.Add(loader);
ITemplateGenerator gen = GetGeneratorForWildCard(ref resource);
Assert.NotNull(gen);
Assert.IsType(typeof (HamlGenerator), gen);
}
[Fact]
private void TestMultipleLoaders()
{
const string resource = "rendering\\resourcetest.*";
Add("haml", new HamlGenerator());
Add("tiny", new Tiny.TinyGenerator());
if (_templateLoaders.Count == 0)
_templateLoaders.Add(new FileTemplateLoader());
ResourceTemplateLoader loader = new ResourceTemplateLoader();
loader.LoadTemplates("rendering/", loader.GetType().Assembly, "HttpServer.Rendering");
_templateLoaders.Add(loader);
string result = Render(resource, null);
Assert.NotNull(result);
Assert.True(result.StartsWith("This file is used to test the resource template loader"));
((FileTemplateLoader)_templateLoaders[0]).PathPrefix = "..\\..\\";
result = Render(resource, null);
Assert.NotNull(result);
Assert.True(result.StartsWith("This file is used to test the resource template loader"));
}
#endif
/// <summary>
/// Render a partial
/// </summary>
/// <param name="filename">Path and filename</param>
/// <param name="templateArguments">Variables used in the template. Should be specified as "name, value, name, value" where name is variable name and value is variable contents.</param>
/// <param name="partialArguments">Arguments passed from parent template</param>
/// <returns></returns>
/// <exception cref="InvalidOperationException"></exception>
/// <exception cref="TemplateException"></exception>
/// <exception cref="ArgumentException"></exception>
public string RenderPartial(string filename, TemplateArguments templateArguments, TemplateArguments partialArguments)
{
templateArguments.Update(partialArguments);
return Render(filename, templateArguments);
}
/// <summary>
/// Generate HTML from a template.
/// </summary>
/// <param name="filename">Path and filename</param>
/// <param name="args">Variables used in the template. Should be specified as "name, value, name, value" where name is variable name and value is variable contents.</param>
/// <exception cref="InvalidOperationException"></exception>
/// <exception cref="CompilerException"></exception>
/// <exception cref="ArgumentException"></exception>
/// <example>
/// <code>
/// string html = cache.Generate("views\\users\\view.haml", new TemplateArguments("user", dbUser, "isAdmin", dbUser.IsAdmin), null);
/// </code>
/// </example>
public string Render(string filename, TemplateArguments args)
{
if (args == null)
args = new TemplateArguments();
// Generate a new proper filename (the generator gets saved aswell) : todo, this works perfectly but isnt so good looking, is it?
GetGeneratorForWildCard(ref filename);
// Generate a name identifying the template
string templateName = "TemplateClass" + filename.GetHashCode() + args.GetHashCode();
templateName = templateName.Replace('-', 'N');
TemplateInfoImp info;
lock (_compiledTemplates)
{
if (_compiledTemplates.ContainsKey(templateName))
info = _compiledTemplates[templateName];
else
{
info = new TemplateInfoImp();
info.Filename = filename;
info.Template = null;
info.CompiledWhen = DateTime.MinValue;
_compiledTemplates.Add(templateName, info);
}
}
lock (info)
{
if (!CheckTemplate(info) || info.Template == null)
{
string code = GenerateCode(ref filename);
info.Template = Compile(filename, code, args, templateName);
info.CompiledWhen = DateTime.Now;
info.Filename = filename;
}
return info.Template.Invoke(args, this);
}
}
#region Nested type: TemplateInfoImp
/// <summary>
/// Keeps information about templates, so we know when to regenerate it.
/// </summary>
private class TemplateInfoImp : ITemplateInfo
{
private DateTime _compiledWhen;
private string _filename;
private ITinyTemplate _template;
public DateTime CompiledWhen
{
get { return _compiledWhen; }
set { _compiledWhen = value; }
}
public string Filename
{
get { return _filename; }
set { _filename = value; }
}
public ITinyTemplate Template
{
get { return _template; }
set { _template = value; }
}
}
#endregion
}
}
| |
//----------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Security
{
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IdentityModel.Policy;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.Runtime;
using System.Runtime.Diagnostics;
using System.Security.Cryptography;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Diagnostics.Application;
using System.ServiceModel.Security.Tokens;
using System.Xml;
using Reference = System.IdentityModel.Reference;
using SignedInfo = System.IdentityModel.SignedInfo;
using SignedXml = System.IdentityModel.SignedXml;
using StandardSignedInfo = System.IdentityModel.StandardSignedInfo;
class WSSecurityOneDotZeroReceiveSecurityHeader : ReceiveSecurityHeader
{
WrappedKeySecurityToken pendingDecryptionToken;
ReferenceList pendingReferenceList;
SignedXml pendingSignature;
List<string> earlyDecryptedDataReferences;
public WSSecurityOneDotZeroReceiveSecurityHeader(Message message, string actor, bool mustUnderstand, bool relay,
SecurityStandardsManager standardsManager,
SecurityAlgorithmSuite algorithmSuite,
int headerIndex,
MessageDirection transferDirection)
: base(message, actor, mustUnderstand, relay, standardsManager, algorithmSuite, headerIndex, transferDirection)
{
}
protected static SymmetricAlgorithm CreateDecryptionAlgorithm(SecurityToken token, string encryptionMethod, SecurityAlgorithmSuite suite)
{
if (encryptionMethod == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(
SR.GetString(SR.EncryptionMethodMissingInEncryptedData)));
}
suite.EnsureAcceptableEncryptionAlgorithm(encryptionMethod);
SymmetricSecurityKey symmetricSecurityKey = SecurityUtils.GetSecurityKey<SymmetricSecurityKey>(token);
if (symmetricSecurityKey == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(
SR.GetString(SR.TokenCannotCreateSymmetricCrypto, token)));
}
suite.EnsureAcceptableDecryptionSymmetricKeySize(symmetricSecurityKey, token);
SymmetricAlgorithm algorithm = symmetricSecurityKey.GetSymmetricAlgorithm(encryptionMethod);
if (algorithm == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(
SR.GetString(SR.UnableToCreateSymmetricAlgorithmFromToken, encryptionMethod)));
}
return algorithm;
}
void DecryptBody(XmlDictionaryReader bodyContentReader, SecurityToken token)
{
EncryptedData bodyXml = new EncryptedData();
bodyXml.ShouldReadXmlReferenceKeyInfoClause = this.MessageDirection == MessageDirection.Output;
bodyXml.SecurityTokenSerializer = this.StandardsManager.SecurityTokenSerializer;
bodyXml.ReadFrom(bodyContentReader, MaxReceivedMessageSize);
if (!bodyContentReader.EOF && bodyContentReader.NodeType != XmlNodeType.EndElement)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.BadEncryptedBody)));
}
if (token == null)
{
token = ResolveKeyIdentifier(bodyXml.KeyIdentifier, this.PrimaryTokenResolver, false);
}
RecordEncryptionToken(token);
using (SymmetricAlgorithm algorithm = CreateDecryptionAlgorithm(token, bodyXml.EncryptionMethod, this.AlgorithmSuite))
{
bodyXml.SetUpDecryption(algorithm);
this.SecurityVerifiedMessage.SetDecryptedBody(bodyXml.GetDecryptedBuffer());
}
}
protected virtual DecryptedHeader DecryptHeader(XmlDictionaryReader reader, WrappedKeySecurityToken wrappedKeyToken)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new MessageSecurityException(SR.GetString(SR.HeaderDecryptionNotSupportedInWsSecurityJan2004)));
}
protected override byte[] DecryptSecurityHeaderElement(
EncryptedData encryptedData, WrappedKeySecurityToken wrappedKeyToken, out SecurityToken encryptionToken)
{
if ((encryptedData.KeyIdentifier != null) || (wrappedKeyToken == null))
{
// The EncryptedData might have a KeyInfo inside it. Try resolving the SecurityKeyIdentifier.
encryptionToken = ResolveKeyIdentifier(encryptedData.KeyIdentifier, this.CombinedPrimaryTokenResolver, false);
if (wrappedKeyToken != null && wrappedKeyToken.ReferenceList != null && encryptedData.HasId && wrappedKeyToken.ReferenceList.ContainsReferredId(encryptedData.Id) && (wrappedKeyToken != encryptionToken))
{
// We have a EncryptedKey with a ReferenceList inside it. This would mean that
// all the EncryptedData pointed by the ReferenceList should be encrypted only
// by this key. The individual EncryptedData elements if containing a KeyInfo
// clause should point back to the same EncryptedKey token.
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.EncryptedKeyWasNotEncryptedWithTheRequiredEncryptingToken, wrappedKeyToken)));
}
}
else
{
encryptionToken = wrappedKeyToken;
}
using (SymmetricAlgorithm algorithm = CreateDecryptionAlgorithm(encryptionToken, encryptedData.EncryptionMethod, this.AlgorithmSuite))
{
encryptedData.SetUpDecryption(algorithm);
return encryptedData.GetDecryptedBuffer();
}
}
protected override WrappedKeySecurityToken DecryptWrappedKey(XmlDictionaryReader reader)
{
if (TD.WrappedKeyDecryptionStartIsEnabled())
{
TD.WrappedKeyDecryptionStart(this.EventTraceActivity);
}
WrappedKeySecurityToken token = (WrappedKeySecurityToken)this.StandardsManager.SecurityTokenSerializer.ReadToken(
reader, this.PrimaryTokenResolver);
this.AlgorithmSuite.EnsureAcceptableKeyWrapAlgorithm(token.WrappingAlgorithm, token.WrappingSecurityKey is AsymmetricSecurityKey);
if (TD.WrappedKeyDecryptionSuccessIsEnabled())
{
TD.WrappedKeyDecryptionSuccess(this.EventTraceActivity);
}
return token;
}
bool EnsureDigestValidityIfIdMatches(
SignedInfo signedInfo,
string id, XmlDictionaryReader reader, bool doSoapAttributeChecks,
MessagePartSpecification signatureParts, MessageHeaderInfo info, bool checkForTokensAtHeaders)
{
if (signedInfo == null)
{
return false;
}
if (doSoapAttributeChecks)
{
VerifySoapAttributeMatchForHeader(info, signatureParts, reader);
}
bool signed = false;
bool isRecognizedSecurityToken = checkForTokensAtHeaders && this.StandardsManager.SecurityTokenSerializer.CanReadToken(reader);
try
{
signed = signedInfo.EnsureDigestValidityIfIdMatches(id, reader);
}
catch (CryptographicException exception)
{
//
// Wrap the crypto exception here so that the perf couter can be updated correctly
//
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.FailedSignatureVerification), exception));
}
if (signed && isRecognizedSecurityToken)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.SecurityTokenFoundOutsideSecurityHeader, info.Namespace, info.Name)));
}
return signed;
}
protected override void ExecuteMessageProtectionPass(bool hasAtLeastOneSupportingTokenExpectedToBeSigned)
{
SignatureTargetIdManager idManager = this.StandardsManager.IdManager;
MessagePartSpecification encryptionParts = this.RequiredEncryptionParts ?? MessagePartSpecification.NoParts;
MessagePartSpecification signatureParts = this.RequiredSignatureParts ?? MessagePartSpecification.NoParts;
bool checkForTokensAtHeaders = hasAtLeastOneSupportingTokenExpectedToBeSigned;
bool doSoapAttributeChecks = !signatureParts.IsBodyIncluded;
bool encryptBeforeSign = this.EncryptBeforeSignMode;
SignedInfo signedInfo = this.pendingSignature != null ? this.pendingSignature.Signature.SignedInfo : null;
SignatureConfirmations signatureConfirmations = this.GetSentSignatureConfirmations();
if (signatureConfirmations != null && signatureConfirmations.Count > 0 && signatureConfirmations.IsMarkedForEncryption)
{
// If Signature Confirmations are encrypted then the signature should
// be encrypted as well.
this.VerifySignatureEncryption();
}
MessageHeaders headers = this.SecurityVerifiedMessage.Headers;
XmlDictionaryReader reader = this.SecurityVerifiedMessage.GetReaderAtFirstHeader();
bool atLeastOneHeaderOrBodyEncrypted = false;
for (int i = 0; i < headers.Count; i++)
{
if (reader.NodeType != XmlNodeType.Element)
{
reader.MoveToContent();
}
if (i == this.HeaderIndex)
{
reader.Skip();
continue;
}
bool isHeaderEncrypted = false;
string id = idManager.ExtractId(reader);
if (id != null)
{
isHeaderEncrypted = TryDeleteReferenceListEntry(id);
}
if (!isHeaderEncrypted && reader.IsStartElement(SecurityXXX2005Strings.EncryptedHeader, SecurityXXX2005Strings.Namespace))
{
XmlDictionaryReader localreader = headers.GetReaderAtHeader(i);
localreader.ReadStartElement(SecurityXXX2005Strings.EncryptedHeader, SecurityXXX2005Strings.Namespace);
if (localreader.IsStartElement(EncryptedData.ElementName, XD.XmlEncryptionDictionary.Namespace))
{
string encryptedDataId = localreader.GetAttribute(XD.XmlEncryptionDictionary.Id, null);
if (encryptedDataId != null && TryDeleteReferenceListEntry(encryptedDataId))
{
isHeaderEncrypted = true;
}
}
}
this.ElementManager.VerifyUniquenessAndSetHeaderId(id, i);
MessageHeaderInfo info = headers[i];
if (!isHeaderEncrypted && encryptionParts.IsHeaderIncluded(info.Name, info.Namespace))
{
this.SecurityVerifiedMessage.OnUnencryptedPart(info.Name, info.Namespace);
}
bool headerSigned;
if ((!isHeaderEncrypted || encryptBeforeSign) && id != null)
{
headerSigned = EnsureDigestValidityIfIdMatches(signedInfo, id, reader, doSoapAttributeChecks, signatureParts, info, checkForTokensAtHeaders);
}
else
{
headerSigned = false;
}
if (isHeaderEncrypted)
{
XmlDictionaryReader decryptionReader = headerSigned ? headers.GetReaderAtHeader(i) : reader;
DecryptedHeader decryptedHeader = DecryptHeader(decryptionReader, this.pendingDecryptionToken);
info = decryptedHeader;
id = decryptedHeader.Id;
this.ElementManager.VerifyUniquenessAndSetDecryptedHeaderId(id, i);
headers.ReplaceAt(i, decryptedHeader);
if (!ReferenceEquals(decryptionReader, reader))
{
decryptionReader.Close();
}
if (!encryptBeforeSign && id != null)
{
XmlDictionaryReader decryptedHeaderReader = decryptedHeader.GetHeaderReader();
headerSigned = EnsureDigestValidityIfIdMatches(signedInfo, id, decryptedHeaderReader, doSoapAttributeChecks, signatureParts, info, checkForTokensAtHeaders);
decryptedHeaderReader.Close();
}
}
if (!headerSigned && signatureParts.IsHeaderIncluded(info.Name, info.Namespace))
{
this.SecurityVerifiedMessage.OnUnsignedPart(info.Name, info.Namespace);
}
if (headerSigned && isHeaderEncrypted)
{
// We have a header that is signed and encrypted. So the accompanying primary signature
// should be encrypted as well.
this.VerifySignatureEncryption();
}
if (isHeaderEncrypted && !headerSigned)
{
// We require all encrypted headers (outside the security header) to be signed.
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.EncryptedHeaderNotSigned, info.Name, info.Namespace)));
}
if (!headerSigned && !isHeaderEncrypted)
{
reader.Skip();
}
atLeastOneHeaderOrBodyEncrypted |= isHeaderEncrypted;
}
reader.ReadEndElement();
if (reader.NodeType != XmlNodeType.Element)
{
reader.MoveToContent();
}
string bodyId = idManager.ExtractId(reader);
this.ElementManager.VerifyUniquenessAndSetBodyId(bodyId);
this.SecurityVerifiedMessage.SetBodyPrefixAndAttributes(reader);
bool expectBodyEncryption = encryptionParts.IsBodyIncluded || HasPendingDecryptionItem();
bool bodySigned;
if ((!expectBodyEncryption || encryptBeforeSign) && bodyId != null)
{
bodySigned = EnsureDigestValidityIfIdMatches(signedInfo, bodyId, reader, false, null, null, false);
}
else
{
bodySigned = false;
}
bool bodyEncrypted;
if (expectBodyEncryption)
{
XmlDictionaryReader bodyReader = bodySigned ? this.SecurityVerifiedMessage.CreateFullBodyReader() : reader;
bodyReader.ReadStartElement();
string bodyContentId = idManager.ExtractId(bodyReader);
this.ElementManager.VerifyUniquenessAndSetBodyContentId(bodyContentId);
bodyEncrypted = bodyContentId != null && TryDeleteReferenceListEntry(bodyContentId);
if (bodyEncrypted)
{
DecryptBody(bodyReader, this.pendingDecryptionToken);
}
if (!ReferenceEquals(bodyReader, reader))
{
bodyReader.Close();
}
if (!encryptBeforeSign && signedInfo != null && signedInfo.HasUnverifiedReference(bodyId))
{
bodyReader = this.SecurityVerifiedMessage.CreateFullBodyReader();
bodySigned = EnsureDigestValidityIfIdMatches(signedInfo, bodyId, bodyReader, false, null, null, false);
bodyReader.Close();
}
}
else
{
bodyEncrypted = false;
}
if (bodySigned && bodyEncrypted)
{
this.VerifySignatureEncryption();
}
reader.Close();
if (this.pendingSignature != null)
{
this.pendingSignature.CompleteSignatureVerification();
this.pendingSignature = null;
}
this.pendingDecryptionToken = null;
atLeastOneHeaderOrBodyEncrypted |= bodyEncrypted;
if (!bodySigned && signatureParts.IsBodyIncluded)
{
this.SecurityVerifiedMessage.OnUnsignedPart(XD.MessageDictionary.Body.Value, this.Version.Envelope.Namespace);
}
if (!bodyEncrypted && encryptionParts.IsBodyIncluded)
{
this.SecurityVerifiedMessage.OnUnencryptedPart(XD.MessageDictionary.Body.Value, this.Version.Envelope.Namespace);
}
this.SecurityVerifiedMessage.OnMessageProtectionPassComplete(atLeastOneHeaderOrBodyEncrypted);
}
protected override bool IsReaderAtEncryptedData(XmlDictionaryReader reader)
{
bool encrypted = reader.IsStartElement(EncryptedData.ElementName, XD.XmlEncryptionDictionary.Namespace);
if (encrypted == true)
this.HasAtLeastOneItemInsideSecurityHeaderEncrypted = true;
return encrypted;
}
protected override bool IsReaderAtEncryptedKey(XmlDictionaryReader reader)
{
return reader.IsStartElement(EncryptedKey.ElementName, XD.XmlEncryptionDictionary.Namespace);
}
protected override bool IsReaderAtReferenceList(XmlDictionaryReader reader)
{
return reader.IsStartElement(ReferenceList.ElementName, ReferenceList.NamespaceUri);
}
protected override bool IsReaderAtSignature(XmlDictionaryReader reader)
{
return reader.IsStartElement(XD.XmlSignatureDictionary.Signature, XD.XmlSignatureDictionary.Namespace);
}
protected override bool IsReaderAtSecurityTokenReference(XmlDictionaryReader reader)
{
return reader.IsStartElement(XD.SecurityJan2004Dictionary.SecurityTokenReference, XD.SecurityJan2004Dictionary.Namespace);
}
protected override void ProcessReferenceListCore(ReferenceList referenceList, WrappedKeySecurityToken wrappedKeyToken)
{
this.pendingReferenceList = referenceList;
this.pendingDecryptionToken = wrappedKeyToken;
}
protected override ReferenceList ReadReferenceListCore(XmlDictionaryReader reader)
{
ReferenceList referenceList = new ReferenceList();
referenceList.ReadFrom(reader);
return referenceList;
}
protected override EncryptedData ReadSecurityHeaderEncryptedItem(XmlDictionaryReader reader, bool readXmlreferenceKeyInfoClause)
{
EncryptedData encryptedData = new EncryptedData();
encryptedData.ShouldReadXmlReferenceKeyInfoClause = readXmlreferenceKeyInfoClause;
encryptedData.SecurityTokenSerializer = this.StandardsManager.SecurityTokenSerializer;
encryptedData.ReadFrom(reader);
return encryptedData;
}
protected override SignedXml ReadSignatureCore(XmlDictionaryReader signatureReader)
{
SignedXml signedXml = new SignedXml(ServiceModelDictionaryManager.Instance, this.StandardsManager.SecurityTokenSerializer);
signedXml.Signature.SignedInfo.ResourcePool = this.ResourcePool;
signedXml.ReadFrom(signatureReader);
return signedXml;
}
protected static bool TryResolveKeyIdentifier(
SecurityKeyIdentifier keyIdentifier, SecurityTokenResolver resolver, bool isFromSignature, out SecurityToken token)
{
if (keyIdentifier == null)
{
if (isFromSignature)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.NoKeyInfoInSignatureToFindVerificationToken)));
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.NoKeyInfoInEncryptedItemToFindDecryptingToken)));
}
}
return resolver.TryResolveToken(keyIdentifier, out token);
}
protected static SecurityToken ResolveKeyIdentifier(SecurityKeyIdentifier keyIdentifier, SecurityTokenResolver resolver, bool isFromSignature)
{
SecurityToken token;
if (!TryResolveKeyIdentifier(keyIdentifier, resolver, isFromSignature, out token))
{
if (isFromSignature)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(
SR.GetString(SR.UnableToResolveKeyInfoForVerifyingSignature, keyIdentifier, resolver)));
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(
SR.GetString(SR.UnableToResolveKeyInfoForDecryption, keyIdentifier, resolver)));
}
}
return token;
}
SecurityToken ResolveSignatureToken(SecurityKeyIdentifier keyIdentifier, SecurityTokenResolver resolver, bool isPrimarySignature)
{
SecurityToken token;
TryResolveKeyIdentifier(keyIdentifier, resolver, true, out token);
if (token == null && !isPrimarySignature)
{
// check if there is a rsa key token authenticator
if (keyIdentifier.Count == 1)
{
RsaKeyIdentifierClause rsaClause;
if (keyIdentifier.TryFind<RsaKeyIdentifierClause>(out rsaClause))
{
RsaSecurityTokenAuthenticator rsaAuthenticator = FindAllowedAuthenticator<RsaSecurityTokenAuthenticator>(false);
if (rsaAuthenticator != null)
{
token = new RsaSecurityToken(rsaClause.Rsa);
ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies = rsaAuthenticator.ValidateToken(token);
SupportingTokenAuthenticatorSpecification spec;
TokenTracker rsaTracker = GetSupportingTokenTracker(rsaAuthenticator, out spec);
if (rsaTracker == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.UnknownTokenAuthenticatorUsedInTokenProcessing, rsaAuthenticator)));
}
rsaTracker.RecordToken(token);
SecurityTokenAuthorizationPoliciesMapping.Add(token, authorizationPolicies);
}
}
}
}
if (token == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(
SR.GetString(SR.UnableToResolveKeyInfoForVerifyingSignature, keyIdentifier, resolver)));
}
return token;
}
protected override void ReadSecurityTokenReference(XmlDictionaryReader reader)
{
string strId = reader.GetAttribute(XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace);
SecurityKeyIdentifierClause strClause = this.StandardsManager.SecurityTokenSerializer.ReadKeyIdentifierClause(reader);
if (String.IsNullOrEmpty(strClause.Id))
{
strClause.Id = strId;
}
if (!String.IsNullOrEmpty(strClause.Id))
{
this.ElementManager.AppendSecurityTokenReference(strClause, strClause.Id);
}
}
bool HasPendingDecryptionItem()
{
return this.pendingReferenceList != null && this.pendingReferenceList.DataReferenceCount > 0;
}
protected override bool TryDeleteReferenceListEntry(string id)
{
return this.pendingReferenceList != null && this.pendingReferenceList.TryRemoveReferredId(id);
}
protected override void EnsureDecryptionComplete()
{
if (this.earlyDecryptedDataReferences != null)
{
for (int i = 0; i < this.earlyDecryptedDataReferences.Count; i++)
{
if (!TryDeleteReferenceListEntry(this.earlyDecryptedDataReferences[i]))
{
throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.UnexpectedEncryptedElementInSecurityHeader)), this.Message);
}
}
}
if (HasPendingDecryptionItem())
{
throw TraceUtility.ThrowHelperError(
new MessageSecurityException(SR.GetString(SR.UnableToResolveDataReference, this.pendingReferenceList.GetReferredId(0))), this.Message);
}
}
protected override void OnDecryptionOfSecurityHeaderItemRequiringReferenceListEntry(string id)
{
if (!TryDeleteReferenceListEntry(id))
{
if (this.earlyDecryptedDataReferences == null)
{
this.earlyDecryptedDataReferences = new List<string>(4);
}
this.earlyDecryptedDataReferences.Add(id);
}
}
protected override SecurityToken VerifySignature(SignedXml signedXml, bool isPrimarySignature,
SecurityHeaderTokenResolver resolver, object signatureTarget, string id)
{
if (TD.SignatureVerificationStartIsEnabled())
{
TD.SignatureVerificationStart(this.EventTraceActivity);
}
SecurityToken token = ResolveSignatureToken(signedXml.Signature.KeyIdentifier, resolver, isPrimarySignature);
if (isPrimarySignature)
{
RecordSignatureToken(token);
}
ReadOnlyCollection<SecurityKey> keys = token.SecurityKeys;
SecurityKey securityKey = (keys != null && keys.Count > 0) ? keys[0] : null;
if (securityKey == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(
SR.GetString(SR.UnableToCreateICryptoFromTokenForSignatureVerification, token)));
}
this.AlgorithmSuite.EnsureAcceptableSignatureKeySize(securityKey, token);
this.AlgorithmSuite.EnsureAcceptableSignatureAlgorithm(securityKey, signedXml.Signature.SignedInfo.SignatureMethod);
signedXml.StartSignatureVerification(securityKey);
StandardSignedInfo signedInfo = (StandardSignedInfo)signedXml.Signature.SignedInfo;
ValidateDigestsOfTargetsInSecurityHeader(signedInfo, this.Timestamp, isPrimarySignature, signatureTarget, id);
if (!isPrimarySignature)
{
if ((!this.RequireMessageProtection) && (securityKey is AsymmetricSecurityKey) && (this.Version.Addressing != AddressingVersion.None))
{
// For Transport Security using Asymmetric Keys verify that
// the 'To' header is signed.
int headerIndex = this.Message.Headers.FindHeader(XD.AddressingDictionary.To.Value, this.Message.Version.Addressing.Namespace);
if (headerIndex == -1)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.TransportSecuredMessageMissingToHeader)));
XmlDictionaryReader toHeaderReader = this.Message.Headers.GetReaderAtHeader(headerIndex);
id = toHeaderReader.GetAttribute(XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace);
// DevDiv:938534 - We added a flag that allow unsigned headers. If this is set, we do not throw an Exception but move on to CompleteSignatureVerification()
if (LocalAppContextSwitches.AllowUnsignedToHeader)
{
// The lack of an id indicates that the sender did not wish to sign the header. We can safely assume that null indicates this header is not signed.
// If id is not null, then we need to validate the Digest and ensure signature is valid. The exception is thrown deeper in the System.IdentityModel stack.
if (id != null)
{
signedXml.EnsureDigestValidityIfIdMatches(id, toHeaderReader);
}
}
else
{
// default behavior for all platforms
if (id == null)
{
//
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.UnsignedToHeaderInTransportSecuredMessage)));
}
signedXml.EnsureDigestValidity(id, toHeaderReader);
}
}
signedXml.CompleteSignatureVerification();
return token;
}
this.pendingSignature = signedXml;
if (TD.SignatureVerificationSuccessIsEnabled())
{
TD.SignatureVerificationSuccess(this.EventTraceActivity);
}
return token;
}
void ValidateDigestsOfTargetsInSecurityHeader(StandardSignedInfo signedInfo, SecurityTimestamp timestamp, bool isPrimarySignature, object signatureTarget, string id)
{
Fx.Assert(!isPrimarySignature || (isPrimarySignature && (signatureTarget == null)), "For primary signature we try to validate all the references.");
for (int i = 0; i < signedInfo.ReferenceCount; i++)
{
Reference reference = signedInfo[i];
this.AlgorithmSuite.EnsureAcceptableDigestAlgorithm(reference.DigestMethod);
string referredId = reference.ExtractReferredId();
if (isPrimarySignature || (id == referredId))
{
if (timestamp != null && timestamp.Id == referredId && !reference.TransformChain.NeedsInclusiveContext &&
timestamp.DigestAlgorithm == reference.DigestMethod && timestamp.GetDigest() != null)
{
reference.EnsureDigestValidity(referredId, timestamp.GetDigest());
this.ElementManager.SetTimestampSigned(referredId);
}
else
{
if (signatureTarget != null)
reference.EnsureDigestValidity(id, signatureTarget);
else
{
int tokenIndex = -1;
XmlDictionaryReader reader = null;
if (reference.IsStrTranform())
{
if (this.ElementManager.TryGetTokenElementIndexFromStrId(referredId, out tokenIndex))
{
ReceiveSecurityHeaderEntry entry;
this.ElementManager.GetElementEntry(tokenIndex, out entry);
bool isSignedToken = (entry.bindingMode == ReceiveSecurityHeaderBindingModes.Signed)
|| (entry.bindingMode == ReceiveSecurityHeaderBindingModes.SignedEndorsing);
// This means it is a protected(signed)primary token.
if (!this.ElementManager.IsPrimaryTokenSigned)
{
this.ElementManager.IsPrimaryTokenSigned = entry.bindingMode == ReceiveSecurityHeaderBindingModes.Primary &&
entry.elementCategory == ReceiveSecurityHeaderElementCategory.Token;
}
this.ElementManager.SetSigned(tokenIndex);
// We pass true if it is a signed supporting token, signed primary token or a SignedEndorsing token. We pass false if it is a SignedEncrypted Token.
reader = this.ElementManager.GetReader(tokenIndex, isSignedToken);
}
}
else
reader = this.ElementManager.GetSignatureVerificationReader(referredId, this.EncryptBeforeSignMode);
if (reader != null)
{
reference.EnsureDigestValidity(referredId, reader);
reader.Close();
}
}
}
if (!isPrimarySignature)
{
// We were given an id to verify and we have verified it. So just break out
// of the loop.
break;
}
}
}
// This check makes sure that if RequireSignedPrimaryToken is true (ProtectTokens is enabled on sbe) then the incoming message
// should have the primary signature over the primary(signing)token.
if (isPrimarySignature && this.RequireSignedPrimaryToken && !this.ElementManager.IsPrimaryTokenSigned)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.SupportingTokenIsNotSigned, new IssuedSecurityTokenParameters())));
}
// NOTE: On both client and server side, WCF quietly consumes protected tokens even if protect token is not enabled on sbe.
// To change this behaviour add another check below and throw appropriate exception message.
}
void VerifySoapAttributeMatchForHeader(MessageHeaderInfo info, MessagePartSpecification signatureParts, XmlDictionaryReader reader)
{
if (!signatureParts.IsHeaderIncluded(info.Name, info.Namespace))
{
return;
}
EnvelopeVersion currentVersion = this.Version.Envelope;
EnvelopeVersion otherVersion = currentVersion == EnvelopeVersion.Soap11 ? EnvelopeVersion.Soap12 : EnvelopeVersion.Soap11;
bool presentInCurrentVersion;
bool presentInOtherVersion;
presentInCurrentVersion = null != reader.GetAttribute(XD.MessageDictionary.MustUnderstand, currentVersion.DictionaryNamespace);
presentInOtherVersion = null != reader.GetAttribute(XD.MessageDictionary.MustUnderstand, otherVersion.DictionaryNamespace);
if (presentInOtherVersion && !presentInCurrentVersion)
{
throw TraceUtility.ThrowHelperError(
new MessageSecurityException(SR.GetString(
SR.InvalidAttributeInSignedHeader, info.Name, info.Namespace,
XD.MessageDictionary.MustUnderstand, otherVersion.DictionaryNamespace,
XD.MessageDictionary.MustUnderstand, currentVersion.DictionaryNamespace)), this.SecurityVerifiedMessage);
}
presentInCurrentVersion = null != reader.GetAttribute(currentVersion.DictionaryActor, currentVersion.DictionaryNamespace);
presentInOtherVersion = null != reader.GetAttribute(otherVersion.DictionaryActor, otherVersion.DictionaryNamespace);
if (presentInOtherVersion && !presentInCurrentVersion)
{
throw TraceUtility.ThrowHelperError(
new MessageSecurityException(SR.GetString(
SR.InvalidAttributeInSignedHeader, info.Name, info.Namespace,
otherVersion.DictionaryActor, otherVersion.DictionaryNamespace,
currentVersion.DictionaryActor, currentVersion.DictionaryNamespace)), this.SecurityVerifiedMessage);
}
}
}
}
| |
#region License
/*
* HttpListenerResponse.cs
*
* This code is derived from HttpListenerResponse.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2012-2015 sta.blockhead
*
* 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
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <[email protected]>
*/
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
namespace WebSocketSharp.Net
{
/// <summary>
/// Provides the access to a response to a request received by the <see cref="HttpListener"/>.
/// </summary>
/// <remarks>
/// The HttpListenerResponse class cannot be inherited.
/// </remarks>
public sealed class HttpListenerResponse : IDisposable
{
#region Private Fields
private bool _chunked;
private Encoding _contentEncoding;
private long _contentLength;
private bool _contentLengthWasSet;
private string _contentType;
private HttpListenerContext _context;
private CookieCollection _cookies;
private bool _disposed;
private bool _forceCloseChunked;
private WebHeaderCollection _headers;
private bool _headersWereSent;
private bool _keepAlive;
private string _location;
private ResponseStream _outputStream;
private int _statusCode;
private string _statusDescription;
private Version _version;
#endregion
#region Internal Constructors
internal HttpListenerResponse (HttpListenerContext context)
{
_context = context;
_headers = new WebHeaderCollection ();
_keepAlive = true;
_statusCode = 200;
_statusDescription = "OK";
_version = HttpVersion.Version11;
}
#endregion
#region Internal Properties
internal bool CloseConnection {
get {
return _headers["Connection"] == "close";
}
}
internal bool ForceCloseChunked {
get {
return _forceCloseChunked;
}
}
internal bool HeadersSent {
get {
return _headersWereSent;
}
}
#endregion
#region Public Properties
/// <summary>
/// Gets or sets the encoding for the entity body data included in the response.
/// </summary>
/// <value>
/// A <see cref="Encoding"/> that represents the encoding for the entity body data,
/// or <see langword="null"/> if no encoding is specified.
/// </value>
/// <exception cref="InvalidOperationException">
/// The response has already been sent.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public Encoding ContentEncoding {
get {
return _contentEncoding;
}
set {
checkDisposedOrHeadersSent ();
_contentEncoding = value;
}
}
/// <summary>
/// Gets or sets the size of the entity body data included in the response.
/// </summary>
/// <value>
/// A <see cref="long"/> that represents the value of the Content-Length entity-header.
/// The value is a number of bytes in the entity body data.
/// </value>
/// <exception cref="ArgumentOutOfRangeException">
/// The value specified for a set operation is less than zero.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The response has already been sent.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public long ContentLength64 {
get {
return _contentLength;
}
set {
checkDisposedOrHeadersSent ();
if (value < 0)
throw new ArgumentOutOfRangeException ("Less than zero.", "value");
_contentLengthWasSet = true;
_contentLength = value;
}
}
/// <summary>
/// Gets or sets the media type of the entity body included in the response.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the value of the Content-Type entity-header.
/// </value>
/// <exception cref="ArgumentException">
/// The value specified for a set operation is empty.
/// </exception>
/// <exception cref="ArgumentNullException">
/// The value specified for a set operation is <see langword="null"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The response has already been sent.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public string ContentType {
get {
return _contentType;
}
set {
checkDisposedOrHeadersSent ();
if (value == null)
throw new ArgumentNullException ("value");
if (value.Length == 0)
throw new ArgumentException ("An empty string.", "value");
_contentType = value;
}
}
/// <summary>
/// Gets or sets the cookies sent with the response.
/// </summary>
/// <value>
/// A <see cref="CookieCollection"/> that contains the cookies sent with the response.
/// </value>
/// <exception cref="InvalidOperationException">
/// The response has already been sent.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public CookieCollection Cookies {
get {
return _cookies ?? (_cookies = new CookieCollection ());
}
set {
checkDisposedOrHeadersSent ();
_cookies = value;
}
}
/// <summary>
/// Gets or sets the HTTP headers sent to the client.
/// </summary>
/// <value>
/// A <see cref="WebHeaderCollection"/> that contains the headers sent to the client.
/// </value>
/// <exception cref="ArgumentNullException">
/// The value specified for a set operation is <see langword="null"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The response has already been sent.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public WebHeaderCollection Headers {
get {
return _headers;
}
set {
/*
* "If you attempt to set a Content-Length, Keep-Alive, Transfer-Encoding,
* or WWW-Authenticate header using the Headers property, an exception
* will be thrown. Use the ContentLength64 or KeepAlive properties to set
* these headers. You cannot set the Transfer-Encoding or WWW-Authenticate
* headers manually."
*/
// TODO: Check if this is marked readonly after the headers are sent.
checkDisposedOrHeadersSent ();
if (value == null)
throw new ArgumentNullException ("value");
_headers = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether the server requests a persistent connection.
/// </summary>
/// <value>
/// <c>true</c> if the server requests a persistent connection; otherwise, <c>false</c>.
/// The default value is <c>true</c>.
/// </value>
/// <exception cref="InvalidOperationException">
/// The response has already been sent.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public bool KeepAlive {
get {
return _keepAlive;
}
set {
checkDisposedOrHeadersSent ();
_keepAlive = value;
}
}
/// <summary>
/// Gets a <see cref="Stream"/> to use to write the entity body data.
/// </summary>
/// <value>
/// A <see cref="Stream"/> to use to write the entity body data.
/// </value>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public Stream OutputStream {
get {
checkDisposed ();
return _outputStream ?? (_outputStream = _context.Connection.GetResponseStream ());
}
}
/// <summary>
/// Gets or sets the HTTP version used in the response.
/// </summary>
/// <value>
/// A <see cref="Version"/> that represents the version used in the response.
/// </value>
/// <exception cref="ArgumentException">
/// The value specified for a set operation doesn't have its <c>Major</c> property set to 1 or
/// doesn't have its <c>Minor</c> property set to either 0 or 1.
/// </exception>
/// <exception cref="ArgumentNullException">
/// The value specified for a set operation is <see langword="null"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The response has already been sent.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public Version ProtocolVersion {
get {
return _version;
}
set {
checkDisposedOrHeadersSent ();
if (value == null)
throw new ArgumentNullException ("value");
if (value.Major != 1 || (value.Minor != 0 && value.Minor != 1))
throw new ArgumentException ("Not 1.0 or 1.1.", "value");
_version = value;
}
}
/// <summary>
/// Gets or sets the URL to which the client is redirected to locate a requested resource.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the value of the Location response-header.
/// </value>
/// <exception cref="ArgumentException">
/// The value specified for a set operation is empty.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The response has already been sent.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public string RedirectLocation {
get {
return _location;
}
set {
checkDisposedOrHeadersSent ();
if (value.Length == 0)
throw new ArgumentException ("An empty string.", "value");
_location = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether the response uses the chunked transfer encoding.
/// </summary>
/// <value>
/// <c>true</c> if the response uses the chunked transfer encoding; otherwise, <c>false</c>.
/// </value>
/// <exception cref="InvalidOperationException">
/// The response has already been sent.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public bool SendChunked {
get {
return _chunked;
}
set {
checkDisposedOrHeadersSent ();
_chunked = value;
}
}
/// <summary>
/// Gets or sets the HTTP status code returned to the client.
/// </summary>
/// <value>
/// An <see cref="int"/> that represents the status code for the response to the request.
/// The default value is <see cref="HttpStatusCode.OK"/>.
/// </value>
/// <exception cref="InvalidOperationException">
/// The response has already been sent.
/// </exception>
/// <exception cref="System.Net.ProtocolViolationException">
/// The value specified for a set operation is invalid. Valid values are between 100 and 999.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public int StatusCode {
get {
return _statusCode;
}
set {
checkDisposedOrHeadersSent ();
if (value < 100 || value > 999)
throw new System.Net.ProtocolViolationException ("A value isn't between 100 and 999.");
_statusCode = value;
_statusDescription = value.GetStatusDescription ();
}
}
/// <summary>
/// Gets or sets the description of the HTTP status code returned to the client.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the description of the status code.
/// </value>
/// <exception cref="InvalidOperationException">
/// The response has already been sent.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public string StatusDescription {
get {
return _statusDescription;
}
set {
checkDisposedOrHeadersSent ();
_statusDescription = value != null && value.Length > 0
? value
: _statusCode.GetStatusDescription ();
}
}
#endregion
#region Private Methods
private bool canAddOrUpdate (Cookie cookie)
{
if (_cookies == null || _cookies.Count == 0)
return true;
var found = findCookie (cookie).ToList ();
if (found.Count == 0)
return true;
var ver = cookie.Version;
foreach (var c in found)
if (c.Version == ver)
return true;
return false;
}
private void checkDisposed ()
{
if (_disposed)
throw new ObjectDisposedException (GetType ().ToString ());
}
private void checkDisposedOrHeadersSent ()
{
if (_disposed)
throw new ObjectDisposedException (GetType ().ToString ());
if (_headersWereSent)
throw new InvalidOperationException ("Cannot be changed after the headers are sent.");
}
private void close (bool force)
{
_disposed = true;
_context.Connection.Close (force);
}
private IEnumerable<Cookie> findCookie (Cookie cookie)
{
var name = cookie.Name;
var domain = cookie.Domain;
var path = cookie.Path;
if (_cookies != null)
foreach (Cookie c in _cookies)
if (c.Name.Equals (name, StringComparison.OrdinalIgnoreCase) &&
c.Domain.Equals (domain, StringComparison.OrdinalIgnoreCase) &&
c.Path.Equals (path, StringComparison.Ordinal))
yield return c;
}
#endregion
#region Internal Methods
internal void SendHeaders (MemoryStream stream, bool closing)
{
if (_contentType != null) {
var type = _contentType.IndexOf ("charset=", StringComparison.Ordinal) == -1 &&
_contentEncoding != null
? String.Format ("{0}; charset={1}", _contentType, _contentEncoding.WebName)
: _contentType;
_headers.InternalSet ("Content-Type", type, true);
}
if (_headers["Server"] == null)
_headers.InternalSet ("Server", "websocket-sharp/1.0", true);
var prov = CultureInfo.InvariantCulture;
if (_headers["Date"] == null)
_headers.InternalSet ("Date", DateTime.UtcNow.ToString ("r", prov), true);
if (!_chunked) {
if (!_contentLengthWasSet && closing) {
_contentLengthWasSet = true;
_contentLength = 0;
}
if (_contentLengthWasSet)
_headers.InternalSet ("Content-Length", _contentLength.ToString (prov), true);
}
var ver = _context.Request.ProtocolVersion;
if (!_contentLengthWasSet && !_chunked && ver > HttpVersion.Version10)
_chunked = true;
/*
* Apache forces closing the connection for these status codes:
* - HttpStatusCode.BadRequest 400
* - HttpStatusCode.RequestTimeout 408
* - HttpStatusCode.LengthRequired 411
* - HttpStatusCode.RequestEntityTooLarge 413
* - HttpStatusCode.RequestUriTooLong 414
* - HttpStatusCode.InternalServerError 500
* - HttpStatusCode.ServiceUnavailable 503
*/
var closeConn = _statusCode == 400 ||
_statusCode == 408 ||
_statusCode == 411 ||
_statusCode == 413 ||
_statusCode == 414 ||
_statusCode == 500 ||
_statusCode == 503;
if (!closeConn)
closeConn = !_context.Request.KeepAlive;
// They sent both KeepAlive: true and Connection: close!?
if (!_keepAlive || closeConn) {
_headers.InternalSet ("Connection", "close", true);
closeConn = true;
}
if (_chunked)
_headers.InternalSet ("Transfer-Encoding", "chunked", true);
var reuses = _context.Connection.Reuses;
if (reuses >= 100) {
_forceCloseChunked = true;
if (!closeConn) {
_headers.InternalSet ("Connection", "close", true);
closeConn = true;
}
}
if (!closeConn) {
_headers.InternalSet (
"Keep-Alive", String.Format ("timeout=15,max={0}", 100 - reuses), true);
if (ver < HttpVersion.Version11)
_headers.InternalSet ("Connection", "keep-alive", true);
}
if (_location != null)
_headers.InternalSet ("Location", _location, true);
if (_cookies != null)
foreach (Cookie cookie in _cookies)
_headers.InternalSet ("Set-Cookie", cookie.ToResponseString (), true);
var enc = _contentEncoding ?? Encoding.Default;
var writer = new StreamWriter (stream, enc, 256);
writer.Write ("HTTP/{0} {1} {2}\r\n", _version, _statusCode, _statusDescription);
writer.Write (_headers.ToStringMultiValue (true));
writer.Flush ();
// Assumes that the stream was at position 0.
stream.Position = enc.CodePage == 65001 ? 3 : enc.GetPreamble ().Length;
if (_outputStream == null)
_outputStream = _context.Connection.GetResponseStream ();
_headersWereSent = true;
}
#endregion
#region Public Methods
/// <summary>
/// Closes the connection to the client without returning a response.
/// </summary>
public void Abort ()
{
if (_disposed)
return;
close (true);
}
/// <summary>
/// Adds an HTTP header with the specified <paramref name="name"/> and <paramref name="value"/>
/// to the headers for the response.
/// </summary>
/// <param name="name">
/// A <see cref="string"/> that represents the name of the header to add.
/// </param>
/// <param name="value">
/// A <see cref="string"/> that represents the value of the header to add.
/// </param>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="name"/> or <paramref name="value"/> contains invalid characters.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="name"/> is a restricted header name.
/// </para>
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="name"/> is <see langword="null"/> or empty.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65,535 characters.
/// </exception>
/// <exception cref="InvalidOperationException">
/// <para>
/// The response has already been sent.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The header cannot be allowed to add to the current headers.
/// </para>
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public void AddHeader (string name, string value)
{
checkDisposedOrHeadersSent ();
_headers.Set (name, value);
}
/// <summary>
/// Appends the specified <paramref name="cookie"/> to the cookies sent with the response.
/// </summary>
/// <param name="cookie">
/// A <see cref="Cookie"/> to append.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="cookie"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The response has already been sent.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public void AppendCookie (Cookie cookie)
{
checkDisposedOrHeadersSent ();
Cookies.Add (cookie);
}
/// <summary>
/// Appends a <paramref name="value"/> to the specified HTTP header sent with the response.
/// </summary>
/// <param name="name">
/// A <see cref="string"/> that represents the name of the header to append
/// <paramref name="value"/> to.
/// </param>
/// <param name="value">
/// A <see cref="string"/> that represents the value to append to the header.
/// </param>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="name"/> or <paramref name="value"/> contains invalid characters.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="name"/> is a restricted header name.
/// </para>
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="name"/> is <see langword="null"/> or empty.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65,535 characters.
/// </exception>
/// <exception cref="InvalidOperationException">
/// <para>
/// The response has already been sent.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The current headers cannot allow the header to append a value.
/// </para>
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public void AppendHeader (string name, string value)
{
checkDisposedOrHeadersSent ();
_headers.Add (name, value);
}
/// <summary>
/// Returns the response to the client and releases the resources used by
/// this <see cref="HttpListenerResponse"/> instance.
/// </summary>
public void Close ()
{
if (_disposed)
return;
close (false);
}
/// <summary>
/// Returns the response with the specified array of <see cref="byte"/> to the client and
/// releases the resources used by this <see cref="HttpListenerResponse"/> instance.
/// </summary>
/// <param name="responseEntity">
/// An array of <see cref="byte"/> that contains the response entity body data.
/// </param>
/// <param name="willBlock">
/// <c>true</c> if this method blocks execution while flushing the stream to the client;
/// otherwise, <c>false</c>.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="responseEntity"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The response has already been sent.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public void Close (byte[] responseEntity, bool willBlock)
{
if (responseEntity == null)
throw new ArgumentNullException ("responseEntity");
var len = responseEntity.Length;
ContentLength64 = len;
var output = OutputStream;
if (willBlock) {
output.Write (responseEntity, 0, len);
close (false);
return;
}
output.BeginWrite (
responseEntity,
0,
len,
ar => {
output.EndWrite (ar);
close (false);
},
null);
}
/// <summary>
/// Copies properties from the specified <see cref="HttpListenerResponse"/> to this response.
/// </summary>
/// <param name="templateResponse">
/// A <see cref="HttpListenerResponse"/> to copy.
/// </param>
/// <exception cref="InvalidOperationException">
/// The response has already been sent.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public void CopyFrom (HttpListenerResponse templateResponse)
{
checkDisposedOrHeadersSent ();
_headers.Clear ();
_headers.Add (templateResponse._headers);
_contentLength = templateResponse._contentLength;
_statusCode = templateResponse._statusCode;
_statusDescription = templateResponse._statusDescription;
_keepAlive = templateResponse._keepAlive;
_version = templateResponse._version;
}
/// <summary>
/// Configures the response to redirect the client's request to the specified
/// <paramref name="url"/>.
/// </summary>
/// <param name="url">
/// A <see cref="string"/> that represents the URL to redirect the client's request to.
/// </param>
/// <exception cref="InvalidOperationException">
/// The response has already been sent.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public void Redirect (string url)
{
StatusCode = (int) HttpStatusCode.Redirect;
_location = url;
}
/// <summary>
/// Adds or updates a <paramref name="cookie"/> in the cookies sent with the response.
/// </summary>
/// <param name="cookie">
/// A <see cref="Cookie"/> to set.
/// </param>
/// <exception cref="ArgumentException">
/// <paramref name="cookie"/> already exists in the cookies and couldn't be replaced.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="cookie"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The response has already been sent.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public void SetCookie (Cookie cookie)
{
checkDisposedOrHeadersSent ();
if (cookie == null)
throw new ArgumentNullException ("cookie");
if (!canAddOrUpdate (cookie))
throw new ArgumentException ("Cannot be replaced.", "cookie");
Cookies.Add (cookie);
}
#endregion
#region Explicit Interface Implementations
/// <summary>
/// Releases all resources used by the <see cref="HttpListenerResponse"/>.
/// </summary>
void IDisposable.Dispose ()
{
if (_disposed)
return;
close (true); // Same as the Abort method.
}
#endregion
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Net.Http;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
using Microsoft.WindowsAzure.Management.Monitoring.Metrics;
namespace Microsoft.WindowsAzure.Management.Monitoring.Metrics
{
public partial class MetricsClient : ServiceClient<MetricsClient>, IMetricsClient
{
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 IMetricDefinitionOperations _metricDefinitions;
public virtual IMetricDefinitionOperations MetricDefinitions
{
get { return this._metricDefinitions; }
}
private IMetricSettingOperations _metricSettings;
public virtual IMetricSettingOperations MetricSettings
{
get { return this._metricSettings; }
}
private IMetricValueOperations _metricValues;
public virtual IMetricValueOperations MetricValues
{
get { return this._metricValues; }
}
/// <summary>
/// Initializes a new instance of the MetricsClient class.
/// </summary>
private MetricsClient()
: base()
{
this._metricDefinitions = new MetricDefinitionOperations(this);
this._metricSettings = new MetricSettingOperations(this);
this._metricValues = new MetricValueOperations(this);
this._apiVersion = "2013-10-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the MetricsClient 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'>
/// Required. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public MetricsClient(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 MetricsClient 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 MetricsClient(SubscriptionCloudCredentials credentials)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.core.windows.net");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the MetricsClient class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
private MetricsClient(HttpClient httpClient)
: base(httpClient)
{
this._metricDefinitions = new MetricDefinitionOperations(this);
this._metricSettings = new MetricSettingOperations(this);
this._metricValues = new MetricValueOperations(this);
this._apiVersion = "2013-10-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the MetricsClient 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'>
/// Required. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public MetricsClient(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 MetricsClient 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 MetricsClient(SubscriptionCloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.core.windows.net");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another MetricsClient
/// instance
/// </summary>
/// <param name='client'>
/// Instance of MetricsClient to clone to
/// </param>
protected override void Clone(ServiceClient<MetricsClient> client)
{
base.Clone(client);
if (client is MetricsClient)
{
MetricsClient clonedClient = ((MetricsClient)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);
}
}
}
}
| |
// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Permissive License.
// See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
// All other rights reserved.
//---------------------------------------------------------------------------
//
// TextPatternAvalon.cs: Scenarios, Regression Tests for Avalon TextPattern
// support
//
//---------------------------------------------------------------------------
#define CODE_ANALYSIS // Required for FxCop suppression attributes
using System;
using System.Globalization;
using Drawing = System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Windows.Automation;
using System.Windows.Automation.Text;
using System.Windows;
using System.CodeDom;
using System.Collections;
using System.Reflection;
using System.Threading;
using System.Diagnostics.CodeAnalysis; // Required for FxCop suppression attributes
using InternalHelper;
using MS.Win32;
namespace Microsoft.Test.UIAutomation.Tests.Scenarios
{
using InternalHelper;
using InternalHelper.Tests;
using InternalHelper.Tests.Patterns;
using InternalHelper.Enumerations;
using Microsoft.Test.UIAutomation;
using Microsoft.Test.UIAutomation.Core;
using Microsoft.Test.UIAutomation.TestManager;
using Microsoft.Test.UIAutomation.Interfaces;
/// -----------------------------------------------------------------------
/// <summary></summary>
/// -----------------------------------------------------------------------
public class AvalonTextScenarioTests: ScenarioObject, IDisposable
{
#region Member Variables
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
public const string TestSuite = NAMESPACE + "." + THIS; // used by calling test harness
const string THIS = "AvalonTextScenarioTests"; // used by calling test harness
TextPattern _pattern; // Local variable for TextPattern of current automation element
ManualResetEvent _NotifiedEvent; // used by Dispose
#endregion Member Variables
#region constructor
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId="typeOfControl")]
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId="typeOfPattern")]
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId="dirResults")]
public AvalonTextScenarioTests(AutomationElement element, string testSuite, TestPriorities priority, TypeOfControl typeOfControl, TypeOfPattern typeOfPattern, string dirResults, bool testEvents, IApplicationCommands commands)
:
base(element, testSuite, priority, TypeOfControl.UnknownControl, TypeOfPattern.Unknown, null, testEvents, commands)
{
_NotifiedEvent = new System.Threading.ManualResetEvent(false);
}
#endregion constructor
#region Avalon Scenario Tests
/// -------------------------------------------------------------------
/// <summary>
/// Template for Avalon Text Pattern Scenarios
/// This particular scenario takes no arguments from the calling
/// test harness/scenario driver
/// </summary>
/// -------------------------------------------------------------------
[TestCaseAttribute("Avalon Scenario #1 (no arguments)",
TestSummary = "Template for an Avalon TextPattern Scenario that does not take any arguments from calling test harness driver",
Priority = TestPriorities.Pri0,
Status = TestStatus.Works,
Author = "Microsoft Corp.",
TestCaseType = TestCaseType.Scenario,
Client = Client.ATG,
Description = new string[] {
"Pre-condition: Get Scenario Pre-Conditions",
"TBD",
})]
public void AvalonScenario1(TestCaseAttribute testCase)
{
HeaderComment(testCase);
// Pre-condition: Get Scenario Pre-Conditions
TS_ScenarioPreConditions(true, CheckType.IncorrectElementConfiguration);
// TBD
Comment("This test has passed");
m_TestStep++;
}
/// -------------------------------------------------------------------
/// <summary>
/// Template for Avalon Text Pattern Scenarios
/// This particular scenario takes two (string) arguments from the calling
/// test harness/scenario driver
/// </summary>
/// -------------------------------------------------------------------
[TestCaseAttribute("Avalon Scenario #2 (takes arguments)",
TestSummary = "Template for an Avalon TextPattern Scenario that *DOES* take arguments from calling test harness driver",
Priority = TestPriorities.Pri0,
Status = TestStatus.Works,
Author = "Microsoft Corp.",
TestCaseType = TestCaseType.Scenario | TestCaseType.Arguments,
Client = Client.ATG,
Description = new string[] {
"Pre-condition: Get Scenario Pre-Conditions",
"Cause test to suceed or fail based on value of second string argument",
})]
public void AvalonScenario2(TestCaseAttribute testCase, object[] arguments)
{
// Validate arguments passed to test
if (arguments == null)
throw new ArgumentException("arguments is null");
if (arguments[0] == null)
throw new ArgumentException("arguments[0] is null");
if (arguments[1] == null)
throw new ArgumentException("arguments[1] is null");
if (arguments.Length != 2)
throw new ArgumentException("arguments is wrong length");
if (!(arguments[0] is string) || !(arguments[1] is string))
throw new ArgumentException("arguments are of wrong type");
// cast arguments to local variables
string string1 = (string)arguments[0];
string string2 = (string)arguments[1];
HeaderComment(testCase);
// Pre-condition: Get Scenario Pre-Conditions
TS_ScenarioPreConditions(true, CheckType.IncorrectElementConfiguration);
// Cause test to suceed or fail based on value of second string argument
Comment("string1 = " + string1);
Comment("string2 = " + string2);
if (string2 == "IncorrectElementConfiguration")
ThrowMe(CheckType.IncorrectElementConfiguration,
"Some condition required for the test to actually be performed wasn't met. " +
"Exit gracefully without setting a failure condition for this scenario");
else if (string2 == "Verification")
ThrowMe(CheckType.Verification, "Test failed, call ThrowMe with CheckType.Verification to log this test scenario as a failure");
else
Comment("This test has passed");
m_TestStep++; // increment counter as a best practice
}
#endregion Avalon Scenario Tests
#region helpers
// -------------------------------------------------------------------
// Determine if the application we are hitting supports knowledge about the control's text implementation
// -------------------------------------------------------------------
private void TS_ScenarioPreConditions(bool requireTextPattern, CheckType checkType)
{
string className;
string localizedControlType;
// This is hard-coded as a critical failure
if (m_le == null)
{
ThrowMe( CheckType.Verification, "Unable to get AutomationElement for control with focus");
}
// Give info about control
TextLibrary.GetClassName(m_le, out className, out localizedControlType);
Comment("Automation ID = " + m_le.Current.AutomationId.ToString() +
" (" + className + " / " + localizedControlType + ")");
try
{
_pattern = m_le.GetCurrentPattern(TextPattern.Pattern) as TextPattern;
}
catch (Exception exception)
{
if (Library.IsCriticalException(exception))
throw;
Comment("Acquiring TextPattern for automation element with focus raised exception");
Comment(" Message = " + exception.Message);
Comment(" Type = " + exception.GetType().ToString());
ThrowMe(checkType, "Unable to proceed with test, should not have received exception acquiring TextPattern"); // hard-coded... on purpose
}
m_TestStep++;
}
#endregion helpers
#region Dispose
/// -------------------------------------------------------------------
/// <summary>
/// Dispose method(s)
/// </summary>
/// -------------------------------------------------------------------
protected virtual void Dispose(bool disposing) // Required by OACR for member _NotifiedEvent
{
if (disposing)
{
if (_NotifiedEvent != null)
{
_NotifiedEvent.Close();
}
}
}
/// -------------------------------------------------------------------
/// <summary>
/// Dispose method(s)
/// </summary>
/// -------------------------------------------------------------------
public void Dispose() // Required by OACR for member _NotifiedEvent
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion Dispose
}
}
| |
namespace YAF.Lucene.Net.Search
{
/*
* 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 FixedBitSet = YAF.Lucene.Net.Util.FixedBitSet;
using OpenBitSet = YAF.Lucene.Net.Util.OpenBitSet;
/// <summary>
/// Base class for <see cref="DocIdSet"/> to be used with <see cref="IFieldCache"/>. The implementation
/// of its iterator is very stupid and slow if the implementation of the
/// <see cref="MatchDoc(int)"/> method is not optimized, as iterators simply increment
/// the document id until <see cref="MatchDoc(int)"/> returns <c>true</c>. Because of this
/// <see cref="MatchDoc(int)"/> must be as fast as possible and in no case do any
/// I/O.
/// <para/>
/// @lucene.internal
/// </summary>
public abstract class FieldCacheDocIdSet : DocIdSet
{
protected readonly int m_maxDoc;
protected readonly IBits m_acceptDocs;
public FieldCacheDocIdSet(int maxDoc, IBits acceptDocs)
{
this.m_maxDoc = maxDoc;
this.m_acceptDocs = acceptDocs;
}
/// <summary>
/// This method checks, if a doc is a hit
/// </summary>
protected internal abstract bool MatchDoc(int doc);
/// <summary>
/// This DocIdSet is always cacheable (does not go back
/// to the reader for iteration)
/// </summary>
public override sealed bool IsCacheable
{
get
{
return true;
}
}
public override sealed IBits Bits
{
get { return (m_acceptDocs == null) ? (IBits)new BitsAnonymousInnerClassHelper(this) : new BitsAnonymousInnerClassHelper2(this); }
}
private class BitsAnonymousInnerClassHelper : IBits
{
private readonly FieldCacheDocIdSet outerInstance;
public BitsAnonymousInnerClassHelper(FieldCacheDocIdSet outerInstance)
{
this.outerInstance = outerInstance;
}
public virtual bool Get(int docid)
{
return outerInstance.MatchDoc(docid);
}
public virtual int Length
{
get { return outerInstance.m_maxDoc; }
}
}
private class BitsAnonymousInnerClassHelper2 : IBits
{
private readonly FieldCacheDocIdSet outerInstance;
public BitsAnonymousInnerClassHelper2(FieldCacheDocIdSet outerInstance)
{
this.outerInstance = outerInstance;
}
public virtual bool Get(int docid)
{
return outerInstance.MatchDoc(docid) && outerInstance.m_acceptDocs.Get(docid);
}
public virtual int Length
{
get { return outerInstance.m_maxDoc; }
}
}
public override sealed DocIdSetIterator GetIterator()
{
if (m_acceptDocs == null)
{
// Specialization optimization disregard acceptDocs
return new DocIdSetIteratorAnonymousInnerClassHelper(this);
}
else if (m_acceptDocs is FixedBitSet || m_acceptDocs is OpenBitSet)
{
// special case for FixedBitSet / OpenBitSet: use the iterator and filter it
// (used e.g. when Filters are chained by FilteredQuery)
return new FilteredDocIdSetIteratorAnonymousInnerClassHelper(this, ((DocIdSet)m_acceptDocs).GetIterator());
}
else
{
// Stupid consultation of acceptDocs and matchDoc()
return new DocIdSetIteratorAnonymousInnerClassHelper2(this);
}
}
private class DocIdSetIteratorAnonymousInnerClassHelper : DocIdSetIterator
{
private readonly FieldCacheDocIdSet outerInstance;
public DocIdSetIteratorAnonymousInnerClassHelper(FieldCacheDocIdSet outerInstance)
{
this.outerInstance = outerInstance;
doc = -1;
}
private int doc;
public override int DocID
{
get { return doc; }
}
public override int NextDoc()
{
do
{
doc++;
if (doc >= outerInstance.m_maxDoc)
{
return doc = NO_MORE_DOCS;
}
} while (!outerInstance.MatchDoc(doc));
return doc;
}
public override int Advance(int target)
{
for (doc = target; doc < outerInstance.m_maxDoc; doc++)
{
if (outerInstance.MatchDoc(doc))
{
return doc;
}
}
return doc = NO_MORE_DOCS;
}
public override long GetCost()
{
return outerInstance.m_maxDoc;
}
}
private class FilteredDocIdSetIteratorAnonymousInnerClassHelper : FilteredDocIdSetIterator
{
private readonly FieldCacheDocIdSet outerInstance;
public FilteredDocIdSetIteratorAnonymousInnerClassHelper(FieldCacheDocIdSet outerInstance, Lucene.Net.Search.DocIdSetIterator iterator)
: base(iterator)
{
this.outerInstance = outerInstance;
}
protected override bool Match(int doc)
{
return outerInstance.MatchDoc(doc);
}
}
private class DocIdSetIteratorAnonymousInnerClassHelper2 : DocIdSetIterator
{
private readonly FieldCacheDocIdSet outerInstance;
public DocIdSetIteratorAnonymousInnerClassHelper2(FieldCacheDocIdSet outerInstance)
{
this.outerInstance = outerInstance;
doc = -1;
}
private int doc;
public override int DocID
{
get { return doc; }
}
public override int NextDoc()
{
do
{
doc++;
if (doc >= outerInstance.m_maxDoc)
{
return doc = NO_MORE_DOCS;
}
} while (!(outerInstance.MatchDoc(doc) && outerInstance.m_acceptDocs.Get(doc)));
return doc;
}
public override int Advance(int target)
{
for (doc = target; doc < outerInstance.m_maxDoc; doc++)
{
if (outerInstance.MatchDoc(doc) && outerInstance.m_acceptDocs.Get(doc))
{
return doc;
}
}
return doc = NO_MORE_DOCS;
}
public override long GetCost()
{
return outerInstance.m_maxDoc;
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="DataGridPagerStyle.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.UI.WebControls {
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Web;
using System.Web.UI;
/// <devdoc>
/// <para>Specifies the <see cref='System.Web.UI.WebControls.DataGrid'/> pager style for the control. This class cannot be inherited.</para>
/// </devdoc>
public sealed class DataGridPagerStyle : TableItemStyle {
/// <devdoc>
/// <para>Represents the Mode property.</para>
/// </devdoc>
const int PROP_MODE = 0x00080000;
/// <devdoc>
/// <para>Represents the Next Page Text property.</para>
/// </devdoc>
const int PROP_NEXTPAGETEXT = 0x00100000;
/// <devdoc>
/// <para>Represents the Previous Page Text property.</para>
/// </devdoc>
const int PROP_PREVPAGETEXT = 0x00200000;
/// <devdoc>
/// <para>Represents the Page Button Count property.</para>
/// </devdoc>
const int PROP_PAGEBUTTONCOUNT = 0x00400000;
/// <devdoc>
/// <para>Represents the Position property.</para>
/// </devdoc>
const int PROP_POSITION = 0x00800000;
/// <devdoc>
/// <para>Represents the Visible property.</para>
/// </devdoc>
const int PROP_VISIBLE = 0x01000000;
private DataGrid owner;
/// <devdoc>
/// Creates a new instance of DataGridPagerStyle.
/// </devdoc>
internal DataGridPagerStyle(DataGrid owner) {
this.owner = owner;
}
/// <devdoc>
/// </devdoc>
internal bool IsPagerOnBottom {
get {
PagerPosition position = Position;
return(position == PagerPosition.Bottom) ||
(position == PagerPosition.TopAndBottom);
}
}
/// <devdoc>
/// </devdoc>
internal bool IsPagerOnTop {
get {
PagerPosition position = Position;
return(position == PagerPosition.Top) ||
(position == PagerPosition.TopAndBottom);
}
}
/// <devdoc>
/// Gets or sets the type of Paging UI to use.
/// </devdoc>
[
WebCategory("Appearance"),
DefaultValue(PagerMode.NextPrev),
NotifyParentProperty(true),
WebSysDescription(SR.DataGridPagerStyle_Mode)
]
public PagerMode Mode {
get {
if (IsSet(PROP_MODE)) {
return(PagerMode)(ViewState["Mode"]);
}
return PagerMode.NextPrev;
}
set {
if (value < PagerMode.NextPrev || value > PagerMode.NumericPages) {
throw new ArgumentOutOfRangeException("value");
}
ViewState["Mode"] = value;
SetBit(PROP_MODE);
owner.OnPagerChanged();
}
}
/// <devdoc>
/// Gets or sets the text to be used for the Next page
/// button.
/// </devdoc>
[
Localizable(true),
WebCategory("Appearance"),
DefaultValue(">"),
NotifyParentProperty(true),
WebSysDescription(SR.PagerSettings_NextPageText)
]
public string NextPageText {
get {
if (IsSet(PROP_NEXTPAGETEXT)) {
return(string)(ViewState["NextPageText"]);
}
return ">";
}
set {
ViewState["NextPageText"] = value;
SetBit(PROP_NEXTPAGETEXT);
owner.OnPagerChanged();
}
}
/// <devdoc>
/// <para>Gets or sets the number of pages to show in the
/// paging UI when the mode is <see langword='PagerMode.NumericPages'/>
/// .</para>
/// </devdoc>
[
WebCategory("Behavior"),
DefaultValue(10),
NotifyParentProperty(true),
WebSysDescription(SR.DataGridPagerStyle_PageButtonCount)
]
public int PageButtonCount {
get {
if (IsSet(PROP_PAGEBUTTONCOUNT)) {
return(int)(ViewState["PageButtonCount"]);
}
return 10;
}
set {
if (value < 1) {
throw new ArgumentOutOfRangeException("value");
}
ViewState["PageButtonCount"] = value;
SetBit(PROP_PAGEBUTTONCOUNT);
owner.OnPagerChanged();
}
}
/// <devdoc>
/// <para> Gets or sets the vertical
/// position of the paging UI bar with
/// respect to its associated control.</para>
/// </devdoc>
[
WebCategory("Layout"),
DefaultValue(PagerPosition.Bottom),
NotifyParentProperty(true),
WebSysDescription(SR.DataGridPagerStyle_Position)
]
public PagerPosition Position {
get {
if (IsSet(PROP_POSITION)) {
return(PagerPosition)(ViewState["Position"]);
}
return PagerPosition.Bottom;
}
set {
if (value < PagerPosition.Bottom || value > PagerPosition.TopAndBottom) {
throw new ArgumentOutOfRangeException("value");
}
ViewState["Position"] = value;
SetBit(PROP_POSITION);
owner.OnPagerChanged();
}
}
/// <devdoc>
/// <para>Gets or sets the text to be used for the Previous
/// page button.</para>
/// </devdoc>
[
Localizable(true),
WebCategory("Appearance"),
DefaultValue("<"),
NotifyParentProperty(true),
WebSysDescription(SR.PagerSettings_PreviousPageText)
]
public string PrevPageText {
get {
if (IsSet(PROP_PREVPAGETEXT)) {
return(string)(ViewState["PrevPageText"]);
}
return "<";
}
set {
ViewState["PrevPageText"] = value;
SetBit(PROP_PREVPAGETEXT);
owner.OnPagerChanged();
}
}
/// <devdoc>
/// <para> Gets or set whether the paging
/// UI is to be shown.</para>
/// </devdoc>
[
WebCategory("Appearance"),
DefaultValue(true),
NotifyParentProperty(true),
WebSysDescription(SR.DataGridPagerStyle_Visible)
]
public bool Visible {
get {
if (IsSet(PROP_VISIBLE)) {
return(bool)(ViewState["PagerVisible"]);
}
return true;
}
set {
ViewState["PagerVisible"] = value;
SetBit(PROP_VISIBLE);
owner.OnPagerChanged();
}
}
/// <devdoc>
/// <para>Copies the data grid pager style from the specified <see cref='System.Web.UI.WebControls.Style'/>.</para>
/// </devdoc>
public override void CopyFrom(Style s) {
if (s != null && !s.IsEmpty) {
base.CopyFrom(s);
if (s is DataGridPagerStyle) {
DataGridPagerStyle ps = (DataGridPagerStyle)s;
if (ps.IsSet(PROP_MODE))
this.Mode = ps.Mode;
if (ps.IsSet(PROP_NEXTPAGETEXT))
this.NextPageText = ps.NextPageText;
if (ps.IsSet(PROP_PREVPAGETEXT))
this.PrevPageText = ps.PrevPageText;
if (ps.IsSet(PROP_PAGEBUTTONCOUNT))
this.PageButtonCount = ps.PageButtonCount;
if (ps.IsSet(PROP_POSITION))
this.Position = ps.Position;
if (ps.IsSet(PROP_VISIBLE))
this.Visible = ps.Visible;
}
}
}
/// <devdoc>
/// <para>Merges the data grid pager style from the specified <see cref='System.Web.UI.WebControls.Style'/>.</para>
/// </devdoc>
public override void MergeWith(Style s) {
if (s != null && !s.IsEmpty) {
if (IsEmpty) {
// merge into an empty style is equivalent to a copy, which
// is more efficient
CopyFrom(s);
return;
}
base.MergeWith(s);
if (s is DataGridPagerStyle) {
DataGridPagerStyle ps = (DataGridPagerStyle)s;
if (ps.IsSet(PROP_MODE) && !this.IsSet(PROP_MODE))
this.Mode = ps.Mode;
if (ps.IsSet(PROP_NEXTPAGETEXT) && !this.IsSet(PROP_NEXTPAGETEXT))
this.NextPageText = ps.NextPageText;
if (ps.IsSet(PROP_PREVPAGETEXT) && !this.IsSet(PROP_PREVPAGETEXT))
this.PrevPageText = ps.PrevPageText;
if (ps.IsSet(PROP_PAGEBUTTONCOUNT) && !this.IsSet(PROP_PAGEBUTTONCOUNT))
this.PageButtonCount = ps.PageButtonCount;
if (ps.IsSet(PROP_POSITION) && !this.IsSet(PROP_POSITION))
this.Position = ps.Position;
if (ps.IsSet(PROP_VISIBLE) && !this.IsSet(PROP_VISIBLE))
this.Visible = ps.Visible;
}
}
}
/// <devdoc>
/// <para>Restores the data grip pager style to the default values.</para>
/// </devdoc>
public override void Reset() {
if (IsSet(PROP_MODE))
ViewState.Remove("Mode");
if (IsSet(PROP_NEXTPAGETEXT))
ViewState.Remove("NextPageText");
if (IsSet(PROP_PREVPAGETEXT))
ViewState.Remove("PrevPageText");
if (IsSet(PROP_PAGEBUTTONCOUNT))
ViewState.Remove("PageButtonCount");
if (IsSet(PROP_POSITION))
ViewState.Remove("Position");
if (IsSet(PROP_VISIBLE))
ViewState.Remove("PagerVisible");
base.Reset();
}
}
}
| |
using System;
using System.Runtime.CompilerServices;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using System.Windows.Input;
using Sannel.House.Client.Models;
namespace Sannel.House.Client.Interfaces
{
[CompilerGenerated]
public class StubIBaseViewModel : IBaseViewModel
{
private readonly Dictionary<string, object> _stubs = new Dictionary<string, object>();
bool global::Sannel.House.Client.Interfaces.IBaseViewModel.IsBusy
{
get
{
return ((IsBusy_Get_Delegate)_stubs[nameof(IsBusy_Get_Delegate)]).Invoke();
}
}
public delegate bool IsBusy_Get_Delegate();
public StubIBaseViewModel IsBusy_Get(IsBusy_Get_Delegate del)
{
_stubs[nameof(IsBusy_Get_Delegate)] = del;
return this;
}
void global::Sannel.House.Client.Interfaces.IBaseViewModel.NavigatedTo(object arg)
{
((NavigatedTo_Object_Delegate)_stubs[nameof(NavigatedTo_Object_Delegate)]).Invoke(arg);
}
public delegate void NavigatedTo_Object_Delegate(object arg);
public StubIBaseViewModel NavigatedTo(NavigatedTo_Object_Delegate del)
{
_stubs[nameof(NavigatedTo_Object_Delegate)] = del;
return this;
}
void global::Sannel.House.Client.Interfaces.IBaseViewModel.NavigatedFrom()
{
((NavigatedFrom_Delegate)_stubs[nameof(NavigatedFrom_Delegate)]).Invoke();
}
public delegate void NavigatedFrom_Delegate();
public StubIBaseViewModel NavigatedFrom(NavigatedFrom_Delegate del)
{
_stubs[nameof(NavigatedFrom_Delegate)] = del;
return this;
}
public event global::System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void On_PropertyChanged(object sender)
{
global::System.ComponentModel.PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) { handler(sender, null); }
}
public void PropertyChanged_Raise(object sender)
{
On_PropertyChanged(sender);
}
}
}
namespace Sannel.House.Client.Interfaces
{
[CompilerGenerated]
public class StubIErrorViewModel : IErrorViewModel
{
private readonly Dictionary<string, object> _stubs = new Dictionary<string, object>();
global::System.Collections.ObjectModel.ObservableCollection<string> global::Sannel.House.Client.Interfaces.IErrorViewModel.ErrorKeys
{
get
{
return ((ErrorKeys_Get_Delegate)_stubs[nameof(ErrorKeys_Get_Delegate)]).Invoke();
}
}
public delegate global::System.Collections.ObjectModel.ObservableCollection<string> ErrorKeys_Get_Delegate();
public StubIErrorViewModel ErrorKeys_Get(ErrorKeys_Get_Delegate del)
{
_stubs[nameof(ErrorKeys_Get_Delegate)] = del;
return this;
}
bool global::Sannel.House.Client.Interfaces.IErrorViewModel.HasErrors
{
get
{
return ((HasErrors_Get_Delegate)_stubs[nameof(HasErrors_Get_Delegate)]).Invoke();
}
set
{
((HasErrors_Set_Delegate)_stubs[nameof(HasErrors_Set_Delegate)]).Invoke(value);
}
}
public delegate bool HasErrors_Get_Delegate();
public StubIErrorViewModel HasErrors_Get(HasErrors_Get_Delegate del)
{
_stubs[nameof(HasErrors_Get_Delegate)] = del;
return this;
}
public delegate void HasErrors_Set_Delegate(bool value);
public StubIErrorViewModel HasErrors_Set(HasErrors_Set_Delegate del)
{
_stubs[nameof(HasErrors_Set_Delegate)] = del;
return this;
}
bool global::Sannel.House.Client.Interfaces.IBaseViewModel.IsBusy
{
get
{
return ((IBaseViewModel_IsBusy_Get_Delegate)_stubs[nameof(IBaseViewModel_IsBusy_Get_Delegate)]).Invoke();
}
}
public delegate bool IBaseViewModel_IsBusy_Get_Delegate();
public StubIErrorViewModel IsBusy_Get(IBaseViewModel_IsBusy_Get_Delegate del)
{
_stubs[nameof(IBaseViewModel_IsBusy_Get_Delegate)] = del;
return this;
}
void global::Sannel.House.Client.Interfaces.IBaseViewModel.NavigatedTo(object arg)
{
((IBaseViewModel_NavigatedTo_Object_Delegate)_stubs[nameof(IBaseViewModel_NavigatedTo_Object_Delegate)]).Invoke(arg);
}
public delegate void IBaseViewModel_NavigatedTo_Object_Delegate(object arg);
public StubIErrorViewModel NavigatedTo(IBaseViewModel_NavigatedTo_Object_Delegate del)
{
_stubs[nameof(IBaseViewModel_NavigatedTo_Object_Delegate)] = del;
return this;
}
void global::Sannel.House.Client.Interfaces.IBaseViewModel.NavigatedFrom()
{
((IBaseViewModel_NavigatedFrom_Delegate)_stubs[nameof(IBaseViewModel_NavigatedFrom_Delegate)]).Invoke();
}
public delegate void IBaseViewModel_NavigatedFrom_Delegate();
public StubIErrorViewModel NavigatedFrom(IBaseViewModel_NavigatedFrom_Delegate del)
{
_stubs[nameof(IBaseViewModel_NavigatedFrom_Delegate)] = del;
return this;
}
public event global::System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void On_PropertyChanged(object sender)
{
global::System.ComponentModel.PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) { handler(sender, null); }
}
public void PropertyChanged_Raise(object sender)
{
On_PropertyChanged(sender);
}
}
}
namespace Sannel.House.Client.Interfaces
{
[CompilerGenerated]
public class StubIHomeViewModel : IHomeViewModel
{
private readonly Dictionary<string, object> _stubs = new Dictionary<string, object>();
bool global::Sannel.House.Client.Interfaces.IBaseViewModel.IsBusy
{
get
{
return ((IBaseViewModel_IsBusy_Get_Delegate)_stubs[nameof(IBaseViewModel_IsBusy_Get_Delegate)]).Invoke();
}
}
public delegate bool IBaseViewModel_IsBusy_Get_Delegate();
public StubIHomeViewModel IsBusy_Get(IBaseViewModel_IsBusy_Get_Delegate del)
{
_stubs[nameof(IBaseViewModel_IsBusy_Get_Delegate)] = del;
return this;
}
void global::Sannel.House.Client.Interfaces.IBaseViewModel.NavigatedTo(object arg)
{
((IBaseViewModel_NavigatedTo_Object_Delegate)_stubs[nameof(IBaseViewModel_NavigatedTo_Object_Delegate)]).Invoke(arg);
}
public delegate void IBaseViewModel_NavigatedTo_Object_Delegate(object arg);
public StubIHomeViewModel NavigatedTo(IBaseViewModel_NavigatedTo_Object_Delegate del)
{
_stubs[nameof(IBaseViewModel_NavigatedTo_Object_Delegate)] = del;
return this;
}
void global::Sannel.House.Client.Interfaces.IBaseViewModel.NavigatedFrom()
{
((IBaseViewModel_NavigatedFrom_Delegate)_stubs[nameof(IBaseViewModel_NavigatedFrom_Delegate)]).Invoke();
}
public delegate void IBaseViewModel_NavigatedFrom_Delegate();
public StubIHomeViewModel NavigatedFrom(IBaseViewModel_NavigatedFrom_Delegate del)
{
_stubs[nameof(IBaseViewModel_NavigatedFrom_Delegate)] = del;
return this;
}
public event global::System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void On_PropertyChanged(object sender)
{
global::System.ComponentModel.PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) { handler(sender, null); }
}
public void PropertyChanged_Raise(object sender)
{
On_PropertyChanged(sender);
}
}
}
namespace Sannel.House.Client.Interfaces
{
[CompilerGenerated]
public class StubINavigationService : INavigationService
{
private readonly Dictionary<string, object> _stubs = new Dictionary<string, object>();
void global::Sannel.House.Client.Interfaces.INavigationService.Navigate<T>(object parameter)
{
((Navigate_Object_Delegate<T>)_stubs[nameof(Navigate_Object_Delegate<T>)]).Invoke(parameter);
}
public delegate void Navigate_Object_Delegate<T>(object parameter) where T : IBaseViewModel;
public StubINavigationService Navigate<T>(Navigate_Object_Delegate<T> del) where T : IBaseViewModel
{
_stubs[nameof(Navigate_Object_Delegate<T>)] = del;
return this;
}
void global::Sannel.House.Client.Interfaces.INavigationService.Navigate<T>()
{
((Navigate_Delegate<T>)_stubs[nameof(Navigate_Delegate<T>)]).Invoke();
}
public delegate void Navigate_Delegate<T>() where T : IBaseViewModel;
public StubINavigationService Navigate<T>(Navigate_Delegate<T> del) where T : IBaseViewModel
{
_stubs[nameof(Navigate_Delegate<T>)] = del;
return this;
}
void global::Sannel.House.Client.Interfaces.INavigationService.Navigate(global::System.Type t, object parameter)
{
((Navigate_Type_Object_Delegate)_stubs[nameof(Navigate_Type_Object_Delegate)]).Invoke(t, parameter);
}
public delegate void Navigate_Type_Object_Delegate(global::System.Type t, object parameter);
public StubINavigationService Navigate(Navigate_Type_Object_Delegate del)
{
_stubs[nameof(Navigate_Type_Object_Delegate)] = del;
return this;
}
void global::Sannel.House.Client.Interfaces.INavigationService.Navigate(global::System.Type t)
{
((Navigate_Type_Delegate)_stubs[nameof(Navigate_Type_Delegate)]).Invoke(t);
}
public delegate void Navigate_Type_Delegate(global::System.Type t);
public StubINavigationService Navigate(Navigate_Type_Delegate del)
{
_stubs[nameof(Navigate_Type_Delegate)] = del;
return this;
}
void global::Sannel.House.Client.Interfaces.INavigationService.ClearHistory()
{
((ClearHistory_Delegate)_stubs[nameof(ClearHistory_Delegate)]).Invoke();
}
public delegate void ClearHistory_Delegate();
public StubINavigationService ClearHistory(ClearHistory_Delegate del)
{
_stubs[nameof(ClearHistory_Delegate)] = del;
return this;
}
}
}
namespace Sannel.House.Client.Interfaces
{
[CompilerGenerated]
public class StubILoginViewModel : ILoginViewModel
{
private readonly Dictionary<string, object> _stubs = new Dictionary<string, object>();
string global::Sannel.House.Client.Interfaces.ILoginViewModel.Username
{
get
{
return ((Username_Get_Delegate)_stubs[nameof(Username_Get_Delegate)]).Invoke();
}
set
{
((Username_Set_Delegate)_stubs[nameof(Username_Set_Delegate)]).Invoke(value);
}
}
public delegate string Username_Get_Delegate();
public StubILoginViewModel Username_Get(Username_Get_Delegate del)
{
_stubs[nameof(Username_Get_Delegate)] = del;
return this;
}
public delegate void Username_Set_Delegate(string value);
public StubILoginViewModel Username_Set(Username_Set_Delegate del)
{
_stubs[nameof(Username_Set_Delegate)] = del;
return this;
}
string global::Sannel.House.Client.Interfaces.ILoginViewModel.Password
{
get
{
return ((Password_Get_Delegate)_stubs[nameof(Password_Get_Delegate)]).Invoke();
}
set
{
((Password_Set_Delegate)_stubs[nameof(Password_Set_Delegate)]).Invoke(value);
}
}
public delegate string Password_Get_Delegate();
public StubILoginViewModel Password_Get(Password_Get_Delegate del)
{
_stubs[nameof(Password_Get_Delegate)] = del;
return this;
}
public delegate void Password_Set_Delegate(string value);
public StubILoginViewModel Password_Set(Password_Set_Delegate del)
{
_stubs[nameof(Password_Set_Delegate)] = del;
return this;
}
bool global::Sannel.House.Client.Interfaces.ILoginViewModel.StayLoggedIn
{
get
{
return ((StayLoggedIn_Get_Delegate)_stubs[nameof(StayLoggedIn_Get_Delegate)]).Invoke();
}
set
{
((StayLoggedIn_Set_Delegate)_stubs[nameof(StayLoggedIn_Set_Delegate)]).Invoke(value);
}
}
public delegate bool StayLoggedIn_Get_Delegate();
public StubILoginViewModel StayLoggedIn_Get(StayLoggedIn_Get_Delegate del)
{
_stubs[nameof(StayLoggedIn_Get_Delegate)] = del;
return this;
}
public delegate void StayLoggedIn_Set_Delegate(bool value);
public StubILoginViewModel StayLoggedIn_Set(StayLoggedIn_Set_Delegate del)
{
_stubs[nameof(StayLoggedIn_Set_Delegate)] = del;
return this;
}
global::System.Windows.Input.ICommand global::Sannel.House.Client.Interfaces.ILoginViewModel.LoginCommand
{
get
{
return ((LoginCommand_Get_Delegate)_stubs[nameof(LoginCommand_Get_Delegate)]).Invoke();
}
}
public delegate global::System.Windows.Input.ICommand LoginCommand_Get_Delegate();
public StubILoginViewModel LoginCommand_Get(LoginCommand_Get_Delegate del)
{
_stubs[nameof(LoginCommand_Get_Delegate)] = del;
return this;
}
global::System.Collections.ObjectModel.ObservableCollection<string> global::Sannel.House.Client.Interfaces.IErrorViewModel.ErrorKeys
{
get
{
return ((IErrorViewModel_ErrorKeys_Get_Delegate)_stubs[nameof(IErrorViewModel_ErrorKeys_Get_Delegate)]).Invoke();
}
}
public delegate global::System.Collections.ObjectModel.ObservableCollection<string> IErrorViewModel_ErrorKeys_Get_Delegate();
public StubILoginViewModel ErrorKeys_Get(IErrorViewModel_ErrorKeys_Get_Delegate del)
{
_stubs[nameof(IErrorViewModel_ErrorKeys_Get_Delegate)] = del;
return this;
}
bool global::Sannel.House.Client.Interfaces.IErrorViewModel.HasErrors
{
get
{
return ((IErrorViewModel_HasErrors_Get_Delegate)_stubs[nameof(IErrorViewModel_HasErrors_Get_Delegate)]).Invoke();
}
set
{
((IErrorViewModel_HasErrors_Set_Delegate)_stubs[nameof(IErrorViewModel_HasErrors_Set_Delegate)]).Invoke(value);
}
}
public delegate bool IErrorViewModel_HasErrors_Get_Delegate();
public StubILoginViewModel HasErrors_Get(IErrorViewModel_HasErrors_Get_Delegate del)
{
_stubs[nameof(IErrorViewModel_HasErrors_Get_Delegate)] = del;
return this;
}
public delegate void IErrorViewModel_HasErrors_Set_Delegate(bool value);
public StubILoginViewModel HasErrors_Set(IErrorViewModel_HasErrors_Set_Delegate del)
{
_stubs[nameof(IErrorViewModel_HasErrors_Set_Delegate)] = del;
return this;
}
bool global::Sannel.House.Client.Interfaces.IBaseViewModel.IsBusy
{
get
{
return ((IBaseViewModel_IsBusy_Get_Delegate)_stubs[nameof(IBaseViewModel_IsBusy_Get_Delegate)]).Invoke();
}
}
public delegate bool IBaseViewModel_IsBusy_Get_Delegate();
public StubILoginViewModel IsBusy_Get(IBaseViewModel_IsBusy_Get_Delegate del)
{
_stubs[nameof(IBaseViewModel_IsBusy_Get_Delegate)] = del;
return this;
}
void global::Sannel.House.Client.Interfaces.IBaseViewModel.NavigatedTo(object arg)
{
((IBaseViewModel_NavigatedTo_Object_Delegate)_stubs[nameof(IBaseViewModel_NavigatedTo_Object_Delegate)]).Invoke(arg);
}
public delegate void IBaseViewModel_NavigatedTo_Object_Delegate(object arg);
public StubILoginViewModel NavigatedTo(IBaseViewModel_NavigatedTo_Object_Delegate del)
{
_stubs[nameof(IBaseViewModel_NavigatedTo_Object_Delegate)] = del;
return this;
}
void global::Sannel.House.Client.Interfaces.IBaseViewModel.NavigatedFrom()
{
((IBaseViewModel_NavigatedFrom_Delegate)_stubs[nameof(IBaseViewModel_NavigatedFrom_Delegate)]).Invoke();
}
public delegate void IBaseViewModel_NavigatedFrom_Delegate();
public StubILoginViewModel NavigatedFrom(IBaseViewModel_NavigatedFrom_Delegate del)
{
_stubs[nameof(IBaseViewModel_NavigatedFrom_Delegate)] = del;
return this;
}
public event global::System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void On_PropertyChanged(object sender)
{
global::System.ComponentModel.PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) { handler(sender, null); }
}
public void PropertyChanged_Raise(object sender)
{
On_PropertyChanged(sender);
}
}
}
namespace Sannel.House.Client.Interfaces
{
[CompilerGenerated]
public class StubIServerContext : IServerContext
{
private readonly Dictionary<string, object> _stubs = new Dictionary<string, object>();
global::System.Threading.Tasks.Task<global::System.Tuple<bool, string>> global::Sannel.House.Client.Interfaces.IServerContext.LoginAsync(string username, string password)
{
return ((LoginAsync_String_String_Delegate)_stubs[nameof(LoginAsync_String_String_Delegate)]).Invoke(username, password);
}
public delegate global::System.Threading.Tasks.Task<global::System.Tuple<bool, string>> LoginAsync_String_String_Delegate(string username, string password);
public StubIServerContext LoginAsync(LoginAsync_String_String_Delegate del)
{
_stubs[nameof(LoginAsync_String_String_Delegate)] = del;
return this;
}
global::System.Threading.Tasks.Task global::Sannel.House.Client.Interfaces.IServerContext.LogOffAsync()
{
return ((LogOffAsync_Delegate)_stubs[nameof(LogOffAsync_Delegate)]).Invoke();
}
public delegate global::System.Threading.Tasks.Task LogOffAsync_Delegate();
public StubIServerContext LogOffAsync(LogOffAsync_Delegate del)
{
_stubs[nameof(LogOffAsync_Delegate)] = del;
return this;
}
global::System.Threading.Tasks.Task<global::System.Collections.Generic.IList<string>> global::Sannel.House.Client.Interfaces.IServerContext.GetRolesAsync()
{
return ((GetRolesAsync_Delegate)_stubs[nameof(GetRolesAsync_Delegate)]).Invoke();
}
public delegate global::System.Threading.Tasks.Task<global::System.Collections.Generic.IList<string>> GetRolesAsync_Delegate();
public StubIServerContext GetRolesAsync(GetRolesAsync_Delegate del)
{
_stubs[nameof(GetRolesAsync_Delegate)] = del;
return this;
}
global::System.Threading.Tasks.Task<global::Sannel.House.Client.Models.ClientProfile> global::Sannel.House.Client.Interfaces.IServerContext.GetProfileAsync()
{
return ((GetProfileAsync_Delegate)_stubs[nameof(GetProfileAsync_Delegate)]).Invoke();
}
public delegate global::System.Threading.Tasks.Task<global::Sannel.House.Client.Models.ClientProfile> GetProfileAsync_Delegate();
public StubIServerContext GetProfileAsync(GetProfileAsync_Delegate del)
{
_stubs[nameof(GetProfileAsync_Delegate)] = del;
return this;
}
global::System.Threading.Tasks.Task<global::System.Collections.Generic.IList<global::Sannel.House.Client.Models.TemperatureSetting>> global::Sannel.House.Client.Interfaces.IServerContext.GetTemperatureSettingsAsync()
{
return ((GetTemperatureSettingsAsync_Delegate)_stubs[nameof(GetTemperatureSettingsAsync_Delegate)]).Invoke();
}
public delegate global::System.Threading.Tasks.Task<global::System.Collections.Generic.IList<global::Sannel.House.Client.Models.TemperatureSetting>> GetTemperatureSettingsAsync_Delegate();
public StubIServerContext GetTemperatureSettingsAsync(GetTemperatureSettingsAsync_Delegate del)
{
_stubs[nameof(GetTemperatureSettingsAsync_Delegate)] = del;
return this;
}
global::System.Threading.Tasks.Task global::Sannel.House.Client.Interfaces.IServerContext.PutTemperatureSettingAsync(global::Sannel.House.Client.Models.TemperatureSetting setting)
{
return ((PutTemperatureSettingAsync_TemperatureSetting_Delegate)_stubs[nameof(PutTemperatureSettingAsync_TemperatureSetting_Delegate)]).Invoke(setting);
}
public delegate global::System.Threading.Tasks.Task PutTemperatureSettingAsync_TemperatureSetting_Delegate(global::Sannel.House.Client.Models.TemperatureSetting setting);
public StubIServerContext PutTemperatureSettingAsync(PutTemperatureSettingAsync_TemperatureSetting_Delegate del)
{
_stubs[nameof(PutTemperatureSettingAsync_TemperatureSetting_Delegate)] = del;
return this;
}
global::System.Threading.Tasks.Task<long> global::Sannel.House.Client.Interfaces.IServerContext.PostTemperatureSettingAsync(global::Sannel.House.Client.Models.TemperatureSetting setting)
{
return ((PostTemperatureSettingAsync_TemperatureSetting_Delegate)_stubs[nameof(PostTemperatureSettingAsync_TemperatureSetting_Delegate)]).Invoke(setting);
}
public delegate global::System.Threading.Tasks.Task<long> PostTemperatureSettingAsync_TemperatureSetting_Delegate(global::Sannel.House.Client.Models.TemperatureSetting setting);
public StubIServerContext PostTemperatureSettingAsync(PostTemperatureSettingAsync_TemperatureSetting_Delegate del)
{
_stubs[nameof(PostTemperatureSettingAsync_TemperatureSetting_Delegate)] = del;
return this;
}
}
}
namespace Sannel.House.Client.Interfaces
{
[CompilerGenerated]
public class StubISettings : ISettings
{
private readonly Dictionary<string, object> _stubs = new Dictionary<string, object>();
global::System.Uri global::Sannel.House.Client.Interfaces.ISettings.ServerUrl
{
get
{
return ((ServerUrl_Get_Delegate)_stubs[nameof(ServerUrl_Get_Delegate)]).Invoke();
}
set
{
((ServerUrl_Set_Delegate)_stubs[nameof(ServerUrl_Set_Delegate)]).Invoke(value);
}
}
public delegate global::System.Uri ServerUrl_Get_Delegate();
public StubISettings ServerUrl_Get(ServerUrl_Get_Delegate del)
{
_stubs[nameof(ServerUrl_Get_Delegate)] = del;
return this;
}
public delegate void ServerUrl_Set_Delegate(global::System.Uri value);
public StubISettings ServerUrl_Set(ServerUrl_Set_Delegate del)
{
_stubs[nameof(ServerUrl_Set_Delegate)] = del;
return this;
}
string global::Sannel.House.Client.Interfaces.ISettings.AuthzCookieValue
{
get
{
return ((AuthzCookieValue_Get_Delegate)_stubs[nameof(AuthzCookieValue_Get_Delegate)]).Invoke();
}
set
{
((AuthzCookieValue_Set_Delegate)_stubs[nameof(AuthzCookieValue_Set_Delegate)]).Invoke(value);
}
}
public delegate string AuthzCookieValue_Get_Delegate();
public StubISettings AuthzCookieValue_Get(AuthzCookieValue_Get_Delegate del)
{
_stubs[nameof(AuthzCookieValue_Get_Delegate)] = del;
return this;
}
public delegate void AuthzCookieValue_Set_Delegate(string value);
public StubISettings AuthzCookieValue_Set(AuthzCookieValue_Set_Delegate del)
{
_stubs[nameof(AuthzCookieValue_Set_Delegate)] = del;
return this;
}
}
}
namespace Sannel.House.Client.Interfaces
{
[CompilerGenerated]
public class StubISettingsViewModel : ISettingsViewModel
{
private readonly Dictionary<string, object> _stubs = new Dictionary<string, object>();
string global::Sannel.House.Client.Interfaces.ISettingsViewModel.ServerUrl
{
get
{
return ((ServerUrl_Get_Delegate)_stubs[nameof(ServerUrl_Get_Delegate)]).Invoke();
}
set
{
((ServerUrl_Set_Delegate)_stubs[nameof(ServerUrl_Set_Delegate)]).Invoke(value);
}
}
public delegate string ServerUrl_Get_Delegate();
public StubISettingsViewModel ServerUrl_Get(ServerUrl_Get_Delegate del)
{
_stubs[nameof(ServerUrl_Get_Delegate)] = del;
return this;
}
public delegate void ServerUrl_Set_Delegate(string value);
public StubISettingsViewModel ServerUrl_Set(ServerUrl_Set_Delegate del)
{
_stubs[nameof(ServerUrl_Set_Delegate)] = del;
return this;
}
global::System.Windows.Input.ICommand global::Sannel.House.Client.Interfaces.ISettingsViewModel.ContinueCommand
{
get
{
return ((ContinueCommand_Get_Delegate)_stubs[nameof(ContinueCommand_Get_Delegate)]).Invoke();
}
}
public delegate global::System.Windows.Input.ICommand ContinueCommand_Get_Delegate();
public StubISettingsViewModel ContinueCommand_Get(ContinueCommand_Get_Delegate del)
{
_stubs[nameof(ContinueCommand_Get_Delegate)] = del;
return this;
}
global::System.Collections.ObjectModel.ObservableCollection<string> global::Sannel.House.Client.Interfaces.IErrorViewModel.ErrorKeys
{
get
{
return ((IErrorViewModel_ErrorKeys_Get_Delegate)_stubs[nameof(IErrorViewModel_ErrorKeys_Get_Delegate)]).Invoke();
}
}
public delegate global::System.Collections.ObjectModel.ObservableCollection<string> IErrorViewModel_ErrorKeys_Get_Delegate();
public StubISettingsViewModel ErrorKeys_Get(IErrorViewModel_ErrorKeys_Get_Delegate del)
{
_stubs[nameof(IErrorViewModel_ErrorKeys_Get_Delegate)] = del;
return this;
}
bool global::Sannel.House.Client.Interfaces.IErrorViewModel.HasErrors
{
get
{
return ((IErrorViewModel_HasErrors_Get_Delegate)_stubs[nameof(IErrorViewModel_HasErrors_Get_Delegate)]).Invoke();
}
set
{
((IErrorViewModel_HasErrors_Set_Delegate)_stubs[nameof(IErrorViewModel_HasErrors_Set_Delegate)]).Invoke(value);
}
}
public delegate bool IErrorViewModel_HasErrors_Get_Delegate();
public StubISettingsViewModel HasErrors_Get(IErrorViewModel_HasErrors_Get_Delegate del)
{
_stubs[nameof(IErrorViewModel_HasErrors_Get_Delegate)] = del;
return this;
}
public delegate void IErrorViewModel_HasErrors_Set_Delegate(bool value);
public StubISettingsViewModel HasErrors_Set(IErrorViewModel_HasErrors_Set_Delegate del)
{
_stubs[nameof(IErrorViewModel_HasErrors_Set_Delegate)] = del;
return this;
}
bool global::Sannel.House.Client.Interfaces.IBaseViewModel.IsBusy
{
get
{
return ((IBaseViewModel_IsBusy_Get_Delegate)_stubs[nameof(IBaseViewModel_IsBusy_Get_Delegate)]).Invoke();
}
}
public delegate bool IBaseViewModel_IsBusy_Get_Delegate();
public StubISettingsViewModel IsBusy_Get(IBaseViewModel_IsBusy_Get_Delegate del)
{
_stubs[nameof(IBaseViewModel_IsBusy_Get_Delegate)] = del;
return this;
}
void global::Sannel.House.Client.Interfaces.IBaseViewModel.NavigatedTo(object arg)
{
((IBaseViewModel_NavigatedTo_Object_Delegate)_stubs[nameof(IBaseViewModel_NavigatedTo_Object_Delegate)]).Invoke(arg);
}
public delegate void IBaseViewModel_NavigatedTo_Object_Delegate(object arg);
public StubISettingsViewModel NavigatedTo(IBaseViewModel_NavigatedTo_Object_Delegate del)
{
_stubs[nameof(IBaseViewModel_NavigatedTo_Object_Delegate)] = del;
return this;
}
void global::Sannel.House.Client.Interfaces.IBaseViewModel.NavigatedFrom()
{
((IBaseViewModel_NavigatedFrom_Delegate)_stubs[nameof(IBaseViewModel_NavigatedFrom_Delegate)]).Invoke();
}
public delegate void IBaseViewModel_NavigatedFrom_Delegate();
public StubISettingsViewModel NavigatedFrom(IBaseViewModel_NavigatedFrom_Delegate del)
{
_stubs[nameof(IBaseViewModel_NavigatedFrom_Delegate)] = del;
return this;
}
public event global::System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void On_PropertyChanged(object sender)
{
global::System.ComponentModel.PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) { handler(sender, null); }
}
public void PropertyChanged_Raise(object sender)
{
On_PropertyChanged(sender);
}
}
}
namespace Sannel.House.Client.Interfaces
{
[CompilerGenerated]
public class StubIShellViewModel : IShellViewModel
{
private readonly Dictionary<string, object> _stubs = new Dictionary<string, object>();
bool global::Sannel.House.Client.Interfaces.IShellViewModel.IsBusy
{
get
{
return ((IsBusy_Get_Delegate)_stubs[nameof(IsBusy_Get_Delegate)]).Invoke();
}
set
{
((IsBusy_Set_Delegate)_stubs[nameof(IsBusy_Set_Delegate)]).Invoke(value);
}
get
{
return ((IBaseViewModel_IsBusy_Get_Delegate)_stubs[nameof(IBaseViewModel_IsBusy_Get_Delegate)]).Invoke();
}
}
public delegate bool IsBusy_Get_Delegate();
public StubIShellViewModel IsBusy_Get(IsBusy_Get_Delegate del)
{
_stubs[nameof(IsBusy_Get_Delegate)] = del;
return this;
}
public delegate void IsBusy_Set_Delegate(bool value);
public StubIShellViewModel IsBusy_Set(IsBusy_Set_Delegate del)
{
_stubs[nameof(IsBusy_Set_Delegate)] = del;
return this;
}
bool global::Sannel.House.Client.Interfaces.IShellViewModel.IsPaneOpen
{
get
{
return ((IsPaneOpen_Get_Delegate)_stubs[nameof(IsPaneOpen_Get_Delegate)]).Invoke();
}
set
{
((IsPaneOpen_Set_Delegate)_stubs[nameof(IsPaneOpen_Set_Delegate)]).Invoke(value);
}
}
public delegate bool IsPaneOpen_Get_Delegate();
public StubIShellViewModel IsPaneOpen_Get(IsPaneOpen_Get_Delegate del)
{
_stubs[nameof(IsPaneOpen_Get_Delegate)] = del;
return this;
}
public delegate void IsPaneOpen_Set_Delegate(bool value);
public StubIShellViewModel IsPaneOpen_Set(IsPaneOpen_Set_Delegate del)
{
_stubs[nameof(IsPaneOpen_Set_Delegate)] = del;
return this;
}
global::Sannel.House.Client.Interfaces.IUser global::Sannel.House.Client.Interfaces.IShellViewModel.User
{
get
{
return ((User_Get_Delegate)_stubs[nameof(User_Get_Delegate)]).Invoke();
}
}
public delegate global::Sannel.House.Client.Interfaces.IUser User_Get_Delegate();
public StubIShellViewModel User_Get(User_Get_Delegate del)
{
_stubs[nameof(User_Get_Delegate)] = del;
return this;
}
global::System.Collections.ObjectModel.ObservableCollection<global::Sannel.House.Client.Models.MenuItem> global::Sannel.House.Client.Interfaces.IShellViewModel.MenuTop
{
get
{
return ((MenuTop_Get_Delegate)_stubs[nameof(MenuTop_Get_Delegate)]).Invoke();
}
}
public delegate global::System.Collections.ObjectModel.ObservableCollection<global::Sannel.House.Client.Models.MenuItem> MenuTop_Get_Delegate();
public StubIShellViewModel MenuTop_Get(MenuTop_Get_Delegate del)
{
_stubs[nameof(MenuTop_Get_Delegate)] = del;
return this;
}
global::System.Collections.ObjectModel.ObservableCollection<global::Sannel.House.Client.Models.MenuItem> global::Sannel.House.Client.Interfaces.IShellViewModel.MenuBottom
{
get
{
return ((MenuBottom_Get_Delegate)_stubs[nameof(MenuBottom_Get_Delegate)]).Invoke();
}
}
public delegate global::System.Collections.ObjectModel.ObservableCollection<global::Sannel.House.Client.Models.MenuItem> MenuBottom_Get_Delegate();
public StubIShellViewModel MenuBottom_Get(MenuBottom_Get_Delegate del)
{
_stubs[nameof(MenuBottom_Get_Delegate)] = del;
return this;
}
void global::Sannel.House.Client.Interfaces.IShellViewModel.MenuItemClick(global::Sannel.House.Client.Models.MenuItem item)
{
((MenuItemClick_MenuItem_Delegate)_stubs[nameof(MenuItemClick_MenuItem_Delegate)]).Invoke(item);
}
public delegate void MenuItemClick_MenuItem_Delegate(global::Sannel.House.Client.Models.MenuItem item);
public StubIShellViewModel MenuItemClick(MenuItemClick_MenuItem_Delegate del)
{
_stubs[nameof(MenuItemClick_MenuItem_Delegate)] = del;
return this;
}
public delegate bool IBaseViewModel_IsBusy_Get_Delegate();
public StubIShellViewModel IsBusy_Get(IBaseViewModel_IsBusy_Get_Delegate del)
{
_stubs[nameof(IBaseViewModel_IsBusy_Get_Delegate)] = del;
return this;
}
void global::Sannel.House.Client.Interfaces.IBaseViewModel.NavigatedTo(object arg)
{
((IBaseViewModel_NavigatedTo_Object_Delegate)_stubs[nameof(IBaseViewModel_NavigatedTo_Object_Delegate)]).Invoke(arg);
}
public delegate void IBaseViewModel_NavigatedTo_Object_Delegate(object arg);
public StubIShellViewModel NavigatedTo(IBaseViewModel_NavigatedTo_Object_Delegate del)
{
_stubs[nameof(IBaseViewModel_NavigatedTo_Object_Delegate)] = del;
return this;
}
void global::Sannel.House.Client.Interfaces.IBaseViewModel.NavigatedFrom()
{
((IBaseViewModel_NavigatedFrom_Delegate)_stubs[nameof(IBaseViewModel_NavigatedFrom_Delegate)]).Invoke();
}
public delegate void IBaseViewModel_NavigatedFrom_Delegate();
public StubIShellViewModel NavigatedFrom(IBaseViewModel_NavigatedFrom_Delegate del)
{
_stubs[nameof(IBaseViewModel_NavigatedFrom_Delegate)] = del;
return this;
}
public event global::System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void On_PropertyChanged(object sender)
{
global::System.ComponentModel.PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) { handler(sender, null); }
}
public void PropertyChanged_Raise(object sender)
{
On_PropertyChanged(sender);
}
}
}
namespace Sannel.House.Client.Interfaces
{
[CompilerGenerated]
public class StubITemperatureSettingViewModel : ITemperatureSettingViewModel
{
private readonly Dictionary<string, object> _stubs = new Dictionary<string, object>();
global::Sannel.House.Client.Models.TemperatureSetting global::Sannel.House.Client.Interfaces.ITemperatureSettingViewModel.SundayDefault
{
get
{
return ((SundayDefault_Get_Delegate)_stubs[nameof(SundayDefault_Get_Delegate)]).Invoke();
}
}
public delegate global::Sannel.House.Client.Models.TemperatureSetting SundayDefault_Get_Delegate();
public StubITemperatureSettingViewModel SundayDefault_Get(SundayDefault_Get_Delegate del)
{
_stubs[nameof(SundayDefault_Get_Delegate)] = del;
return this;
}
global::Sannel.House.Client.Models.TemperatureSetting global::Sannel.House.Client.Interfaces.ITemperatureSettingViewModel.MondayDefault
{
get
{
return ((MondayDefault_Get_Delegate)_stubs[nameof(MondayDefault_Get_Delegate)]).Invoke();
}
}
public delegate global::Sannel.House.Client.Models.TemperatureSetting MondayDefault_Get_Delegate();
public StubITemperatureSettingViewModel MondayDefault_Get(MondayDefault_Get_Delegate del)
{
_stubs[nameof(MondayDefault_Get_Delegate)] = del;
return this;
}
global::Sannel.House.Client.Models.TemperatureSetting global::Sannel.House.Client.Interfaces.ITemperatureSettingViewModel.TuesdayDefault
{
get
{
return ((TuesdayDefault_Get_Delegate)_stubs[nameof(TuesdayDefault_Get_Delegate)]).Invoke();
}
}
public delegate global::Sannel.House.Client.Models.TemperatureSetting TuesdayDefault_Get_Delegate();
public StubITemperatureSettingViewModel TuesdayDefault_Get(TuesdayDefault_Get_Delegate del)
{
_stubs[nameof(TuesdayDefault_Get_Delegate)] = del;
return this;
}
global::Sannel.House.Client.Models.TemperatureSetting global::Sannel.House.Client.Interfaces.ITemperatureSettingViewModel.WednesdayDefault
{
get
{
return ((WednesdayDefault_Get_Delegate)_stubs[nameof(WednesdayDefault_Get_Delegate)]).Invoke();
}
}
public delegate global::Sannel.House.Client.Models.TemperatureSetting WednesdayDefault_Get_Delegate();
public StubITemperatureSettingViewModel WednesdayDefault_Get(WednesdayDefault_Get_Delegate del)
{
_stubs[nameof(WednesdayDefault_Get_Delegate)] = del;
return this;
}
global::Sannel.House.Client.Models.TemperatureSetting global::Sannel.House.Client.Interfaces.ITemperatureSettingViewModel.ThursdayDefault
{
get
{
return ((ThursdayDefault_Get_Delegate)_stubs[nameof(ThursdayDefault_Get_Delegate)]).Invoke();
}
}
public delegate global::Sannel.House.Client.Models.TemperatureSetting ThursdayDefault_Get_Delegate();
public StubITemperatureSettingViewModel ThursdayDefault_Get(ThursdayDefault_Get_Delegate del)
{
_stubs[nameof(ThursdayDefault_Get_Delegate)] = del;
return this;
}
global::Sannel.House.Client.Models.TemperatureSetting global::Sannel.House.Client.Interfaces.ITemperatureSettingViewModel.FridayDefault
{
get
{
return ((FridayDefault_Get_Delegate)_stubs[nameof(FridayDefault_Get_Delegate)]).Invoke();
}
}
public delegate global::Sannel.House.Client.Models.TemperatureSetting FridayDefault_Get_Delegate();
public StubITemperatureSettingViewModel FridayDefault_Get(FridayDefault_Get_Delegate del)
{
_stubs[nameof(FridayDefault_Get_Delegate)] = del;
return this;
}
global::Sannel.House.Client.Models.TemperatureSetting global::Sannel.House.Client.Interfaces.ITemperatureSettingViewModel.SaturdayDefault
{
get
{
return ((SaturdayDefault_Get_Delegate)_stubs[nameof(SaturdayDefault_Get_Delegate)]).Invoke();
}
}
public delegate global::Sannel.House.Client.Models.TemperatureSetting SaturdayDefault_Get_Delegate();
public StubITemperatureSettingViewModel SaturdayDefault_Get(SaturdayDefault_Get_Delegate del)
{
_stubs[nameof(SaturdayDefault_Get_Delegate)] = del;
return this;
}
void global::Sannel.House.Client.Interfaces.ITemperatureSettingViewModel.Refresh()
{
((Refresh_Delegate)_stubs[nameof(Refresh_Delegate)]).Invoke();
}
public delegate void Refresh_Delegate();
public StubITemperatureSettingViewModel Refresh(Refresh_Delegate del)
{
_stubs[nameof(Refresh_Delegate)] = del;
return this;
}
global::System.Windows.Input.ICommand global::Sannel.House.Client.Interfaces.ITemperatureSettingViewModel.UpdateDefaultCommand
{
get
{
return ((UpdateDefaultCommand_Get_Delegate)_stubs[nameof(UpdateDefaultCommand_Get_Delegate)]).Invoke();
}
}
public delegate global::System.Windows.Input.ICommand UpdateDefaultCommand_Get_Delegate();
public StubITemperatureSettingViewModel UpdateDefaultCommand_Get(UpdateDefaultCommand_Get_Delegate del)
{
_stubs[nameof(UpdateDefaultCommand_Get_Delegate)] = del;
return this;
}
global::System.Threading.Tasks.Task global::Sannel.House.Client.Interfaces.ITemperatureSettingViewModel.SaveTemperatureSettingAsync(global::Sannel.House.Client.Models.TemperatureSetting temperature)
{
return ((SaveTemperatureSettingAsync_TemperatureSetting_Delegate)_stubs[nameof(SaveTemperatureSettingAsync_TemperatureSetting_Delegate)]).Invoke(temperature);
}
public delegate global::System.Threading.Tasks.Task SaveTemperatureSettingAsync_TemperatureSetting_Delegate(global::Sannel.House.Client.Models.TemperatureSetting temperature);
public StubITemperatureSettingViewModel SaveTemperatureSettingAsync(SaveTemperatureSettingAsync_TemperatureSetting_Delegate del)
{
_stubs[nameof(SaveTemperatureSettingAsync_TemperatureSetting_Delegate)] = del;
return this;
}
global::Sannel.House.Client.Models.TemperatureSetting global::Sannel.House.Client.Interfaces.ITemperatureSettingViewModel.CreateNewTemperatureSetting()
{
return ((CreateNewTemperatureSetting_Delegate)_stubs[nameof(CreateNewTemperatureSetting_Delegate)]).Invoke();
}
public delegate global::Sannel.House.Client.Models.TemperatureSetting CreateNewTemperatureSetting_Delegate();
public StubITemperatureSettingViewModel CreateNewTemperatureSetting(CreateNewTemperatureSetting_Delegate del)
{
_stubs[nameof(CreateNewTemperatureSetting_Delegate)] = del;
return this;
}
global::System.Collections.ObjectModel.ObservableCollection<string> global::Sannel.House.Client.Interfaces.IErrorViewModel.ErrorKeys
{
get
{
return ((IErrorViewModel_ErrorKeys_Get_Delegate)_stubs[nameof(IErrorViewModel_ErrorKeys_Get_Delegate)]).Invoke();
}
}
public delegate global::System.Collections.ObjectModel.ObservableCollection<string> IErrorViewModel_ErrorKeys_Get_Delegate();
public StubITemperatureSettingViewModel ErrorKeys_Get(IErrorViewModel_ErrorKeys_Get_Delegate del)
{
_stubs[nameof(IErrorViewModel_ErrorKeys_Get_Delegate)] = del;
return this;
}
bool global::Sannel.House.Client.Interfaces.IErrorViewModel.HasErrors
{
get
{
return ((IErrorViewModel_HasErrors_Get_Delegate)_stubs[nameof(IErrorViewModel_HasErrors_Get_Delegate)]).Invoke();
}
set
{
((IErrorViewModel_HasErrors_Set_Delegate)_stubs[nameof(IErrorViewModel_HasErrors_Set_Delegate)]).Invoke(value);
}
}
public delegate bool IErrorViewModel_HasErrors_Get_Delegate();
public StubITemperatureSettingViewModel HasErrors_Get(IErrorViewModel_HasErrors_Get_Delegate del)
{
_stubs[nameof(IErrorViewModel_HasErrors_Get_Delegate)] = del;
return this;
}
public delegate void IErrorViewModel_HasErrors_Set_Delegate(bool value);
public StubITemperatureSettingViewModel HasErrors_Set(IErrorViewModel_HasErrors_Set_Delegate del)
{
_stubs[nameof(IErrorViewModel_HasErrors_Set_Delegate)] = del;
return this;
}
bool global::Sannel.House.Client.Interfaces.IBaseViewModel.IsBusy
{
get
{
return ((IBaseViewModel_IsBusy_Get_Delegate)_stubs[nameof(IBaseViewModel_IsBusy_Get_Delegate)]).Invoke();
}
}
public delegate bool IBaseViewModel_IsBusy_Get_Delegate();
public StubITemperatureSettingViewModel IsBusy_Get(IBaseViewModel_IsBusy_Get_Delegate del)
{
_stubs[nameof(IBaseViewModel_IsBusy_Get_Delegate)] = del;
return this;
}
void global::Sannel.House.Client.Interfaces.IBaseViewModel.NavigatedTo(object arg)
{
((IBaseViewModel_NavigatedTo_Object_Delegate)_stubs[nameof(IBaseViewModel_NavigatedTo_Object_Delegate)]).Invoke(arg);
}
public delegate void IBaseViewModel_NavigatedTo_Object_Delegate(object arg);
public StubITemperatureSettingViewModel NavigatedTo(IBaseViewModel_NavigatedTo_Object_Delegate del)
{
_stubs[nameof(IBaseViewModel_NavigatedTo_Object_Delegate)] = del;
return this;
}
void global::Sannel.House.Client.Interfaces.IBaseViewModel.NavigatedFrom()
{
((IBaseViewModel_NavigatedFrom_Delegate)_stubs[nameof(IBaseViewModel_NavigatedFrom_Delegate)]).Invoke();
}
public delegate void IBaseViewModel_NavigatedFrom_Delegate();
public StubITemperatureSettingViewModel NavigatedFrom(IBaseViewModel_NavigatedFrom_Delegate del)
{
_stubs[nameof(IBaseViewModel_NavigatedFrom_Delegate)] = del;
return this;
}
public event global::System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void On_PropertyChanged(object sender)
{
global::System.ComponentModel.PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) { handler(sender, null); }
}
public void PropertyChanged_Raise(object sender)
{
On_PropertyChanged(sender);
}
}
}
namespace Sannel.House.Client.Interfaces
{
[CompilerGenerated]
public class StubIUser : IUser
{
private readonly Dictionary<string, object> _stubs = new Dictionary<string, object>();
bool global::Sannel.House.Client.Interfaces.IUser.IsLoggedIn
{
get
{
return ((IsLoggedIn_Get_Delegate)_stubs[nameof(IsLoggedIn_Get_Delegate)]).Invoke();
}
}
public delegate bool IsLoggedIn_Get_Delegate();
public StubIUser IsLoggedIn_Get(IsLoggedIn_Get_Delegate del)
{
_stubs[nameof(IsLoggedIn_Get_Delegate)] = del;
return this;
}
string global::Sannel.House.Client.Interfaces.IUser.Name
{
get
{
return ((Name_Get_Delegate)_stubs[nameof(Name_Get_Delegate)]).Invoke();
}
}
public delegate string Name_Get_Delegate();
public StubIUser Name_Get(Name_Get_Delegate del)
{
_stubs[nameof(Name_Get_Delegate)] = del;
return this;
}
global::System.Collections.ObjectModel.ObservableCollection<string> global::Sannel.House.Client.Interfaces.IUser.Groups
{
get
{
return ((Groups_Get_Delegate)_stubs[nameof(Groups_Get_Delegate)]).Invoke();
}
}
public delegate global::System.Collections.ObjectModel.ObservableCollection<string> Groups_Get_Delegate();
public StubIUser Groups_Get(Groups_Get_Delegate del)
{
_stubs[nameof(Groups_Get_Delegate)] = del;
return this;
}
global::System.Collections.ObjectModel.ObservableCollection<global::Sannel.House.Client.Models.MenuItem> global::Sannel.House.Client.Interfaces.IUser.MenuTop
{
get
{
return ((MenuTop_Get_Delegate)_stubs[nameof(MenuTop_Get_Delegate)]).Invoke();
}
}
public delegate global::System.Collections.ObjectModel.ObservableCollection<global::Sannel.House.Client.Models.MenuItem> MenuTop_Get_Delegate();
public StubIUser MenuTop_Get(MenuTop_Get_Delegate del)
{
_stubs[nameof(MenuTop_Get_Delegate)] = del;
return this;
}
global::System.Collections.ObjectModel.ObservableCollection<global::Sannel.House.Client.Models.MenuItem> global::Sannel.House.Client.Interfaces.IUser.MenuBottom
{
get
{
return ((MenuBottom_Get_Delegate)_stubs[nameof(MenuBottom_Get_Delegate)]).Invoke();
}
}
public delegate global::System.Collections.ObjectModel.ObservableCollection<global::Sannel.House.Client.Models.MenuItem> MenuBottom_Get_Delegate();
public StubIUser MenuBottom_Get(MenuBottom_Get_Delegate del)
{
_stubs[nameof(MenuBottom_Get_Delegate)] = del;
return this;
}
public event global::System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void On_PropertyChanged(object sender)
{
global::System.ComponentModel.PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) { handler(sender, null); }
}
public void PropertyChanged_Raise(object sender)
{
On_PropertyChanged(sender);
}
}
}
namespace Sannel.House.Client.Interfaces
{
[CompilerGenerated]
public class StubIUserManager : IUserManager
{
private readonly Dictionary<string, object> _stubs = new Dictionary<string, object>();
global::System.Threading.Tasks.Task<bool> global::Sannel.House.Client.Interfaces.IUserManager.LoadProfileAsync()
{
return ((LoadProfileAsync_Delegate)_stubs[nameof(LoadProfileAsync_Delegate)]).Invoke();
}
public delegate global::System.Threading.Tasks.Task<bool> LoadProfileAsync_Delegate();
public StubIUserManager LoadProfileAsync(LoadProfileAsync_Delegate del)
{
_stubs[nameof(LoadProfileAsync_Delegate)] = del;
return this;
}
global::System.Threading.Tasks.Task global::Sannel.House.Client.Interfaces.IUserManager.LogoffAsync()
{
return ((LogoffAsync_Delegate)_stubs[nameof(LogoffAsync_Delegate)]).Invoke();
}
public delegate global::System.Threading.Tasks.Task LogoffAsync_Delegate();
public StubIUserManager LogoffAsync(LogoffAsync_Delegate del)
{
_stubs[nameof(LogoffAsync_Delegate)] = del;
return this;
}
}
}
| |
/* ========================================================================
* FlexiCamera for Unity3D:
* https://github.com/NoxHarmonium/flexicamera
* <!!filename!!>
* ========================================================================
* Copyright Sean Dawson 2013
*
* 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 UnityEngine;
using System.Collections.Generic;
using System.Linq;
namespace FlexiCamera.InputAdapters
{
public class FingerGesturesInputAdapter : InputAdapter
{
protected const int INPUT_MESSAGE_LIST_PREALLOC = 10;
List<InputMessage> _updates = new List<InputMessage>(INPUT_MESSAGE_LIST_PREALLOC);
/// <summary>
/// Gets the updates to gesture states since the last call
/// </summary>
public override List<InputMessage> GetUpdates()
{
List<InputMessage> updates = _updates;
_updates = new List<InputMessage>(INPUT_MESSAGE_LIST_PREALLOC);
return updates;
}
//--------------------------------------------------------------------------
// Finger Gesture handlers
//--------------------------------------------------------------------------
// Continous Gestures
public void OnFingerDown(FingerDownEvent e)
{
_updates.Add(new InputMessage(
InputMessage.InputTypes.FingerDown,
InputMessage.MessageTypes.Transient,
e.Position
));
}
public void OnFingerUp(FingerUpEvent e)
{
_updates.Add(new InputMessage(
InputMessage.InputTypes.FingerUp,
InputMessage.MessageTypes.Transient,
e.Position
));
}
public void OnFingerStationary(FingerMotionEvent e)
{
_updates.Add(new InputMessage(
InputMessage.InputTypes.FingerStationary,
InputMessage.MessageTypes.Transient,
e.Position
));
}
public void OnFingerMove(FingerMotionEvent e)
{
_updates.Add(new InputMessage(
InputMessage.InputTypes.FingerMoving,
InputMessage.MessageTypes.Transient,
e.Position
));
}
// Discrete Gestures
public void OnTap(TapGesture tap)
{
if (tap.State == GestureRecognitionState.Recognized) {
_updates.Add(new InputMessage(
InputMessage.InputTypes.OneFingerTap,
InputMessage.MessageTypes.Transient,
tap.Fingers.Select(f => f.Position).ToList(),
tap.Fingers.Select(f => f.DeltaPosition).ToList()
));
}
}
public void OnLongPress(LongPressGesture longPress)
{
if (longPress.State == GestureRecognitionState.Recognized) {
_updates.Add(new InputMessage(
InputMessage.InputTypes.OneFingerLongTap,
InputMessage.MessageTypes.Transient,
longPress.Fingers.Select(f => f.Position).ToList(),
longPress.Fingers.Select(f => f.DeltaPosition).ToList()
));
}
}
/*
// TODO: Impliment Swipe
public void OnSwipe(SwipeGesture swipe)
{
Vector2 velocity = new Vector2();
switch (swipe.Direction) {
case FingerGestures.SwipeDirection.Right:
velocity = Vector2.right * swipe.Velocity;
break;
case FingerGestures.SwipeDirection.Left:
velocity = Vector2.right * -swipe.Velocity;
break;
case FingerGestures.SwipeDirection.Up:
velocity = Vector2.up * swipe.Velocity;
break;
case FingerGestures.SwipeDirection.Down:
velocity = Vector2.up * -swipe.Velocity;
break;
}
HandleDragMoveEvent(swipe.Position, velocity, _swipeZones, true);
}
*/
public void OnDrag(DragGesture drag)
{
InputMessage.MessageTypes type = InputMessage.MessageTypes.Failed;
switch (drag.Phase) {
case ContinuousGesturePhase.Started:
type = InputMessage.MessageTypes.Begin;
break;
case ContinuousGesturePhase.Updated:
type = InputMessage.MessageTypes.Update;
break;
case ContinuousGesturePhase.Ended:
type = InputMessage.MessageTypes.End;
break;
default:
break;
}
_updates.Add(new InputMessage(
InputMessage.InputTypes.OneFingerDrag,
type,
drag.Fingers.Select(f => f.Position).ToList(),
drag.Fingers.Select(f => f.DeltaPosition).ToList()
));
}
public void OnTwoFingerDrag(DragGesture drag)
{
InputMessage.MessageTypes type = InputMessage.MessageTypes.Failed;
switch (drag.Phase) {
case ContinuousGesturePhase.Started:
type = InputMessage.MessageTypes.Begin;
break;
case ContinuousGesturePhase.Updated:
type = InputMessage.MessageTypes.Update;
break;
case ContinuousGesturePhase.Ended:
type = InputMessage.MessageTypes.End;
break;
default:
break;
}
_updates.Add(new InputMessage(
InputMessage.InputTypes.TwoFingerDrag,
type,
drag.Fingers.Select(f => f.Position).ToList(),
drag.Fingers.Select(f => f.DeltaPosition).ToList()
));
}
public void OnTwist(TwistGesture twist)
{
InputMessage.MessageTypes type = InputMessage.MessageTypes.Failed;
switch (twist.Phase) {
case ContinuousGesturePhase.Started:
type = InputMessage.MessageTypes.Begin;
break;
case ContinuousGesturePhase.Updated:
type = InputMessage.MessageTypes.Update;
break;
case ContinuousGesturePhase.Ended:
type = InputMessage.MessageTypes.End;
break;
default:
break;
}
_updates.Add(new InputMessage(
InputMessage.InputTypes.TwoFingerTwist,
type,
twist.Fingers.Select(f => f.Position).ToList(),
twist.Fingers.Select(f => f.DeltaPosition).ToList(),
new List<float> { twist.DeltaRotation }
));
}
public void OnPinch(PinchGesture pinch)
{
InputMessage.MessageTypes type = InputMessage.MessageTypes.Failed;
switch (pinch.Phase) {
case ContinuousGesturePhase.Started:
type = InputMessage.MessageTypes.Begin;
break;
case ContinuousGesturePhase.Updated:
type = InputMessage.MessageTypes.Update;
break;
case ContinuousGesturePhase.Ended:
type = InputMessage.MessageTypes.End;
break;
default:
break;
}
_updates.Add(new InputMessage(
InputMessage.InputTypes.TwoFingerPinch,
type,
pinch.Fingers.Select(f => f.Position).ToList(),
pinch.Fingers.Select(f => f.DeltaPosition).ToList(),
new List<float> { pinch.Delta }
));
}
}
}
| |
using ClosedXML.Excel;
using System;
namespace ClosedXML.Examples
{
public class CFColorScaleLowMidHigh : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().ColorScale()
.LowestValue(XLColor.Red)
.Midpoint(XLCFContentType.Percent, "50", XLColor.Yellow)
.HighestValue(XLColor.Green);
workbook.SaveAs(filePath);
}
}
public class CFColorScaleLowHigh : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().ColorScale()
.Minimum(XLCFContentType.Number, "2", XLColor.Red)
.Maximum(XLCFContentType.Percentile, "90", XLColor.Green);
workbook.SaveAs(filePath);
}
}
public class CFColorScaleMinimumMaximum : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().ColorScale()
.LowestValue(XLColor.FromHtml("#FFFF7128"))
.HighestValue(XLColor.FromHtml("#FFFFEF9C"));
workbook.SaveAs(filePath);
}
}
public class CFStartsWith : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue("Hello")
.CellBelow().SetValue("Hellos")
.CellBelow().SetValue("Hell")
.CellBelow().SetValue("Holl");
ws.RangeUsed().AddConditionalFormat().WhenStartsWith("Hell")
.Fill.SetBackgroundColor(XLColor.Red)
.Border.SetOutsideBorder(XLBorderStyleValues.Thick)
.Border.SetOutsideBorderColor(XLColor.Blue)
.Font.SetBold();
workbook.SaveAs(filePath);
}
}
public class CFEndsWith : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue("Hello")
.CellBelow().SetValue("Hellos")
.CellBelow().SetValue("Hell")
.CellBelow().SetValue("Holl");
ws.RangeUsed().AddConditionalFormat().WhenEndsWith("ll")
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFIsBlank : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue("Hello")
.CellBelow().SetValue("")
.CellBelow().SetValue("")
.CellBelow().SetValue("Holl");
ws.RangeUsed().AddConditionalFormat().WhenIsBlank()
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFNotBlank : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue("Hello")
.CellBelow().SetValue("")
.CellBelow().SetValue("")
.CellBelow().SetValue("Holl");
ws.RangeUsed().AddConditionalFormat().WhenNotBlank()
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFIsError : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue("Hello")
.CellBelow().SetFormulaA1("1/0")
.CellBelow().SetFormulaA1("1/0")
.CellBelow().SetValue("Holl");
ws.RangeUsed().AddConditionalFormat().WhenIsError()
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFNotError : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue("Hello")
.CellBelow().SetFormulaA1("1/0")
.CellBelow().SetFormulaA1("1/0")
.CellBelow().SetValue("Holl");
ws.RangeUsed().AddConditionalFormat().WhenNotError()
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFContains : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue("Hello")
.CellBelow().SetValue("Hellos")
.CellBelow().SetValue("Hell")
.CellBelow().SetValue("Holl");
ws.RangeUsed().AddConditionalFormat().WhenContains("Hell")
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFNotContains : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue("Hello")
.CellBelow().SetValue("Hellos")
.CellBelow().SetValue("Hell")
.CellBelow().SetValue("Holl");
ws.RangeUsed().AddConditionalFormat().WhenNotContains("Hell")
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFEqualsString : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue("Hello")
.CellBelow().SetValue("Hellos")
.CellBelow().SetValue("Hell")
.CellBelow().SetValue("Holl");
ws.RangeUsed().AddConditionalFormat().WhenEquals("Hell")
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFEqualsNumber : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().WhenEquals(2)
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFNotEqualsString : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue("Hello")
.CellBelow().SetValue("Hellos")
.CellBelow().SetValue("Hell")
.CellBelow().SetValue("Holl");
ws.RangeUsed().AddConditionalFormat().WhenNotEquals("Hell")
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFNotEqualsNumber : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().WhenNotEquals(2)
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFGreaterThan : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().WhenGreaterThan("2")
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFEqualOrGreaterThan : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().WhenEqualOrGreaterThan("2")
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFLessThan : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().WhenLessThan("2")
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFEqualOrLessThan : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().WhenEqualOrLessThan("2")
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFBetween : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().WhenBetween("2", "3")
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFNotBetween : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().WhenNotBetween("2", "3")
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFUnique : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().WhenIsUnique()
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFDuplicate : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().WhenIsDuplicate()
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFIsTrue : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().WhenIsTrue("TRUE")
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFTop : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().WhenIsTop(2)
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFBottom : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().WhenIsBottom(10, XLTopBottomType.Percent)
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFDataBar : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().DataBar(XLColor.Red, true)
.LowestValue()
.Maximum(XLCFContentType.Percent, "100");
workbook.SaveAs(filePath);
}
}
public class CFDataBarNegative : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.Cell(1, 1).SetValue(-1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.Range(ws.Cell(1, 1), ws.Cell(4, 1))
.AddConditionalFormat()
.DataBar(XLColor.Green, XLColor.Red, showBarOnly: false)
.LowestValue()
.HighestValue();
ws.Cell(1, 3).SetValue(-20)
.CellBelow().SetValue(40)
.CellBelow().SetValue(-60)
.CellBelow().SetValue(30);
ws.Range(ws.Cell(1, 3), ws.Cell(4, 3))
.AddConditionalFormat()
.DataBar(XLColor.Green, XLColor.Red, showBarOnly: true)
.Minimum(XLCFContentType.Number, -100)
.Maximum(XLCFContentType.Number, 100);
workbook.SaveAs(filePath);
}
}
public class CFIconSet : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().IconSet(XLIconSetStyle.ThreeTrafficLights2, true, true)
.AddValue(XLCFIconSetOperator.EqualOrGreaterThan, "0", XLCFContentType.Number)
.AddValue(XLCFIconSetOperator.EqualOrGreaterThan, "2", XLCFContentType.Number)
.AddValue(XLCFIconSetOperator.EqualOrGreaterThan, "3", XLCFContentType.Number);
workbook.SaveAs(filePath);
}
}
public class CFTwoConditions : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().IconSet(XLIconSetStyle.ThreeTrafficLights2, true, true)
.AddValue(XLCFIconSetOperator.EqualOrGreaterThan, "0", XLCFContentType.Number)
.AddValue(XLCFIconSetOperator.EqualOrGreaterThan, "2", XLCFContentType.Number)
.AddValue(XLCFIconSetOperator.EqualOrGreaterThan, "3", XLCFContentType.Number);
ws.RangeUsed().AddConditionalFormat().WhenContains("1")
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFInsertRows : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.Cell(2, 1).SetValue(1)
.CellRight().SetValue(1)
.CellRight().SetValue(2)
.CellRight().SetValue(3);
var range = ws.RangeUsed();
range.AddConditionalFormat().WhenEquals("1").Font.SetBold();
range.InsertRowsAbove(1);
workbook.SaveAs(filePath);
}
}
public class CFTest : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(1)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3)
.CellBelow().SetValue(4);
ws.RangeUsed().AddConditionalFormat().DataBar(XLColor.Red, XLColor.Green)
.LowestValue()
.HighestValue();
workbook.SaveAs(filePath);
}
}
public class CFMultipleConditions : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
var range = ws.Range("A1:A10");
range.AddConditionalFormat().WhenEquals("3")
.Fill.SetBackgroundColor(XLColor.Blue);
range.AddConditionalFormat().WhenEquals("2")
.Fill.SetBackgroundColor(XLColor.Green);
range.AddConditionalFormat().WhenEquals("1")
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
public class CFStopIfTrue : IXLExample
{
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Sheet1");
ws.FirstCell().SetValue(6)
.CellBelow().SetValue(1)
.CellBelow().SetValue(2)
.CellBelow().SetValue(3);
ws.RangeUsed().AddConditionalFormat().SetStopIfTrue().WhenGreaterThan(5);
ws.RangeUsed().AddConditionalFormat().IconSet(XLIconSetStyle.ThreeTrafficLights2, true, true)
.AddValue(XLCFIconSetOperator.EqualOrGreaterThan, "0", XLCFContentType.Number)
.AddValue(XLCFIconSetOperator.EqualOrGreaterThan, "2", XLCFContentType.Number)
.AddValue(XLCFIconSetOperator.EqualOrGreaterThan, "3", XLCFContentType.Number);
workbook.SaveAs(filePath);
}
}
public class CFDatesOccurring : IXLExample
{
public void Create(String filePath)
{
using (var workbook = new XLWorkbook())
{
var ws = workbook.AddWorksheet("Sheet1");
var range = ws.Range("A1:A10");
range.AddConditionalFormat()
.WhenDateIs(XLTimePeriod.Tomorrow)
.Fill.SetBackgroundColor(XLColor.GrannySmithApple);
range.AddConditionalFormat()
.WhenDateIs(XLTimePeriod.Yesterday)
.Fill.SetBackgroundColor(XLColor.Orange);
range.AddConditionalFormat()
.WhenDateIs(XLTimePeriod.InTheLast7Days)
.Fill.SetBackgroundColor(XLColor.Blue);
range.AddConditionalFormat()
.WhenDateIs(XLTimePeriod.ThisMonth)
.Fill.SetBackgroundColor(XLColor.Red);
workbook.SaveAs(filePath);
}
}
}
public class CFDataBars : IXLExample
{
public void Create(string filePath)
{
using var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet();
ws.Range("A2:F3").Value = 1;
ws.Range("A4:F4").Value = 2;
ws.Range("A5:F5").Value = 3;
ws.Range("A6:F6").Value = 4;
ws.Cell("A1").Value = "Automatic";
ws.Range("A2:A6").AddConditionalFormat().DataBar(XLColor.Amber);
ws.Cell("B1").Value = "Lowest/Highest";
ws.Range("B2:B6").AddConditionalFormat().DataBar(XLColor.BallBlue)
.LowestValue()
.HighestValue();
ws.Cell("C1").Value = "Value";
ws.Range("C2:C6").AddConditionalFormat().DataBar(XLColor.Cadet)
.Minimum(XLCFContentType.Number, 0)
.Maximum(XLCFContentType.Number, 10);
ws.Cell("D1").Value = "Percent";
ws.Range("D2:D6").AddConditionalFormat().DataBar(XLColor.Desert)
.Minimum(XLCFContentType.Percent, 50)
.Maximum(XLCFContentType.Percent, 100);
ws.Cell("E1").Value = "Formula";
ws.Range("E2:E6").AddConditionalFormat().DataBar(XLColor.Ecru)
.Minimum(XLCFContentType.Formula, "-SUM($A$2:$E$2)")
.Maximum(XLCFContentType.Formula, "SUM($A$6:$E$6)");
ws.Cell("F1").Value = "Percentile";
ws.Range("F2:F6").AddConditionalFormat().DataBar(XLColor.Fandango)
.Minimum(XLCFContentType.Percentile, 30)
.Maximum(XLCFContentType.Percentile, 70);
workbook.SaveAs(filePath);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using V2.PaidTimeOffDAL.Framework;
using V2.PaidTimeOffDAL;
using V2.PaidTimeOffBLL.Framework;
namespace V2.PaidTimeOffBLL
{
#region PTORequestEO
[Serializable()]
public class PTORequestEO : ENTBaseWorkflowEO
{
#region Properties
public int ENTUserAccountId { get; set; }
public DateTime RequestDate { get; set; }
public PTODayTypeBO.PTODayTypeEnum PTODayTypeId { get; set; }
public PTORequestTypeBO.PTORequestTypeEnum PTORequestTypeId { get; set; }
public string RequestDateString
{
get { return RequestDate.ToStandardDateFormat(); }
}
public string RequestTypeString
{
get
{
string text;
switch (PTORequestTypeId)
{
case PTORequestTypeBO.PTORequestTypeEnum.Personal:
text = "Personal";
break;
case PTORequestTypeBO.PTORequestTypeEnum.Vacation:
text = "Vacation";
break;
case PTORequestTypeBO.PTORequestTypeEnum.Unpaid:
text = "Unpaid";
break;
default:
throw new Exception("PTO Request Type unkown.");
}
switch (PTODayTypeId)
{
case PTODayTypeBO.PTODayTypeEnum.AM:
text += "-AM";
break;
case PTODayTypeBO.PTODayTypeEnum.PM:
text += "-PM";
break;
case PTODayTypeBO.PTODayTypeEnum.Full:
break;
default:
throw new Exception("PTO Day Tyep unknown.");
}
return text;
}
}
#endregion Properties
#region Overrides
public override bool Load(int id)
{
//Get the entity object from the DAL.
PTORequest pTORequest = new PTORequestData().Select(id);
MapEntityToProperties(pTORequest);
//Chapter 12
StorePropertyValues();
return true;
}
protected override void MapEntityToCustomProperties(IENTBaseEntity entity)
{
PTORequest pTORequest = (PTORequest)entity;
ID = pTORequest.PTORequestId;
ENTUserAccountId = pTORequest.ENTUserAccountId;
RequestDate = pTORequest.RequestDate;
PTODayTypeId = (PTODayTypeBO.PTODayTypeEnum)pTORequest.PTODayTypeId;
PTORequestTypeId = (PTORequestTypeBO.PTORequestTypeEnum)pTORequest.PTORequestTypeId;
base.LoadWorkflow(this.GetType().AssemblyQualifiedName, ID);
}
public override bool Save(HRPaidTimeOffDataContext db, ref ENTValidationErrors validationErrors, int userAccountId)
{
if (DBAction == DBActionEnum.Save)
{
//Validate the object
Validate(db, ref validationErrors);
//Check if there were any validation errors
if (validationErrors.Count == 0)
{
bool isNewRecord = IsNewRecord();
if (isNewRecord)
{
//Add
ID = new PTORequestData().Insert(db, ENTUserAccountId, RequestDate, Convert.ToInt32(PTODayTypeId), Convert.ToInt32(PTORequestTypeId), userAccountId);
AuditAdd(db, ref validationErrors, userAccountId);
}
else
{
//Update
if (!new PTORequestData().Update(db, ID, ENTUserAccountId, RequestDate, Convert.ToInt32(PTODayTypeId), Convert.ToInt32(PTORequestTypeId), userAccountId, Version))
{
UpdateFailed(ref validationErrors);
if (isNewRecord)
ID = 0;
return false;
}
else
{
AuditUpdate(db, ref validationErrors, userAccountId);
}
}
if (base.SaveWorkflow(db, ref validationErrors, this, userAccountId))
{
return true;
}
else
{
if (isNewRecord)
ID = 0;
return false;
}
}
else
{
//Didn't pass validation.
ID = 0;
return false;
}
}
else
{
throw new Exception("DBAction not Save.");
}
}
protected override void Validate(HRPaidTimeOffDataContext db, ref ENTValidationErrors validationErrors)
{
//Check if this was already selected as a request.
}
protected override void DeleteForReal(HRPaidTimeOffDataContext db)
{
if (DBAction == DBActionEnum.Delete)
{
new PTORequestData().Delete(db, ID);
}
else
{
throw new Exception("DBAction not delete.");
}
}
protected override void ValidateDelete(HRPaidTimeOffDataContext db, ref ENTValidationErrors validationErrors)
{
}
public override void Init()
{
PTODayTypeId = PTODayTypeBO.PTODayTypeEnum.Full;
PTORequestTypeId = PTORequestTypeBO.PTORequestTypeEnum.Vacation;
}
protected override string GetDisplayText()
{
return RequestDate.ToStandardDateFormat();
}
#endregion Overrides
public void SetRequestToCancelled(HRPaidTimeOffDataContext db)
{
new PTORequestData().UpdateCancelled(db, ID, true);
}
public static void GetUsed(ref double usedPersonalDays, ref double usedVacationDays, ref double unpaid,
int ptoRequestId, int userAccountId, short year)
{
PTORequestSelectByENTUserAccountIdYearResult result = new PTORequestData().SelectByENTUserAccountIdYear(ptoRequestId, userAccountId, year);
if (result != null)
{
usedVacationDays = Convert.ToDouble(result.CountOfFullVacation + result.CountOfHalfVacation);
usedPersonalDays = Convert.ToDouble(result.CountOfFullPersonal + result.CountOfHalfPersonal);
unpaid = Convert.ToDouble(result.CountOfFullUnpaid + result.CountOfHalfUnPaid);
}
else
{
usedPersonalDays = 0;
usedVacationDays = 0;
unpaid = 0;
}
}
}
#endregion PTORequestEO
#region PTORequestEOList
[Serializable()]
public class PTORequestEOList : ENTBaseEOList<PTORequestEO>
{
#region Overrides
public override void Load()
{
LoadFromList(new PTORequestData().Select());
}
#endregion Overrides
#region Private Methods
private void LoadFromList(List<PTORequest> pTORequests)
{
if (pTORequests.Count > 0)
{
foreach (PTORequest pTORequest in pTORequests)
{
PTORequestEO newPTORequestEO = new PTORequestEO();
newPTORequestEO.MapEntityToProperties(pTORequest);
this.Add(newPTORequestEO);
}
}
}
#endregion Private Methods
#region Internal Methods
#endregion Internal Methods
public void LoadPreviousByENTUserAccountId(int ptoRequestId, int entUserAccountId)
{
LoadFromList(new PTORequestData().SelectPreviousByENTUserAccountId(ptoRequestId, entUserAccountId));
}
public void LoadByENTUserAccountId(int entUserAccountId)
{
LoadFromList(new PTORequestData().SelectByENTUserAccountId(entUserAccountId));
}
public List<PTORequestEO> GetByRequestDate(DateTime requestDate)
{
var ret =
from r in this
where r.RequestDate == requestDate
select r;
return ret.ToList();
}
public void LoadByCurrentOwnerId(int entUserAccountId)
{
LoadFromList(new PTORequestData().SelectByCurrentOwnerId(entUserAccountId, typeof(PTORequestEO).AssemblyQualifiedName));
}
}
#endregion PTORequestEOList
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;
namespace FileHelpers.Tests.CommonTests
{
[TestFixture]
public class InNewLineTest
{
[Test]
public void InNewLine0()
{
var engine = new FileHelperEngine<InNewLineType0>();
InNewLineType0[] res = engine.ReadFile(TestCommon.GetPath("Good", "InNewLine0.txt"));
Assert.AreEqual(3, res.Length);
Assert.AreEqual(3, engine.TotalRecords);
Assert.AreEqual("166.90.252.2", res[0].IpAddress);
Assert.AreEqual("67.105.166.35", res[1].IpAddress);
Assert.AreEqual("67.105.166.35", res[2].IpAddress);
}
[Test]
public void InNewLine0rw()
{
var engine = new FileHelperEngine<InNewLineType0>();
InNewLineType0[] res = engine.ReadFile(TestCommon.GetPath("Good", "InNewLine0.txt"));
string tmp = engine.WriteString(res);
res = (InNewLineType0[]) engine.ReadString(tmp);
Assert.AreEqual(3, res.Length);
Assert.AreEqual(3, engine.TotalRecords);
Assert.AreEqual("166.90.252.2", res[0].IpAddress);
Assert.AreEqual("67.105.166.35", res[1].IpAddress);
Assert.AreEqual("67.105.166.35", res[2].IpAddress);
}
[Test]
public void InNewLine1()
{
var engine = new FileHelperEngine<InNewLineType1>();
InNewLineType1[] res = engine.ReadFile(TestCommon.GetPath("Good", "InNewLine1.txt"));
Assert.AreEqual(3, res.Length);
Assert.AreEqual(3, engine.TotalRecords);
Assert.AreEqual("166.90.252.2", res[0].IpAddress);
Assert.AreEqual("67.105.166.35", res[1].IpAddress);
Assert.AreEqual("67.105.166.35", res[2].IpAddress);
}
[Test]
public void InNewLine1rw()
{
var engine = new FileHelperEngine<InNewLineType1>();
InNewLineType1[] res = engine.ReadFile(TestCommon.GetPath("Good", "InNewLine1.txt"));
string tmp = engine.WriteString(res);
res = (InNewLineType1[]) engine.ReadString(tmp);
Assert.AreEqual(3, res.Length);
Assert.AreEqual(3, engine.TotalRecords);
Assert.AreEqual("166.90.252.2", res[0].IpAddress);
Assert.AreEqual("67.105.166.35", res[1].IpAddress);
Assert.AreEqual("67.105.166.35", res[2].IpAddress);
}
[Test]
public void InNewLineFixed1()
{
var engine = new FileHelperEngine<InNewLineFixedType1>();
InNewLineFixedType1[] res = engine.ReadFile(TestCommon.GetPath("Good", "InNewLineFixed1.txt"));
Assert.AreEqual(3, res.Length);
Assert.AreEqual(3, engine.TotalRecords);
Assert.AreEqual("166.090.252.002", res[0].IpAddress);
Assert.AreEqual("067.105.166.035", res[1].IpAddress);
Assert.AreEqual("067.105.166.035", res[2].IpAddress);
}
[Test]
public void InNewLineFixed1rw()
{
var engine = new FileHelperEngine<InNewLineFixedType1>();
InNewLineFixedType1[] res = engine.ReadFile(TestCommon.GetPath("Good", "InNewLineFixed1.txt"));
string tmp = engine.WriteString(res);
res = engine.ReadString(tmp);
Assert.AreEqual(3, res.Length);
Assert.AreEqual(3, engine.TotalRecords);
Assert.AreEqual("166.090.252.002", res[0].IpAddress);
Assert.AreEqual("067.105.166.035", res[1].IpAddress);
Assert.AreEqual("067.105.166.035", res[2].IpAddress);
}
[Test]
public void InNewLine2()
{
var engine = new FileHelperEngine<InNewLineType2>();
InNewLineType2[] res = engine.ReadFile(TestCommon.GetPath("Good", "InNewLine2.txt"));
Assert.AreEqual(3, res.Length);
Assert.AreEqual(3, engine.TotalRecords);
Assert.AreEqual("166.90.252.2", res[0].IpAddress);
Assert.AreEqual("67.105.166.35", res[1].IpAddress);
Assert.AreEqual("67.105.166.35", res[2].IpAddress);
Assert.AreEqual(111, res[0].FieldLast);
Assert.AreEqual(222, res[1].FieldLast);
Assert.AreEqual(333, res[2].FieldLast);
}
[Test]
public void InNewLine2rw()
{
var engine = new FileHelperEngine<InNewLineType2>();
InNewLineType2[] res =
engine.ReadString(engine.WriteString(engine.ReadFile(TestCommon.GetPath("Good", "InNewLine2.txt"))));
Assert.AreEqual(3, res.Length);
Assert.AreEqual(3, engine.TotalRecords);
Assert.AreEqual("166.90.252.2", res[0].IpAddress);
Assert.AreEqual("67.105.166.35", res[1].IpAddress);
Assert.AreEqual("67.105.166.35", res[2].IpAddress);
Assert.AreEqual(111, res[0].FieldLast);
Assert.AreEqual(222, res[1].FieldLast);
Assert.AreEqual(333, res[2].FieldLast);
}
[Test]
public void InNewLineFixed2()
{
var engine = new FileHelperEngine<InNewLineFixedType2>();
InNewLineFixedType2[] res = engine.ReadFile(TestCommon.GetPath("Good", "InNewLineFixed2.txt"));
Assert.AreEqual(3, res.Length);
Assert.AreEqual(3, engine.TotalRecords);
Assert.AreEqual("166.090.252.002", res[0].IpAddress);
Assert.AreEqual("067.105.166.035", res[1].IpAddress);
Assert.AreEqual("067.105.166.035", res[2].IpAddress);
Assert.AreEqual(111, res[0].FieldLast);
Assert.AreEqual(222, res[1].FieldLast);
Assert.AreEqual(333, res[2].FieldLast);
}
[Test]
public void InNewLineFixed2rw()
{
var engine = new FileHelperEngine<InNewLineFixedType2>();
InNewLineFixedType2[] res = engine.ReadFile(TestCommon.GetPath("Good", "InNewLineFixed2.txt"));
string tmp = engine.WriteString(res);
res = engine.ReadString(tmp);
Assert.AreEqual(3, res.Length);
Assert.AreEqual(3, engine.TotalRecords);
Assert.AreEqual("166.090.252.002", res[0].IpAddress);
Assert.AreEqual("067.105.166.035", res[1].IpAddress);
Assert.AreEqual("067.105.166.035", res[2].IpAddress);
Assert.AreEqual(111, res[0].FieldLast);
Assert.AreEqual(222, res[1].FieldLast);
Assert.AreEqual(333, res[2].FieldLast);
}
[Test]
public void InNewLine3Bad()
{
var engine = new FileHelperEngine<InNewLineType2>();
Assert.Throws<BadUsageException>(() =>
engine.ReadFile(TestCommon.GetPath("Bad", "InNewLine3.txt")));
}
[Test]
public void InNewLine4Bad()
{
var engine = new FileHelperEngine<InNewLineType2>();
Assert.Throws<BadUsageException>(() =>
engine.ReadFile(TestCommon.GetPath("Bad", "InNewLine4.txt")));
}
[Test]
public void InNewLineAfterOptional1()
{
var engine = new FileHelperEngine<InNewLineAfterOptional>();
var res = engine.ReadFile(TestCommon.GetPath("Good", "InNewLineAfterOptional1.txt"));
Assert.AreEqual(3, res.Length);
Assert.AreEqual(3, engine.TotalRecords);
Assert.AreEqual(107, res[0].Field1);
Assert.AreEqual("37052652", res[0].Field2);
Assert.AreEqual(82, res[1].Field1);
Assert.AreEqual("", res[1].Field2);
Assert.AreEqual(181, res[2].Field1);
Assert.AreEqual("", res[2].Field2);
Assert.AreEqual("166.090.252.002", res[0].IpAddress);
Assert.AreEqual("067.105.166.035", res[1].IpAddress);
Assert.AreEqual("067.105.166.035", res[2].IpAddress);
Assert.AreEqual(111, res[0].FieldLast);
Assert.AreEqual(222, res[1].FieldLast);
Assert.AreEqual(333, res[2].FieldLast);
}
[Test]
public void InNewLineAfterOptional2()
{
var engine = new FileHelperEngine<InNewLineAfterOptional>();
Assert.Throws<BadUsageException>(() =>
engine.ReadFile(TestCommon.GetPath("Bad", "InNewLineAfterOptional2.txt")));
}
[DelimitedRecord(",")]
private sealed class InNewLineType1
{
public byte Field1;
public long Field2;
[FieldInNewLine]
public string IpAddress;
}
[DelimitedRecord(",")]
private sealed class InNewLineType2
{
public byte Field1;
public long Field2;
[FieldInNewLine]
public string IpAddress;
public int FieldLast;
}
[DelimitedRecord(",")]
private sealed class InNewLineType0
{
[FieldConverter(ConverterKind.Date, "dd-MM hh:mm:ss yyyy")]
public DateTime Date1;
[FieldConverter(ConverterKind.Date, "dd-MM-yyyy hh:mm:ss")]
public DateTime Date2;
public byte Field1;
public long Field2;
[FieldInNewLine]
public string IpAddress;
}
[FixedLengthRecord]
private sealed class InNewLineFixedType1
{
[FieldFixedLength(3)]
public byte Field1;
[FieldFixedLength(8)]
public long Field2;
[FieldFixedLength(15)]
[FieldInNewLine]
public string IpAddress;
}
[FixedLengthRecord]
private sealed class InNewLineFixedType2
{
[FieldFixedLength(3)]
public byte Field1;
[FieldFixedLength(8)]
public long Field2;
[FieldFixedLength(15)]
[FieldInNewLine]
public string IpAddress;
[FieldFixedLength(3)]
public int FieldLast;
}
[FixedLengthRecord]
private sealed class InNewLineAfterOptional
{
[FieldFixedLength(3)]
public byte Field1;
[FieldOptional]
[FieldFixedLength(8)]
public string Field2;
[FieldFixedLength(15)]
[FieldInNewLine]
public string IpAddress;
[FieldFixedLength(3)]
public int FieldLast;
}
}
}
| |
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System.Activities.Presentation.Internal
{
using System;
using System.IO;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
using System.Windows.Media.Imaging;
using System.Diagnostics;
using System.Runtime;
using System.Activities.Presentation;
// <summary>
// Helper class that knows how to load up icons that live in assemblies and follow
// our extensibility icon naming convention.
// </summary>
internal static class ManifestImages
{
private static readonly string[] SupportedExtensions = new string[] {
".png", ".xaml", ".bmp", ".gif", ".jpg", ".jpeg"
};
// <summary>
// ----s open the assembly to which the specified Type belongs and tries
// to find and return an image that follows the naming conventions of:
//
// My.Namespace.MyControl.Icon.png
//
// and matches the desired size most closely, if multiple such images are found.
// </summary>
// <param name="type">Type to look up</param>
// <param name="desiredSize">Desired size (may not be met)</param>
// <returns>Null (if no image was found), Image instance (for non-Xaml images),
// or object instance (for Xaml-instantiated structures)</returns>
// <exception cref="ArgumentNullException">if type is null</exception>
public static object GetImage(Type type, Size desiredSize)
{
if (type == null)
{
throw FxTrace.Exception.ArgumentNull("type");
}
Assembly assembly = type.Assembly;
string[] resourceNames = assembly.GetManifestResourceNames();
if (resourceNames == null || resourceNames.Length == 0)
{
return null;
}
string fullTypeName = type.FullName;
string typeName = type.Name;
// Do a full namespace match first
ImageInfo bestMatch = FindBestMatch(type, assembly, resourceNames, desiredSize, delegate(string extensionlessResourceName)
{
return fullTypeName.Equals(extensionlessResourceName);
});
// Do a partial name match second, if full name didn't give us anything
bestMatch = bestMatch ?? FindBestMatch(type, assembly, resourceNames, desiredSize, delegate(string extensionlessResourceName)
{
return extensionlessResourceName != null && extensionlessResourceName.EndsWith(typeName, StringComparison.Ordinal);
});
if (bestMatch != null)
{
return bestMatch.Image;
}
return null;
}
private static ImageInfo FindBestMatch(
Type type,
Assembly assembly,
string[] resourceNames,
Size desiredSize,
MatchNameDelegate matchName)
{
Fx.Assert(type != null, "FindBestMatch - type parameter should not be null");
Fx.Assert(resourceNames != null && resourceNames.Length > 0, "resourceNames parameter should not be null");
Fx.Assert(matchName != null, "matchName parameter should not be null");
ImageInfo bestMatch = null;
for (int i = 0; i < resourceNames.Length; i++)
{
string extension = Path.GetExtension(resourceNames[i]);
if (!IsExtensionSupported(extension))
{
continue;
}
if (!matchName(StripIconExtension(resourceNames[i])))
{
continue;
}
ImageInfo info = ProcessResource(assembly, resourceNames[i]);
if (info == null)
{
continue;
}
// Try to match the found resource to the requested size
float sizeMatch = info.Match(desiredSize);
// Check for exact size match
if (sizeMatch < float.Epsilon)
{
return info;
}
// Keep the best image found so far
if (bestMatch == null ||
bestMatch.LastMatch > sizeMatch)
{
bestMatch = info;
}
}
return bestMatch;
}
// Tries to load up an image
private static ImageInfo ProcessResource(Assembly assembly, string resourceName)
{
Stream stream = assembly.GetManifestResourceStream(resourceName);
if (stream == null)
{
return null;
}
if (IsXamlContent(resourceName))
{
return new XamlImageInfo(stream);
}
else
{
return new BitmapImageInfo(stream);
}
}
// Checks to see whether the given extension is supported
private static bool IsExtensionSupported(string extension)
{
for (int i = 0; i < SupportedExtensions.Length; i++)
{
if (SupportedExtensions[i].Equals(extension, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
// Returns true if the passed in resource name ends in ".xaml"
private static bool IsXamlContent(string resourceName)
{
return ".xaml".Equals(Path.GetExtension(resourceName), StringComparison.OrdinalIgnoreCase);
}
// Strips ".Icon.ext" from a resource name
private static string StripIconExtension(string resourceName)
{
if (resourceName == null)
{
return null;
}
resourceName = Path.GetFileNameWithoutExtension(resourceName);
int dotIconIndex = resourceName.LastIndexOf(".Icon", StringComparison.OrdinalIgnoreCase);
if (dotIconIndex > 0)
{
return resourceName.Substring(0, dotIconIndex);
}
return null;
}
private delegate bool MatchNameDelegate(string extensionlessResourceName);
// Helper class that has information about an image
private abstract class ImageInfo
{
private float _lastMatch = 1;
protected ImageInfo()
{
}
public float LastMatch
{ get { return _lastMatch; } }
public abstract object Image
{ get; }
protected abstract Size Size
{ get; }
protected abstract bool HasFixedSize
{ get; }
// gets value range from 0 to 1: 0 == perfect match, 1 == complete opposite
public float Match(Size desiredSize)
{
if (!this.HasFixedSize)
{
_lastMatch = 0;
}
else
{
Size actualSize = this.Size;
float desiredAspectRatio = Math.Max(float.Epsilon, GetAspectRatio(desiredSize));
float actualAspectRatio = Math.Max(float.Epsilon, GetAspectRatio(actualSize));
float desiredArea = Math.Max(float.Epsilon, GetArea(desiredSize));
float actualArea = Math.Max(float.Epsilon, GetArea(actualSize));
// these values range from 0 to 1, 1 being perfect match, 0 being not so perfect match
float ratioDiff = desiredAspectRatio < actualAspectRatio ? desiredAspectRatio / actualAspectRatio : actualAspectRatio / desiredAspectRatio;
float areaDiff = desiredArea < actualArea ? desiredArea / actualArea : actualArea / desiredArea;
float diff = ratioDiff * areaDiff;
_lastMatch = Math.Min(1f, Math.Max(0f, 1f - diff));
}
return _lastMatch;
}
private static float GetAspectRatio(Size size)
{
if (size.Height < float.Epsilon)
{
return 0;
}
return (float)(size.Width / size.Height);
}
private static float GetArea(Size size)
{
return (float)(size.Width * size.Height);
}
}
// Helper class that knows how to deal with Xaml
private class XamlImageInfo : ImageInfo
{
private object _image;
public XamlImageInfo(Stream stream)
{
_image = XamlReader.Load(stream);
}
public override object Image
{
get { return _image; }
}
protected override Size Size
{
get { return Size.Empty; }
}
protected override bool HasFixedSize
{
get { return false; }
}
}
// Helper class that knows how to deal with bitmaps
private class BitmapImageInfo : ImageInfo
{
private Image _image;
private Size _size;
public BitmapImageInfo(Stream stream)
{
BitmapImage bmp = new BitmapImage();
bmp.BeginInit();
bmp.StreamSource = stream;
bmp.EndInit();
_image = new Image();
_image.Source = bmp;
_size = new Size(bmp.Width, bmp.Height);
}
public override object Image
{
get { return _image; }
}
protected override Size Size
{
get { return _size; }
}
protected override bool HasFixedSize
{
get { return true; }
}
}
}
}
| |
//
// Microsoft.CSharp.CSharpCodeProviderTest.cs
//
// Author:
// Gert Driesen ([email protected])
//
// (C) 2005 Novell
//
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Globalization;
using System.IO;
using System.Reflection;
using Microsoft.CSharp;
using NUnit.Framework;
namespace MonoTests.Microsoft.CSharp
{
[TestFixture]
public class CSharpCodeProviderTest
{
private string _tempDir;
private CodeDomProvider _codeProvider;
private static readonly string _sourceTest1 = "public class Test1 {}";
private static readonly string _sourceTest2 = "public class Test2 {}";
[SetUp]
public void SetUp ()
{
_codeProvider = new CSharpCodeProvider ();
_tempDir = CreateTempDirectory ();
}
[TearDown]
public void TearDown ()
{
RemoveDirectory (_tempDir);
}
[Test]
public void FileExtension ()
{
Assert.AreEqual ("cs", _codeProvider.FileExtension);
}
[Test]
public void LanguageOptionsTest ()
{
Assert.AreEqual (LanguageOptions.None, _codeProvider.LanguageOptions);
}
[Test]
public void GeneratorSupports ()
{
ICodeGenerator codeGenerator = _codeProvider.CreateGenerator ();
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.DeclareEnums), "#1");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.ArraysOfArrays), "#2");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.AssemblyAttributes), "#3");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.ChainedConstructorArguments), "#4");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.ComplexExpressions), "#5");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.DeclareDelegates), "#6");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.DeclareEnums), "#7");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.DeclareEvents), "#8");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.DeclareInterfaces), "#9");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.DeclareValueTypes), "#10");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.EntryPointMethod), "#11");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.GotoStatements), "#12");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.MultidimensionalArrays), "#13");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.MultipleInterfaceMembers), "#14");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.NestedTypes), "#15");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.ParameterAttributes), "#16");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.PublicStaticMembers), "#17");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.ReferenceParameters), "#18");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.ReturnTypeAttributes), "#19");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.StaticConstructors), "#20");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.TryCatchStatements), "#21");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.Win32Resources), "#22");
#if NET_2_0
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.DeclareIndexerProperties), "#23");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.GenericTypeDeclaration), "#24");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.GenericTypeReference), "#25");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.PartialTypes), "#26");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.Resources), "#27");
#endif
}
[Test]
public void CompileFromFile_InMemory ()
{
// create source file
string sourceFile = Path.Combine (_tempDir, "file." + _codeProvider.FileExtension);
using (FileStream f = new FileStream (sourceFile, FileMode.Create)) {
using (StreamWriter s = new StreamWriter (f)) {
s.Write (_sourceTest1);
s.Close ();
}
f.Close ();
}
CompilerParameters options = new CompilerParameters ();
options.GenerateExecutable = false;
options.GenerateInMemory = true;
options.TempFiles = new TempFileCollection (_tempDir);
ICodeCompiler compiler = _codeProvider.CreateCompiler ();
CompilerResults results = compiler.CompileAssemblyFromFile (options,
sourceFile);
// verify compilation was successful
AssertCompileResults (results, true);
Assert.AreEqual (string.Empty, results.CompiledAssembly.Location, "#1");
Assert.IsNull (results.PathToAssembly, "#2");
Assert.IsNotNull (results.CompiledAssembly.GetType ("Test1"), "#3");
// verify we don't cleanup files in temp directory too agressively
string[] tempFiles = Directory.GetFiles (_tempDir);
Assert.AreEqual (1, tempFiles.Length, "#4");
Assert.AreEqual (sourceFile, tempFiles[0], "#5");
}
[Test]
public void CompileFromFileBatch_InMemory ()
{
// create source file
string sourceFile1 = Path.Combine (_tempDir, "file." + _codeProvider.FileExtension);
using (FileStream f = new FileStream (sourceFile1, FileMode.Create)) {
using (StreamWriter s = new StreamWriter (f)) {
s.Write (_sourceTest1);
s.Close ();
}
f.Close ();
}
string sourceFile2 = Path.Combine (_tempDir, "file2." + _codeProvider.FileExtension);
using (FileStream f = new FileStream (sourceFile2, FileMode.Create)) {
using (StreamWriter s = new StreamWriter (f)) {
s.Write (_sourceTest2);
s.Close ();
}
f.Close ();
}
CompilerParameters options = new CompilerParameters ();
options.GenerateExecutable = false;
options.GenerateInMemory = true;
options.TempFiles = new TempFileCollection (_tempDir);
ICodeCompiler compiler = _codeProvider.CreateCompiler ();
CompilerResults results = compiler.CompileAssemblyFromFileBatch (options,
new string[] { sourceFile1, sourceFile2 });
// verify compilation was successful
AssertCompileResults (results, true);
Assert.AreEqual (string.Empty, results.CompiledAssembly.Location, "#1");
Assert.IsNull (results.PathToAssembly, "#2");
Assert.IsNotNull (results.CompiledAssembly.GetType ("Test1"), "#3");
Assert.IsNotNull (results.CompiledAssembly.GetType ("Test2"), "#4");
// verify we don't cleanup files in temp directory too agressively
string[] tempFiles = Directory.GetFiles (_tempDir);
Assert.AreEqual (2, tempFiles.Length, "#5");
Assert.IsTrue (File.Exists (sourceFile1), "#6");
Assert.IsTrue (File.Exists (sourceFile2), "#7");
}
[Test]
public void CompileFromSource_InMemory ()
{
// create a file in temp directory to ensure that compiler is not removing
// too much (temporary) files
string tempFile = Path.Combine (_tempDir, "file." + _codeProvider.FileExtension);
using (FileStream fs = File.Create (tempFile)) {
fs.Close ();
}
CompilerParameters options = new CompilerParameters ();
options.GenerateExecutable = false;
options.GenerateInMemory = true;
options.TempFiles = new TempFileCollection (_tempDir);
ICodeCompiler compiler = _codeProvider.CreateCompiler ();
CompilerResults results = compiler.CompileAssemblyFromSource (options,
_sourceTest1);
// verify compilation was successful
AssertCompileResults (results, true);
Assert.AreEqual (string.Empty, results.CompiledAssembly.Location, "#1");
Assert.IsNull (results.PathToAssembly, "#2");
Assert.IsNotNull (results.CompiledAssembly.GetType ("Test1"), "#3");
// verify we don't cleanup files in temp directory too agressively
string[] tempFiles = Directory.GetFiles (_tempDir);
Assert.AreEqual (1, tempFiles.Length, "#4");
Assert.AreEqual (tempFile, tempFiles[0], "#5");
}
[Test]
public void CompileFromSourceBatch_InMemory ()
{
// create a file in temp directory to ensure that compiler is not removing
// too much (temporary) files
string tempFile = Path.Combine (_tempDir, "file." + _codeProvider.FileExtension);
using (FileStream fs = File.Create (tempFile)) {
fs.Close ();
}
CompilerParameters options = new CompilerParameters ();
options.GenerateExecutable = false;
options.GenerateInMemory = true;
options.TempFiles = new TempFileCollection (_tempDir);
ICodeCompiler compiler = _codeProvider.CreateCompiler ();
CompilerResults results = compiler.CompileAssemblyFromSourceBatch (options,
new string[] { _sourceTest1, _sourceTest2 });
// verify compilation was successful
AssertCompileResults (results, true);
Assert.AreEqual (string.Empty, results.CompiledAssembly.Location, "#1");
Assert.IsNull (results.PathToAssembly, "#2");
Assert.IsNotNull (results.CompiledAssembly.GetType ("Test1"), "#3");
Assert.IsNotNull (results.CompiledAssembly.GetType ("Test2"), "#4");
// verify we don't cleanup files in temp directory too agressively
string[] tempFiles = Directory.GetFiles (_tempDir);
Assert.AreEqual (1, tempFiles.Length, "#5");
Assert.AreEqual (tempFile, tempFiles[0], "#6");
}
[Test]
public void CompileFromDom_NotInMemory ()
{
// create a file in temp directory to ensure that compiler is not removing
// too much (temporary) files
string tempFile = Path.Combine (_tempDir, "file." + _codeProvider.FileExtension);
using (FileStream fs = File.Create (tempFile)) {
fs.Close ();
}
// compile and verify result in separate appdomain to avoid file locks
AppDomain testDomain = CreateTestDomain ();
CrossDomainTester compileTester = CreateCrossDomainTester (testDomain);
string outputAssembly = null;
try {
outputAssembly = compileTester.CompileAssemblyFromDom (_tempDir);
} finally {
AppDomain.Unload (testDomain);
}
// there should be two files in temp dir: temp file and output assembly
string[] tempFiles = Directory.GetFiles (_tempDir);
Assert.AreEqual (2, tempFiles.Length, "#1");
Assert.IsTrue (File.Exists (outputAssembly), "#2");
Assert.IsTrue (File.Exists (tempFile), "#3");
}
[Test]
public void CompileFromDomBatch_NotInMemory ()
{
// create a file in temp directory to ensure that compiler is not removing
// too much (temporary) files
string tempFile = Path.Combine (_tempDir, "file." + _codeProvider.FileExtension);
using (FileStream fs = File.Create (tempFile)) {
fs.Close ();
}
// compile and verify result in separate appdomain to avoid file locks
AppDomain testDomain = CreateTestDomain ();
CrossDomainTester compileTester = CreateCrossDomainTester (testDomain);
string outputAssembly = null;
try {
outputAssembly = compileTester.CompileAssemblyFromDomBatch (_tempDir);
} finally {
AppDomain.Unload (testDomain);
}
// there should be two files in temp dir: temp file and output assembly
string[] tempFiles = Directory.GetFiles (_tempDir);
Assert.AreEqual (2, tempFiles.Length, "#1");
Assert.IsTrue (File.Exists (outputAssembly), "#2");
Assert.IsTrue (File.Exists (tempFile), "#3");
}
[Test]
public void CompileFromDom_InMemory ()
{
// create a file in temp directory to ensure that compiler is not removing
// too much (temporary) files
string tempFile = Path.Combine (_tempDir, "file." + _codeProvider.FileExtension);
using (FileStream fs = File.Create (tempFile)) {
fs.Close ();
}
CompilerParameters options = new CompilerParameters ();
options.GenerateExecutable = false;
options.GenerateInMemory = true;
options.TempFiles = new TempFileCollection (_tempDir);
ICodeCompiler compiler = _codeProvider.CreateCompiler ();
CompilerResults results = compiler.CompileAssemblyFromDom (options, new CodeCompileUnit ());
// verify compilation was successful
AssertCompileResults (results, true);
Assert.AreEqual (string.Empty, results.CompiledAssembly.Location, "#1");
Assert.IsNull (results.PathToAssembly, "#2");
// verify we don't cleanup files in temp directory too agressively
string[] tempFiles = Directory.GetFiles (_tempDir);
Assert.AreEqual (1, tempFiles.Length, "#3");
Assert.AreEqual (tempFile, tempFiles[0], "#4");
}
[Test]
public void CompileFromDomBatch_InMemory ()
{
// create a file in temp directory to ensure that compiler is not removing
// too much (temporary) files
string tempFile = Path.Combine (_tempDir, "file." + _codeProvider.FileExtension);
using (FileStream fs = File.Create (tempFile)) {
fs.Close ();
}
CompilerParameters options = new CompilerParameters ();
options.GenerateExecutable = false;
options.GenerateInMemory = true;
options.TempFiles = new TempFileCollection (_tempDir);
ICodeCompiler compiler = _codeProvider.CreateCompiler ();
CompilerResults results = compiler.CompileAssemblyFromDomBatch (options,
new CodeCompileUnit[] { new CodeCompileUnit (), new CodeCompileUnit () });
// verify compilation was successful
AssertCompileResults (results, true);
Assert.AreEqual (string.Empty, results.CompiledAssembly.Location, "#1");
Assert.IsNull (results.PathToAssembly, "#2");
// verify we don't cleanup files in temp directory too agressively
string[] tempFiles = Directory.GetFiles (_tempDir);
Assert.AreEqual (1, tempFiles.Length, "#3");
Assert.AreEqual (tempFile, tempFiles[0], "#4");
}
private static string CreateTempDirectory ()
{
// create a uniquely named zero-byte file
string tempFile = Path.GetTempFileName ();
// remove the temporary file
File.Delete (tempFile);
// create a directory named after the unique temporary file
Directory.CreateDirectory (tempFile);
// return the path to the temporary directory
return tempFile;
}
private static void RemoveDirectory (string path)
{
try {
if (Directory.Exists (path)) {
string[] directoryNames = Directory.GetDirectories (path);
foreach (string directoryName in directoryNames) {
RemoveDirectory (directoryName);
}
string[] fileNames = Directory.GetFiles (path);
foreach (string fileName in fileNames) {
File.Delete (fileName);
}
Directory.Delete (path, true);
}
} catch (Exception ex) {
throw new AssertionException ("Unable to cleanup '" + path + "'.", ex);
}
}
private static void AssertCompileResults (CompilerResults results, bool allowWarnings)
{
foreach (CompilerError compilerError in results.Errors) {
if (allowWarnings && compilerError.IsWarning) {
continue;
}
Assert.Fail (compilerError.ToString ());
}
}
private static AppDomain CreateTestDomain ()
{
return AppDomain.CreateDomain ("CompileFromDom", AppDomain.CurrentDomain.Evidence,
AppDomain.CurrentDomain.SetupInformation);
}
private static CrossDomainTester CreateCrossDomainTester (AppDomain domain)
{
Type testerType = typeof (CrossDomainTester);
return (CrossDomainTester) domain.CreateInstanceAndUnwrap (
testerType.Assembly.FullName, testerType.FullName, false,
BindingFlags.Public | BindingFlags.Instance, null, new object[0],
CultureInfo.InvariantCulture, new object[0], domain.Evidence);
}
private class CrossDomainTester : MarshalByRefObject
{
public string CompileAssemblyFromDom (string tempDir)
{
CompilerParameters options = new CompilerParameters ();
options.GenerateExecutable = false;
options.GenerateInMemory = false;
options.TempFiles = new TempFileCollection (tempDir);
CSharpCodeProvider codeProvider = new CSharpCodeProvider ();
ICodeCompiler compiler = codeProvider.CreateCompiler ();
CompilerResults results = compiler.CompileAssemblyFromDom (options, new CodeCompileUnit ());
// verify compilation was successful
AssertCompileResults (results, true);
Assert.IsTrue (results.CompiledAssembly.Location.Length != 0,
"Location should not be empty string");
Assert.IsNotNull (results.PathToAssembly, "PathToAssembly should not be null");
return results.PathToAssembly;
}
public string CompileAssemblyFromDomBatch (string tempDir)
{
CompilerParameters options = new CompilerParameters ();
options.GenerateExecutable = false;
options.GenerateInMemory = false;
options.TempFiles = new TempFileCollection (tempDir);
CSharpCodeProvider codeProvider = new CSharpCodeProvider ();
ICodeCompiler compiler = codeProvider.CreateCompiler ();
CompilerResults results = compiler.CompileAssemblyFromDomBatch (options, new CodeCompileUnit[] { new CodeCompileUnit (), new CodeCompileUnit () });
// verify compilation was successful
AssertCompileResults (results, true);
Assert.IsTrue (results.CompiledAssembly.Location.Length != 0,
"Location should not be empty string");
Assert.IsNotNull (results.PathToAssembly, "PathToAssembly should not be null");
return results.PathToAssembly;
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.Sql;
using Microsoft.Azure.Management.Sql.Models;
namespace Microsoft.Azure.Management.Sql
{
/// <summary>
/// The Windows Azure SQL Database management API provides a RESTful set of
/// web services that interact with Windows Azure SQL Database services to
/// manage your databases. The API enables users to create, retrieve,
/// update, and delete databases and servers.
/// </summary>
public static partial class DatabaseBackupOperationsExtensions
{
/// <summary>
/// Begins creating or updating an Azure SQL Server backup
/// LongTermRetention vault. To determine the status of the operation
/// call GetBackupLongTermRetentionVaultOperationStatus.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseBackupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the database is
/// hosted.
/// </param>
/// <param name='backupLongTermRetentionVaultName'>
/// Required. The name of the Azure SQL Server backup LongTermRetention
/// vault.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for creating or updating a backup
/// LongTermRetention vault.
/// </param>
/// <returns>
/// Response for long running Azure operations.
/// </returns>
public static BackupLongTermRetentionVaultCreateOrUpdateResponse BeginCreateOrUpdateBackupLongTermRetentionVault(this IDatabaseBackupOperations operations, string resourceGroupName, string serverName, string backupLongTermRetentionVaultName, BackupLongTermRetentionVaultCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDatabaseBackupOperations)s).BeginCreateOrUpdateBackupLongTermRetentionVaultAsync(resourceGroupName, serverName, backupLongTermRetentionVaultName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Begins creating or updating an Azure SQL Server backup
/// LongTermRetention vault. To determine the status of the operation
/// call GetBackupLongTermRetentionVaultOperationStatus.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseBackupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the database is
/// hosted.
/// </param>
/// <param name='backupLongTermRetentionVaultName'>
/// Required. The name of the Azure SQL Server backup LongTermRetention
/// vault.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for creating or updating a backup
/// LongTermRetention vault.
/// </param>
/// <returns>
/// Response for long running Azure operations.
/// </returns>
public static Task<BackupLongTermRetentionVaultCreateOrUpdateResponse> BeginCreateOrUpdateBackupLongTermRetentionVaultAsync(this IDatabaseBackupOperations operations, string resourceGroupName, string serverName, string backupLongTermRetentionVaultName, BackupLongTermRetentionVaultCreateOrUpdateParameters parameters)
{
return operations.BeginCreateOrUpdateBackupLongTermRetentionVaultAsync(resourceGroupName, serverName, backupLongTermRetentionVaultName, parameters, CancellationToken.None);
}
/// <summary>
/// Begins creating or updating an Azure SQL Server backup
/// LongTermRetention policy. To determine the status of the operation
/// call GetDatabaseBackupLongTermRetentionPolicyOperationStatus.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseBackupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the database is
/// hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database to be operated on.
/// </param>
/// <param name='backupLongTermRetentionPolicyName'>
/// Required. The name of the Azure SQL Database backup
/// LongTermRetention policy.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for creating or updating a
/// database backup LongTermRetention policy.
/// </param>
/// <returns>
/// Response for long running Azure operations.
/// </returns>
public static DatabaseBackupLongTermRetentionPolicyCreateOrUpdateResponse BeginCreateOrUpdateDatabaseBackupLongTermRetentionPolicy(this IDatabaseBackupOperations operations, string resourceGroupName, string serverName, string databaseName, string backupLongTermRetentionPolicyName, DatabaseBackupLongTermRetentionPolicyCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDatabaseBackupOperations)s).BeginCreateOrUpdateDatabaseBackupLongTermRetentionPolicyAsync(resourceGroupName, serverName, databaseName, backupLongTermRetentionPolicyName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Begins creating or updating an Azure SQL Server backup
/// LongTermRetention policy. To determine the status of the operation
/// call GetDatabaseBackupLongTermRetentionPolicyOperationStatus.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseBackupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the database is
/// hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database to be operated on.
/// </param>
/// <param name='backupLongTermRetentionPolicyName'>
/// Required. The name of the Azure SQL Database backup
/// LongTermRetention policy.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for creating or updating a
/// database backup LongTermRetention policy.
/// </param>
/// <returns>
/// Response for long running Azure operations.
/// </returns>
public static Task<DatabaseBackupLongTermRetentionPolicyCreateOrUpdateResponse> BeginCreateOrUpdateDatabaseBackupLongTermRetentionPolicyAsync(this IDatabaseBackupOperations operations, string resourceGroupName, string serverName, string databaseName, string backupLongTermRetentionPolicyName, DatabaseBackupLongTermRetentionPolicyCreateOrUpdateParameters parameters)
{
return operations.BeginCreateOrUpdateDatabaseBackupLongTermRetentionPolicyAsync(resourceGroupName, serverName, databaseName, backupLongTermRetentionPolicyName, parameters, CancellationToken.None);
}
/// <summary>
/// Creates or updates an Azure SQL Server backup LongTermRetention
/// vault.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseBackupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the database is
/// hosted.
/// </param>
/// <param name='backupLongTermRetentionVaultName'>
/// Required. The name of the Azure SQL Server backup LongTermRetention
/// vault.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for creating or updating a backup
/// LongTermRetention vault.
/// </param>
/// <returns>
/// Response for long running Azure operations.
/// </returns>
public static BackupLongTermRetentionVaultCreateOrUpdateResponse CreateOrUpdateBackupLongTermRetentionVault(this IDatabaseBackupOperations operations, string resourceGroupName, string serverName, string backupLongTermRetentionVaultName, BackupLongTermRetentionVaultCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDatabaseBackupOperations)s).CreateOrUpdateBackupLongTermRetentionVaultAsync(resourceGroupName, serverName, backupLongTermRetentionVaultName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates an Azure SQL Server backup LongTermRetention
/// vault.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseBackupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the database is
/// hosted.
/// </param>
/// <param name='backupLongTermRetentionVaultName'>
/// Required. The name of the Azure SQL Server backup LongTermRetention
/// vault.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for creating or updating a backup
/// LongTermRetention vault.
/// </param>
/// <returns>
/// Response for long running Azure operations.
/// </returns>
public static Task<BackupLongTermRetentionVaultCreateOrUpdateResponse> CreateOrUpdateBackupLongTermRetentionVaultAsync(this IDatabaseBackupOperations operations, string resourceGroupName, string serverName, string backupLongTermRetentionVaultName, BackupLongTermRetentionVaultCreateOrUpdateParameters parameters)
{
return operations.CreateOrUpdateBackupLongTermRetentionVaultAsync(resourceGroupName, serverName, backupLongTermRetentionVaultName, parameters, CancellationToken.None);
}
/// <summary>
/// Creates or updates an Azure SQL Database backup LongTermRetention
/// policy.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseBackupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the database is
/// hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database to be operated on
/// (Updated or created).
/// </param>
/// <param name='backupLongTermRetentionPolicyName'>
/// Required. The name of the Azure SQL Database backup
/// LongTermRetention policy.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for creating or updating a
/// database backup LongTermRetention policy.
/// </param>
/// <returns>
/// Response for long running Azure operations.
/// </returns>
public static DatabaseBackupLongTermRetentionPolicyCreateOrUpdateResponse CreateOrUpdateDatabaseBackupLongTermRetentionPolicy(this IDatabaseBackupOperations operations, string resourceGroupName, string serverName, string databaseName, string backupLongTermRetentionPolicyName, DatabaseBackupLongTermRetentionPolicyCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDatabaseBackupOperations)s).CreateOrUpdateDatabaseBackupLongTermRetentionPolicyAsync(resourceGroupName, serverName, databaseName, backupLongTermRetentionPolicyName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates an Azure SQL Database backup LongTermRetention
/// policy.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseBackupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the database is
/// hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database to be operated on
/// (Updated or created).
/// </param>
/// <param name='backupLongTermRetentionPolicyName'>
/// Required. The name of the Azure SQL Database backup
/// LongTermRetention policy.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for creating or updating a
/// database backup LongTermRetention policy.
/// </param>
/// <returns>
/// Response for long running Azure operations.
/// </returns>
public static Task<DatabaseBackupLongTermRetentionPolicyCreateOrUpdateResponse> CreateOrUpdateDatabaseBackupLongTermRetentionPolicyAsync(this IDatabaseBackupOperations operations, string resourceGroupName, string serverName, string databaseName, string backupLongTermRetentionPolicyName, DatabaseBackupLongTermRetentionPolicyCreateOrUpdateParameters parameters)
{
return operations.CreateOrUpdateDatabaseBackupLongTermRetentionPolicyAsync(resourceGroupName, serverName, databaseName, backupLongTermRetentionPolicyName, parameters, CancellationToken.None);
}
/// <summary>
/// Returns an Azure SQL Server backup LongTermRetention vault
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseBackupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the resource
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server.
/// </param>
/// <param name='backupLongTermRetentionVaultName'>
/// Required. The name of the Azure SQL Database backup
/// LongTermRetention vault.
/// </param>
/// <returns>
/// Represents the response to a Get Azure Sql Server backup
/// LongTermRetention vault request.
/// </returns>
public static BackupLongTermRetentionVaultGetResponse GetBackupLongTermRetentionVault(this IDatabaseBackupOperations operations, string resourceGroupName, string serverName, string backupLongTermRetentionVaultName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDatabaseBackupOperations)s).GetBackupLongTermRetentionVaultAsync(resourceGroupName, serverName, backupLongTermRetentionVaultName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns an Azure SQL Server backup LongTermRetention vault
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseBackupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the resource
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server.
/// </param>
/// <param name='backupLongTermRetentionVaultName'>
/// Required. The name of the Azure SQL Database backup
/// LongTermRetention vault.
/// </param>
/// <returns>
/// Represents the response to a Get Azure Sql Server backup
/// LongTermRetention vault request.
/// </returns>
public static Task<BackupLongTermRetentionVaultGetResponse> GetBackupLongTermRetentionVaultAsync(this IDatabaseBackupOperations operations, string resourceGroupName, string serverName, string backupLongTermRetentionVaultName)
{
return operations.GetBackupLongTermRetentionVaultAsync(resourceGroupName, serverName, backupLongTermRetentionVaultName, CancellationToken.None);
}
/// <summary>
/// Gets the status of an Azure Sql Server backup LongTermRetention
/// vault create or update operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseBackupOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation
/// </param>
/// <returns>
/// Response for long running Azure operations.
/// </returns>
public static BackupLongTermRetentionVaultCreateOrUpdateResponse GetBackupLongTermRetentionVaultOperationStatus(this IDatabaseBackupOperations operations, string operationStatusLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDatabaseBackupOperations)s).GetBackupLongTermRetentionVaultOperationStatusAsync(operationStatusLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the status of an Azure Sql Server backup LongTermRetention
/// vault create or update operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseBackupOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation
/// </param>
/// <returns>
/// Response for long running Azure operations.
/// </returns>
public static Task<BackupLongTermRetentionVaultCreateOrUpdateResponse> GetBackupLongTermRetentionVaultOperationStatusAsync(this IDatabaseBackupOperations operations, string operationStatusLink)
{
return operations.GetBackupLongTermRetentionVaultOperationStatusAsync(operationStatusLink, CancellationToken.None);
}
/// <summary>
/// Returns an Azure SQL Database backup LongTermRetention policy
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseBackupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the resource
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database.
/// </param>
/// <param name='backupLongTermRetentionPolicyName'>
/// Required. The name of the Azure SQL Database backup
/// LongTermRetention policy.
/// </param>
/// <returns>
/// Represents the response to a Get Azure Sql Database backup
/// LongTermRetention policy request.
/// </returns>
public static DatabaseBackupLongTermRetentionPolicyGetResponse GetDatabaseBackupLongTermRetentionPolicy(this IDatabaseBackupOperations operations, string resourceGroupName, string serverName, string databaseName, string backupLongTermRetentionPolicyName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDatabaseBackupOperations)s).GetDatabaseBackupLongTermRetentionPolicyAsync(resourceGroupName, serverName, databaseName, backupLongTermRetentionPolicyName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns an Azure SQL Database backup LongTermRetention policy
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseBackupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the resource
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database.
/// </param>
/// <param name='backupLongTermRetentionPolicyName'>
/// Required. The name of the Azure SQL Database backup
/// LongTermRetention policy.
/// </param>
/// <returns>
/// Represents the response to a Get Azure Sql Database backup
/// LongTermRetention policy request.
/// </returns>
public static Task<DatabaseBackupLongTermRetentionPolicyGetResponse> GetDatabaseBackupLongTermRetentionPolicyAsync(this IDatabaseBackupOperations operations, string resourceGroupName, string serverName, string databaseName, string backupLongTermRetentionPolicyName)
{
return operations.GetDatabaseBackupLongTermRetentionPolicyAsync(resourceGroupName, serverName, databaseName, backupLongTermRetentionPolicyName, CancellationToken.None);
}
/// <summary>
/// Gets the status of an Azure Sql Database backup LongTermRetention
/// policy create or update operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseBackupOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation
/// </param>
/// <returns>
/// Response for long running Azure operations.
/// </returns>
public static DatabaseBackupLongTermRetentionPolicyCreateOrUpdateResponse GetDatabaseBackupLongTermRetentionPolicyOperationStatus(this IDatabaseBackupOperations operations, string operationStatusLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDatabaseBackupOperations)s).GetDatabaseBackupLongTermRetentionPolicyOperationStatusAsync(operationStatusLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the status of an Azure Sql Database backup LongTermRetention
/// policy create or update operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseBackupOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation
/// </param>
/// <returns>
/// Response for long running Azure operations.
/// </returns>
public static Task<DatabaseBackupLongTermRetentionPolicyCreateOrUpdateResponse> GetDatabaseBackupLongTermRetentionPolicyOperationStatusAsync(this IDatabaseBackupOperations operations, string operationStatusLink)
{
return operations.GetDatabaseBackupLongTermRetentionPolicyOperationStatusAsync(operationStatusLink, CancellationToken.None);
}
/// <summary>
/// Returns an Azure SQL deleted database backup (a resource
/// representing a deleted database that can be restored).
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseBackupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server to retrieve
/// deleted databases for.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database to retrieve deleted
/// databases for.
/// </param>
/// <returns>
/// Represents the response to a Get Azure Sql Database deleted
/// database backup request.
/// </returns>
public static DeletedDatabaseBackupGetResponse GetDeletedDatabaseBackup(this IDatabaseBackupOperations operations, string resourceGroupName, string serverName, string databaseName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDatabaseBackupOperations)s).GetDeletedDatabaseBackupAsync(resourceGroupName, serverName, databaseName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns an Azure SQL deleted database backup (a resource
/// representing a deleted database that can be restored).
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseBackupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server to retrieve
/// deleted databases for.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database to retrieve deleted
/// databases for.
/// </param>
/// <returns>
/// Represents the response to a Get Azure Sql Database deleted
/// database backup request.
/// </returns>
public static Task<DeletedDatabaseBackupGetResponse> GetDeletedDatabaseBackupAsync(this IDatabaseBackupOperations operations, string resourceGroupName, string serverName, string databaseName)
{
return operations.GetDeletedDatabaseBackupAsync(resourceGroupName, serverName, databaseName, CancellationToken.None);
}
/// <summary>
/// Returns an Azure SQL Database geo backup.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseBackupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server to retrieve geo
/// backups for.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database to retrieve geo
/// backups for.
/// </param>
/// <returns>
/// Represents the response to a Get Azure Sql Database geo backup
/// request.
/// </returns>
public static GeoBackupGetResponse GetGeoBackup(this IDatabaseBackupOperations operations, string resourceGroupName, string serverName, string databaseName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDatabaseBackupOperations)s).GetGeoBackupAsync(resourceGroupName, serverName, databaseName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns an Azure SQL Database geo backup.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseBackupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server to retrieve geo
/// backups for.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database to retrieve geo
/// backups for.
/// </param>
/// <returns>
/// Represents the response to a Get Azure Sql Database geo backup
/// request.
/// </returns>
public static Task<GeoBackupGetResponse> GetGeoBackupAsync(this IDatabaseBackupOperations operations, string resourceGroupName, string serverName, string databaseName)
{
return operations.GetGeoBackupAsync(resourceGroupName, serverName, databaseName, CancellationToken.None);
}
/// <summary>
/// Returns a list of Azure SQL Server backup LongTermRetention vaults
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseBackupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the resource
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database.
/// </param>
/// <returns>
/// Represents the response to a List Azure Sql Server backup
/// LongTermRetention vault request.
/// </returns>
public static BackupLongTermRetentionVaultListResponse ListBackupLongTermRetentionVaults(this IDatabaseBackupOperations operations, string resourceGroupName, string serverName, string databaseName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDatabaseBackupOperations)s).ListBackupLongTermRetentionVaultsAsync(resourceGroupName, serverName, databaseName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns a list of Azure SQL Server backup LongTermRetention vaults
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseBackupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the resource
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database.
/// </param>
/// <returns>
/// Represents the response to a List Azure Sql Server backup
/// LongTermRetention vault request.
/// </returns>
public static Task<BackupLongTermRetentionVaultListResponse> ListBackupLongTermRetentionVaultsAsync(this IDatabaseBackupOperations operations, string resourceGroupName, string serverName, string databaseName)
{
return operations.ListBackupLongTermRetentionVaultsAsync(resourceGroupName, serverName, databaseName, CancellationToken.None);
}
/// <summary>
/// Returns a list of Azure SQL Database backup LongTermRetention
/// policies
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseBackupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the resource
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database.
/// </param>
/// <returns>
/// Represents the response to a List Azure Sql Database backup
/// LongTermRetention policy request.
/// </returns>
public static DatabaseBackupLongTermRetentionPolicyListResponse ListDatabaseBackupLongTermRetentionPolicies(this IDatabaseBackupOperations operations, string resourceGroupName, string serverName, string databaseName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDatabaseBackupOperations)s).ListDatabaseBackupLongTermRetentionPoliciesAsync(resourceGroupName, serverName, databaseName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns a list of Azure SQL Database backup LongTermRetention
/// policies
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseBackupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the resource
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database.
/// </param>
/// <returns>
/// Represents the response to a List Azure Sql Database backup
/// LongTermRetention policy request.
/// </returns>
public static Task<DatabaseBackupLongTermRetentionPolicyListResponse> ListDatabaseBackupLongTermRetentionPoliciesAsync(this IDatabaseBackupOperations operations, string resourceGroupName, string serverName, string databaseName)
{
return operations.ListDatabaseBackupLongTermRetentionPoliciesAsync(resourceGroupName, serverName, databaseName, CancellationToken.None);
}
/// <summary>
/// Returns a list of Azure SQL deleted database backups (a resource
/// representing a deleted database that can be restored).
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseBackupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server to retrieve
/// deleted databases for.
/// </param>
/// <returns>
/// Represents the response to a List Azure Sql Database deleted
/// database backups request.
/// </returns>
public static DeletedDatabaseBackupListResponse ListDeletedDatabaseBackups(this IDatabaseBackupOperations operations, string resourceGroupName, string serverName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDatabaseBackupOperations)s).ListDeletedDatabaseBackupsAsync(resourceGroupName, serverName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns a list of Azure SQL deleted database backups (a resource
/// representing a deleted database that can be restored).
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseBackupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server to retrieve
/// deleted databases for.
/// </param>
/// <returns>
/// Represents the response to a List Azure Sql Database deleted
/// database backups request.
/// </returns>
public static Task<DeletedDatabaseBackupListResponse> ListDeletedDatabaseBackupsAsync(this IDatabaseBackupOperations operations, string resourceGroupName, string serverName)
{
return operations.ListDeletedDatabaseBackupsAsync(resourceGroupName, serverName, CancellationToken.None);
}
/// <summary>
/// Returns a list of Azure SQL Database geo backups.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseBackupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server to retrieve geo
/// backups for.
/// </param>
/// <returns>
/// Represents the response to a List Azure Sql Database geo backups
/// request.
/// </returns>
public static GeoBackupListResponse ListGeoBackups(this IDatabaseBackupOperations operations, string resourceGroupName, string serverName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDatabaseBackupOperations)s).ListGeoBackupsAsync(resourceGroupName, serverName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns a list of Azure SQL Database geo backups.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseBackupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server to retrieve geo
/// backups for.
/// </param>
/// <returns>
/// Represents the response to a List Azure Sql Database geo backups
/// request.
/// </returns>
public static Task<GeoBackupListResponse> ListGeoBackupsAsync(this IDatabaseBackupOperations operations, string resourceGroupName, string serverName)
{
return operations.ListGeoBackupsAsync(resourceGroupName, serverName, CancellationToken.None);
}
/// <summary>
/// Returns a list of Azure SQL Database restore points.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseBackupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database from which to retrieve
/// available restore points.
/// </param>
/// <returns>
/// Represents the response to a List Azure Sql Database restore points
/// request.
/// </returns>
public static RestorePointListResponse ListRestorePoints(this IDatabaseBackupOperations operations, string resourceGroupName, string serverName, string databaseName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDatabaseBackupOperations)s).ListRestorePointsAsync(resourceGroupName, serverName, databaseName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns a list of Azure SQL Database restore points.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseBackupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database from which to retrieve
/// available restore points.
/// </param>
/// <returns>
/// Represents the response to a List Azure Sql Database restore points
/// request.
/// </returns>
public static Task<RestorePointListResponse> ListRestorePointsAsync(this IDatabaseBackupOperations operations, string resourceGroupName, string serverName, string databaseName)
{
return operations.ListRestorePointsAsync(resourceGroupName, serverName, databaseName, CancellationToken.None);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using Automatonymous;
using Encog.ML.Data;
using Encog.ML.Data.Basic;
using Encog.Neural.Networks;
using Encog.Persist;
using Encog.Util.Arrayutil;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using RabbitMQ.Client;
using aXon.Rover;
using aXon.Rover.Enumerations;
using aXon.Rover.Models;
using aXon.TaskTransport;
using aXon.TaskTransport.Messages;
using aXon.Warehouse.Modules.Robotics.Robot.Models;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;
namespace aXon.RX02.ControlServer
{
public class RobotManager
{
private readonly Robot _robot;
private RobotState _state;
private RobotStateMachine _machine;
private readonly MongoDataService ds = new MongoDataService();
public MqttClient Client;
private static IConnection _Connection;
private MessageQueue<RobotJobMessage> _messageQueue;
private NeuralRobot _neural;
private BasicNetwork _NeuralNet;
public RobotManager(string serial)
{
Client = new MqttClient(IPAddress.Parse("192.168.1.19"));
byte code = Client.Connect("aXon" + serial);
var ques = BuildQueues(serial);
byte[] qos = new byte[ques.Length];
for (int x = 0; x != ques.Length;x++ )
{
qos[x] = MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE;
}
Client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
Client.Subscribe(ques, qos);
_robot = ds.GetCollectionQueryModel<Robot>(Query.EQ("SerialNumber", serial)).FirstOrDefault();
if (_robot == null)
{
_robot = new Robot
{
Id = Guid.NewGuid(),
SerialNumber = serial,
IsActiveRecord = true,
LastEditDateTime = DateTime.Now,
CreateDateTime = DateTime.Now,
CurrentMode = RoverMode.WaitingForJob,
CurrentLocation = new Position(0, 0)
};
MongoCollection<Robot> col = ds.DataBase.GetCollection<Robot>("Robot");
col.Save(_robot);
}
_state = new RobotState() { Name = _robot.SerialNumber };
InitConnection();
_messageQueue = new MessageQueue<RobotJobMessage>(true,_Connection){GetNext=false};
_messageQueue.OnReceivedMessage += _messageQueue_OnReceivedMessage;
_machine = new RobotStateMachine();
_machine.RaiseEvent(_state, _machine.AuthenticateEvent);
Client.Publish(@"/" + serial + @"/AUTH", new byte[] {1});
_messageQueue.GetNext = true;
}
private static string[] BuildQueues(string serial)
{
var queues = new[]
{
"/serial/ACK",
"/serial/AUTH",
"/serial/BD",
"/serial/FD",
"/serial/LD",
"/serial/RD",
"/serial/ARV",
"/serial/LW",
"/serial/STOP",
"/serial/RCLX",
"/serial/RClY",
"/serial/VR",
"/serial/MVW"
};
var newQueues = new List<string>();
foreach (string q in queues)
{
newQueues.Add(q.Replace("serial", serial));
}
string[] ques = newQueues.ToArray();
return ques;
}
void _messageQueue_OnReceivedMessage(object sender, RobotJobMessage args)
{
Console.WriteLine("Job Arrive: " + args.RobotSerial + " NetId: " + args.NetworkId.ToString());
_machine.RaiseEvent(_state, _machine.JobArrivesEvent);
var network = ds.GetCollectionQueryModel<NeuralNetwork>(Query.EQ("_id",args.NetworkId)).FirstOrDefault();
var fn = network.Id.ToString();
_NeuralNet = GetNeuralNetwork(network, fn);
ProcessMovement();
}
private BasicNetwork GetNeuralNetwork(NeuralNetwork network, string fn)
{
BasicNetwork nn;
if(RobotContol.NetworkLock==null)
RobotContol.NetworkLock="t";
lock (RobotContol.NetworkLock)
{
var rawbytes = ds.OpenFile(network.Id);
File.WriteAllBytes(fn, rawbytes);
nn = (BasicNetwork) EncogDirectoryPersistence.LoadObject(new FileInfo(fn));
File.Delete(fn);
}
_neural = new NeuralRobot(new BasicNetwork(), true, network.StartPosition, network.EndPosition);
RobotContol.Warehouse = ds.GetCollectionQueryModel<aXon.Rover.Models.Warehouse>().FirstOrDefault();
return nn;
}
private CommandDirection ProcessNeuralRecomendation(BasicNetwork nn)
{
var input = new BasicMLData(2);
NormalizedField _hStats = new NormalizedField(NormalizationAction.Normalize, "Heading", 359, 0, .9, -.9);
input[0] = _neural.sim.DistanceToDestination;
input[1] = _hStats.Normalize(_neural.sim.Heading);
IMLData output = nn.Compute(input);
double f = output[0];
double l = output[1];
double r = output[2];
double rev = output[3];
var dirs = new Dictionary<CommandDirection, double>
{
{CommandDirection.MoveForward, f},
{CommandDirection.TurnLeft, l},
{CommandDirection.TurnRight, r},
{CommandDirection.MoveInReverse, rev}
};
KeyValuePair<CommandDirection, double> d = dirs.First(v => v.Value == 1.0);
CommandDirection thrust = d.Key;
return thrust;
}
private static void InitConnection()
{
var factory = new ConnectionFactory
{
HostName = "192.169.164.138",
AutomaticRecoveryEnabled = true,
NetworkRecoveryInterval = TimeSpan.FromSeconds(10)
};
_Connection = factory.CreateConnection();
}
private void Client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
Console.WriteLine("Topic Arrived: " + e.Topic);
if (!e.Topic.Contains(_robot.SerialNumber)) return;
switch (e.Topic.Split('/')[2])
{
case "ACK":
break;
case "AUTH":
_machine.RaiseEvent(_state, _machine.ReadyForWorkEvent);
//TODO: Need to add Code to Subscribe to RobotJobs on RabbitMq
_messageQueue.GetNext = true;
break;
case "FD":
break;
case "LD":
break;
case "RD":
break;
case "ARV":
ProcessMovement();
break;
case "LW":
break;
case "STOP":
_machine.RaiseEvent(_state, _machine.ObstructionEvent);
break;
case "RCLX":
break;
case "RClY":
break;
case "VR":
break;
}
}
private void ProcessMovement()
{
Console.WriteLine("Process movement Called");
if (!_neural.sim.Traveling)
{
}
else
{
var thrust = ProcessNeuralRecomendation(_NeuralNet);
_neural.sim.Turn(thrust);
switch (thrust)
{
case CommandDirection.TurnRight: //East
Console.WriteLine("move East");
Client.Publish(@"/" + _robot.SerialNumber , new byte[] {4});
break;
case CommandDirection.MoveInReverse: //south
Console.WriteLine("move South");
Client.Publish(@"/" + _robot.SerialNumber , new byte[] {3});
break;
case CommandDirection.MoveForward: //north
Console.WriteLine("move North");
Client.Publish(@"/" + _robot.SerialNumber , new byte[] {2});
break;
case CommandDirection.TurnLeft: //west
Console.WriteLine("move West");
Client.Publish(@"/" + _robot.SerialNumber , new byte[] {5});
break;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Net;
using System.Xml;
using Orleans.GrainDirectory;
using Orleans.Providers;
using Orleans.Streams;
using Orleans.Storage;
using System.Reflection;
namespace Orleans.Runtime.Configuration
{
// helper utility class to handle default vs. explicitly set config value.
[Serializable]
internal class ConfigValue<T>
{
public T Value;
public bool IsDefaultValue;
public ConfigValue(T val, bool isDefaultValue)
{
Value = val;
IsDefaultValue = isDefaultValue;
}
}
/// <summary>
/// Data object holding Silo global configuration parameters.
/// </summary>
[Serializable]
public class GlobalConfiguration : MessagingConfiguration
{
/// <summary>
/// Liveness configuration that controls the type of the liveness protocol that silo use for membership.
/// </summary>
public enum LivenessProviderType
{
/// <summary>Default value to allow discrimination of override values.</summary>
NotSpecified,
/// <summary>Grain is used to store membership information.
/// This option is not reliable and thus should only be used in local development setting.</summary>
MembershipTableGrain,
/// <summary>AzureTable is used to store membership information.
/// This option can be used in production.</summary>
AzureTable,
/// <summary>SQL Server is used to store membership information.
/// This option can be used in production.</summary>
SqlServer,
/// <summary>Apache ZooKeeper is used to store membership information.
/// This option can be used in production.</summary>
ZooKeeper,
/// <summary>Use custom provider from third-party assembly</summary>
Custom
}
/// <summary>
/// Reminders configuration that controls the type of the protocol that silo use to implement Reminders.
/// </summary>
public enum ReminderServiceProviderType
{
/// <summary>Default value to allow discrimination of override values.</summary>
NotSpecified,
/// <summary>Grain is used to store reminders information.
/// This option is not reliable and thus should only be used in local development setting.</summary>
ReminderTableGrain,
/// <summary>AzureTable is used to store reminders information.
/// This option can be used in production.</summary>
AzureTable,
/// <summary>SQL Server is used to store reminders information.
/// This option can be used in production.</summary>
SqlServer,
/// <summary>Used for benchmarking; it simply delays for a specified delay during each operation.</summary>
MockTable,
/// <summary>Reminder Service is disabled.</summary>
Disabled,
/// <summary>Use custom Reminder Service from third-party assembly</summary>
Custom
}
/// <summary>
/// Configuration for Gossip Channels
/// </summary>
public enum GossipChannelType
{
/// <summary>Default value to allow discrimination of override values.</summary>
NotSpecified,
/// <summary>An Azure Table serving as a channel. </summary>
AzureTable,
}
/// <summary>
/// Gossip channel configuration.
/// </summary>
[Serializable]
public class GossipChannelConfiguration
{
public GossipChannelType ChannelType { get; set; }
public string ConnectionString { get; set; }
}
/// <summary>
/// Configuration type that controls the type of the grain directory caching algorithm that silo use.
/// </summary>
public enum DirectoryCachingStrategyType
{
/// <summary>Don't cache.</summary>
None,
/// <summary>Standard fixed-size LRU.</summary>
LRU,
/// <summary>Adaptive caching with fixed maximum size and refresh. This option should be used in production.</summary>
Adaptive
}
public ApplicationConfiguration Application { get; private set; }
/// <summary>
/// SeedNodes are only used in local development setting with LivenessProviderType.MembershipTableGrain
/// SeedNodes are never used in production.
/// </summary>
public IList<IPEndPoint> SeedNodes { get; private set; }
/// <summary>
/// The subnet on which the silos run.
/// This option should only be used when running on multi-homed cluster. It should not be used when running in Azure.
/// </summary>
public byte[] Subnet { get; set; }
/// <summary>
/// Determines if primary node is required to be configured as a seed node.
/// True if LivenessType is set to MembershipTableGrain, false otherwise.
/// </summary>
public bool PrimaryNodeIsRequired
{
get { return LivenessType == LivenessProviderType.MembershipTableGrain; }
}
/// <summary>
/// Global switch to disable silo liveness protocol (should be used only for testing).
/// The LivenessEnabled attribute, if provided and set to "false", suppresses liveness enforcement.
/// If a silo is suspected to be dead, but this attribute is set to "false", the suspicions will not propagated to the system and enforced,
/// This parameter is intended for use only for testing and troubleshooting.
/// In production, liveness should always be enabled.
/// Default is true (eanabled)
/// </summary>
public bool LivenessEnabled { get; set; }
/// <summary>
/// The number of seconds to periodically probe other silos for their liveness or for the silo to send "I am alive" heartbeat messages about itself.
/// </summary>
public TimeSpan ProbeTimeout { get; set; }
/// <summary>
/// The number of seconds to periodically fetch updates from the membership table.
/// </summary>
public TimeSpan TableRefreshTimeout { get; set; }
/// <summary>
/// Expiration time in seconds for death vote in the membership table.
/// </summary>
public TimeSpan DeathVoteExpirationTimeout { get; set; }
/// <summary>
/// The number of seconds to periodically write in the membership table that this silo is alive. Used ony for diagnostics.
/// </summary>
public TimeSpan IAmAliveTablePublishTimeout { get; set; }
/// <summary>
/// The number of seconds to attempt to join a cluster of silos before giving up.
/// </summary>
public TimeSpan MaxJoinAttemptTime { get; set; }
internal ConfigValue<int> ExpectedClusterSizeConfigValue { get; set; }
/// <summary>
/// The expected size of a cluster. Need not be very accurate, can be an overestimate.
/// </summary>
public int ExpectedClusterSize { get { return ExpectedClusterSizeConfigValue.Value; } set { ExpectedClusterSizeConfigValue = new ConfigValue<int>(value, false); } }
/// <summary>
/// The number of missed "I am alive" heartbeat messages from a silo or number of un-replied probes that lead to suspecting this silo as dead.
/// </summary>
public int NumMissedProbesLimit { get; set; }
/// <summary>
/// The number of silos each silo probes for liveness.
/// </summary>
public int NumProbedSilos { get; set; }
/// <summary>
/// The number of non-expired votes that are needed to declare some silo as dead (should be at most NumMissedProbesLimit)
/// </summary>
public int NumVotesForDeathDeclaration { get; set; }
/// <summary>
/// The number of missed "I am alive" updates in the table from a silo that causes warning to be logged. Does not impact the liveness protocol.
/// </summary>
public int NumMissedTableIAmAliveLimit { get; set; }
/// <summary>
/// Whether to use the gossip optimization to speed up spreading liveness information.
/// </summary>
public bool UseLivenessGossip { get; set; }
/// <summary>
/// Whether new silo that joins the cluster has to validate the initial connectivity with all other Active silos.
/// </summary>
public bool ValidateInitialConnectivity { get; set; }
/// <summary>
/// Service Id.
/// </summary>
public Guid ServiceId { get; set; }
/// <summary>
/// Deployment Id.
/// </summary>
public string DeploymentId { get; set; }
#region MultiClusterNetwork
/// <summary>
/// Whether this cluster is configured to be part of a multicluster network
/// </summary>
public bool HasMultiClusterNetwork
{
get
{
return !(string.IsNullOrEmpty(ClusterId));
}
}
/// <summary>
/// Cluster id (one per deployment, unique across all the deployments/clusters)
/// </summary>
public string ClusterId { get; set; }
/// <summary>
///A list of cluster ids, to be used if no multicluster configuration is found in gossip channels.
/// </summary>
public IReadOnlyList<string> DefaultMultiCluster { get; set; }
/// <summary>
/// The maximum number of silos per cluster should be designated to serve as gateways.
/// </summary>
public int MaxMultiClusterGateways { get; set; }
/// <summary>
/// The number of seconds between background gossips.
/// </summary>
public TimeSpan BackgroundGossipInterval { get; set; }
/// <summary>
/// A list of connection strings for gossip channels.
/// </summary>
public IReadOnlyList<GossipChannelConfiguration> GossipChannels { get; set; }
#endregion
/// <summary>
/// Connection string for the underlying data provider for liveness and reminders. eg. Azure Storage, ZooKeeper, SQL Server, ect.
/// In order to override this value for reminders set <see cref="DataConnectionStringForReminders"/>
/// </summary>
public string DataConnectionString { get; set; }
/// <summary>
/// When using ADO, identifies the underlying data provider for liveness and reminders. This three-part naming syntax is also used
/// when creating a new factory and for identifying the provider in an application configuration file so that the provider name,
/// along with its associated connection string, can be retrieved at run time. https://msdn.microsoft.com/en-us/library/dd0w4a2z%28v=vs.110%29.aspx
/// In order to override this value for reminders set <see cref="AdoInvariantForReminders"/>
/// </summary>
public string AdoInvariant { get; set; }
/// <summary>
/// Set this property to override <see cref="DataConnectionString"/> for reminders.
/// </summary>
public string DataConnectionStringForReminders
{
get
{
return string.IsNullOrWhiteSpace(dataConnectionStringForReminders) ? DataConnectionString : dataConnectionStringForReminders;
}
set { dataConnectionStringForReminders = value; }
}
/// <summary>
/// Set this property to override <see cref="AdoInvariant"/> for reminders.
/// </summary>
public string AdoInvariantForReminders
{
get
{
return string.IsNullOrWhiteSpace(adoInvariantForReminders) ? AdoInvariant : adoInvariantForReminders;
}
set { adoInvariantForReminders = value; }
}
internal TimeSpan CollectionQuantum { get; set; }
/// <summary>
/// The CacheSize attribute specifies the maximum number of grains to cache directory information for.
/// </summary>
public int CacheSize { get; set; }
/// <summary>
/// The InitialTTL attribute specifies the initial (minimum) time, in seconds, to keep a cache entry before revalidating.
/// </summary>
public TimeSpan InitialCacheTTL { get; set; }
/// <summary>
/// The MaximumTTL attribute specifies the maximum time, in seconds, to keep a cache entry before revalidating.
/// </summary>
public TimeSpan MaximumCacheTTL { get; set; }
/// <summary>
/// The TTLExtensionFactor attribute specifies the factor by which cache entry TTLs should be extended when they are found to be stable.
/// </summary>
public double CacheTTLExtensionFactor { get; set; }
/// <summary>
/// Retry count for Azure Table operations.
/// </summary>
public int MaxStorageBusyRetries { get; private set; }
/// <summary>
/// The DirectoryCachingStrategy attribute specifies the caching strategy to use.
/// The options are None, which means don't cache directory entries locally;
/// LRU, which indicates that a standard fixed-size least recently used strategy should be used; and
/// Adaptive, which indicates that an adaptive strategy with a fixed maximum size should be used.
/// The Adaptive strategy is used by default.
/// </summary>
public DirectoryCachingStrategyType DirectoryCachingStrategy { get; set; }
public bool UseVirtualBucketsConsistentRing { get; set; }
public int NumVirtualBucketsConsistentRing { get; set; }
/// <summary>
/// The LivenessType attribute controls the liveness method used for silo reliability.
/// </summary>
private LivenessProviderType livenessServiceType;
public LivenessProviderType LivenessType
{
get
{
return livenessServiceType;
}
set
{
if (value == LivenessProviderType.NotSpecified)
throw new ArgumentException("Cannot set LivenessType to " + LivenessProviderType.NotSpecified, "LivenessType");
livenessServiceType = value;
}
}
/// <summary>
/// Assembly to use for custom MembershipTable implementation
/// </summary>
public string MembershipTableAssembly { get; set; }
/// <summary>
/// Assembly to use for custom ReminderTable implementation
/// </summary>
public string ReminderTableAssembly { get; set; }
/// <summary>
/// The ReminderServiceType attribute controls the type of the reminder service implementation used by silos.
/// </summary>
private ReminderServiceProviderType reminderServiceType;
public ReminderServiceProviderType ReminderServiceType
{
get
{
return reminderServiceType;
}
set
{
SetReminderServiceType(value);
}
}
// It's a separate function so we can clearly see when we set the value.
// With property you can't seaprate getter from setter in intellicense.
internal void SetReminderServiceType(ReminderServiceProviderType reminderType)
{
if (reminderType == ReminderServiceProviderType.NotSpecified)
throw new ArgumentException("Cannot set ReminderServiceType to " + ReminderServiceProviderType.NotSpecified, "ReminderServiceType");
reminderServiceType = reminderType;
}
public TimeSpan MockReminderTableTimeout { get; set; }
internal bool UseMockReminderTable;
/// <summary>
/// Configuration for various runtime providers.
/// </summary>
public IDictionary<string, ProviderCategoryConfiguration> ProviderConfigurations { get; set; }
/// <summary>
/// The time span between when we have added an entry for an activation to the grain directory and when we are allowed
/// to conditionally remove that entry.
/// Conditional deregistration is used for lazy clean-up of activations whose prompt deregistration failed for some reason (e.g., message failure).
/// This should always be at least one minute, since we compare the times on the directory partition, so message delays and clcks skues have
/// to be allowed.
/// </summary>
public TimeSpan DirectoryLazyDeregistrationDelay { get; set; }
public TimeSpan ClientRegistrationRefresh { get; set; }
internal bool PerformDeadlockDetection { get; set; }
public string DefaultPlacementStrategy { get; set; }
public string DefaultMultiClusterRegistrationStrategy { get; set; }
public TimeSpan DeploymentLoadPublisherRefreshTime { get; set; }
public int ActivationCountBasedPlacementChooseOutOf { get; set; }
/// <summary>
/// Determines if ADO should be used for storage of Membership and Reminders info.
/// True if either or both of LivenessType and ReminderServiceType are set to SqlServer, false otherwise.
/// </summary>
internal bool UseSqlSystemStore
{
get
{
return !String.IsNullOrWhiteSpace(DataConnectionString) && (
(LivenessEnabled && LivenessType == LivenessProviderType.SqlServer)
|| ReminderServiceType == ReminderServiceProviderType.SqlServer);
}
}
/// <summary>
/// Determines if ZooKeeper should be used for storage of Membership and Reminders info.
/// True if LivenessType is set to ZooKeeper, false otherwise.
/// </summary>
internal bool UseZooKeeperSystemStore
{
get
{
return !String.IsNullOrWhiteSpace(DataConnectionString) && (
(LivenessEnabled && LivenessType == LivenessProviderType.ZooKeeper));
}
}
/// <summary>
/// Determines if Azure Storage should be used for storage of Membership and Reminders info.
/// True if either or both of LivenessType and ReminderServiceType are set to AzureTable, false otherwise.
/// </summary>
internal bool UseAzureSystemStore
{
get
{
return !String.IsNullOrWhiteSpace(DataConnectionString)
&& !UseSqlSystemStore && !UseZooKeeperSystemStore;
}
}
internal bool RunsInAzure { get { return UseAzureSystemStore && !String.IsNullOrWhiteSpace(DeploymentId); } }
private static readonly TimeSpan DEFAULT_LIVENESS_PROBE_TIMEOUT = TimeSpan.FromSeconds(10);
private static readonly TimeSpan DEFAULT_LIVENESS_TABLE_REFRESH_TIMEOUT = TimeSpan.FromSeconds(60);
private static readonly TimeSpan DEFAULT_LIVENESS_DEATH_VOTE_EXPIRATION_TIMEOUT = TimeSpan.FromSeconds(120);
private static readonly TimeSpan DEFAULT_LIVENESS_I_AM_ALIVE_TABLE_PUBLISH_TIMEOUT = TimeSpan.FromMinutes(5);
private static readonly TimeSpan DEFAULT_LIVENESS_MAX_JOIN_ATTEMPT_TIME = TimeSpan.FromMinutes(5); // 5 min
private const int DEFAULT_LIVENESS_NUM_MISSED_PROBES_LIMIT = 3;
private const int DEFAULT_LIVENESS_NUM_PROBED_SILOS = 3;
private const int DEFAULT_LIVENESS_NUM_VOTES_FOR_DEATH_DECLARATION = 2;
private const int DEFAULT_LIVENESS_NUM_TABLE_I_AM_ALIVE_LIMIT = 2;
private const bool DEFAULT_LIVENESS_USE_LIVENESS_GOSSIP = true;
private const bool DEFAULT_VALIDATE_INITIAL_CONNECTIVITY = true;
private const int DEFAULT_MAX_MULTICLUSTER_GATEWAYS = 10;
private static readonly TimeSpan DEFAULT_BACKGROUND_GOSSIP_INTERVAL = TimeSpan.FromSeconds(30);
private const int DEFAULT_LIVENESS_EXPECTED_CLUSTER_SIZE = 20;
private const int DEFAULT_CACHE_SIZE = 1000000;
private static readonly TimeSpan DEFAULT_INITIAL_CACHE_TTL = TimeSpan.FromSeconds(30);
private static readonly TimeSpan DEFAULT_MAXIMUM_CACHE_TTL = TimeSpan.FromSeconds(240);
private const double DEFAULT_TTL_EXTENSION_FACTOR = 2.0;
private const DirectoryCachingStrategyType DEFAULT_DIRECTORY_CACHING_STRATEGY = DirectoryCachingStrategyType.Adaptive;
internal static readonly TimeSpan DEFAULT_COLLECTION_QUANTUM = TimeSpan.FromMinutes(1);
internal static readonly TimeSpan DEFAULT_COLLECTION_AGE_LIMIT = TimeSpan.FromHours(2);
public static bool ENFORCE_MINIMUM_REQUIREMENT_FOR_AGE_LIMIT = true;
private static readonly TimeSpan DEFAULT_UNREGISTER_RACE_DELAY = TimeSpan.FromMinutes(1);
private static readonly TimeSpan DEFAULT_CLIENT_REGISTRATION_REFRESH = TimeSpan.FromMinutes(5);
public const bool DEFAULT_PERFORM_DEADLOCK_DETECTION = false;
public static readonly string DEFAULT_PLACEMENT_STRATEGY = typeof(RandomPlacement).Name;
public static readonly string DEFAULT_MULTICLUSTER_REGISTRATION_STRATEGY = typeof(ClusterLocalRegistration).Name;
private static readonly TimeSpan DEFAULT_DEPLOYMENT_LOAD_PUBLISHER_REFRESH_TIME = TimeSpan.FromSeconds(1);
private const int DEFAULT_ACTIVATION_COUNT_BASED_PLACEMENT_CHOOSE_OUT_OF = 2;
private const bool DEFAULT_USE_VIRTUAL_RING_BUCKETS = true;
private const int DEFAULT_NUM_VIRTUAL_RING_BUCKETS = 30;
private static readonly TimeSpan DEFAULT_MOCK_REMINDER_TABLE_TIMEOUT = TimeSpan.FromMilliseconds(50);
private string dataConnectionStringForReminders;
private string adoInvariantForReminders;
internal GlobalConfiguration()
: base(true)
{
Application = new ApplicationConfiguration();
SeedNodes = new List<IPEndPoint>();
livenessServiceType = LivenessProviderType.NotSpecified;
LivenessEnabled = true;
ProbeTimeout = DEFAULT_LIVENESS_PROBE_TIMEOUT;
TableRefreshTimeout = DEFAULT_LIVENESS_TABLE_REFRESH_TIMEOUT;
DeathVoteExpirationTimeout = DEFAULT_LIVENESS_DEATH_VOTE_EXPIRATION_TIMEOUT;
IAmAliveTablePublishTimeout = DEFAULT_LIVENESS_I_AM_ALIVE_TABLE_PUBLISH_TIMEOUT;
NumMissedProbesLimit = DEFAULT_LIVENESS_NUM_MISSED_PROBES_LIMIT;
NumProbedSilos = DEFAULT_LIVENESS_NUM_PROBED_SILOS;
NumVotesForDeathDeclaration = DEFAULT_LIVENESS_NUM_VOTES_FOR_DEATH_DECLARATION;
NumMissedTableIAmAliveLimit = DEFAULT_LIVENESS_NUM_TABLE_I_AM_ALIVE_LIMIT;
UseLivenessGossip = DEFAULT_LIVENESS_USE_LIVENESS_GOSSIP;
ValidateInitialConnectivity = DEFAULT_VALIDATE_INITIAL_CONNECTIVITY;
MaxJoinAttemptTime = DEFAULT_LIVENESS_MAX_JOIN_ATTEMPT_TIME;
MaxMultiClusterGateways = DEFAULT_MAX_MULTICLUSTER_GATEWAYS;
BackgroundGossipInterval = DEFAULT_BACKGROUND_GOSSIP_INTERVAL;
ExpectedClusterSizeConfigValue = new ConfigValue<int>(DEFAULT_LIVENESS_EXPECTED_CLUSTER_SIZE, true);
ServiceId = Guid.Empty;
DeploymentId = Environment.UserName;
DataConnectionString = "";
// Assume the ado invariant is for sql server storage if not explicitly specified
AdoInvariant = Constants.INVARIANT_NAME_SQL_SERVER;
CollectionQuantum = DEFAULT_COLLECTION_QUANTUM;
CacheSize = DEFAULT_CACHE_SIZE;
InitialCacheTTL = DEFAULT_INITIAL_CACHE_TTL;
MaximumCacheTTL = DEFAULT_MAXIMUM_CACHE_TTL;
CacheTTLExtensionFactor = DEFAULT_TTL_EXTENSION_FACTOR;
DirectoryCachingStrategy = DEFAULT_DIRECTORY_CACHING_STRATEGY;
DirectoryLazyDeregistrationDelay = DEFAULT_UNREGISTER_RACE_DELAY;
ClientRegistrationRefresh = DEFAULT_CLIENT_REGISTRATION_REFRESH;
PerformDeadlockDetection = DEFAULT_PERFORM_DEADLOCK_DETECTION;
reminderServiceType = ReminderServiceProviderType.NotSpecified;
DefaultPlacementStrategy = DEFAULT_PLACEMENT_STRATEGY;
DefaultMultiClusterRegistrationStrategy = DEFAULT_MULTICLUSTER_REGISTRATION_STRATEGY;
DeploymentLoadPublisherRefreshTime = DEFAULT_DEPLOYMENT_LOAD_PUBLISHER_REFRESH_TIME;
ActivationCountBasedPlacementChooseOutOf = DEFAULT_ACTIVATION_COUNT_BASED_PLACEMENT_CHOOSE_OUT_OF;
UseVirtualBucketsConsistentRing = DEFAULT_USE_VIRTUAL_RING_BUCKETS;
NumVirtualBucketsConsistentRing = DEFAULT_NUM_VIRTUAL_RING_BUCKETS;
UseMockReminderTable = false;
MockReminderTableTimeout = DEFAULT_MOCK_REMINDER_TABLE_TIMEOUT;
ProviderConfigurations = new Dictionary<string, ProviderCategoryConfiguration>();
}
public override string ToString()
{
var sb = new StringBuilder();
sb.AppendFormat(" System Ids:").AppendLine();
sb.AppendFormat(" ServiceId: {0}", ServiceId).AppendLine();
sb.AppendFormat(" DeploymentId: {0}", DeploymentId).AppendLine();
sb.Append(" Subnet: ").Append(Subnet == null ? "" : Subnet.ToStrings(x => x.ToString(CultureInfo.InvariantCulture), ".")).AppendLine();
sb.Append(" Seed nodes: ");
bool first = true;
foreach (IPEndPoint node in SeedNodes)
{
if (!first)
{
sb.Append(", ");
}
sb.Append(node.ToString());
first = false;
}
sb.AppendLine();
sb.AppendFormat(base.ToString());
sb.AppendFormat(" Liveness:").AppendLine();
sb.AppendFormat(" LivenessEnabled: {0}", LivenessEnabled).AppendLine();
sb.AppendFormat(" LivenessType: {0}", LivenessType).AppendLine();
sb.AppendFormat(" ProbeTimeout: {0}", ProbeTimeout).AppendLine();
sb.AppendFormat(" TableRefreshTimeout: {0}", TableRefreshTimeout).AppendLine();
sb.AppendFormat(" DeathVoteExpirationTimeout: {0}", DeathVoteExpirationTimeout).AppendLine();
sb.AppendFormat(" NumMissedProbesLimit: {0}", NumMissedProbesLimit).AppendLine();
sb.AppendFormat(" NumProbedSilos: {0}", NumProbedSilos).AppendLine();
sb.AppendFormat(" NumVotesForDeathDeclaration: {0}", NumVotesForDeathDeclaration).AppendLine();
sb.AppendFormat(" UseLivenessGossip: {0}", UseLivenessGossip).AppendLine();
sb.AppendFormat(" ValidateInitialConnectivity: {0}", ValidateInitialConnectivity).AppendLine();
sb.AppendFormat(" IAmAliveTablePublishTimeout: {0}", IAmAliveTablePublishTimeout).AppendLine();
sb.AppendFormat(" NumMissedTableIAmAliveLimit: {0}", NumMissedTableIAmAliveLimit).AppendLine();
sb.AppendFormat(" MaxJoinAttemptTime: {0}", MaxJoinAttemptTime).AppendLine();
sb.AppendFormat(" ExpectedClusterSize: {0}", ExpectedClusterSize).AppendLine();
if (HasMultiClusterNetwork)
{
sb.AppendLine(" MultiClusterNetwork:");
sb.AppendFormat(" ClusterId: {0}", ClusterId ?? "").AppendLine();
sb.AppendFormat(" DefaultMultiCluster: {0}", DefaultMultiCluster != null ? string.Join(",", DefaultMultiCluster) : "null").AppendLine();
sb.AppendFormat(" MaxMultiClusterGateways: {0}", MaxMultiClusterGateways).AppendLine();
sb.AppendFormat(" BackgroundGossipInterval: {0}", BackgroundGossipInterval).AppendLine();
sb.AppendFormat(" GossipChannels: {0}", string.Join(",", GossipChannels.Select(conf => conf.ChannelType.ToString() + ":" + conf.ConnectionString))).AppendLine();
}
else
{
sb.AppendLine(" MultiClusterNetwork: N/A");
}
sb.AppendFormat(" SystemStore:").AppendLine();
// Don't print connection credentials in log files, so pass it through redactment filter
string connectionStringForLog = ConfigUtilities.RedactConnectionStringInfo(DataConnectionString);
sb.AppendFormat(" SystemStore ConnectionString: {0}", connectionStringForLog).AppendLine();
string remindersConnectionStringForLog = ConfigUtilities.RedactConnectionStringInfo(DataConnectionStringForReminders);
sb.AppendFormat(" Reminders ConnectionString: {0}", remindersConnectionStringForLog).AppendLine();
sb.Append(Application.ToString()).AppendLine();
sb.Append(" PlacementStrategy: ").AppendLine();
sb.Append(" ").Append(" Default Placement Strategy: ").Append(DefaultPlacementStrategy).AppendLine();
sb.Append(" ").Append(" Deployment Load Publisher Refresh Time: ").Append(DeploymentLoadPublisherRefreshTime).AppendLine();
sb.Append(" ").Append(" Activation CountBased Placement Choose Out Of: ").Append(ActivationCountBasedPlacementChooseOutOf).AppendLine();
sb.AppendFormat(" Grain directory cache:").AppendLine();
sb.AppendFormat(" Maximum size: {0} grains", CacheSize).AppendLine();
sb.AppendFormat(" Initial TTL: {0}", InitialCacheTTL).AppendLine();
sb.AppendFormat(" Maximum TTL: {0}", MaximumCacheTTL).AppendLine();
sb.AppendFormat(" TTL extension factor: {0:F2}", CacheTTLExtensionFactor).AppendLine();
sb.AppendFormat(" Directory Caching Strategy: {0}", DirectoryCachingStrategy).AppendLine();
sb.AppendFormat(" Grain directory:").AppendLine();
sb.AppendFormat(" Lazy deregistration delay: {0}", DirectoryLazyDeregistrationDelay).AppendLine();
sb.AppendFormat(" Client registration refresh: {0}", ClientRegistrationRefresh).AppendLine();
sb.AppendFormat(" Reminder Service:").AppendLine();
sb.AppendFormat(" ReminderServiceType: {0}", ReminderServiceType).AppendLine();
if (ReminderServiceType == ReminderServiceProviderType.MockTable)
{
sb.AppendFormat(" MockReminderTableTimeout: {0}ms", MockReminderTableTimeout.TotalMilliseconds).AppendLine();
}
sb.AppendFormat(" Consistent Ring:").AppendLine();
sb.AppendFormat(" Use Virtual Buckets Consistent Ring: {0}", UseVirtualBucketsConsistentRing).AppendLine();
sb.AppendFormat(" Num Virtual Buckets Consistent Ring: {0}", NumVirtualBucketsConsistentRing).AppendLine();
sb.AppendFormat(" Providers:").AppendLine();
sb.Append(ProviderConfigurationUtility.PrintProviderConfigurations(ProviderConfigurations));
return sb.ToString();
}
internal override void Load(XmlElement root)
{
var logger = LogManager.GetLogger("OrleansConfiguration", LoggerType.Runtime);
SeedNodes = new List<IPEndPoint>();
XmlElement child;
foreach (XmlNode c in root.ChildNodes)
{
child = c as XmlElement;
if (child != null && child.LocalName == "Networking")
{
Subnet = child.HasAttribute("Subnet")
? ConfigUtilities.ParseSubnet(child.GetAttribute("Subnet"), "Invalid Subnet")
: null;
}
}
foreach (XmlNode c in root.ChildNodes)
{
child = c as XmlElement;
if (child == null) continue; // Skip comment lines
switch (child.LocalName)
{
case "Liveness":
if (child.HasAttribute("LivenessEnabled"))
{
LivenessEnabled = ConfigUtilities.ParseBool(child.GetAttribute("LivenessEnabled"),
"Invalid boolean value for the LivenessEnabled attribute on the Liveness element");
}
if (child.HasAttribute("ProbeTimeout"))
{
ProbeTimeout = ConfigUtilities.ParseTimeSpan(child.GetAttribute("ProbeTimeout"),
"Invalid time value for the ProbeTimeout attribute on the Liveness element");
}
if (child.HasAttribute("TableRefreshTimeout"))
{
TableRefreshTimeout = ConfigUtilities.ParseTimeSpan(child.GetAttribute("TableRefreshTimeout"),
"Invalid time value for the TableRefreshTimeout attribute on the Liveness element");
}
if (child.HasAttribute("DeathVoteExpirationTimeout"))
{
DeathVoteExpirationTimeout = ConfigUtilities.ParseTimeSpan(child.GetAttribute("DeathVoteExpirationTimeout"),
"Invalid time value for the DeathVoteExpirationTimeout attribute on the Liveness element");
}
if (child.HasAttribute("NumMissedProbesLimit"))
{
NumMissedProbesLimit = ConfigUtilities.ParseInt(child.GetAttribute("NumMissedProbesLimit"),
"Invalid integer value for the NumMissedIAmAlive attribute on the Liveness element");
}
if (child.HasAttribute("NumProbedSilos"))
{
NumProbedSilos = ConfigUtilities.ParseInt(child.GetAttribute("NumProbedSilos"),
"Invalid integer value for the NumProbedSilos attribute on the Liveness element");
}
if (child.HasAttribute("NumVotesForDeathDeclaration"))
{
NumVotesForDeathDeclaration = ConfigUtilities.ParseInt(child.GetAttribute("NumVotesForDeathDeclaration"),
"Invalid integer value for the NumVotesForDeathDeclaration attribute on the Liveness element");
}
if (child.HasAttribute("UseLivenessGossip"))
{
UseLivenessGossip = ConfigUtilities.ParseBool(child.GetAttribute("UseLivenessGossip"),
"Invalid boolean value for the UseLivenessGossip attribute on the Liveness element");
}
if (child.HasAttribute("ValidateInitialConnectivity"))
{
ValidateInitialConnectivity = ConfigUtilities.ParseBool(child.GetAttribute("ValidateInitialConnectivity"),
"Invalid boolean value for the ValidateInitialConnectivity attribute on the Liveness element");
}
if (child.HasAttribute("IAmAliveTablePublishTimeout"))
{
IAmAliveTablePublishTimeout = ConfigUtilities.ParseTimeSpan(child.GetAttribute("IAmAliveTablePublishTimeout"),
"Invalid time value for the IAmAliveTablePublishTimeout attribute on the Liveness element");
}
if (child.HasAttribute("NumMissedTableIAmAliveLimit"))
{
NumMissedTableIAmAliveLimit = ConfigUtilities.ParseInt(child.GetAttribute("NumMissedTableIAmAliveLimit"),
"Invalid integer value for the NumMissedTableIAmAliveLimit attribute on the Liveness element");
}
if (child.HasAttribute("MaxJoinAttemptTime"))
{
MaxJoinAttemptTime = ConfigUtilities.ParseTimeSpan(child.GetAttribute("MaxJoinAttemptTime"),
"Invalid time value for the MaxJoinAttemptTime attribute on the Liveness element");
}
if (child.HasAttribute("ExpectedClusterSize"))
{
int expectedClusterSize = ConfigUtilities.ParseInt(child.GetAttribute("ExpectedClusterSize"),
"Invalid integer value for the ExpectedClusterSize attribute on the Liveness element");
ExpectedClusterSizeConfigValue = new ConfigValue<int>(expectedClusterSize, false);
}
break;
case "Azure":
case "SystemStore":
if (child.LocalName == "Azure")
{
// Log warning about deprecated <Azure> element, but then continue on to parse it for connection string info
logger.Warn(ErrorCode.SiloConfigDeprecated, "The Azure element has been deprecated -- use SystemStore element instead.");
}
if (child.HasAttribute("SystemStoreType"))
{
var sst = child.GetAttribute("SystemStoreType");
if (!"None".Equals(sst, StringComparison.InvariantCultureIgnoreCase))
{
LivenessType = (LivenessProviderType)Enum.Parse(typeof(LivenessProviderType), sst);
ReminderServiceProviderType reminderServiceProviderType;
SetReminderServiceType(Enum.TryParse(sst, out reminderServiceProviderType)
? reminderServiceProviderType
: ReminderServiceProviderType.Disabled);
}
}
if (child.HasAttribute("MembershipTableAssembly"))
{
MembershipTableAssembly = child.GetAttribute("MembershipTableAssembly");
if (LivenessType != LivenessProviderType.Custom)
throw new FormatException("SystemStoreType should be \"Custom\" when MembershipTableAssembly is specified");
if (MembershipTableAssembly.EndsWith(".dll"))
throw new FormatException("Use fully qualified assembly name for \"MembershipTableAssembly\"");
}
if (child.HasAttribute("ReminderTableAssembly"))
{
ReminderTableAssembly = child.GetAttribute("ReminderTableAssembly");
if (ReminderServiceType != ReminderServiceProviderType.Custom)
throw new FormatException("ReminderServiceType should be \"Custom\" when ReminderTableAssembly is specified");
if (ReminderTableAssembly.EndsWith(".dll"))
throw new FormatException("Use fully qualified assembly name for \"ReminderTableAssembly\"");
}
if (LivenessType == LivenessProviderType.Custom && string.IsNullOrEmpty(MembershipTableAssembly))
throw new FormatException("MembershipTableAssembly should be set when SystemStoreType is \"Custom\"");
if (ReminderServiceType == ReminderServiceProviderType.Custom && String.IsNullOrEmpty(ReminderTableAssembly))
throw new FormatException("ReminderTableAssembly should be set when ReminderServiceType is \"Custom\"");
if (child.HasAttribute("ServiceId"))
{
ServiceId = ConfigUtilities.ParseGuid(child.GetAttribute("ServiceId"),
"Invalid Guid value for the ServiceId attribute on the Azure element");
}
if (child.HasAttribute("DeploymentId"))
{
DeploymentId = child.GetAttribute("DeploymentId");
}
if (child.HasAttribute(Constants.DATA_CONNECTION_STRING_NAME))
{
DataConnectionString = child.GetAttribute(Constants.DATA_CONNECTION_STRING_NAME);
if (String.IsNullOrWhiteSpace(DataConnectionString))
{
throw new FormatException("SystemStore.DataConnectionString cannot be blank");
}
}
if (child.HasAttribute(Constants.DATA_CONNECTION_FOR_REMINDERS_STRING_NAME))
{
DataConnectionStringForReminders = child.GetAttribute(Constants.DATA_CONNECTION_FOR_REMINDERS_STRING_NAME);
if (String.IsNullOrWhiteSpace(DataConnectionStringForReminders))
{
throw new FormatException("SystemStore.DataConnectionStringForReminders cannot be blank");
}
}
if (child.HasAttribute(Constants.ADO_INVARIANT_NAME))
{
var adoInvariant = child.GetAttribute(Constants.ADO_INVARIANT_NAME);
if (String.IsNullOrWhiteSpace(adoInvariant))
{
throw new FormatException("SystemStore.AdoInvariant cannot be blank");
}
AdoInvariant = adoInvariant;
}
if (child.HasAttribute(Constants.ADO_INVARIANT_FOR_REMINDERS_NAME))
{
var adoInvariantForReminders = child.GetAttribute(Constants.ADO_INVARIANT_FOR_REMINDERS_NAME);
if (String.IsNullOrWhiteSpace(adoInvariantForReminders))
{
throw new FormatException("SystemStore.adoInvariantForReminders cannot be blank");
}
AdoInvariantForReminders = adoInvariantForReminders;
}
if (child.HasAttribute("MaxStorageBusyRetries"))
{
MaxStorageBusyRetries = ConfigUtilities.ParseInt(child.GetAttribute("MaxStorageBusyRetries"),
"Invalid integer value for the MaxStorageBusyRetries attribute on the SystemStore element");
}
if (child.HasAttribute("UseMockReminderTable"))
{
MockReminderTableTimeout = ConfigUtilities.ParseTimeSpan(child.GetAttribute("UseMockReminderTable"), "Invalid timeout value");
UseMockReminderTable = true;
}
break;
case "MultiClusterNetwork":
ClusterId = child.GetAttribute("ClusterId");
// we always trim cluster ids to avoid surprises when parsing comma-separated lists
if (ClusterId != null)
ClusterId = ClusterId.Trim();
if (string.IsNullOrEmpty(ClusterId))
throw new FormatException("MultiClusterNetwork.ClusterId cannot be blank");
if (ClusterId.Contains(","))
throw new FormatException("MultiClusterNetwork.ClusterId cannot contain commas: " + ClusterId);
if (child.HasAttribute("DefaultMultiCluster"))
{
var toparse = child.GetAttribute("DefaultMultiCluster").Trim();
if (string.IsNullOrEmpty(toparse))
{
DefaultMultiCluster = new List<string>(); // empty cluster
}
else
{
DefaultMultiCluster = toparse.Split(',').Select(id => id.Trim()).ToList();
foreach (var id in DefaultMultiCluster)
if (string.IsNullOrEmpty(id))
throw new FormatException("MultiClusterNetwork.DefaultMultiCluster cannot contain blank cluster ids: " + toparse);
}
}
if (child.HasAttribute("BackgroundGossipInterval"))
{
BackgroundGossipInterval = ConfigUtilities.ParseTimeSpan(child.GetAttribute("BackgroundGossipInterval"),
"Invalid time value for the BackgroundGossipInterval attribute on the MultiClusterNetwork element");
}
if (child.HasAttribute("MaxMultiClusterGateways"))
{
MaxMultiClusterGateways = ConfigUtilities.ParseInt(child.GetAttribute("MaxMultiClusterGateways"),
"Invalid time value for the MaxMultiClusterGateways attribute on the MultiClusterNetwork element");
}
var channels = new List<GossipChannelConfiguration>();
foreach (XmlNode childchild in child.ChildNodes)
{
var channelspec = childchild as XmlElement;
if (channelspec == null || channelspec.LocalName != "GossipChannel")
continue;
channels.Add(new GossipChannelConfiguration()
{
ChannelType = (GlobalConfiguration.GossipChannelType)
Enum.Parse(typeof(GlobalConfiguration.GossipChannelType), channelspec.GetAttribute("Type")),
ConnectionString = channelspec.GetAttribute("ConnectionString")
});
}
GossipChannels = channels;
break;
case "SeedNode":
SeedNodes.Add(ConfigUtilities.ParseIPEndPoint(child, Subnet).GetResult());
break;
case "Messaging":
base.Load(child);
break;
case "Application":
Application.Load(child, logger);
break;
case "PlacementStrategy":
if (child.HasAttribute("DefaultPlacementStrategy"))
DefaultPlacementStrategy = child.GetAttribute("DefaultPlacementStrategy");
if (child.HasAttribute("DeploymentLoadPublisherRefreshTime"))
DeploymentLoadPublisherRefreshTime = ConfigUtilities.ParseTimeSpan(child.GetAttribute("DeploymentLoadPublisherRefreshTime"),
"Invalid time span value for PlacementStrategy.DeploymentLoadPublisherRefreshTime");
if (child.HasAttribute("ActivationCountBasedPlacementChooseOutOf"))
ActivationCountBasedPlacementChooseOutOf = ConfigUtilities.ParseInt(child.GetAttribute("ActivationCountBasedPlacementChooseOutOf"),
"Invalid ActivationCountBasedPlacementChooseOutOf setting");
break;
case "Caching":
if (child.HasAttribute("CacheSize"))
CacheSize = ConfigUtilities.ParseInt(child.GetAttribute("CacheSize"),
"Invalid integer value for Caching.CacheSize");
if (child.HasAttribute("InitialTTL"))
InitialCacheTTL = ConfigUtilities.ParseTimeSpan(child.GetAttribute("InitialTTL"),
"Invalid time value for Caching.InitialTTL");
if (child.HasAttribute("MaximumTTL"))
MaximumCacheTTL = ConfigUtilities.ParseTimeSpan(child.GetAttribute("MaximumTTL"),
"Invalid time value for Caching.MaximumTTL");
if (child.HasAttribute("TTLExtensionFactor"))
CacheTTLExtensionFactor = ConfigUtilities.ParseDouble(child.GetAttribute("TTLExtensionFactor"),
"Invalid double value for Caching.TTLExtensionFactor");
if (CacheTTLExtensionFactor <= 1.0)
{
throw new FormatException("Caching.TTLExtensionFactor must be greater than 1.0");
}
if (child.HasAttribute("DirectoryCachingStrategy"))
DirectoryCachingStrategy = ConfigUtilities.ParseEnum<DirectoryCachingStrategyType>(child.GetAttribute("DirectoryCachingStrategy"),
"Invalid value for Caching.Strategy");
break;
case "Directory":
if (child.HasAttribute("DirectoryLazyDeregistrationDelay"))
{
DirectoryLazyDeregistrationDelay = ConfigUtilities.ParseTimeSpan(child.GetAttribute("DirectoryLazyDeregistrationDelay"),
"Invalid time span value for Directory.DirectoryLazyDeregistrationDelay");
}
if (child.HasAttribute("ClientRegistrationRefresh"))
{
ClientRegistrationRefresh = ConfigUtilities.ParseTimeSpan(child.GetAttribute("ClientRegistrationRefresh"),
"Invalid time span value for Directory.ClientRegistrationRefresh");
}
break;
default:
if (child.LocalName.EndsWith("Providers", StringComparison.Ordinal))
{
var providerCategory = ProviderCategoryConfiguration.Load(child);
if (ProviderConfigurations.ContainsKey(providerCategory.Name))
{
var existingCategory = ProviderConfigurations[providerCategory.Name];
existingCategory.Merge(providerCategory);
}
else
{
ProviderConfigurations.Add(providerCategory.Name, providerCategory);
}
}
break;
}
}
}
/// <summary>
/// Registers a given type of <typeparamref name="T"/> where <typeparamref name="T"/> is bootstrap provider
/// </summary>
/// <typeparam name="T">Non-abstract type which implements <see cref="IBootstrapProvider"/> interface</typeparam>
/// <param name="providerName">Name of the bootstrap provider</param>
/// <param name="properties">Properties that will be passed to bootstrap provider upon initialization</param>
public void RegisterBootstrapProvider<T>(string providerName, IDictionary<string, string> properties = null) where T : IBootstrapProvider
{
Type providerType = typeof(T);
var providerTypeInfo = providerType.GetTypeInfo();
if (providerTypeInfo.IsAbstract ||
providerTypeInfo.IsGenericType ||
!typeof(IBootstrapProvider).IsAssignableFrom(providerType))
throw new ArgumentException("Expected non-generic, non-abstract type which implements IBootstrapProvider interface", "typeof(T)");
ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.BOOTSTRAP_PROVIDER_CATEGORY_NAME, providerTypeInfo.FullName, providerName, properties);
}
/// <summary>
/// Registers a given bootstrap provider.
/// </summary>
/// <param name="providerTypeFullName">Full name of the bootstrap provider type</param>
/// <param name="providerName">Name of the bootstrap provider</param>
/// <param name="properties">Properties that will be passed to the bootstrap provider upon initialization </param>
public void RegisterBootstrapProvider(string providerTypeFullName, string providerName, IDictionary<string, string> properties = null)
{
ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.BOOTSTRAP_PROVIDER_CATEGORY_NAME, providerTypeFullName, providerName, properties);
}
/// <summary>
/// Registers a given type of <typeparamref name="T"/> where <typeparamref name="T"/> is stream provider
/// </summary>
/// <typeparam name="T">Non-abstract type which implements <see cref="IStreamProvider"/> stream</typeparam>
/// <param name="providerName">Name of the stream provider</param>
/// <param name="properties">Properties that will be passed to stream provider upon initialization</param>
public void RegisterStreamProvider<T>(string providerName, IDictionary<string, string> properties = null) where T : Orleans.Streams.IStreamProvider
{
Type providerType = typeof(T);
var providerTypeInfo = providerType.GetTypeInfo();
if (providerTypeInfo.IsAbstract ||
providerTypeInfo.IsGenericType ||
!typeof(Orleans.Streams.IStreamProvider).IsAssignableFrom(providerType))
throw new ArgumentException("Expected non-generic, non-abstract type which implements IStreamProvider interface", "typeof(T)");
ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.STREAM_PROVIDER_CATEGORY_NAME, providerType.FullName, providerName, properties);
}
/// <summary>
/// Registers a given stream provider.
/// </summary>
/// <param name="providerTypeFullName">Full name of the stream provider type</param>
/// <param name="providerName">Name of the stream provider</param>
/// <param name="properties">Properties that will be passed to the stream provider upon initialization </param>
public void RegisterStreamProvider(string providerTypeFullName, string providerName, IDictionary<string, string> properties = null)
{
ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.STREAM_PROVIDER_CATEGORY_NAME, providerTypeFullName, providerName, properties);
}
/// <summary>
/// Registers a given type of <typeparamref name="T"/> where <typeparamref name="T"/> is storage provider
/// </summary>
/// <typeparam name="T">Non-abstract type which implements <see cref="IStorageProvider"/> storage</typeparam>
/// <param name="providerName">Name of the storage provider</param>
/// <param name="properties">Properties that will be passed to storage provider upon initialization</param>
public void RegisterStorageProvider<T>(string providerName, IDictionary<string, string> properties = null) where T : IStorageProvider
{
Type providerType = typeof(T);
var providerTypeInfo = providerType.GetTypeInfo();
if (providerTypeInfo.IsAbstract ||
providerTypeInfo.IsGenericType ||
!typeof(IStorageProvider).IsAssignableFrom(providerType))
throw new ArgumentException("Expected non-generic, non-abstract type which implements IStorageProvider interface", "typeof(T)");
ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.STORAGE_PROVIDER_CATEGORY_NAME, providerTypeInfo.FullName, providerName, properties);
}
/// <summary>
/// Registers a given storage provider.
/// </summary>
/// <param name="providerTypeFullName">Full name of the storage provider type</param>
/// <param name="providerName">Name of the storage provider</param>
/// <param name="properties">Properties that will be passed to the storage provider upon initialization </param>
public void RegisterStorageProvider(string providerTypeFullName, string providerName, IDictionary<string, string> properties = null)
{
ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.STORAGE_PROVIDER_CATEGORY_NAME, providerTypeFullName, providerName, properties);
}
/// <summary>
/// Retrieves an existing provider configuration
/// </summary>
/// <param name="providerTypeFullName">Full name of the stream provider type</param>
/// <param name="providerName">Name of the stream provider</param>
/// <param name="config">The provider configuration, if exists</param>
/// <returns>True if a configuration for this provider already exists, false otherwise.</returns>
public bool TryGetProviderConfiguration(string providerTypeFullName, string providerName, out IProviderConfiguration config)
{
return ProviderConfigurationUtility.TryGetProviderConfiguration(ProviderConfigurations, providerTypeFullName, providerName, out config);
}
/// <summary>
/// Retrieves an enumeration of all currently configured provider configurations.
/// </summary>
/// <returns>An enumeration of all currently configured provider configurations.</returns>
public IEnumerable<IProviderConfiguration> GetAllProviderConfigurations()
{
return ProviderConfigurationUtility.GetAllProviderConfigurations(ProviderConfigurations);
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using EasyRoads3D;
public class RoadObjectScript : MonoBehaviour {
static public string version = "";
public int objectType = 0;
public bool displayRoad = true;
public float roadWidth = 5.0f;
public float indent = 3.0f;
public float surrounding = 5.0f;
public float raise = 1.0f;
public float raiseMarkers = 0.5f;
public bool OOQDOOQQ = false;
public bool renderRoad = true;
public bool beveledRoad = false;
public bool applySplatmap = false;
public int splatmapLayer = 4;
public bool autoUpdate = true;
public float geoResolution = 5.0f;
public int roadResolution = 1;
public float tuw = 15.0f;
public int splatmapSmoothLevel;
public float opacity = 1.0f;
public int expand = 0;
public int offsetX = 0;
public int offsetY = 0;
private Material surfaceMaterial;
public float surfaceOpacity = 1.0f;
public float smoothDistance = 1.0f;
public float smoothSurDistance = 3.0f;
private bool handleInsertFlag;
public bool handleVegetation = true;
public float OCOCODCCDD = 2.0f;
public float ODDQODQCOO = 1f;
public int materialType = 0;
String[] materialStrings;
public string uname;
public string email;
private MarkerScript[] mSc;
private bool OODODDCDQQ;
private bool[] OQDDCQCCDQ = null;
private bool[] OODQCQCDQO = null;
public string[] ODODQCCDOC;
public string[] ODODQOQO;
public int[] ODODQOQOInt;
public int ODDDQCOOQD = -1;
public int OODQCOQQQQ = -1;
static public GUISkin OODCOCOOCC;
static public GUISkin OQQQCCOOOQ;
public bool OCDCOQDCDQ = false;
private Vector3 cPos;
private Vector3 ePos;
public bool ODQQCDQDQD;
static public Texture2D OQQOCCQOOC;
public int markers = 1;
public OCQCDCCDOC OQCODQCQOC;
private GameObject ODOQDQOO;
public bool OOCQCCQOQQ;
public bool doTerrain;
private Transform ODQDODOODQ = null;
public GameObject[] ODQDODOODQs;
private static string OCDQCCOCOC = null;
public Transform obj;
private string OQQODDQQOO;
public static string erInit = "";
static public Transform OQCQDODCQQ;
private RoadObjectScript ODOOCQDQCD;
public bool flyby;
private Vector3 pos;
private float fl;
private float oldfl;
private bool OQDDDDCCQC;
private bool OCOCQOQDQQ;
private bool OCQOOQCQQD;
public Transform OCCQOQDDDO;
public int OdQODQOD = 1;
public float OOQQQDOD = 0f;
public float OOQQQDODOffset = 0f;
public float OOQQQDODLength = 0f;
public bool ODODDDOO = false;
static public string[] ODOQDOQO;
static public string[] ODODOQQO;
static public string[] ODODQOOQ;
public int ODQDOOQO = 0;
public string[] ODQQQQQO;
public string[] ODODDQOO;
public bool[] ODODQQOD;
public int[] OOQQQOQO;
public int ODOQOOQO = 0;
public bool forceY = false;
public float yChange = 0f;
public float floorDepth = 2f;
public float waterLevel = 1.5f;
public bool lockWaterLevel = true;
public float lastY = 0f;
public string distance = "0";
public string markerDisplayStr = "Hide Markers";
static public string[] objectStrings;
public string objectText = "Road";
public bool applyAnimation = false;
public float waveSize = 1.5f;
public float waveHeight = 0.15f;
public bool snapY = true;
private TextAnchor origAnchor;
public bool autoODODDQQO;
public Texture2D roadTexture;
public Texture2D roadMaterial;
public string[] OQDDOCDDOO;
public string[] OCCCCCOOOQ;
public int selectedWaterMaterial;
public int selectedWaterScript;
private bool doRestore = false;
public bool doFlyOver;
public static GameObject tracer;
public Camera goCam;
public float speed = 1f;
public float offset = 0f;
public bool camInit;
public GameObject customMesh = null;
static public bool disableFreeAlerts = true;
public bool multipleTerrains;
public bool editRestore = true;
public Material roadMaterialEdit;
static public int backupLocation = 0;
public string[] backupStrings = new string[2]{"Outside Assets folder path","Inside Assets folder path"};
public Vector3[] leftVecs = new Vector3[0];
public Vector3[] rightVecs = new Vector3[0];
public bool applyTangents = false;
public bool sosBuild = false;
public float splinePos = 0;
public float camHeight = 3;
public Vector3 splinePosV3 = Vector3.zero;
public bool iOS = false;
public void OCOOCQODQD(List<ODODDQQO> arr, String[] DOODQOQO, String[] OODDQOQO){
ODOODDDODD(transform, arr, DOODQOQO, OODDQOQO);
}
public void OQCDCQOQDO(MarkerScript markerScript){
ODQDODOODQ = markerScript.transform;
List<GameObject> tmp = new List<GameObject>();
for(int i=0;i<ODQDODOODQs.Length;i++){
if(ODQDODOODQs[i] != markerScript.gameObject)tmp.Add(ODQDODOODQs[i]);
}
tmp.Add(markerScript.gameObject);
ODQDODOODQs = tmp.ToArray();
ODQDODOODQ = markerScript.transform;
OQCODQCQOC.OQQDCQDOCD(ODQDODOODQ, ODQDODOODQs, markerScript.OQCQOQCQCC, markerScript.OQDOCODDQO, OCCQOQDDDO, out markerScript.ODQDODOODQs, out markerScript.trperc, ODQDODOODQs);
OODQCOQQQQ = -1;
}
public void ODCCCDCCDQ(MarkerScript markerScript){
if(markerScript.OQDOCODDQO != markerScript.ODOOQQOO || markerScript.OQDOCODDQO != markerScript.ODOOQQOO){
OQCODQCQOC.OQQDCQDOCD(ODQDODOODQ, ODQDODOODQs, markerScript.OQCQOQCQCC, markerScript.OQDOCODDQO, OCCQOQDDDO, out markerScript.ODQDODOODQs, out markerScript.trperc, ODQDODOODQs);
markerScript.ODQDOQOO = markerScript.OQCQOQCQCC;
markerScript.ODOOQQOO = markerScript.OQDOCODDQO;
}
if(ODOOCQDQCD.autoUpdate) OQDODQOODQ(ODOOCQDQCD.geoResolution, false, false);
}
public void ResetMaterials(MarkerScript markerScript){
if(OQCODQCQOC != null)OQCODQCQOC.OQQDCQDOCD(ODQDODOODQ, ODQDODOODQs, markerScript.OQCQOQCQCC, markerScript.OQDOCODDQO, OCCQOQDDDO, out markerScript.ODQDODOODQs, out markerScript.trperc, ODQDODOODQs);
}
public void ODOODCODQC(MarkerScript markerScript){
if(markerScript.OQDOCODDQO != markerScript.ODOOQQOO){
OQCODQCQOC.OQQDCQDOCD(ODQDODOODQ, ODQDODOODQs, markerScript.OQCQOQCQCC, markerScript.OQDOCODDQO, OCCQOQDDDO, out markerScript.ODQDODOODQs, out markerScript.trperc, ODQDODOODQs);
markerScript.ODOOQQOO = markerScript.OQDOCODDQO;
}
OQDODQOODQ(ODOOCQDQCD.geoResolution, false, false);
}
private void ODDQODCQDQ(string ctrl, MarkerScript markerScript){
int i = 0;
foreach(Transform tr in markerScript.ODQDODOODQs){
MarkerScript wsScript = (MarkerScript) tr.GetComponent<MarkerScript>();
if(ctrl == "rs") wsScript.LeftSurrounding(markerScript.rs - markerScript.ODOQQOOO, markerScript.trperc[i]);
else if(ctrl == "ls") wsScript.RightSurrounding(markerScript.ls - markerScript.DODOQQOO, markerScript.trperc[i]);
else if(ctrl == "ri") wsScript.LeftIndent(markerScript.ri - markerScript.OOQOQQOO, markerScript.trperc[i]);
else if(ctrl == "li") wsScript.RightIndent(markerScript.li - markerScript.ODODQQOO, markerScript.trperc[i]);
else if(ctrl == "rt") wsScript.LeftTilting(markerScript.rt - markerScript.ODDQODOO, markerScript.trperc[i]);
else if(ctrl == "lt") wsScript.RightTilting(markerScript.lt - markerScript.ODDOQOQQ, markerScript.trperc[i]);
else if(ctrl == "floorDepth") wsScript.FloorDepth(markerScript.floorDepth - markerScript.oldFloorDepth, markerScript.trperc[i]);
i++;
}
}
public void OQQOCCDODC(){
if(markers > 1) OQDODQOODQ(ODOOCQDQCD.geoResolution, false, false);
}
public void ODOODDDODD(Transform tr, List<ODODDQQO> arr, String[] DOODQOQO, String[] OODDQOQO){
version = "2.5.6";
OODCOCOOCC = (GUISkin)Resources.Load("ER3DSkin", typeof(GUISkin));
OQQOCCQOOC = (Texture2D)Resources.Load("ER3DLogo", typeof(Texture2D));
if(RoadObjectScript.objectStrings == null){
RoadObjectScript.objectStrings = new string[3];
RoadObjectScript.objectStrings[0] = "Road Object"; RoadObjectScript.objectStrings[1]="River Object";RoadObjectScript.objectStrings[2]="Procedural Mesh Object";
}
obj = tr;
OQCODQCQOC = new OCQCDCCDOC();
ODOOCQDQCD = obj.GetComponent<RoadObjectScript>();
foreach(Transform child in obj){
if(child.name == "Markers") OCCQOQDDDO = child;
}
RoadObjectScript[] rscrpts = (RoadObjectScript[])FindObjectsOfType(typeof(RoadObjectScript));
OCQCDCCDOC.terrainList.Clear();
Terrain[] terrains = (Terrain[])FindObjectsOfType(typeof(Terrain));
foreach(Terrain terrain in terrains) {
Terrains t = new Terrains();
t.terrain = terrain;
if(!terrain.gameObject.GetComponent<EasyRoads3DTerrainID>()){
EasyRoads3DTerrainID terrainscript = (EasyRoads3DTerrainID)terrain.gameObject.AddComponent("EasyRoads3DTerrainID");
string id = UnityEngine.Random.Range(100000000,999999999).ToString();
terrainscript.terrainid = id;
t.id = id;
}else{
t.id = terrain.gameObject.GetComponent<EasyRoads3DTerrainID>().terrainid;
}
OQCODQCQOC.OQOOCOCDDQ(t);
}
OQCDOODQQQ.OQOOCOCDDQ();
if(roadMaterialEdit == null){
roadMaterialEdit = (Material)Resources.Load("materials/roadMaterialEdit", typeof(Material));
}
if(objectType == 0 && GameObject.Find(gameObject.name + "/road") == null){
GameObject road = new GameObject("road");
road.transform.parent = transform;
}
OQCODQCQOC.OQQDOCCQCD(obj, OCDQCCOCOC, ODOOCQDQCD.roadWidth, surfaceOpacity, out ODQQCDQDQD, out indent, applyAnimation, waveSize, waveHeight);
OQCODQCQOC.ODDQODQCOO = ODDQODQCOO;
OQCODQCQOC.OCOCODCCDD = OCOCODCCDD;
OQCODQCQOC.OdQODQOD = OdQODQOD + 1;
OQCODQCQOC.OOQQQDOD = OOQQQDOD;
OQCODQCQOC.OOQQQDODOffset = OOQQQDODOffset;
OQCODQCQOC.OOQQQDODLength = OOQQQDODLength;
OQCODQCQOC.objectType = objectType;
OQCODQCQOC.snapY = snapY;
OQCODQCQOC.terrainRendered = OOCQCCQOQQ;
OQCODQCQOC.handleVegetation = handleVegetation;
OQCODQCQOC.raise = raise;
OQCODQCQOC.roadResolution = roadResolution;
OQCODQCQOC.multipleTerrains = multipleTerrains;
OQCODQCQOC.editRestore = editRestore;
OQCODQCQOC.roadMaterialEdit = roadMaterialEdit;
OQCODQCQOC.renderRoad = renderRoad;
OQCODQCQOC.rscrpts = rscrpts.Length;
if(backupLocation == 0)OOCDCOQDQC.backupFolder = "/EasyRoads3D";
else OOCDCOQDQC.backupFolder = "/Assets/EasyRoads3D/backups";
ODODQOQO = OQCODQCQOC.ODDDCOQDCC();
ODODQOQOInt = OQCODQCQOC.OCDDCDCCQD();
if(OOCQCCQOQQ){
doRestore = true;
}
ODDCCCQCOC();
if(arr != null || ODODQOOQ == null) OOCQQQQQQQ(arr, DOODQOQO, OODDQOQO);
if(doRestore) return;
}
public void UpdateBackupFolder(){
}
public void OODODDQDOQ(){
if(!ODODDDOO || objectType == 2){
if(OQDDCQCCDQ != null){
for(int i = 0; i < OQDDCQCCDQ.Length; i++){
OQDDCQCCDQ[i] = false;
OODQCQCDQO[i] = false;
}
}
}
}
public void OOOCOOQCOD(Vector3 pos){
if(!displayRoad){
displayRoad = true;
OQCODQCQOC.OQOCOCCQOC(displayRoad, OCCQOQDDDO);
}
pos.y += ODOOCQDQCD.raiseMarkers;
if(forceY && ODOQDQOO != null){
float dist = Vector3.Distance(pos, ODOQDQOO.transform.position);
pos.y = ODOQDQOO.transform.position.y + (yChange * (dist / 100f));
}else if(forceY && markers == 0) lastY = pos.y;
GameObject go = null;
if(ODOQDQOO != null) go = (GameObject)Instantiate(ODOQDQOO);
else go = (GameObject)Instantiate(Resources.Load("marker", typeof(GameObject)));
Transform newnode = go.transform;
newnode.position = pos;
newnode.parent = OCCQOQDDDO;
markers++;
string n;
if(markers < 10) n = "Marker000" + markers.ToString();
else if (markers < 100) n = "Marker00" + markers.ToString();
else n = "Marker0" + markers.ToString();
newnode.gameObject.name = n;
MarkerScript scr = newnode.GetComponent<MarkerScript>();
scr.ODQQCDQDQD = false;
scr.objectScript = obj.GetComponent<RoadObjectScript>();
if(ODOQDQOO == null){
scr.waterLevel = ODOOCQDQCD.waterLevel;
scr.floorDepth = ODOOCQDQCD.floorDepth;
scr.ri = ODOOCQDQCD.indent;
scr.li = ODOOCQDQCD.indent;
scr.rs = ODOOCQDQCD.surrounding;
scr.ls = ODOOCQDQCD.surrounding;
scr.tension = 0.5f;
if(objectType == 1){
pos.y -= waterLevel;
newnode.position = pos;
}
}
if(objectType == 2){
#if UNITY_3_5
if(scr.surface != null)scr.surface.gameObject.active = false;
#else
if(scr.surface != null)scr.surface.gameObject.SetActive(false);
#endif
}
ODOQDQOO = newnode.gameObject;
if(markers > 1){
OQDODQOODQ(ODOOCQDQCD.geoResolution, false, false);
if(materialType == 0){
OQCODQCQOC.ODODDDCCOQ(materialType);
}
}
}
public void OQDODQOODQ(float geo, bool renderMode, bool camMode){
OQCODQCQOC.OQQOODDODO.Clear();
int ii = 0;
ODQDQDQCDQ k;
foreach(Transform child in obj)
{
if(child.name == "Markers"){
foreach(Transform marker in child) {
MarkerScript markerScript = marker.GetComponent<MarkerScript>();
markerScript.objectScript = obj.GetComponent<RoadObjectScript>();
if(!markerScript.ODQQCDQDQD) markerScript.ODQQCDQDQD = OQCODQCQOC.OOODQCODOC(marker);
k = new ODQDQDQCDQ();
k.position = marker.position;
k.num = OQCODQCQOC.OQQOODDODO.Count;
k.object1 = marker;
k.object2 = markerScript.surface;
k.tension = markerScript.tension;
k.ri = markerScript.ri;
if(k.ri < 1)k.ri = 1f;
k.li =markerScript.li;
if(k.li < 1)k.li = 1f;
k.rt = markerScript.rt;
k.lt = markerScript.lt;
k.rs = markerScript.rs;
if(k.rs < 1)k.rs = 1f;
k.OQCCOQQQQO = markerScript.rs;
k.ls = markerScript.ls;
if(k.ls < 1)k.ls = 1f;
k.OQQOOODQCC = markerScript.ls;
k.renderFlag = markerScript.bridgeObject;
k.OCOCCCCCQQ = markerScript.distHeights;
k.newSegment = markerScript.newSegment;
k.tunnelFlag = markerScript.tunnelFlag;
k.floorDepth = markerScript.floorDepth;
k.waterLevel = waterLevel;
k.lockWaterLevel = markerScript.lockWaterLevel;
k.sharpCorner = markerScript.sharpCorner;
k.OCDQOQOCOC = OQCODQCQOC;
markerScript.markerNum = ii;
markerScript.distance = "-1";
markerScript.OCOCCDDCOD = "-1";
OQCODQCQOC.OQQOODDODO.Add(k);
ii++;
}
}
}
distance = "-1";
OQCODQCQOC.OOQCQCQOCO = ODOOCQDQCD.roadWidth;
OQCODQCQOC.OQODCDQQDC(geo, obj, ODOOCQDQCD.OOQDOOQQ, renderMode, camMode, objectType);
if(OQCODQCQOC.leftVecs.Count > 0){
leftVecs = OQCODQCQOC.leftVecs.ToArray();
rightVecs = OQCODQCQOC.rightVecs.ToArray();
}
}
public void StartCam(){
OQDODQOODQ(0.5f, false, true);
}
public void ODDCCCQCOC(){
int i = 0;
foreach(Transform child in obj)
{
if(child.name == "Markers"){
i = 1;
string n;
foreach(Transform marker in child) {
if(i < 10) n = "Marker000" + i.ToString();
else if (i < 100) n = "Marker00" + i.ToString();
else n = "Marker0" + i.ToString();
marker.name = n;
ODOQDQOO = marker.gameObject;
i++;
}
}
}
markers = i - 1;
OQDODQOODQ(ODOOCQDQCD.geoResolution, false, false);
}
public List<Transform> RebuildObjs(){
RoadObjectScript[] scripts = (RoadObjectScript[])FindObjectsOfType(typeof(RoadObjectScript));
List<Transform> rObj = new List<Transform>();
foreach (RoadObjectScript script in scripts) {
if(script.transform != transform) rObj.Add(script.transform);
}
return rObj;
}
public void RestoreTerrain1(){
OQDODQOODQ(ODOOCQDQCD.geoResolution, false, false);
if(OQCODQCQOC != null) OQCODQCQOC.OQCODQODOQ();
ODODDDOO = false;
}
public void OQCCOODCDO(){
OQCODQCQOC.OQCCOODCDO(ODOOCQDQCD.applySplatmap, ODOOCQDQCD.splatmapSmoothLevel, ODOOCQDQCD.renderRoad, ODOOCQDQCD.tuw, ODOOCQDQCD.roadResolution, ODOOCQDQCD.raise, ODOOCQDQCD.opacity, ODOOCQDQCD.expand, ODOOCQDQCD.offsetX, ODOOCQDQCD.offsetY, ODOOCQDQCD.beveledRoad, ODOOCQDQCD.splatmapLayer, ODOOCQDQCD.OdQODQOD, OOQQQDOD, OOQQQDODOffset, OOQQQDODLength);
}
public void OQQOCOQQOC(){
OQCODQCQOC.OQQOCOQQOC(ODOOCQDQCD.renderRoad, ODOOCQDQCD.tuw, ODOOCQDQCD.roadResolution, ODOOCQDQCD.raise, ODOOCQDQCD.beveledRoad, ODOOCQDQCD.OdQODQOD, OOQQQDOD, OOQQQDODOffset, OOQQQDODLength);
}
public void ODDCCQDCQC(Vector3 pos, bool doInsert){
if(!displayRoad){
displayRoad = true;
OQCODQCQOC.OQOCOCCQOC(displayRoad, OCCQOQDDDO);
}
int first = -1;
int second = -1;
float dist1 = 10000;
float dist2 = 10000;
Vector3 newpos = pos;
ODQDQDQCDQ k;
ODQDQDQCDQ k1 = (ODQDQDQCDQ)OQCODQCQOC.OQQOODDODO[0];
ODQDQDQCDQ k2 = (ODQDQDQCDQ)OQCODQCQOC.OQQOODDODO[1];
OQCODQCQOC.OOQQDCQQCQ(pos, out first, out second, out dist1, out dist2, out k1, out k2, out newpos);
pos = newpos;
if(doInsert && first >= 0 && second >= 0){
if(ODOOCQDQCD.OOQDOOQQ && second == OQCODQCQOC.OQQOODDODO.Count - 1){
OOOCOOQCOD(pos);
}else{
k = (ODQDQDQCDQ)OQCODQCQOC.OQQOODDODO[second];
string name = k.object1.name;
string n;
int j = second + 2;
for(int i = second; i < OQCODQCQOC.OQQOODDODO.Count - 1; i++){
k = (ODQDQDQCDQ)OQCODQCQOC.OQQOODDODO[i];
if(j < 10) n = "Marker000" + j.ToString();
else if (j < 100) n = "Marker00" + j.ToString();
else n = "Marker0" + j.ToString();
k.object1.name = n;
j++;
}
k = (ODQDQDQCDQ)OQCODQCQOC.OQQOODDODO[first];
Transform newnode = (Transform)Instantiate(k.object1.transform, pos, k.object1.rotation);
newnode.gameObject.name = name;
newnode.parent = OCCQOQDDDO;
#if UNITY_4_5
newnode.SetSiblingIndex(second);
#elif UNITY_4_6
newnode.SetSiblingIndex(second);
#endif
MarkerScript scr = newnode.GetComponent<MarkerScript>();
scr.ODQQCDQDQD = false;
float totalDist = dist1 + dist2;
float perc1 = dist1 / totalDist;
float paramDif = k1.ri - k2.ri;
scr.ri = k1.ri - (paramDif * perc1);
paramDif = k1.li - k2.li;
scr.li = k1.li - (paramDif * perc1);
paramDif = k1.rt - k2.rt;
scr.rt = k1.rt - (paramDif * perc1);
paramDif = k1.lt - k2.lt;
scr.lt = k1.lt - (paramDif * perc1);
paramDif = k1.rs - k2.rs;
scr.rs = k1.rs - (paramDif * perc1);
paramDif = k1.ls - k2.ls;
scr.ls = k1.ls - (paramDif * perc1);
OQDODQOODQ(ODOOCQDQCD.geoResolution, false, false);
if(materialType == 0)OQCODQCQOC.ODODDDCCOQ(materialType);
#if UNITY_3_5
if(objectType == 2) scr.surface.gameObject.active = false;
#else
if(objectType == 2) scr.surface.gameObject.SetActive(false);
#endif
}
}
ODDCCCQCOC();
}
public void OQQDCOQODO(){
DestroyImmediate(ODOOCQDQCD.ODQDODOODQ.gameObject);
ODQDODOODQ = null;
ODDCCCQCOC();
}
public void ODCDDDOCDO(){
}
public List<SideObjectParams> ODDDDCDDOC(){
return null;
}
public void OQDCCDDCDQ(){
}
public void OOCQQQQQQQ(List<ODODDQQO> arr, String[] DOODQOQO, String[] OODDQOQO){
}
public bool CheckWaterHeights(){
if(OQCDOODQQQ.terrain == null) return false;
bool flag = true;
float y = OQCDOODQQQ.terrain.transform.position.y;
foreach(Transform child in obj) {
if(child.name == "Markers"){
foreach(Transform marker in child) {
//MarkerScript markerScript = marker.GetComponent<MarkerScript>();
if(marker.position.y - y <= 0.1f) flag = false;
}
}
}
return flag;
}
}
| |
/*
* UltraCart Rest API V2
*
* UltraCart REST API Version 2
*
* OpenAPI spec version: 2.0.0
* Contact: [email protected]
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter;
namespace com.ultracart.admin.v2.Model
{
/// <summary>
/// CustomerCard
/// </summary>
[DataContract]
public partial class CustomerCard : IEquatable<CustomerCard>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="CustomerCard" /> class.
/// </summary>
/// <param name="cardExpirationMonth">Card expiration month (1-12).</param>
/// <param name="cardExpirationYear">Card expiration year (four digit year).</param>
/// <param name="cardNumber">Card number (masked to the last 4).</param>
/// <param name="cardNumberToken">Hosted field token for the card number.</param>
/// <param name="cardType">Card type.</param>
/// <param name="customerProfileCreditCardId">ID of the stored credit card to use.</param>
/// <param name="customerProfileOid">Customer profile object identifier.</param>
/// <param name="lastUsedDts">Last used date.</param>
public CustomerCard(int? cardExpirationMonth = default(int?), int? cardExpirationYear = default(int?), string cardNumber = default(string), string cardNumberToken = default(string), string cardType = default(string), int? customerProfileCreditCardId = default(int?), int? customerProfileOid = default(int?), string lastUsedDts = default(string))
{
this.CardExpirationMonth = cardExpirationMonth;
this.CardExpirationYear = cardExpirationYear;
this.CardNumber = cardNumber;
this.CardNumberToken = cardNumberToken;
this.CardType = cardType;
this.CustomerProfileCreditCardId = customerProfileCreditCardId;
this.CustomerProfileOid = customerProfileOid;
this.LastUsedDts = lastUsedDts;
}
/// <summary>
/// Card expiration month (1-12)
/// </summary>
/// <value>Card expiration month (1-12)</value>
[DataMember(Name="card_expiration_month", EmitDefaultValue=false)]
public int? CardExpirationMonth { get; set; }
/// <summary>
/// Card expiration year (four digit year)
/// </summary>
/// <value>Card expiration year (four digit year)</value>
[DataMember(Name="card_expiration_year", EmitDefaultValue=false)]
public int? CardExpirationYear { get; set; }
/// <summary>
/// Card number (masked to the last 4)
/// </summary>
/// <value>Card number (masked to the last 4)</value>
[DataMember(Name="card_number", EmitDefaultValue=false)]
public string CardNumber { get; set; }
/// <summary>
/// Hosted field token for the card number
/// </summary>
/// <value>Hosted field token for the card number</value>
[DataMember(Name="card_number_token", EmitDefaultValue=false)]
public string CardNumberToken { get; set; }
/// <summary>
/// Card type
/// </summary>
/// <value>Card type</value>
[DataMember(Name="card_type", EmitDefaultValue=false)]
public string CardType { get; set; }
/// <summary>
/// ID of the stored credit card to use
/// </summary>
/// <value>ID of the stored credit card to use</value>
[DataMember(Name="customer_profile_credit_card_id", EmitDefaultValue=false)]
public int? CustomerProfileCreditCardId { get; set; }
/// <summary>
/// Customer profile object identifier
/// </summary>
/// <value>Customer profile object identifier</value>
[DataMember(Name="customer_profile_oid", EmitDefaultValue=false)]
public int? CustomerProfileOid { get; set; }
/// <summary>
/// Last used date
/// </summary>
/// <value>Last used date</value>
[DataMember(Name="last_used_dts", EmitDefaultValue=false)]
public string LastUsedDts { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class CustomerCard {\n");
sb.Append(" CardExpirationMonth: ").Append(CardExpirationMonth).Append("\n");
sb.Append(" CardExpirationYear: ").Append(CardExpirationYear).Append("\n");
sb.Append(" CardNumber: ").Append(CardNumber).Append("\n");
sb.Append(" CardNumberToken: ").Append(CardNumberToken).Append("\n");
sb.Append(" CardType: ").Append(CardType).Append("\n");
sb.Append(" CustomerProfileCreditCardId: ").Append(CustomerProfileCreditCardId).Append("\n");
sb.Append(" CustomerProfileOid: ").Append(CustomerProfileOid).Append("\n");
sb.Append(" LastUsedDts: ").Append(LastUsedDts).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as CustomerCard);
}
/// <summary>
/// Returns true if CustomerCard instances are equal
/// </summary>
/// <param name="input">Instance of CustomerCard to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(CustomerCard input)
{
if (input == null)
return false;
return
(
this.CardExpirationMonth == input.CardExpirationMonth ||
(this.CardExpirationMonth != null &&
this.CardExpirationMonth.Equals(input.CardExpirationMonth))
) &&
(
this.CardExpirationYear == input.CardExpirationYear ||
(this.CardExpirationYear != null &&
this.CardExpirationYear.Equals(input.CardExpirationYear))
) &&
(
this.CardNumber == input.CardNumber ||
(this.CardNumber != null &&
this.CardNumber.Equals(input.CardNumber))
) &&
(
this.CardNumberToken == input.CardNumberToken ||
(this.CardNumberToken != null &&
this.CardNumberToken.Equals(input.CardNumberToken))
) &&
(
this.CardType == input.CardType ||
(this.CardType != null &&
this.CardType.Equals(input.CardType))
) &&
(
this.CustomerProfileCreditCardId == input.CustomerProfileCreditCardId ||
(this.CustomerProfileCreditCardId != null &&
this.CustomerProfileCreditCardId.Equals(input.CustomerProfileCreditCardId))
) &&
(
this.CustomerProfileOid == input.CustomerProfileOid ||
(this.CustomerProfileOid != null &&
this.CustomerProfileOid.Equals(input.CustomerProfileOid))
) &&
(
this.LastUsedDts == input.LastUsedDts ||
(this.LastUsedDts != null &&
this.LastUsedDts.Equals(input.LastUsedDts))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.CardExpirationMonth != null)
hashCode = hashCode * 59 + this.CardExpirationMonth.GetHashCode();
if (this.CardExpirationYear != null)
hashCode = hashCode * 59 + this.CardExpirationYear.GetHashCode();
if (this.CardNumber != null)
hashCode = hashCode * 59 + this.CardNumber.GetHashCode();
if (this.CardNumberToken != null)
hashCode = hashCode * 59 + this.CardNumberToken.GetHashCode();
if (this.CardType != null)
hashCode = hashCode * 59 + this.CardType.GetHashCode();
if (this.CustomerProfileCreditCardId != null)
hashCode = hashCode * 59 + this.CustomerProfileCreditCardId.GetHashCode();
if (this.CustomerProfileOid != null)
hashCode = hashCode * 59 + this.CustomerProfileOid.GetHashCode();
if (this.LastUsedDts != null)
hashCode = hashCode * 59 + this.LastUsedDts.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
// 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 Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Source
{
public sealed class ExpressionBodiedMethodTests : CSharpTestBase
{
[ClrOnlyFact]
public void PartialMethods()
{
var comp = CompileAndVerify(@"
public partial class C
{
static partial void foo() => System.Console.WriteLine(""test"");
}
public partial class C
{
public static void Main(string[] args)
{
foo();
}
static partial void foo();
}
", sourceSymbolValidator: m =>
{
var fooDef = m.GlobalNamespace
.GetMember<NamedTypeSymbol>("C")
.GetMember<SourceMemberMethodSymbol>("foo");
Assert.True(fooDef.IsPartial);
Assert.True(fooDef.IsPartialDefinition);
Assert.False(fooDef.IsPartialImplementation);
Assert.Null(fooDef.PartialDefinitionPart);
var fooImpl = fooDef.PartialImplementationPart
as SourceMemberMethodSymbol;
Assert.NotNull(fooImpl);
Assert.True(fooImpl.IsPartial);
Assert.True(fooImpl.IsPartialImplementation);
Assert.False(fooImpl.IsPartialDefinition);
Assert.True(fooImpl.IsExpressionBodied);
},
expectedOutput: "test");
}
[Fact(Skip = "973907")]
public void Syntax01()
{
// Feature is enabled by default
var comp = CreateCompilationWithMscorlib(@"
class C
{
public int M() => 1;
}");
comp.VerifyDiagnostics();
}
[Fact]
public void Syntax02()
{
var comp = CreateCompilationWithMscorlib45(@"
class C
{
public int M() {} => 1;
}");
comp.VerifyDiagnostics(
// (4,5): error CS8056: Methods cannot combine block bodies with expression bodies.
// public int M() {} => 1;
Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, "public int M() {} => 1;").WithLocation(4, 5),
// (4,16): error CS0161: 'C.M()': not all code paths return a value
// public int M() {} => 1;
Diagnostic(ErrorCode.ERR_ReturnExpected, "M").WithArguments("C.M()").WithLocation(4, 16));
}
[Fact]
public void Syntax03()
{
var comp = CreateCompilationWithMscorlib45(@"
interface C
{
int M() => 1;
}");
comp.VerifyDiagnostics(
// (4,9): error CS0531: 'C.M()': interface members cannot have a definition
// int M() => 1;
Diagnostic(ErrorCode.ERR_InterfaceMemberHasBody, "M").WithArguments("C.M()").WithLocation(4, 9));
}
[Fact]
public void Syntax04()
{
var comp = CreateCompilationWithMscorlib45(@"
abstract class C
{
public abstract int M() => 1;
}");
comp.VerifyDiagnostics(
// (4,23): error CS0500: 'C.M()' cannot declare a body because it is marked abstract
// public abstract int M() => 1;
Diagnostic(ErrorCode.ERR_AbstractHasBody, "M").WithArguments("C.M()").WithLocation(4, 23));
}
[Fact]
public void Syntax05()
{
var comp = CreateCompilationWithMscorlib45(@"
class C
{
public abstract int M() => 1;
}");
comp.VerifyDiagnostics(
// (4,24): error CS0500: 'C.M()' cannot declare a body because it is marked abstract
// public abstract int M() => 1;
Diagnostic(ErrorCode.ERR_AbstractHasBody, "M").WithArguments("C.M()").WithLocation(4, 24),
// (4,24): error CS0513: 'C.M()' is abstract but it is contained in non-abstract class 'C'
// public abstract int M() => 1;
Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "M").WithArguments("C.M()", "C").WithLocation(4, 24));
}
[Fact]
public void Syntax06()
{
var comp = CreateCompilationWithMscorlib45(@"
abstract class C
{
abstract int M() => 1;
}");
comp.VerifyDiagnostics(
// (4,17): error CS0500: 'C.M()' cannot declare a body because it is marked abstract
// abstract int M() => 1;
Diagnostic(ErrorCode.ERR_AbstractHasBody, "M").WithArguments("C.M()").WithLocation(4, 17),
// (4,17): error CS0621: 'C.M()': virtual or abstract members cannot be private
// abstract int M() => 1;
Diagnostic(ErrorCode.ERR_VirtualPrivate, "M").WithArguments("C.M()").WithLocation(4, 17));
}
[Fact]
[WorkItem(1009638, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1009638")]
public void Syntax07()
{
var comp = CreateCompilationWithMscorlib45(@"
public class C {
public bool IsNull<T>(T t) where T : class => t != null;
}");
comp.VerifyDiagnostics();
}
[Fact]
[WorkItem(1029117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1029117")]
public void Syntax08()
{
var comp = CreateCompilationWithMscorlib45(@"
namespace MyNamespace
{
public partial struct Foo
{
public double Bar => 0;
}
public partial struct Foo
{
}
}");
comp.VerifyDiagnostics();
}
[Fact]
public void LambdaTest01()
{
var comp = CreateCompilationWithMscorlib45(@"
using System;
class C
{
public Func<int, Func<int, int>> M() => x => y => x + y;
}");
comp.VerifyDiagnostics();
}
[Fact]
public void SimpleTest()
{
var text = @"
class C
{
public int P => 2;
public int M() => P;
public static explicit operator C(int i) => new C();
public static C operator++(C c) => (C)c.M();
}";
var comp = CreateCompilationWithMscorlib45(text);
comp.VerifyDiagnostics();
var global = comp.GlobalNamespace;
var c = global.GetTypeMember("C");
var m = c.GetMember<SourceMethodSymbol>("M");
Assert.False(m.IsImplicitlyDeclared);
Assert.True(m.IsExpressionBodied);
var pp = c.GetMember<SourceUserDefinedOperatorSymbol>("op_Increment");
Assert.False(pp.IsImplicitlyDeclared);
Assert.True(pp.IsExpressionBodied);
var conv = c.GetMember<SourceUserDefinedConversionSymbol>("op_Explicit");
Assert.False(conv.IsImplicitlyDeclared);
Assert.True(conv.IsExpressionBodied);
}
[Fact]
public void Override01()
{
var comp = CreateCompilationWithMscorlib45(@"
class B
{
public virtual int M() { return 0; }
}
class C : B
{
public override int M() => 1;
}").VerifyDiagnostics();
}
[Fact]
public void VoidExpression()
{
var comp = CreateCompilationWithMscorlib45(@"
class C
{
public void M() => System.Console.WriteLine(""foo"");
}").VerifyDiagnostics();
}
[Fact]
public void VoidExpression2()
{
var comp = CreateCompilationWithMscorlib45(@"
class C
{
public int M() => System.Console.WriteLine(""foo"");
}").VerifyDiagnostics(
// (4,23): error CS0029: Cannot implicitly convert type 'void' to 'int'
// public int M() => System.Console.WriteLine("foo");
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"System.Console.WriteLine(""foo"")").WithArguments("void", "int").WithLocation(4, 23));
}
[Fact]
public void InterfaceImplementation01()
{
var comp = CreateCompilationWithMscorlib45(@"
interface I
{
int M();
string N();
}
internal interface J
{
string N();
}
internal interface K
{
decimal O();
}
class C : I, J, K
{
public int M() => 10;
string I.N() => ""foo"";
string J.N() => ""bar"";
public decimal O() => M();
}");
comp.VerifyDiagnostics();
var global = comp.GlobalNamespace;
var i = global.GetTypeMember("I");
var j = global.GetTypeMember("J");
var k = global.GetTypeMember("K");
var c = global.GetTypeMember("C");
var iM = i.GetMember<SourceMethodSymbol>("M");
var iN = i.GetMember<SourceMethodSymbol>("N");
var jN = j.GetMember<SourceMethodSymbol>("N");
var method = c.GetMember<SourceMethodSymbol>("M");
var implements = method.ContainingType.FindImplementationForInterfaceMember(iM);
Assert.Equal(implements, method);
method = (SourceMethodSymbol)c.GetMethod("I.N");
implements = c.FindImplementationForInterfaceMember(iN);
Assert.True(method.IsExplicitInterfaceImplementation);
Assert.Equal(implements, method);
method = (SourceMethodSymbol)c.GetMethod("J.N");
implements = c.FindImplementationForInterfaceMember(jN);
Assert.True(method.IsExplicitInterfaceImplementation);
Assert.Equal(implements, method);
method = c.GetMember<SourceMethodSymbol>("O");
Assert.False(method.IsExplicitInterfaceImplementation);
}
[ClrOnlyFact]
public void Emit01()
{
var comp = CreateCompilationWithMscorlib45(@"
abstract class A
{
protected abstract string Z();
}
abstract class B : A
{
protected sealed override string Z() => ""foo"";
protected abstract string Y();
}
class C : B
{
public const int X = 2;
public static int M(int x) => x * x;
public int N() => X;
private int O() => M(N()) * N();
protected sealed override string Y() => Z() + O();
public static void Main()
{
System.Console.WriteLine(C.X);
System.Console.WriteLine(C.M(C.X));
var c = new C();
System.Console.WriteLine(c.N());
System.Console.WriteLine(c.O());
System.Console.WriteLine(c.Z());
System.Console.WriteLine(c.Y());
}
}", options: TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.Internal));
var verifier = CompileAndVerify(comp, expectedOutput:
@"2
4
2
8
foo
foo8");
}
[ClrOnlyFact]
public void Emit02()
{
var comp = CreateCompilationWithMscorlib45(@"
class C
{
public void M() { System.Console.WriteLine(""Hello""); }
public void M(int i) { System.Console.WriteLine(i); }
public string N(string s) { return s; }
public static void Main()
{
var c = new C();
c.M();
c.M(2);
System.Console.WriteLine(c.N(""World""));
}
}", options: TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.Internal));
var verifier = CompileAndVerify(comp, expectedOutput:
@"Hello
2
World");
}
[Fact]
public void RefReturningExpressionBodiedMethod()
{
var comp = CreateCompilationWithMscorlib45(@"
class C
{
int field = 0;
public ref int M() => ref field;
}");
comp.VerifyDiagnostics();
}
}
}
| |
using System;
using System.Collections;
using Inform;
using System.Data.SqlTypes;
using Xenosynth.Web;
using System.Data;
using Xenosynth.Modules.Cms;
using System.Web;
using System.Web.SessionState;
namespace Xenosynth.Web.UI {
/// <summary>
/// A CmsWebDirectory is a general directory type for cms content.
/// </summary>
[TypeMapping(BaseType = typeof(CmsDirectory))]
public class CmsWebDirectory : CmsDirectory, IHttpHandler, IRequiresSessionState {
[MemberMapping(ColumnName = "TemplateGalleryID", AllowNulls = true)]
private SqlGuid templateGalleryID;
[MemberMapping(ColumnName = "ImageGalleryID", AllowNulls = true)]
private SqlGuid imageGalleryID;
private static Guid typeID = new Guid("f18a7ba6-99e7-44ce-bee5-aa26888b0a12");
public CmsWebDirectory()
: base(typeID) {
}
/// <summary>
/// Whether this directory has a restricted set of templates.
/// </summary>
public bool HasTemplateGallery {
get {
return !this.templateGalleryID.IsNull;
}
}
/// <summary>
/// The ID of the restricted template gallery.
/// </summary>
public Guid TemplateGalleryID {
get {
if (templateGalleryID.IsNull) {
return Guid.Empty;
} else {
return templateGalleryID.Value;
}
}
set {
if (value.Equals(Guid.Empty)) {
templateGalleryID = SqlGuid.Null;
} else {
templateGalleryID = new SqlGuid(value);
}
}
}
/// <summary>
/// Whether this directory has a restricted image gallery.
/// </summary>
public bool HasImageGallery {
get {
return !this.imageGalleryID.IsNull;
}
}
/// <summary>
/// The ID of the restricted image gallery.
/// </summary>
public Guid ImageGalleryID {
get {
if (imageGalleryID.IsNull) {
return Guid.Empty;
} else {
return imageGalleryID.Value;
}
}
set {
if (value.Equals(Guid.Empty)) {
imageGalleryID = SqlGuid.Null;
} else {
imageGalleryID = new SqlGuid(value);
}
}
}
/// <summary>
/// Whether this directory has any CmsPages.
/// </summary>
internal bool HasAnyPages {
get {
CmsPageCollection pages = CmsPage.FindByDirectoryID(this.ID);
return pages.Count > 0;
}
}
/// <summary>
/// Whether this directory has any subdirectories.
/// </summary>
internal bool HasSubdirectories {
get {
return Subdirectories.Count > 0;
}
}
/// <summary>
/// Returns a collection of pages under this directory.
/// </summary>
public CmsPageCollection Pages {
//TODO: Cached?
get { return CmsPage.FindByDirectoryID(this.ID); }
}
/// <summary>
/// Returns a collection of directories under this directory that are not hidden.
/// </summary>
public CmsPageCollection DisplayedPages {
get { return new CmsPageCollection(FindDisplayed(Pages)); }
}
/// <summary>
/// The default file for this directory.
/// </summary>
public override CmsFile DefaultFile {
get {
CmsFile f = CmsFile.FindByFullPath(this.fullPath + "/" + CmsConfiguration.Current.DefaultPageName);
if (f == null && this.HasAnyPages) {
f = this.Pages[0];
}
return f;
}
}
/// <summary>
/// The default page for this directory. This method may be deprecated.
/// </summary>
public CmsPage DefaultPage {
//TODO: Expand this logic!
get {
CmsPage p = (CmsPage)CmsPage.FindByFullPath(this.fullPath + "/" + CmsConfiguration.Current.DefaultPageName);
if (p == null && this.HasAnyPages) {
p = this.Pages[0];
}
return p;
}
}
//public override bool IsVirtual {
// get {
// return true;
// }
//}
/// <summary>
/// Finds a CmsWebDirectory by ID.
/// </summary>
/// <param name="id">
/// A <see cref="Guid"/>
/// </param>
/// <returns>
/// A <see cref="CmsWebDirectory"/>
/// </returns>
public new static CmsWebDirectory FindByID(Guid id) {
DataStore ds = DataStoreServices.GetDataStore("Xenosynth");
return (CmsWebDirectory)ds.FindByPrimaryKey(typeof(CmsWebDirectory), id);
}
/// <summary>
/// Find a CmsWebDirectory by ID.
/// </summary>
/// <param name="id">
/// A <see cref="System.String"/>
/// </param>
/// <returns>
/// A <see cref="CmsWebDirectory"/>
/// </returns>
public static CmsWebDirectory FindByID(string id) {
return FindByID(new Guid(id));
}
/// <summary>
/// Finds a CmsWebDirectory by the full path from its root.
/// </summary>
/// <param name="path">
/// A <see cref="System.String"/>
/// </param>
/// <returns>
/// A <see cref="CmsWebDirectory"/>
/// </returns>
public static CmsWebDirectory FindByFullPath(string path) {
DataStore ds = DataStoreServices.GetDataStore("Xenosynth");
IFindObjectCommand cmd = ds.CreateFindObjectCommand(typeof(CmsWebDirectory), "WHERE FullPath = @FullPath", true);
cmd.CreateInputParameter("@FullPath", path.TrimEnd('/'));
return (CmsWebDirectory)cmd.Execute();
}
internal static void RemoveGallery(Guid templateGalleryID) {
DataStore ds = DataStoreServices.GetDataStore("Xenosynth");
IDataAccessCommand cmd = ds.CreateDataAccessCommand("UPDATE CmsDirectories SET TemplateGalleryID = NULL WHERE TemplateGalleryID = @TemplateGalleryID");
cmd.CreateInputParameter("@TemplateGalleryID", templateGalleryID);
cmd.ExecuteNonQuery();
}
/// <summary>
/// Finds all pages in this directory using a specified template.
/// </summary>
/// <param name="template">
/// A <see cref="CmsTemplate"/>
/// </param>
/// <returns>
/// A <see cref="IList"/>
/// </returns>
public IList FindPagesByTemplate(CmsTemplate template) {
return FindPagesByTemplate(template, false);
}
/// <summary>
/// Finds all pages in this directory, or recursively, using the specified template.
/// </summary>
/// <param name="template">
/// A <see cref="CmsTemplate"/>
/// </param>
/// <param name="recursive">
/// A <see cref="System.Boolean"/>
/// </param>
/// <returns>
/// A <see cref="IList"/>
/// </returns>
public IList FindPagesByTemplate(CmsTemplate template, bool recursive) {
//TODO: Faster search! Recursive?
ArrayList selectedPages = new ArrayList();
if (template != null) {
CmsFileCollection files;
if (recursive) {
files = this.Files;
} else {
files = this.Pages;
}
foreach (CmsFile f in files) {
if (f is CmsPage) {
CmsPage p = (CmsPage)f;
if (p.TemplateID == template.ID) {
selectedPages.Add(p);
}
} else if (f is CmsWebDirectory) {
CmsWebDirectory d = (CmsWebDirectory)f;
selectedPages.AddRange(d.FindPagesByTemplate(template, true));
}
}
}
return selectedPages;
}
/// <summary>
/// Finds all CmsWebDirectories.
/// </summary>
/// <returns>
/// A <see cref="CmsFileCollection"/>
/// </returns>
public static CmsFileCollection FindAll() {
DataStore ds = DataStoreServices.GetDataStore("Xenosynth");
IFindCollectionCommand cmd = ds.CreateFindCollectionCommand(typeof(CmsWebDirectory), "ORDER BY FullPath", true);
return new CmsFileCollection(cmd.Execute());
}
/// <summary>
/// Finds all deleted files from this directory.
/// </summary>
/// <returns>
/// A <see cref="CmsFileCollection"/>
/// </returns>
public CmsFileCollection FindDeletedFiles() {
DataStore ds = DataStoreServices.GetDataStore("Xenosynth");
IFindCollectionCommand cmd = ds.CreateFindCollectionCommand(typeof(CmsFile), "WHERE State = @State AND CmsFiles.ID NOT IN (SELECT CmsFiles.RevisionSourceID FROM CmsFiles WHERE NOT CmsFiles.RevisionSourceID IS NULL) ORDER BY FullPath", true);
cmd.CreateInputParameter("@State", CmsState.Deleted);
return new CmsFileCollection(cmd.Execute());
}
public CmsFileCollection SearchFiles(string text) {
//TODO: Restrict to Directory
string filter = @"
WHERE
(
Title Like @Text
OR CmsFiles.ID IN (
SELECT PageID
FROM LiteralDataItems
WHERE Text Like @Text
)
) AND CmsFiles.ID NOT IN (
SELECT RevisionSourceID
FROM CmsPages
WHERE NOT RevisionSourceID IS NULL
) ORDER BY FullPath";
DataStore ds = DataStoreServices.GetDataStore("Xenosynth");
IFindCollectionCommand cmd = ds.CreateFindCollectionCommand(typeof(CmsFile), filter, true);
cmd.CreateInputParameter("@Text", FormatSearchString(text));
return new CmsFileCollection(cmd.Execute());
}
private string FormatSearchString(string s) {
if (s == null) {
return "%";
} else {
return "%" + s.Replace("*", "%") + "%";
}
}
/// <summary>
/// Searches this directory for CmsPages. Requires enabling full-text search.
/// </summary>
/// <param name="searchTerm">
/// A <see cref="System.String"/>
/// </param>
/// <returns>
/// A <see cref="SearchResultCollection"/>
/// </returns>
public SearchResultCollection SearchPages(string searchTerm) {
//TODO: Restrict to Directory
string query = @"
SELECT TOP 1000
CmsFiles.Title,
CmsFiles.FullPath,
CmsFiles.ID As VersionID,
ISNULL(LiteralDataItemsSearchResults.Rank, 0)
+ ISNULL(CmsPagesSearchResults.Rank, 0) * 3 +
+ ISNULL(CmsFilesSearchResults.Rank,0) * 2 As Rank
FROM CmsFiles
INNER JOIN CmsPages
ON CmsFiles.ID = CmsPages.ID
LEFT OUTER JOIN
(
SELECT PageID, SUM(Rank) As Rank
FROM FREETEXTTABLE(LiteralDataItems, *, @SearchTerm) AS GroupedSearchResults
INNER JOIN LiteralDataItems
ON LiteralDataItems.LiteralItemID = GroupedSearchResults.[Key]
GROUP BY PageID
) AS LiteralDataItemsSearchResults
ON LiteralDataItemsSearchResults.PageID = CmsFiles.ID
LEFT OUTER JOIN
FREETEXTTABLE(CmsPages, *, @SearchTerm) AS CmsPagesSearchResults
ON CmsPages.ID = CmsPagesSearchResults.[Key]
LEFT OUTER JOIN
FREETEXTTABLE(CmsFiles, *, @SearchTerm) AS CmsFilesSearchResults
ON CmsFiles.ID = CmsFilesSearchResults.[Key]
WHERE CmsFiles.State = 200 AND
ISNULL(LiteralDataItemsSearchResults.Rank, 0)
+ ISNULL(CmsPagesSearchResults.Rank,0)
+ ISNULL(CmsFilesSearchResults.Rank,0) > 0
ORDER BY
ISNULL(LiteralDataItemsSearchResults.Rank, 0)
+ ISNULL(CmsPagesSearchResults.Rank,0) * 3
+ ISNULL(CmsFilesSearchResults.Rank,0) * 2 DESC";
DataStore ds = DataStoreServices.GetDataStore("Xenosynth");
IFindCollectionCommand cmd = ds.CreateFindCollectionCommand(typeof(SearchResult), query);
cmd.CreateInputParameter("@SearchTerm", FormatSearchString(searchTerm));
return new SearchResultCollection(cmd.Execute());
}
public DateTime FindLastFileUpdated(bool includeSubdirectories) {
string sql;
DataStore ds = DataStoreServices.GetDataStore("Xenosynth");
if (includeSubdirectories) {
sql = @"
SELECT MAX(DateModified)
FROM CmsFiles
WHERE FullPath LIKE @FullPath
";
IDataAccessCommand cmd = ds.CreateDataAccessCommand(sql);
cmd.CreateInputParameter("@FullPath", this.FullPath + '%');
return (DateTime)cmd.ExecuteScalar();
} else {
sql = @"
SELECT MAX(DateModified)
FROM CmsFiles
WHERE ParentID LIKE @ParentID
";
IDataAccessCommand cmd = ds.CreateDataAccessCommand(sql);
cmd.CreateInputParameter("@ParentID", this.ID);
return (DateTime)cmd.ExecuteScalar();
}
}
/// <summary>
/// Finds the root directory for a WebSite.
/// </summary>
/// <param name="siteID">
/// A <see cref="Guid"/>
/// </param>
/// <returns>
/// A <see cref="CmsWebDirectory"/>
/// </returns>
public static CmsWebDirectory FindRootForSite(Guid siteID) {
DataStore ds = DataStoreServices.GetDataStore("Xenosynth");
IFindObjectCommand cmd = ds.CreateFindObjectCommand(typeof(CmsWebDirectory), "WHERE CmsFiles.ID = (SELECT RootWebDirectoryID FROM xs_WebSites WHERE xs_WebSites.ID = @SiteID) ", true);
cmd.CreateInputParameter("@SiteID", siteID);
return (CmsWebDirectory)cmd.Execute();
}
/// <summary>
/// Finds the root directory for a host header.
/// </summary>
/// <param name="hostHeaderName">
/// A <see cref="System.String"/>
/// </param>
/// <returns>
/// A <see cref="CmsWebDirectory"/>
/// </returns>
public static CmsWebDirectory FindCmsDirectory(string hostHeaderName) {
HostHeaderMapping hhm = HostHeaderMapping.FindHostHeaderMapping(hostHeaderName);
if (hhm != null) {
WebSite site = WebSite.FindByID(hhm.WebSiteID);
return CmsWebDirectory.FindByID(site.RootWebDirectoryID);
} else {
return null;
}
}
/// <summary>
/// This method supports the Xenosynth CMS Module and is not intended to be used directly from your code.
/// </summary>
/// <param name="url">
/// A <see cref="System.String"/>
/// </param>
/// <returns>
/// A <see cref="IHttpHandler"/>
/// </returns>
public override IHttpHandler GetHandler(string url) {
return this;
}
#region IHttpHandler Members
/// <summary>
/// This class supports the Xenosynth CMS Module and is not intended to be used directly from your code.
/// </summary>
public bool IsReusable {
get { return false; }
}
/// <summary>
/// This method supports the Xenosynth CMS Module and is not intended to be used directly from your code.
/// </summary>
/// <param name="context">
/// A <see cref="HttpContext"/>
/// </param>
public void ProcessRequest(HttpContext context) {
if (this.DefaultFileName != null) {
if (!context.Request.FilePath.EndsWith("/")) {
context.Response.Redirect(context.Request.FilePath + "/");
}
CmsHttpContext.Current.TransferRequest(this.DefaultFile);
} else {
throw new HttpException(404, "File '" + context.Request.FilePath + "' not found.");
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsCompositeBoolIntClient
{
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// IntModel operations.
/// </summary>
public partial class IntModel : IServiceOperations<CompositeBoolInt>, IIntModel
{
/// <summary>
/// Initializes a new instance of the IntModel class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public IntModel(CompositeBoolInt client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the CompositeBoolInt
/// </summary>
public CompositeBoolInt Client { get; private set; }
/// <summary>
/// Get null Int value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<int?>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/null").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<int?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<int?>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get invalid Int value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<int?>> GetInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetInvalid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/invalid").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<int?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<int?>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get overflow Int32 value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<int?>> GetOverflowInt32WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetOverflowInt32", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/overflowint32").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<int?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<int?>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get underflow Int32 value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<int?>> GetUnderflowInt32WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetUnderflowInt32", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/underflowint32").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<int?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<int?>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get overflow Int64 value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<long?>> GetOverflowInt64WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetOverflowInt64", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/overflowint64").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<long?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<long?>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get underflow Int64 value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<long?>> GetUnderflowInt64WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetUnderflowInt64", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/underflowint64").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<long?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<long?>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put max int32 value
/// </summary>
/// <param name='intBody'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> PutMax32WithHttpMessagesAsync(int intBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("intBody", intBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutMax32", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/max/32").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
_requestContent = SafeJsonConvert.SerializeObject(intBody, Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put max int64 value
/// </summary>
/// <param name='intBody'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> PutMax64WithHttpMessagesAsync(long intBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("intBody", intBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutMax64", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/max/64").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
_requestContent = SafeJsonConvert.SerializeObject(intBody, Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put min int32 value
/// </summary>
/// <param name='intBody'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> PutMin32WithHttpMessagesAsync(int intBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("intBody", intBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutMin32", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/min/32").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
_requestContent = SafeJsonConvert.SerializeObject(intBody, Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put min int64 value
/// </summary>
/// <param name='intBody'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> PutMin64WithHttpMessagesAsync(long intBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("intBody", intBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutMin64", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/min/64").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
_requestContent = SafeJsonConvert.SerializeObject(intBody, Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get datetime encoded as Unix time value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<System.DateTime?>> GetUnixTimeWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetUnixTime", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/unixtime").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<System.DateTime?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<System.DateTime?>(_responseContent, new UnixTimeJsonConverter());
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put datetime encoded as Unix time
/// </summary>
/// <param name='intBody'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> PutUnixTimeDateWithHttpMessagesAsync(System.DateTime intBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("intBody", intBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutUnixTimeDate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/unixtime").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
_requestContent = SafeJsonConvert.SerializeObject(intBody, new UnixTimeJsonConverter());
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get invalid Unix time value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<System.DateTime?>> GetInvalidUnixTimeWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetInvalidUnixTime", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/invalidunixtime").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<System.DateTime?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<System.DateTime?>(_responseContent, new UnixTimeJsonConverter());
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get null Unix time value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<System.DateTime?>> GetNullUnixTimeWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetNullUnixTime", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/nullunixtime").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<System.DateTime?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<System.DateTime?>(_responseContent, new UnixTimeJsonConverter());
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace ParentLoadSoftDelete.Business.ERLevel
{
/// <summary>
/// E11_City_ReChild (editable child object).<br/>
/// This is a generated base class of <see cref="E11_City_ReChild"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="E10_City"/> collection.
/// </remarks>
[Serializable]
public partial class E11_City_ReChild : BusinessBase<E11_City_ReChild>
{
#region State Fields
[NotUndoable]
[NonSerialized]
internal int city_ID2 = 0;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="City_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> City_Child_NameProperty = RegisterProperty<string>(p => p.City_Child_Name, "CityRoads Child Name");
/// <summary>
/// Gets or sets the CityRoads Child Name.
/// </summary>
/// <value>The CityRoads Child Name.</value>
public string City_Child_Name
{
get { return GetProperty(City_Child_NameProperty); }
set { SetProperty(City_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="E11_City_ReChild"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="E11_City_ReChild"/> object.</returns>
internal static E11_City_ReChild NewE11_City_ReChild()
{
return DataPortal.CreateChild<E11_City_ReChild>();
}
/// <summary>
/// Factory method. Loads a <see cref="E11_City_ReChild"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="E11_City_ReChild"/> object.</returns>
internal static E11_City_ReChild GetE11_City_ReChild(SafeDataReader dr)
{
E11_City_ReChild obj = new E11_City_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="E11_City_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 E11_City_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="E11_City_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="E11_City_ReChild"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(City_Child_NameProperty, dr.GetString("City_Child_Name"));
// parent properties
city_ID2 = dr.GetInt32("City_ID2");
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="E11_City_ReChild"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(E10_City parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddE11_City_ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@City_ID2", parent.City_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@City_Child_Name", ReadProperty(City_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
}
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="E11_City_ReChild"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(E10_City parent)
{
if (!IsDirty)
return;
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateE11_City_ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@City_ID2", parent.City_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@City_Child_Name", ReadProperty(City_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
}
}
/// <summary>
/// Self deletes the <see cref="E11_City_ReChild"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(E10_City parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("DeleteE11_City_ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@City_ID2", parent.City_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
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 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the codecommit-2015-04-13.normal.json service model.
*/
using System;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Amazon.CodeCommit.Model;
using Amazon.CodeCommit.Model.Internal.MarshallTransformations;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.CodeCommit
{
/// <summary>
/// Implementation for accessing CodeCommit
///
/// AWS CodeCommit
/// <para>
/// This is the <i>AWS CodeCommit API Reference</i>. This reference provides descriptions
/// of the AWS CodeCommit API.
/// </para>
///
/// <para>
/// You can use the AWS CodeCommit API to work with the following objects:
/// </para>
/// <ul> <li>Repositories</li> <li>Branches</li> <li>Commits</li> </ul>
/// <para>
/// For information about how to use AWS CodeCommit, see the <i>AWS CodeCommit User Guide</i>.
/// </para>
/// </summary>
public partial class AmazonCodeCommitClient : AmazonServiceClient, IAmazonCodeCommit
{
#region Constructors
/// <summary>
/// Constructs AmazonCodeCommitClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
public AmazonCodeCommitClient()
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonCodeCommitConfig()) { }
/// <summary>
/// Constructs AmazonCodeCommitClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="region">The region to connect.</param>
public AmazonCodeCommitClient(RegionEndpoint region)
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonCodeCommitConfig{RegionEndpoint = region}) { }
/// <summary>
/// Constructs AmazonCodeCommitClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="config">The AmazonCodeCommitClient Configuration Object</param>
public AmazonCodeCommitClient(AmazonCodeCommitConfig config)
: base(FallbackCredentialsFactory.GetCredentials(), config) { }
/// <summary>
/// Constructs AmazonCodeCommitClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
public AmazonCodeCommitClient(AWSCredentials credentials)
: this(credentials, new AmazonCodeCommitConfig())
{
}
/// <summary>
/// Constructs AmazonCodeCommitClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="region">The region to connect.</param>
public AmazonCodeCommitClient(AWSCredentials credentials, RegionEndpoint region)
: this(credentials, new AmazonCodeCommitConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonCodeCommitClient with AWS Credentials and an
/// AmazonCodeCommitClient Configuration object.
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="clientConfig">The AmazonCodeCommitClient Configuration Object</param>
public AmazonCodeCommitClient(AWSCredentials credentials, AmazonCodeCommitConfig clientConfig)
: base(credentials, clientConfig)
{
}
/// <summary>
/// Constructs AmazonCodeCommitClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
public AmazonCodeCommitClient(string awsAccessKeyId, string awsSecretAccessKey)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonCodeCommitConfig())
{
}
/// <summary>
/// Constructs AmazonCodeCommitClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="region">The region to connect.</param>
public AmazonCodeCommitClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonCodeCommitConfig() {RegionEndpoint=region})
{
}
/// <summary>
/// Constructs AmazonCodeCommitClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonCodeCommitClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="clientConfig">The AmazonCodeCommitClient Configuration Object</param>
public AmazonCodeCommitClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonCodeCommitConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, clientConfig)
{
}
/// <summary>
/// Constructs AmazonCodeCommitClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
public AmazonCodeCommitClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonCodeCommitConfig())
{
}
/// <summary>
/// Constructs AmazonCodeCommitClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="region">The region to connect.</param>
public AmazonCodeCommitClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonCodeCommitConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonCodeCommitClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonCodeCommitClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="clientConfig">The AmazonCodeCommitClient Configuration Object</param>
public AmazonCodeCommitClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonCodeCommitConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig)
{
}
#endregion
#region Overrides
/// <summary>
/// Creates the signer for the service.
/// </summary>
protected override AbstractAWSSigner CreateSigner()
{
return new AWS4Signer();
}
#endregion
#region Dispose
/// <summary>
/// Disposes the service client.
/// </summary>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
#endregion
#region BatchGetRepositories
/// <summary>
/// Gets information about one or more repositories.
///
/// <note>
/// <para>
/// The description field for a repository accepts all HTML characters and all valid Unicode
/// characters. Applications that do not HTML-encode the description and display it in
/// a web page could expose users to potentially malicious code. Make sure that you HTML-encode
/// the description field in any application that uses this API to display the repository
/// description on a web page.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the BatchGetRepositories service method.</param>
///
/// <returns>The response from the BatchGetRepositories service method, as returned by CodeCommit.</returns>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionIntegrityChecksFailedException">
/// An encryption integrity check failed.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyAccessDeniedException">
/// An encryption key could not be accessed.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyDisabledException">
/// The encryption key is disabled.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyNotFoundException">
/// No encryption key was found.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyUnavailableException">
/// The encryption key is not available.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.InvalidRepositoryNameException">
/// At least one specified repository name is not valid.
///
/// <note>This exception only occurs when a specified repository name is not valid. Other
/// exceptions occur when a required repository parameter is missing, or when a specified
/// repository does not exist.</note>
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.MaximumRepositoryNamesExceededException">
/// The maximum number of allowed repository names was exceeded. Currently, this number
/// is 25.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.RepositoryNamesRequiredException">
/// A repository names object is required but was not specified.
/// </exception>
public BatchGetRepositoriesResponse BatchGetRepositories(BatchGetRepositoriesRequest request)
{
var marshaller = new BatchGetRepositoriesRequestMarshaller();
var unmarshaller = BatchGetRepositoriesResponseUnmarshaller.Instance;
return Invoke<BatchGetRepositoriesRequest,BatchGetRepositoriesResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the BatchGetRepositories operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the BatchGetRepositories operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<BatchGetRepositoriesResponse> BatchGetRepositoriesAsync(BatchGetRepositoriesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new BatchGetRepositoriesRequestMarshaller();
var unmarshaller = BatchGetRepositoriesResponseUnmarshaller.Instance;
return InvokeAsync<BatchGetRepositoriesRequest,BatchGetRepositoriesResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region CreateBranch
/// <summary>
/// Creates a new branch in a repository and points the branch to a commit.
///
/// <note>Calling the create branch operation does not set a repository's default branch.
/// To do this, call the update default branch operation.</note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateBranch service method.</param>
///
/// <returns>The response from the CreateBranch service method, as returned by CodeCommit.</returns>
/// <exception cref="Amazon.CodeCommit.Model.BranchNameExistsException">
/// The specified branch name already exists.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.BranchNameRequiredException">
/// A branch name is required but was not specified.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.CommitDoesNotExistException">
/// The specified commit does not exist or no commit was specified, and the specified
/// repository has no default branch.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.CommitIdRequiredException">
/// A commit ID was not specified.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionIntegrityChecksFailedException">
/// An encryption integrity check failed.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyAccessDeniedException">
/// An encryption key could not be accessed.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyDisabledException">
/// The encryption key is disabled.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyNotFoundException">
/// No encryption key was found.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyUnavailableException">
/// The encryption key is not available.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.InvalidBranchNameException">
/// The specified branch name is not valid.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.InvalidCommitIdException">
/// The specified commit ID is not valid.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.InvalidRepositoryNameException">
/// At least one specified repository name is not valid.
///
/// <note>This exception only occurs when a specified repository name is not valid. Other
/// exceptions occur when a required repository parameter is missing, or when a specified
/// repository does not exist.</note>
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.RepositoryDoesNotExistException">
/// The specified repository does not exist.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.RepositoryNameRequiredException">
/// A repository name is required but was not specified.
/// </exception>
public CreateBranchResponse CreateBranch(CreateBranchRequest request)
{
var marshaller = new CreateBranchRequestMarshaller();
var unmarshaller = CreateBranchResponseUnmarshaller.Instance;
return Invoke<CreateBranchRequest,CreateBranchResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the CreateBranch operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateBranch operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<CreateBranchResponse> CreateBranchAsync(CreateBranchRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new CreateBranchRequestMarshaller();
var unmarshaller = CreateBranchResponseUnmarshaller.Instance;
return InvokeAsync<CreateBranchRequest,CreateBranchResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region CreateRepository
/// <summary>
/// Creates a new, empty repository.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateRepository service method.</param>
///
/// <returns>The response from the CreateRepository service method, as returned by CodeCommit.</returns>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionIntegrityChecksFailedException">
/// An encryption integrity check failed.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyAccessDeniedException">
/// An encryption key could not be accessed.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyDisabledException">
/// The encryption key is disabled.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyNotFoundException">
/// No encryption key was found.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyUnavailableException">
/// The encryption key is not available.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.InvalidRepositoryDescriptionException">
/// The specified repository description is not valid.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.InvalidRepositoryNameException">
/// At least one specified repository name is not valid.
///
/// <note>This exception only occurs when a specified repository name is not valid. Other
/// exceptions occur when a required repository parameter is missing, or when a specified
/// repository does not exist.</note>
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.RepositoryLimitExceededException">
/// A repository resource limit was exceeded.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.RepositoryNameExistsException">
/// The specified repository name already exists.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.RepositoryNameRequiredException">
/// A repository name is required but was not specified.
/// </exception>
public CreateRepositoryResponse CreateRepository(CreateRepositoryRequest request)
{
var marshaller = new CreateRepositoryRequestMarshaller();
var unmarshaller = CreateRepositoryResponseUnmarshaller.Instance;
return Invoke<CreateRepositoryRequest,CreateRepositoryResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the CreateRepository operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateRepository operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<CreateRepositoryResponse> CreateRepositoryAsync(CreateRepositoryRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new CreateRepositoryRequestMarshaller();
var unmarshaller = CreateRepositoryResponseUnmarshaller.Instance;
return InvokeAsync<CreateRepositoryRequest,CreateRepositoryResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region DeleteRepository
/// <summary>
/// Deletes a repository. If a specified repository was already deleted, a null repository
/// ID will be returned.
///
/// <important>Deleting a repository also deletes all associated objects and metadata.
/// After a repository is deleted, all future push calls to the deleted repository will
/// fail.</important>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteRepository service method.</param>
///
/// <returns>The response from the DeleteRepository service method, as returned by CodeCommit.</returns>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionIntegrityChecksFailedException">
/// An encryption integrity check failed.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyAccessDeniedException">
/// An encryption key could not be accessed.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyDisabledException">
/// The encryption key is disabled.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyNotFoundException">
/// No encryption key was found.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyUnavailableException">
/// The encryption key is not available.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.InvalidRepositoryNameException">
/// At least one specified repository name is not valid.
///
/// <note>This exception only occurs when a specified repository name is not valid. Other
/// exceptions occur when a required repository parameter is missing, or when a specified
/// repository does not exist.</note>
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.RepositoryNameRequiredException">
/// A repository name is required but was not specified.
/// </exception>
public DeleteRepositoryResponse DeleteRepository(DeleteRepositoryRequest request)
{
var marshaller = new DeleteRepositoryRequestMarshaller();
var unmarshaller = DeleteRepositoryResponseUnmarshaller.Instance;
return Invoke<DeleteRepositoryRequest,DeleteRepositoryResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the DeleteRepository operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteRepository operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<DeleteRepositoryResponse> DeleteRepositoryAsync(DeleteRepositoryRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new DeleteRepositoryRequestMarshaller();
var unmarshaller = DeleteRepositoryResponseUnmarshaller.Instance;
return InvokeAsync<DeleteRepositoryRequest,DeleteRepositoryResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region GetBranch
/// <summary>
/// Retrieves information about a repository branch, including its name and the last commit
/// ID.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetBranch service method.</param>
///
/// <returns>The response from the GetBranch service method, as returned by CodeCommit.</returns>
/// <exception cref="Amazon.CodeCommit.Model.BranchDoesNotExistException">
/// The specified branch does not exist.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.BranchNameRequiredException">
/// A branch name is required but was not specified.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionIntegrityChecksFailedException">
/// An encryption integrity check failed.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyAccessDeniedException">
/// An encryption key could not be accessed.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyDisabledException">
/// The encryption key is disabled.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyNotFoundException">
/// No encryption key was found.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyUnavailableException">
/// The encryption key is not available.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.InvalidBranchNameException">
/// The specified branch name is not valid.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.InvalidRepositoryNameException">
/// At least one specified repository name is not valid.
///
/// <note>This exception only occurs when a specified repository name is not valid. Other
/// exceptions occur when a required repository parameter is missing, or when a specified
/// repository does not exist.</note>
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.RepositoryDoesNotExistException">
/// The specified repository does not exist.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.RepositoryNameRequiredException">
/// A repository name is required but was not specified.
/// </exception>
public GetBranchResponse GetBranch(GetBranchRequest request)
{
var marshaller = new GetBranchRequestMarshaller();
var unmarshaller = GetBranchResponseUnmarshaller.Instance;
return Invoke<GetBranchRequest,GetBranchResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the GetBranch operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetBranch operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<GetBranchResponse> GetBranchAsync(GetBranchRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new GetBranchRequestMarshaller();
var unmarshaller = GetBranchResponseUnmarshaller.Instance;
return InvokeAsync<GetBranchRequest,GetBranchResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region GetRepository
/// <summary>
/// Gets information about a repository.
///
/// <note>
/// <para>
/// The description field for a repository accepts all HTML characters and all valid Unicode
/// characters. Applications that do not HTML-encode the description and display it in
/// a web page could expose users to potentially malicious code. Make sure that you HTML-encode
/// the description field in any application that uses this API to display the repository
/// description on a web page.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetRepository service method.</param>
///
/// <returns>The response from the GetRepository service method, as returned by CodeCommit.</returns>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionIntegrityChecksFailedException">
/// An encryption integrity check failed.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyAccessDeniedException">
/// An encryption key could not be accessed.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyDisabledException">
/// The encryption key is disabled.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyNotFoundException">
/// No encryption key was found.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyUnavailableException">
/// The encryption key is not available.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.InvalidRepositoryNameException">
/// At least one specified repository name is not valid.
///
/// <note>This exception only occurs when a specified repository name is not valid. Other
/// exceptions occur when a required repository parameter is missing, or when a specified
/// repository does not exist.</note>
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.RepositoryDoesNotExistException">
/// The specified repository does not exist.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.RepositoryNameRequiredException">
/// A repository name is required but was not specified.
/// </exception>
public GetRepositoryResponse GetRepository(GetRepositoryRequest request)
{
var marshaller = new GetRepositoryRequestMarshaller();
var unmarshaller = GetRepositoryResponseUnmarshaller.Instance;
return Invoke<GetRepositoryRequest,GetRepositoryResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the GetRepository operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetRepository operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<GetRepositoryResponse> GetRepositoryAsync(GetRepositoryRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new GetRepositoryRequestMarshaller();
var unmarshaller = GetRepositoryResponseUnmarshaller.Instance;
return InvokeAsync<GetRepositoryRequest,GetRepositoryResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region ListBranches
/// <summary>
/// Gets information about one or more branches in a repository.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListBranches service method.</param>
///
/// <returns>The response from the ListBranches service method, as returned by CodeCommit.</returns>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionIntegrityChecksFailedException">
/// An encryption integrity check failed.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyAccessDeniedException">
/// An encryption key could not be accessed.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyDisabledException">
/// The encryption key is disabled.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyNotFoundException">
/// No encryption key was found.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyUnavailableException">
/// The encryption key is not available.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.InvalidContinuationTokenException">
/// The specified continuation token is not valid.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.InvalidRepositoryNameException">
/// At least one specified repository name is not valid.
///
/// <note>This exception only occurs when a specified repository name is not valid. Other
/// exceptions occur when a required repository parameter is missing, or when a specified
/// repository does not exist.</note>
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.RepositoryDoesNotExistException">
/// The specified repository does not exist.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.RepositoryNameRequiredException">
/// A repository name is required but was not specified.
/// </exception>
public ListBranchesResponse ListBranches(ListBranchesRequest request)
{
var marshaller = new ListBranchesRequestMarshaller();
var unmarshaller = ListBranchesResponseUnmarshaller.Instance;
return Invoke<ListBranchesRequest,ListBranchesResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the ListBranches operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListBranches operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<ListBranchesResponse> ListBranchesAsync(ListBranchesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new ListBranchesRequestMarshaller();
var unmarshaller = ListBranchesResponseUnmarshaller.Instance;
return InvokeAsync<ListBranchesRequest,ListBranchesResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region ListRepositories
/// <summary>
/// Gets information about one or more repositories.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListRepositories service method.</param>
///
/// <returns>The response from the ListRepositories service method, as returned by CodeCommit.</returns>
/// <exception cref="Amazon.CodeCommit.Model.InvalidContinuationTokenException">
/// The specified continuation token is not valid.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.InvalidOrderException">
/// The specified sort order is not valid.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.InvalidSortByException">
/// The specified sort by value is not valid.
/// </exception>
public ListRepositoriesResponse ListRepositories(ListRepositoriesRequest request)
{
var marshaller = new ListRepositoriesRequestMarshaller();
var unmarshaller = ListRepositoriesResponseUnmarshaller.Instance;
return Invoke<ListRepositoriesRequest,ListRepositoriesResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the ListRepositories operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListRepositories operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<ListRepositoriesResponse> ListRepositoriesAsync(ListRepositoriesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new ListRepositoriesRequestMarshaller();
var unmarshaller = ListRepositoriesResponseUnmarshaller.Instance;
return InvokeAsync<ListRepositoriesRequest,ListRepositoriesResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region UpdateDefaultBranch
/// <summary>
/// Sets or changes the default branch name for the specified repository.
///
/// <note>If you use this operation to change the default branch name to the current
/// default branch name, a success message is returned even though the default branch
/// did not change.</note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateDefaultBranch service method.</param>
///
/// <returns>The response from the UpdateDefaultBranch service method, as returned by CodeCommit.</returns>
/// <exception cref="Amazon.CodeCommit.Model.BranchDoesNotExistException">
/// The specified branch does not exist.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.BranchNameRequiredException">
/// A branch name is required but was not specified.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionIntegrityChecksFailedException">
/// An encryption integrity check failed.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyAccessDeniedException">
/// An encryption key could not be accessed.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyDisabledException">
/// The encryption key is disabled.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyNotFoundException">
/// No encryption key was found.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyUnavailableException">
/// The encryption key is not available.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.InvalidBranchNameException">
/// The specified branch name is not valid.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.InvalidRepositoryNameException">
/// At least one specified repository name is not valid.
///
/// <note>This exception only occurs when a specified repository name is not valid. Other
/// exceptions occur when a required repository parameter is missing, or when a specified
/// repository does not exist.</note>
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.RepositoryDoesNotExistException">
/// The specified repository does not exist.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.RepositoryNameRequiredException">
/// A repository name is required but was not specified.
/// </exception>
public UpdateDefaultBranchResponse UpdateDefaultBranch(UpdateDefaultBranchRequest request)
{
var marshaller = new UpdateDefaultBranchRequestMarshaller();
var unmarshaller = UpdateDefaultBranchResponseUnmarshaller.Instance;
return Invoke<UpdateDefaultBranchRequest,UpdateDefaultBranchResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the UpdateDefaultBranch operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateDefaultBranch operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<UpdateDefaultBranchResponse> UpdateDefaultBranchAsync(UpdateDefaultBranchRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new UpdateDefaultBranchRequestMarshaller();
var unmarshaller = UpdateDefaultBranchResponseUnmarshaller.Instance;
return InvokeAsync<UpdateDefaultBranchRequest,UpdateDefaultBranchResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region UpdateRepositoryDescription
/// <summary>
/// Sets or changes the comment or description for a repository.
///
/// <note>
/// <para>
/// The description field for a repository accepts all HTML characters and all valid Unicode
/// characters. Applications that do not HTML-encode the description and display it in
/// a web page could expose users to potentially malicious code. Make sure that you HTML-encode
/// the description field in any application that uses this API to display the repository
/// description on a web page.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateRepositoryDescription service method.</param>
///
/// <returns>The response from the UpdateRepositoryDescription service method, as returned by CodeCommit.</returns>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionIntegrityChecksFailedException">
/// An encryption integrity check failed.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyAccessDeniedException">
/// An encryption key could not be accessed.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyDisabledException">
/// The encryption key is disabled.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyNotFoundException">
/// No encryption key was found.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyUnavailableException">
/// The encryption key is not available.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.InvalidRepositoryDescriptionException">
/// The specified repository description is not valid.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.InvalidRepositoryNameException">
/// At least one specified repository name is not valid.
///
/// <note>This exception only occurs when a specified repository name is not valid. Other
/// exceptions occur when a required repository parameter is missing, or when a specified
/// repository does not exist.</note>
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.RepositoryDoesNotExistException">
/// The specified repository does not exist.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.RepositoryNameRequiredException">
/// A repository name is required but was not specified.
/// </exception>
public UpdateRepositoryDescriptionResponse UpdateRepositoryDescription(UpdateRepositoryDescriptionRequest request)
{
var marshaller = new UpdateRepositoryDescriptionRequestMarshaller();
var unmarshaller = UpdateRepositoryDescriptionResponseUnmarshaller.Instance;
return Invoke<UpdateRepositoryDescriptionRequest,UpdateRepositoryDescriptionResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the UpdateRepositoryDescription operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateRepositoryDescription operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<UpdateRepositoryDescriptionResponse> UpdateRepositoryDescriptionAsync(UpdateRepositoryDescriptionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new UpdateRepositoryDescriptionRequestMarshaller();
var unmarshaller = UpdateRepositoryDescriptionResponseUnmarshaller.Instance;
return InvokeAsync<UpdateRepositoryDescriptionRequest,UpdateRepositoryDescriptionResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region UpdateRepositoryName
/// <summary>
/// Renames a repository.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateRepositoryName service method.</param>
///
/// <returns>The response from the UpdateRepositoryName service method, as returned by CodeCommit.</returns>
/// <exception cref="Amazon.CodeCommit.Model.InvalidRepositoryNameException">
/// At least one specified repository name is not valid.
///
/// <note>This exception only occurs when a specified repository name is not valid. Other
/// exceptions occur when a required repository parameter is missing, or when a specified
/// repository does not exist.</note>
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.RepositoryDoesNotExistException">
/// The specified repository does not exist.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.RepositoryNameExistsException">
/// The specified repository name already exists.
/// </exception>
/// <exception cref="Amazon.CodeCommit.Model.RepositoryNameRequiredException">
/// A repository name is required but was not specified.
/// </exception>
public UpdateRepositoryNameResponse UpdateRepositoryName(UpdateRepositoryNameRequest request)
{
var marshaller = new UpdateRepositoryNameRequestMarshaller();
var unmarshaller = UpdateRepositoryNameResponseUnmarshaller.Instance;
return Invoke<UpdateRepositoryNameRequest,UpdateRepositoryNameResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the UpdateRepositoryName operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateRepositoryName operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<UpdateRepositoryNameResponse> UpdateRepositoryNameAsync(UpdateRepositoryNameRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new UpdateRepositoryNameRequestMarshaller();
var unmarshaller = UpdateRepositoryNameResponseUnmarshaller.Instance;
return InvokeAsync<UpdateRepositoryNameRequest,UpdateRepositoryNameResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
}
}
| |
#if CORECLR
#if CORECLR
#pragma warning disable
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.17929
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
//
// This source code was auto-generated by xsd, Version=4.0.30319.17929.
//
namespace Microsoft.PowerShell.Cmdletization.Xml
{
using System.Xml.Serialization;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11", IsNullable = false)]
internal partial class PowerShellMetadata
{
private ClassMetadata _classField;
private EnumMetadataEnum[] _enumsField;
/// <remarks/>
public ClassMetadata Class
{
get
{
return this._classField;
}
set
{
this._classField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("Enum", IsNullable = false)]
public EnumMetadataEnum[] Enums
{
get
{
return this._enumsField;
}
set
{
this._enumsField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class ClassMetadata
{
private string _versionField;
private string _defaultNounField;
private ClassMetadataInstanceCmdlets _instanceCmdletsField;
private StaticCmdletMetadata[] _staticCmdletsField;
private ClassMetadataData[] _cmdletAdapterPrivateDataField;
private string _cmdletAdapterField;
private string _classNameField;
private string _classVersionField;
/// <remarks/>
public string Version
{
get
{
return this._versionField;
}
set
{
this._versionField = value;
}
}
/// <remarks/>
public string DefaultNoun
{
get
{
return this._defaultNounField;
}
set
{
this._defaultNounField = value;
}
}
/// <remarks/>
public ClassMetadataInstanceCmdlets InstanceCmdlets
{
get
{
return this._instanceCmdletsField;
}
set
{
this._instanceCmdletsField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("Cmdlet", IsNullable = false)]
public StaticCmdletMetadata[] StaticCmdlets
{
get
{
return this._staticCmdletsField;
}
set
{
this._staticCmdletsField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("Data", IsNullable = false)]
public ClassMetadataData[] CmdletAdapterPrivateData
{
get
{
return this._cmdletAdapterPrivateDataField;
}
set
{
this._cmdletAdapterPrivateDataField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string CmdletAdapter
{
get
{
return this._cmdletAdapterField;
}
set
{
this._cmdletAdapterField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string ClassName
{
get
{
return this._classNameField;
}
set
{
this._classNameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string ClassVersion
{
get
{
return this._classVersionField;
}
set
{
this._classVersionField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class ClassMetadataInstanceCmdlets
{
private GetCmdletParameters _getCmdletParametersField;
private GetCmdletMetadata _getCmdletField;
private InstanceCmdletMetadata[] _cmdletField;
/// <remarks/>
public GetCmdletParameters GetCmdletParameters
{
get
{
return this._getCmdletParametersField;
}
set
{
this._getCmdletParametersField = value;
}
}
/// <remarks/>
public GetCmdletMetadata GetCmdlet
{
get
{
return this._getCmdletField;
}
set
{
this._getCmdletField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Cmdlet")]
public InstanceCmdletMetadata[] Cmdlet
{
get
{
return this._cmdletField;
}
set
{
this._cmdletField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class GetCmdletParameters
{
private PropertyMetadata[] _queryablePropertiesField;
private Association[] _queryableAssociationsField;
private QueryOption[] _queryOptionsField;
private string _defaultCmdletParameterSetField;
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("Property", IsNullable = false)]
public PropertyMetadata[] QueryableProperties
{
get
{
return this._queryablePropertiesField;
}
set
{
this._queryablePropertiesField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute(IsNullable = false)]
public Association[] QueryableAssociations
{
get
{
return this._queryableAssociationsField;
}
set
{
this._queryableAssociationsField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("Option", IsNullable = false)]
public QueryOption[] QueryOptions
{
get
{
return this._queryOptionsField;
}
set
{
this._queryOptionsField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string DefaultCmdletParameterSet
{
get
{
return this._defaultCmdletParameterSetField;
}
set
{
this._defaultCmdletParameterSetField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class PropertyMetadata
{
private TypeMetadata _typeField;
private PropertyQuery[] _itemsField;
private ItemsChoiceType[] _itemsElementNameField;
private string _propertyNameField;
/// <remarks/>
public TypeMetadata Type
{
get
{
return this._typeField;
}
set
{
this._typeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("ExcludeQuery", typeof(WildcardablePropertyQuery))]
[System.Xml.Serialization.XmlElementAttribute("MaxValueQuery", typeof(PropertyQuery))]
[System.Xml.Serialization.XmlElementAttribute("MinValueQuery", typeof(PropertyQuery))]
[System.Xml.Serialization.XmlElementAttribute("RegularQuery", typeof(WildcardablePropertyQuery))]
[System.Xml.Serialization.XmlChoiceIdentifierAttribute("ItemsElementName")]
public PropertyQuery[] Items
{
get
{
return this._itemsField;
}
set
{
this._itemsField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("ItemsElementName")]
[System.Xml.Serialization.XmlIgnoreAttribute()]
public ItemsChoiceType[] ItemsElementName
{
get
{
return this._itemsElementNameField;
}
set
{
this._itemsElementNameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string PropertyName
{
get
{
return this._propertyNameField;
}
set
{
this._propertyNameField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class TypeMetadata
{
private string _pSTypeField;
private string _eTSTypeField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string PSType
{
get
{
return this._pSTypeField;
}
set
{
this._pSTypeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string ETSType
{
get
{
return this._eTSTypeField;
}
set
{
this._eTSTypeField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class Association
{
private AssociationAssociatedInstance _associatedInstanceField;
private string _association1Field;
private string _sourceRoleField;
private string _resultRoleField;
/// <remarks/>
public AssociationAssociatedInstance AssociatedInstance
{
get
{
return this._associatedInstanceField;
}
set
{
this._associatedInstanceField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute("Association")]
public string Association1
{
get
{
return this._association1Field;
}
set
{
this._association1Field = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string SourceRole
{
get
{
return this._sourceRoleField;
}
set
{
this._sourceRoleField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string ResultRole
{
get
{
return this._resultRoleField;
}
set
{
this._resultRoleField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class AssociationAssociatedInstance
{
private TypeMetadata _typeField;
private CmdletParameterMetadataForGetCmdletFilteringParameter _cmdletParameterMetadataField;
/// <remarks/>
public TypeMetadata Type
{
get
{
return this._typeField;
}
set
{
this._typeField = value;
}
}
/// <remarks/>
public CmdletParameterMetadataForGetCmdletFilteringParameter CmdletParameterMetadata
{
get
{
return this._cmdletParameterMetadataField;
}
set
{
this._cmdletParameterMetadataField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class CmdletParameterMetadataForGetCmdletFilteringParameter : CmdletParameterMetadataForGetCmdletParameter
{
private bool _errorOnNoMatchField;
private bool _errorOnNoMatchFieldSpecified;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public bool ErrorOnNoMatch
{
get
{
return this._errorOnNoMatchField;
}
set
{
this._errorOnNoMatchField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool ErrorOnNoMatchSpecified
{
get
{
return this._errorOnNoMatchFieldSpecified;
}
set
{
this._errorOnNoMatchFieldSpecified = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIncludeAttribute(typeof(CmdletParameterMetadataForGetCmdletFilteringParameter))]
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class CmdletParameterMetadataForGetCmdletParameter : CmdletParameterMetadata
{
private bool _valueFromPipelineField;
private bool _valueFromPipelineFieldSpecified;
private bool _valueFromPipelineByPropertyNameField;
private bool _valueFromPipelineByPropertyNameFieldSpecified;
private string[] _cmdletParameterSetsField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public bool ValueFromPipeline
{
get
{
return this._valueFromPipelineField;
}
set
{
this._valueFromPipelineField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool ValueFromPipelineSpecified
{
get
{
return this._valueFromPipelineFieldSpecified;
}
set
{
this._valueFromPipelineFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public bool ValueFromPipelineByPropertyName
{
get
{
return this._valueFromPipelineByPropertyNameField;
}
set
{
this._valueFromPipelineByPropertyNameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool ValueFromPipelineByPropertyNameSpecified
{
get
{
return this._valueFromPipelineByPropertyNameFieldSpecified;
}
set
{
this._valueFromPipelineByPropertyNameFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string[] CmdletParameterSets
{
get
{
return this._cmdletParameterSetsField;
}
set
{
this._cmdletParameterSetsField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIncludeAttribute(typeof(CmdletParameterMetadataForGetCmdletParameter))]
[System.Xml.Serialization.XmlIncludeAttribute(typeof(CmdletParameterMetadataForGetCmdletFilteringParameter))]
[System.Xml.Serialization.XmlIncludeAttribute(typeof(CmdletParameterMetadataForInstanceMethodParameter))]
[System.Xml.Serialization.XmlIncludeAttribute(typeof(CmdletParameterMetadataForStaticMethodParameter))]
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class CmdletParameterMetadata
{
private object _allowEmptyCollectionField;
private object _allowEmptyStringField;
private object _allowNullField;
private object _validateNotNullField;
private object _validateNotNullOrEmptyField;
private CmdletParameterMetadataValidateCount _validateCountField;
private CmdletParameterMetadataValidateLength _validateLengthField;
private CmdletParameterMetadataValidateRange _validateRangeField;
private string[] _validateSetField;
private ObsoleteAttributeMetadata _obsoleteField;
private bool _isMandatoryField;
private bool _isMandatoryFieldSpecified;
private string[] _aliasesField;
private string _pSNameField;
private string _positionField;
/// <remarks/>
public object AllowEmptyCollection
{
get
{
return this._allowEmptyCollectionField;
}
set
{
this._allowEmptyCollectionField = value;
}
}
/// <remarks/>
public object AllowEmptyString
{
get
{
return this._allowEmptyStringField;
}
set
{
this._allowEmptyStringField = value;
}
}
/// <remarks/>
public object AllowNull
{
get
{
return this._allowNullField;
}
set
{
this._allowNullField = value;
}
}
/// <remarks/>
public object ValidateNotNull
{
get
{
return this._validateNotNullField;
}
set
{
this._validateNotNullField = value;
}
}
/// <remarks/>
public object ValidateNotNullOrEmpty
{
get
{
return this._validateNotNullOrEmptyField;
}
set
{
this._validateNotNullOrEmptyField = value;
}
}
/// <remarks/>
public CmdletParameterMetadataValidateCount ValidateCount
{
get
{
return this._validateCountField;
}
set
{
this._validateCountField = value;
}
}
/// <remarks/>
public CmdletParameterMetadataValidateLength ValidateLength
{
get
{
return this._validateLengthField;
}
set
{
this._validateLengthField = value;
}
}
/// <remarks/>
public CmdletParameterMetadataValidateRange ValidateRange
{
get
{
return this._validateRangeField;
}
set
{
this._validateRangeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("AllowedValue", IsNullable = false)]
public string[] ValidateSet
{
get
{
return this._validateSetField;
}
set
{
this._validateSetField = value;
}
}
/// <remarks/>
public ObsoleteAttributeMetadata Obsolete
{
get
{
return this._obsoleteField;
}
set
{
this._obsoleteField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public bool IsMandatory
{
get
{
return this._isMandatoryField;
}
set
{
this._isMandatoryField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool IsMandatorySpecified
{
get
{
return this._isMandatoryFieldSpecified;
}
set
{
this._isMandatoryFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string[] Aliases
{
get
{
return this._aliasesField;
}
set
{
this._aliasesField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string PSName
{
get
{
return this._pSNameField;
}
set
{
this._pSNameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType = "nonNegativeInteger")]
public string Position
{
get
{
return this._positionField;
}
set
{
this._positionField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class CmdletParameterMetadataValidateCount
{
private string _minField;
private string _maxField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType = "nonNegativeInteger")]
public string Min
{
get
{
return this._minField;
}
set
{
this._minField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType = "nonNegativeInteger")]
public string Max
{
get
{
return this._maxField;
}
set
{
this._maxField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class CmdletParameterMetadataValidateLength
{
private string _minField;
private string _maxField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType = "nonNegativeInteger")]
public string Min
{
get
{
return this._minField;
}
set
{
this._minField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType = "nonNegativeInteger")]
public string Max
{
get
{
return this._maxField;
}
set
{
this._maxField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class CmdletParameterMetadataValidateRange
{
private string _minField;
private string _maxField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType = "integer")]
public string Min
{
get
{
return this._minField;
}
set
{
this._minField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType = "integer")]
public string Max
{
get
{
return this._maxField;
}
set
{
this._maxField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class ObsoleteAttributeMetadata
{
private string _messageField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string Message
{
get
{
return this._messageField;
}
set
{
this._messageField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class CmdletParameterMetadataForInstanceMethodParameter : CmdletParameterMetadata
{
private bool _valueFromPipelineByPropertyNameField;
private bool _valueFromPipelineByPropertyNameFieldSpecified;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public bool ValueFromPipelineByPropertyName
{
get
{
return this._valueFromPipelineByPropertyNameField;
}
set
{
this._valueFromPipelineByPropertyNameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool ValueFromPipelineByPropertyNameSpecified
{
get
{
return this._valueFromPipelineByPropertyNameFieldSpecified;
}
set
{
this._valueFromPipelineByPropertyNameFieldSpecified = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class CmdletParameterMetadataForStaticMethodParameter : CmdletParameterMetadata
{
private bool _valueFromPipelineField;
private bool _valueFromPipelineFieldSpecified;
private bool _valueFromPipelineByPropertyNameField;
private bool _valueFromPipelineByPropertyNameFieldSpecified;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public bool ValueFromPipeline
{
get
{
return this._valueFromPipelineField;
}
set
{
this._valueFromPipelineField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool ValueFromPipelineSpecified
{
get
{
return this._valueFromPipelineFieldSpecified;
}
set
{
this._valueFromPipelineFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public bool ValueFromPipelineByPropertyName
{
get
{
return this._valueFromPipelineByPropertyNameField;
}
set
{
this._valueFromPipelineByPropertyNameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool ValueFromPipelineByPropertyNameSpecified
{
get
{
return this._valueFromPipelineByPropertyNameFieldSpecified;
}
set
{
this._valueFromPipelineByPropertyNameFieldSpecified = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class QueryOption
{
private TypeMetadata _typeField;
private CmdletParameterMetadataForGetCmdletParameter _cmdletParameterMetadataField;
private string _optionNameField;
/// <remarks/>
public TypeMetadata Type
{
get
{
return this._typeField;
}
set
{
this._typeField = value;
}
}
/// <remarks/>
public CmdletParameterMetadataForGetCmdletParameter CmdletParameterMetadata
{
get
{
return this._cmdletParameterMetadataField;
}
set
{
this._cmdletParameterMetadataField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string OptionName
{
get
{
return this._optionNameField;
}
set
{
this._optionNameField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class GetCmdletMetadata
{
private CommonCmdletMetadata _cmdletMetadataField;
private GetCmdletParameters _getCmdletParametersField;
/// <remarks/>
public CommonCmdletMetadata CmdletMetadata
{
get
{
return this._cmdletMetadataField;
}
set
{
this._cmdletMetadataField = value;
}
}
/// <remarks/>
public GetCmdletParameters GetCmdletParameters
{
get
{
return this._getCmdletParametersField;
}
set
{
this._getCmdletParametersField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class CommonCmdletMetadata
{
private ObsoleteAttributeMetadata _obsoleteField;
private string _verbField;
private string _nounField;
private string[] _aliasesField;
private ConfirmImpact _confirmImpactField;
private bool _confirmImpactFieldSpecified;
private string _helpUriField;
/// <remarks/>
public ObsoleteAttributeMetadata Obsolete
{
get
{
return this._obsoleteField;
}
set
{
this._obsoleteField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string Verb
{
get
{
return this._verbField;
}
set
{
this._verbField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string Noun
{
get
{
return this._nounField;
}
set
{
this._nounField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string[] Aliases
{
get
{
return this._aliasesField;
}
set
{
this._aliasesField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public ConfirmImpact ConfirmImpact
{
get
{
return this._confirmImpactField;
}
set
{
this._confirmImpactField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool ConfirmImpactSpecified
{
get
{
return this._confirmImpactFieldSpecified;
}
set
{
this._confirmImpactFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType = "anyURI")]
public string HelpUri
{
get
{
return this._helpUriField;
}
set
{
this._helpUriField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
public enum ConfirmImpact
{
/// <remarks/>
None,
/// <remarks/>
Low,
/// <remarks/>
Medium,
/// <remarks/>
High,
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class StaticCmdletMetadata
{
private StaticCmdletMetadataCmdletMetadata _cmdletMetadataField;
private StaticMethodMetadata[] _methodField;
/// <remarks/>
public StaticCmdletMetadataCmdletMetadata CmdletMetadata
{
get
{
return this._cmdletMetadataField;
}
set
{
this._cmdletMetadataField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Method")]
public StaticMethodMetadata[] Method
{
get
{
return this._methodField;
}
set
{
this._methodField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class StaticCmdletMetadataCmdletMetadata : CommonCmdletMetadata
{
private string _defaultCmdletParameterSetField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string DefaultCmdletParameterSet
{
get
{
return this._defaultCmdletParameterSetField;
}
set
{
this._defaultCmdletParameterSetField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class StaticMethodMetadata : CommonMethodMetadata
{
private StaticMethodParameterMetadata[] _parametersField;
private string _cmdletParameterSetField;
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("Parameter", IsNullable = false)]
public StaticMethodParameterMetadata[] Parameters
{
get
{
return this._parametersField;
}
set
{
this._parametersField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string CmdletParameterSet
{
get
{
return this._cmdletParameterSetField;
}
set
{
this._cmdletParameterSetField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class StaticMethodParameterMetadata : CommonMethodParameterMetadata
{
private CmdletParameterMetadataForStaticMethodParameter _cmdletParameterMetadataField;
private CmdletOutputMetadata _cmdletOutputMetadataField;
/// <remarks/>
public CmdletParameterMetadataForStaticMethodParameter CmdletParameterMetadata
{
get
{
return this._cmdletParameterMetadataField;
}
set
{
this._cmdletParameterMetadataField = value;
}
}
/// <remarks/>
public CmdletOutputMetadata CmdletOutputMetadata
{
get
{
return this._cmdletOutputMetadataField;
}
set
{
this._cmdletOutputMetadataField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class CmdletOutputMetadata
{
private object _errorCodeField;
private string _pSNameField;
/// <remarks/>
public object ErrorCode
{
get
{
return this._errorCodeField;
}
set
{
this._errorCodeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string PSName
{
get
{
return this._pSNameField;
}
set
{
this._pSNameField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIncludeAttribute(typeof(InstanceMethodParameterMetadata))]
[System.Xml.Serialization.XmlIncludeAttribute(typeof(StaticMethodParameterMetadata))]
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class CommonMethodParameterMetadata
{
private TypeMetadata _typeField;
private string _parameterNameField;
private string _defaultValueField;
/// <remarks/>
public TypeMetadata Type
{
get
{
return this._typeField;
}
set
{
this._typeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string ParameterName
{
get
{
return this._parameterNameField;
}
set
{
this._parameterNameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string DefaultValue
{
get
{
return this._defaultValueField;
}
set
{
this._defaultValueField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class InstanceMethodParameterMetadata : CommonMethodParameterMetadata
{
private CmdletParameterMetadataForInstanceMethodParameter _cmdletParameterMetadataField;
private CmdletOutputMetadata _cmdletOutputMetadataField;
/// <remarks/>
public CmdletParameterMetadataForInstanceMethodParameter CmdletParameterMetadata
{
get
{
return this._cmdletParameterMetadataField;
}
set
{
this._cmdletParameterMetadataField = value;
}
}
/// <remarks/>
public CmdletOutputMetadata CmdletOutputMetadata
{
get
{
return this._cmdletOutputMetadataField;
}
set
{
this._cmdletOutputMetadataField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIncludeAttribute(typeof(InstanceMethodMetadata))]
[System.Xml.Serialization.XmlIncludeAttribute(typeof(StaticMethodMetadata))]
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class CommonMethodMetadata
{
private CommonMethodMetadataReturnValue _returnValueField;
private string _methodNameField;
/// <remarks/>
public CommonMethodMetadataReturnValue ReturnValue
{
get
{
return this._returnValueField;
}
set
{
this._returnValueField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string MethodName
{
get
{
return this._methodNameField;
}
set
{
this._methodNameField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class CommonMethodMetadataReturnValue
{
private TypeMetadata _typeField;
private CmdletOutputMetadata _cmdletOutputMetadataField;
/// <remarks/>
public TypeMetadata Type
{
get
{
return this._typeField;
}
set
{
this._typeField = value;
}
}
/// <remarks/>
public CmdletOutputMetadata CmdletOutputMetadata
{
get
{
return this._cmdletOutputMetadataField;
}
set
{
this._cmdletOutputMetadataField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class InstanceMethodMetadata : CommonMethodMetadata
{
private InstanceMethodParameterMetadata[] _parametersField;
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("Parameter", IsNullable = false)]
public InstanceMethodParameterMetadata[] Parameters
{
get
{
return this._parametersField;
}
set
{
this._parametersField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class InstanceCmdletMetadata
{
private CommonCmdletMetadata _cmdletMetadataField;
private InstanceMethodMetadata _methodField;
private GetCmdletParameters _getCmdletParametersField;
/// <remarks/>
public CommonCmdletMetadata CmdletMetadata
{
get
{
return this._cmdletMetadataField;
}
set
{
this._cmdletMetadataField = value;
}
}
/// <remarks/>
public InstanceMethodMetadata Method
{
get
{
return this._methodField;
}
set
{
this._methodField = value;
}
}
/// <remarks/>
public GetCmdletParameters GetCmdletParameters
{
get
{
return this._getCmdletParametersField;
}
set
{
this._getCmdletParametersField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIncludeAttribute(typeof(WildcardablePropertyQuery))]
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class PropertyQuery
{
private CmdletParameterMetadataForGetCmdletFilteringParameter _cmdletParameterMetadataField;
/// <remarks/>
public CmdletParameterMetadataForGetCmdletFilteringParameter CmdletParameterMetadata
{
get
{
return this._cmdletParameterMetadataField;
}
set
{
this._cmdletParameterMetadataField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class WildcardablePropertyQuery : PropertyQuery
{
private bool _allowGlobbingField;
private bool _allowGlobbingFieldSpecified;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public bool AllowGlobbing
{
get
{
return this._allowGlobbingField;
}
set
{
this._allowGlobbingField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool AllowGlobbingSpecified
{
get
{
return this._allowGlobbingFieldSpecified;
}
set
{
this._allowGlobbingFieldSpecified = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11", IncludeInSchema = false)]
public enum ItemsChoiceType
{
/// <remarks/>
ExcludeQuery,
/// <remarks/>
MaxValueQuery,
/// <remarks/>
MinValueQuery,
/// <remarks/>
RegularQuery,
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class ClassMetadataData
{
private string _nameField;
private string _valueField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string Name
{
get
{
return this._nameField;
}
set
{
this._nameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTextAttribute()]
public string Value
{
get
{
return this._valueField;
}
set
{
this._valueField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class EnumMetadataEnum
{
private EnumMetadataEnumValue[] _valueField;
private string _enumNameField;
private string _underlyingTypeField;
private bool _bitwiseFlagsField;
private bool _bitwiseFlagsFieldSpecified;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Value")]
public EnumMetadataEnumValue[] Value
{
get
{
return this._valueField;
}
set
{
this._valueField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string EnumName
{
get
{
return this._enumNameField;
}
set
{
this._enumNameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string UnderlyingType
{
get
{
return this._underlyingTypeField;
}
set
{
this._underlyingTypeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public bool BitwiseFlags
{
get
{
return this._bitwiseFlagsField;
}
set
{
this._bitwiseFlagsField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool BitwiseFlagsSpecified
{
get
{
return this._bitwiseFlagsFieldSpecified;
}
set
{
this._bitwiseFlagsFieldSpecified = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class EnumMetadataEnumValue
{
private string _nameField;
private string _valueField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string Name
{
get
{
return this._nameField;
}
set
{
this._nameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType = "integer")]
public string Value
{
get
{
return this._valueField;
}
set
{
this._valueField = value;
}
}
}
}
#endif
#endif
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
// Cleanup Dialog created by 'core'
if( isObject( MessagePopupDlg ) )
MessagePopupDlg.delete();
if( isObject( MessageBoxYesNoDlg ) )
MessageBoxYesNoDlg.delete();
if( isObject( MessageBoxYesNoCancelDlg ) )
MessageBoxYesNoCancelDlg.delete();
if( isObject( MessageBoxOKCancelDetailsDlg ) )
MessageBoxOKCancelDetailsDlg.delete();
if( isObject( MessageBoxOKCancelDlg ) )
MessageBoxOKCancelDlg.delete();
if( isObject( MessageBoxOKDlg ) )
MessageBoxOKDlg.delete();
if( isObject( IODropdownDlg ) )
IODropdownDlg.delete();
// Load Editor Dialogs
exec("./messageBoxOk.ed.gui");
exec("./messageBoxYesNo.ed.gui");
exec("./messageBoxYesNoCancel.ed.gui");
exec("./messageBoxOKCancel.ed.gui");
exec("./messageBoxOKCancelDetailsDlg.ed.gui");
exec("./messagePopup.ed.gui");
exec("./IODropdownDlg.ed.gui");
// --------------------------------------------------------------------
// Message Sound
// --------------------------------------------------------------------
/*new SFXDescription(MessageBoxAudioDescription)
{
volume = 1.0;
isLooping = false;
is3D = false;
channel = $GuiAudioType;
};
new SFXProfile(messageBoxBeep)
{
filename = "./messageBoxSound";
description = MessageBoxAudioDescription;
preload = true;
};*/
//---------------------------------------------------------------------------------------------
// messageCallback
// Calls a callback passed to a message box.
//---------------------------------------------------------------------------------------------
function messageCallback(%dlg, %callback)
{
Canvas.popDialog(%dlg);
eval(%callback);
}
//The # in the function passed replaced with the output
//of the preset menu.
function IOCallback(%dlg, %callback)
{
%id = IODropdownMenu.getSelected();
%text = IODropdownMenu.getTextById(%id);
%callback = strreplace(%callback, "#", %text);
eval(%callback);
Canvas.popDialog(%dlg);
}
//---------------------------------------------------------------------------------------------
// MBSetText
// Sets the text of a message box and resizes it to accomodate the new string.
//---------------------------------------------------------------------------------------------
function MBSetText(%text, %frame, %msg)
{
// Get the extent of the text box.
%ext = %text.getExtent();
// Set the text in the center of the text box.
%text.setText("<just:center>" @ %msg);
// Force the textbox to resize itself vertically.
%text.forceReflow();
// Grab the new extent of the text box.
%newExtent = %text.getExtent();
// Get the vertical change in extent.
%deltaY = getWord(%newExtent, 1) - getWord(%ext, 1);
// Resize the window housing the text box.
%windowPos = %frame.getPosition();
%windowExt = %frame.getExtent();
%frame.resize(getWord(%windowPos, 0), getWord(%windowPos, 1) - (%deltaY / 2),
getWord(%windowExt, 0), getWord(%windowExt, 1) + %deltaY);
%frame.canMove = "0";
//%frame.canClose = "0";
%frame.resizeWidth = "0";
%frame.resizeHeight = "0";
%frame.canMinimize = "0";
%frame.canMaximize = "0";
//sfxPlayOnce( messageBoxBeep );
}
//---------------------------------------------------------------------------------------------
// Various message box display functions. Each one takes a window title, a message, and a
// callback for each button.
//---------------------------------------------------------------------------------------------
function MessageBoxOK(%title, %message, %callback)
{
MBOKFrame.text = %title;
Canvas.pushDialog(MessageBoxOKDlg);
MBSetText(MBOKText, MBOKFrame, %message);
MessageBoxOKDlg.callback = %callback;
}
function MessageBoxOKDlg::onSleep( %this )
{
%this.callback = "";
}
function MessageBoxOKCancel(%title, %message, %callback, %cancelCallback)
{
MBOKCancelFrame.text = %title;
Canvas.pushDialog(MessageBoxOKCancelDlg);
MBSetText(MBOKCancelText, MBOKCancelFrame, %message);
MessageBoxOKCancelDlg.callback = %callback;
MessageBoxOKCancelDlg.cancelCallback = %cancelCallback;
}
function MessageBoxOKCancelDlg::onSleep( %this )
{
%this.callback = "";
}
function MessageBoxOKCancelDetails(%title, %message, %details, %callback, %cancelCallback)
{
if(%details $= "")
{
MBOKCancelDetailsButton.setVisible(false);
}
MBOKCancelDetailsScroll.setVisible(false);
MBOKCancelDetailsFrame.setText( %title );
Canvas.pushDialog(MessageBoxOKCancelDetailsDlg);
MBSetText(MBOKCancelDetailsText, MBOKCancelDetailsFrame, %message);
MBOKCancelDetailsInfoText.setText(%details);
%textExtent = MBOKCancelDetailsText.getExtent();
%textExtentY = getWord(%textExtent, 1);
%textPos = MBOKCancelDetailsText.getPosition();
%textPosY = getWord(%textPos, 1);
%extentY = %textPosY + %textExtentY + 65;
MBOKCancelDetailsInfoText.setExtent(285, 128);
MBOKCancelDetailsFrame.setExtent(300, %extentY);
MessageBoxOKCancelDetailsDlg.callback = %callback;
MessageBoxOKCancelDetailsDlg.cancelCallback = %cancelCallback;
MBOKCancelDetailsFrame.defaultExtent = MBOKCancelDetailsFrame.getExtent();
}
function MBOKCancelDetailsToggleInfoFrame()
{
if(!MBOKCancelDetailsScroll.isVisible())
{
MBOKCancelDetailsScroll.setVisible(true);
MBOKCancelDetailsText.forceReflow();
%textExtent = MBOKCancelDetailsText.getExtent();
%textExtentY = getWord(%textExtent, 1);
%textPos = MBOKCancelDetailsText.getPosition();
%textPosY = getWord(%textPos, 1);
%verticalStretch = %textExtentY;
if((%verticalStretch > 260) || (%verticalStretch < 0))
%verticalStretch = 260;
%extent = MBOKCancelDetailsFrame.defaultExtent;
%height = getWord(%extent, 1);
%posY = %textPosY + %textExtentY + 10;
%posX = getWord(MBOKCancelDetailsScroll.getPosition(), 0);
MBOKCancelDetailsScroll.setPosition(%posX, %posY);
MBOKCancelDetailsScroll.setExtent(getWord(MBOKCancelDetailsScroll.getExtent(), 0), %verticalStretch);
MBOKCancelDetailsFrame.setExtent(300, %height + %verticalStretch + 10);
} else
{
%extent = MBOKCancelDetailsFrame.defaultExtent;
%width = getWord(%extent, 0);
%height = getWord(%extent, 1);
MBOKCancelDetailsFrame.setExtent(%width, %height);
MBOKCancelDetailsScroll.setVisible(false);
}
}
function MessageBoxOKCancelDetailsDlg::onSleep( %this )
{
%this.callback = "";
}
function MessageBoxYesNo(%title, %message, %yesCallback, %noCallback)
{
MBYesNoFrame.text = %title;
MessageBoxYesNoDlg.profile = "GuiOverlayProfile";
Canvas.pushDialog(MessageBoxYesNoDlg);
MBSetText(MBYesNoText, MBYesNoFrame, %message);
MessageBoxYesNoDlg.yesCallBack = %yesCallback;
MessageBoxYesNoDlg.noCallback = %noCallBack;
}
function MessageBoxYesNoCancel(%title, %message, %yesCallback, %noCallback, %cancelCallback)
{
MBYesNoCancelFrame.text = %title;
MessageBoxYesNoDlg.profile = "GuiOverlayProfile";
Canvas.pushDialog(MessageBoxYesNoCancelDlg);
MBSetText(MBYesNoCancelText, MBYesNoCancelFrame, %message);
MessageBoxYesNoCancelDlg.yesCallBack = %yesCallback;
MessageBoxYesNoCancelDlg.noCallback = %noCallBack;
MessageBoxYesNoCancelDlg.cancelCallback = %cancelCallback;
}
function MessageBoxYesNoDlg::onSleep( %this )
{
%this.yesCallback = "";
%this.noCallback = "";
}
//---------------------------------------------------------------------------------------------
// MessagePopup
// Displays a message box with no buttons. Disappears after %delay milliseconds.
//---------------------------------------------------------------------------------------------
function MessagePopup(%title, %message, %delay)
{
// Currently two lines max.
MessagePopFrame.setText(%title);
Canvas.pushDialog(MessagePopupDlg);
MBSetText(MessagePopText, MessagePopFrame, %message);
if (%delay !$= "")
schedule(%delay, 0, CloseMessagePopup);
}
//---------------------------------------------------------------------------------------------
// IODropdown
// By passing in a simgroup or simset, the user will be able to choose a child of that group
// through a guiPopupMenuCtrl
//---------------------------------------------------------------------------------------------
function IODropdown(%title, %message, %simgroup, %callback, %cancelCallback)
{
IODropdownFrame.text = %title;
Canvas.pushDialog(IODropdownDlg);
MBSetText(IODropdownText, IODropdownFrame, %message);
if(isObject(%simgroup))
{
for(%i = 0; %i < %simgroup.getCount(); %i++)
IODropdownMenu.add(%simgroup.getObject(%i).getName());
}
IODropdownMenu.sort();
IODropdownMenu.setFirstSelected(0);
IODropdownDlg.callback = %callback;
IODropdownDlg.cancelCallback = %cancelCallback;
}
function IODropdownDlg::onSleep( %this )
{
%this.callback = "";
%this.cancelCallback = "";
IODropdownMenu.clear();
}
function CloseMessagePopup()
{
Canvas.popDialog(MessagePopupDlg);
}
//---------------------------------------------------------------------------------------------
// "Old" message box function aliases for backwards-compatibility.
//---------------------------------------------------------------------------------------------
function MessageBoxOKOld( %title, %message, %callback )
{
MessageBoxOK( %title, %message, %callback );
}
function MessageBoxOKCancelOld( %title, %message, %callback, %cancelCallback )
{
MessageBoxOKCancel( %title, %message, %callback, %cancelCallback );
}
function MessageBoxYesNoOld( %title, %message, %yesCallback, %noCallback )
{
MessageBoxYesNo( %title, %message, %yesCallback, %noCallback );
}
| |
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 MyWebAPIServer.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using Npgsql;
using NpgsqlTypes;
using System.Data;
using Epi.Data;
namespace Epi.Data.PostgreSQL
{
/// <summary>
/// MySQL implementation of DbDriverBase implementation of IDbDriver implementation.
/// </summary>
public partial class PostgreSQLDatabase : DbDriverBase
{
/// <summary>
/// MySQL Database Constructor
/// </summary>
public PostgreSQLDatabase() : base() { }
/// <summary>
/// Set MySQL path
/// </summary>
/// <param name="filePath"></param>
public void SetDataSourceFilePath(string filePath)
{
this.ConnectionString = filePath;
}
/// <summary>
/// Returns the full name of the data source
/// </summary>
public override string FullName // Implements Database.FullName
{
get
{
return DataSource + "." + DbName;
}
}
/// <summary>
/// Connection String attribute
/// </summary>
public override string ConnectionDescription
{
get { return "MySQL Database: " + this.DbName; }
}
/// <summary>
/// Returns the maximum number of columns a table can have.
/// </summary>
public override int TableColumnMax
{
get { return 1020; }
}
/// <summary>
/// Adds a column to the table
/// </summary>
/// <param name="tableName">name of the table</param>
/// <param name="column">The column</param>
/// <returns>Boolean</returns>
public override bool AddColumn(string tableName, TableColumn column)
{
// E. Knudsen - TODO
return false;
}
public override string SchemaPrefix
{
get
{
return string.Empty;
}
}
/// <summary>
/// Create a table
/// </summary>
/// <param name="tableName">Name of the table to create</param>
/// <param name="columns">Collection of columns for the table</param>
public override void CreateTable(string tableName, List<TableColumn> columns)
{
StringBuilder sb = new StringBuilder();
sb.Append("create table if not exists ");
sb.Append(tableName);
sb.Append(" (");
AddColumns(sb, tableName, columns);
sb.Append("); ");
#region Input Validation
if (sb == null)
{
throw new ArgumentNullException("Query is null");
}
#endregion
NpgsqlCommand command = new NpgsqlCommand(sb.ToString());
NpgsqlConnection conn = new NpgsqlConnection(this.ConnectionString);
try
{
command.Connection = conn;
OpenConnection(conn);
command.ExecuteNonQuery();
}
finally
{
CloseConnection(conn);
}
}
#region Private Members
// Add columns to a My SQL Database
private StringBuilder AddColumns(StringBuilder sb, string tableName, List<TableColumn> columns)
{
foreach (TableColumn column in columns)
{
string columnType = GetDbSpecificColumnType(column.DataType);
sb.Append(column.Name);
sb.Append(" ");
sb.Append(columnType);
if (column.Length != null)
{
if (columnType.Equals("text") ||
(columnType.Equals("integer")) ||
(columnType.Equals("bit")) ||
(columnType.Equals("tinyint")) ||
(columnType.Equals("smallint")) ||
(columnType.Equals("mediumint")) ||
(columnType.Equals("mediumtext")) ||
(columnType.Equals("bigint")) ||
(columnType.Equals("binary"))
)
{
if (column.Length.Value.ToString() != null)
{
sb.Append("(");
sb.Append(column.Length.Value.ToString());
sb.Append(")");
}
}
else if ((columnType.Equals("double")) ||
(columnType.Equals("float")) ||
(columnType.Equals("decimal"))
)
{
sb.Append("(");
sb.Append(column.Length.Value.ToString());
if (column.Precision != null)
{
sb.Append(", ");
sb.Append(column.Precision.ToString());
}
sb.Append(") ");
}
}
if (!column.AllowNull)
{
sb.Append(" not");
}
sb.Append(" null");
if (column.IsIdentity)
{
sb.Append(" auto_increment");
}
if (column.IsPrimaryKey)
{
sb.Append(" primary key");
}
sb.Append(", ");
}
//remove trailing comma and space
sb.Remove(sb.Length - 2, 2);
return sb;
}
/// <summary>
/// Set MySQL Data Type mapping
/// </summary>
/// <param name="dataType">DataType</param>
/// <returns>String</returns>
public override string GetDbSpecificColumnType(GenericDbColumnType dataType)
{
switch (dataType)
{
case GenericDbColumnType.AnsiString:
case GenericDbColumnType.AnsiStringFixedLength:
case GenericDbColumnType.Byte:
case GenericDbColumnType.Guid:
case GenericDbColumnType.String:
case GenericDbColumnType.StringFixedLength:
return "text";
case GenericDbColumnType.Binary:
return "binary";
case GenericDbColumnType.Boolean:
return "bool";
case GenericDbColumnType.Currency:
case GenericDbColumnType.Double:
return "double";
case GenericDbColumnType.Date:
return "date";
case GenericDbColumnType.DateTime:
return "datetime";
case GenericDbColumnType.Decimal:
return "decimal";
case GenericDbColumnType.Image:
return PostgreSQLDbColumnType.Longblob;
case GenericDbColumnType.Int16:
case GenericDbColumnType.UInt16:
return "smallint";
case GenericDbColumnType.Int32:
case GenericDbColumnType.UInt32:
return "integer";
case GenericDbColumnType.Int64:
case GenericDbColumnType.UInt64:
return "bigint";
case GenericDbColumnType.Object:
return "blob";
case GenericDbColumnType.SByte:
return "tinyint";
case GenericDbColumnType.Single:
return "float";
case GenericDbColumnType.StringLong:
return "longtext";
case GenericDbColumnType.Time:
return "time";
case GenericDbColumnType.VarNumeric:
return "decimal";
case GenericDbColumnType.Xml:
return "mediumtext";
default:
throw new GeneralException("genericDbColumnType is unknown");
}
}
#endregion
private string connectionString;
/// <summary>
/// Connection String attribute
/// </summary>
public override string ConnectionString
{
get
{
return connectionString;
}
set
{
this.connectionString = value;
try
{
IDbConnection conn = GetConnection();
this.DbName = conn.Database;
}
catch
{
this.connectionString = null;
}
}
}
/// <summary>
/// Build connection string
/// </summary>
/// <param name="filePath">File path</param>
/// <param name="password">Password</param>
/// <returns>Connection string</returns>
public static string BuildConnectionString(string filePath, string password)
{
//This method may need to be deprecated
//Windows
// "Persist Security Info=False;database=myDB;server=myHost;Connect Timeout=30;user id=myUser; pwd=myPass";
//Linux with MONO: filepath is all of the below statement
// "database=myDB;server=/var/lib/mysql/mysql.sock;user id=myUser; pwd=myPass";
return string.Empty;
}
/// <summary>
/// Builds a connection string using default parameters given a database name
/// </summary>
/// <param name="databaseName">Name of the database</param>
/// <returns>A connection string</returns>
public static string BuildDefaultConnectionString(string databaseName)
{
//This method may need to be deprecated
//Linux: return BuildConnectionString("database=" + databaseName + ";server=//var/lib/mysql/mysql.sock;user id=myUser; pwd=myPass","");
return null;
}
/// <summary>
/// Creates initial connection string from user-supplied database, server, user, and password input.
/// </summary>
/// <param name="database">Data store.</param>
/// <param name="server">Server location of database.</param>
/// <param name="user">User account login Id.</param>
/// <param name="password">User login password.</param>
/// <returns></returns>
public string BuildDefaultConnectionString(string database, string server, int port, string user, string password)
{
NpgsqlConnectionStringBuilder mySQLConnBuild = new NpgsqlConnectionStringBuilder();
//mySQLConnBuild.PersistSecurityInfo = false;
mySQLConnBuild.Database = database;
mySQLConnBuild.Host = server;
mySQLConnBuild.Port = port;
mySQLConnBuild.UserName = user;
mySQLConnBuild.Password = password;
return mySQLConnBuild.ToString();
}
/// <summary>
/// Change the data type of the column in current database
/// </summary>
/// <param name="tableName">name of the table</param>
/// <param name="columnName">name of the column</param>
/// <param name="columnType">new data type of the column</param>
/// <returns>Boolean</returns>
public override bool AlterColumnType(string tableName, string columnName, string columnType)
{
// dpb todo
return false;
}
/// <summary>
/// Tests database connectivity using current ConnnectionString
/// </summary>
/// <returns></returns>
public override bool TestConnection()
{
try
{
return TestConnection(this.ConnectionString);
}
catch (Exception ex)
{
throw new GeneralException("Could not connect to MySQL Database.", ex);
}
}
/// <summary>
/// Tests database connectivity using supplied connection string
/// </summary>
/// <param name="connectionString"></param>
/// <returns></returns>
protected bool TestConnection(string connectionString)
{
NpgsqlConnection testConnection = GetConnection(connectionString);
try
{
OpenConnection(testConnection);
}
finally
{
CloseConnection(testConnection);
}
return true;
}
/// <summary>
/// Gets an connection instance based on current ConnectionString value
/// </summary>
/// <returns>Connection instance</returns>
public override IDbConnection GetConnection()
{
return GetNativeConnection(connectionString);
}
/// <summary>
/// Gets an connection instance based on current ConnectionString value
/// </summary>
/// <returns>Connection instance</returns>
protected NpgsqlConnection GetConnection(string connectionString)
{
NpgsqlConnectionStringBuilder mySQLConnectionStringBuilder = new NpgsqlConnectionStringBuilder(connectionString);
return new NpgsqlConnection(mySQLConnectionStringBuilder.ToString());
}
public override bool IsBulkOperation
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
private string dbName = string.Empty;
/// <summary>
/// Gets or sets the Database name
/// </summary>
public override string DbName
{
get
{
return dbName;
}
set
{
dbName = value;
}
}
/// <summary>
/// Gets an OLE-compatible connection string.
/// This is needed by Epi Map, as ESRI does not understand .NET connection strings.
/// </summary>
public override string OleConnectionString
{
get { return null; }
}
/// <summary>
/// MySQL data source.
/// </summary>
public override string DataSource
{
get
{
NpgsqlConnection sqlconn = GetConnection(connectionString) as NpgsqlConnection;
if (sqlconn != null)
{
return sqlconn.DataSource;
}
else
{
return null;
}
}
}
/// <summary>
/// Gets table schema information
/// </summary>
/// <returns>DataTable with schema information</returns>
public override Epi.DataSets.TableSchema.TablesDataTable GetTableSchema()
{
NpgsqlConnection conn = this.GetNativeConnection();
try
{
OpenConnection(conn);
DataTable table = conn.GetSchema("Tables", new string[0]);
DataSets.TableSchema tableSchema = new Epi.DataSets.TableSchema();
tableSchema.Merge(table);
return tableSchema._Tables;
}
finally
{
CloseConnection(conn);
}
}
#region Native Driver Implementation
/// <summary>
/// Returns a native equivalent of a DbParameter
/// </summary>
/// <returns>A native equivalent of a DbParameter</returns>
protected virtual NpgsqlParameter ConvertToNativeParameter(QueryParameter parameter)
{
//TODO: Test this when MySQL comes back on the radar.
if (parameter.DbType.Equals(DbType.Guid))
{
parameter.Value = new Guid(parameter.Value.ToString());
}
return new NpgsqlParameter(parameter.ParameterName, CovertToNativeDbType(parameter.DbType), parameter.Size, parameter.SourceColumn, parameter.Direction, parameter.IsNullable, parameter.Precision, parameter.Scale, parameter.SourceVersion, parameter.Value);
}
/// <summary>
/// Gets a native connection instance based on current ConnectionString value
/// </summary>
/// <returns>Native connection object</returns>
protected virtual NpgsqlConnection GetNativeConnection()
{
return GetNativeConnection(connectionString);
}
/// <summary>
/// Gets a native connection instance from supplied connection string
/// </summary>
/// <returns>Native connection object</returns>
protected virtual NpgsqlConnection GetNativeConnection(string connectionString)
{
return new NpgsqlConnection(connectionString);
}
/// <summary>
/// Returns a native command object
/// </summary>
/// <param name="transaction">Null is not allowed. </param>
/// <returns></returns>
protected NpgsqlCommand GetNativeCommand(IDbTransaction transaction)
{
NpgsqlTransaction mySqltransaction = transaction as NpgsqlTransaction;
#region Input Validation
if (mySqltransaction == null)
{
throw new ArgumentException("Transaction parameter must be a NpgsqlTransaction.", "transaction");
}
#endregion
return new NpgsqlCommand(null, (NpgsqlConnection)transaction.Connection, (NpgsqlTransaction)transaction);
}
/// <summary>
/// Executes a SELECT statement against the database and returns a disconnected data table. NOTE: Use this overload to work with Typed DataSets.
/// </summary>
/// <param name="selectQuery">The query to be executed against the database</param>
/// <param name="dataTable">Table that will contain the result</param>
/// <returns>A data table object</returns>
public override DataTable Select(Query selectQuery, DataTable dataTable)
{
#region Input Validation
if (selectQuery == null)
{
throw new ArgumentNullException("selectQuery");
}
if (dataTable == null)
{
throw new ArgumentNullException("dataTable");
}
#endregion Input Validation
if (selectQuery.SqlStatement.Contains("TOP 2"))
{
selectQuery = CreateQuery(selectQuery.SqlStatement.Replace("TOP 2 ", string.Empty).Replace(";",string.Empty) + " LIMIT 2");
}
if (selectQuery.SqlStatement.Contains("["))
{
selectQuery = CreateQuery(selectQuery.SqlStatement.Replace("[", string.Empty).Replace("]", string.Empty));
}
IDbConnection connection = GetConnection(connectionString);
NpgsqlDataAdapter adapter = new NpgsqlDataAdapter();
adapter.SelectCommand = (NpgsqlCommand)GetCommand(selectQuery.SqlStatement, connection, selectQuery.Parameters);
try
{
//Logger.Log(selectQuery);
adapter.Fill(dataTable);
adapter.FillSchema(dataTable, SchemaType.Source);
return dataTable;
}
catch (Exception ex)
{
throw new System.ApplicationException("Error executing select query against the database.", ex);
}
}
/// <summary>
/// Warning! This method does not support transactions!
/// </summary>
/// <param name="dataTable"></param>
/// <param name="tableName"></param>
/// <param name="insertQuery"></param>
/// <param name="updateQuery"></param>
public override void Update(DataTable dataTable, string tableName, Query insertQuery, Query updateQuery)
{
#region Input Validation
if (dataTable == null)
{
throw new ArgumentNullException("DataTable");
}
if (string.IsNullOrEmpty(tableName))
{
throw new ArgumentNullException("TableName");
}
if (insertQuery == null)
{
throw new ArgumentNullException("InsertQuery");
}
if (updateQuery == null)
{
throw new ArgumentNullException("UpdateQuery");
}
#endregion Input Validation
IDbConnection connection = GetConnection(connectionString);
NpgsqlDataAdapter adapter = new NpgsqlDataAdapter();
string edittedUpdateQuery = updateQuery.SqlStatement;
//edittedUpdateQuery = updateQuery.SqlStatement.Replace("@OldValue", "`@OldValue`");
//edittedUpdateQuery = edittedUpdateQuery.Replace("@NewValue", "`@NewValue`");
adapter.InsertCommand = (NpgsqlCommand)GetCommand(insertQuery.SqlStatement, connection, insertQuery.Parameters);
adapter.UpdateCommand = (NpgsqlCommand)GetCommand(edittedUpdateQuery, connection, updateQuery.Parameters);
try
{
//Logger.Log(insertQuery);
//Logger.Log(updateQuery);
adapter.Update(dataTable);
}
catch (Exception ex)
{
throw new System.ApplicationException("Error updating data.", ex);
}
}
/// <summary>
/// Updates the GUIDs of a child table with those of the parent via a uniquekey/fkey relationship
/// </summary>
public override void UpdateGUIDs(string childTableName, string parentTableName)
{
}
/// <summary>
/// Updates the foreign and unique keys of a child table with those of the parent via the original keys that existed prior to an import from an Epi Info 3.5.x project.
/// </summary>
public override void UpdateKeys(string childTableName, string parentTableName)
{
}
#endregion
/// <summary>
/// Get a count of the number of tables
/// </summary>
/// <returns>Integer count of tables</returns>
public override int GetTableCount()
{
DataTable dtSchema = GetTableSchema();
return dtSchema.Rows.Count;
}
/// <summary>
/// Return the number of colums in the specified table
/// </summary>
/// <remarks>
/// Originaly intended to be used to keep view tables from getting to wide.
/// </remarks>
/// <param name="tableName"></param>
/// <returns>the number of columns in the </returns>
public override int GetTableColumnCount(string tableName)
{
DataTable table = this.GetSchema("COLUMNS", tableName);
return table.Rows.Count;
}
/// <summary>
/// Select statement
/// </summary>
/// <param name="selectQuery">Query statement</param>
/// <returns>DataTable result from query</returns>
public override System.Data.DataTable Select(Query selectQuery)
{
#region Input Validation
if (selectQuery == null)
{
throw new ArgumentNullException("selectQuery");
}
#endregion
DataTable table = new DataTable();
return Select(selectQuery, table);
}
/// <summary>
/// Checks to see if a given column exists in a given table
/// </summary>
/// <param name="tableName">Name of the table</param>
/// <param name="columnName">Name of the column</param>
/// <returns></returns>
public override bool ColumnExists(string tableName, string columnName)
{
Query query = this.CreateQuery("select * from information_schema.COLUMNS where TABLE_NAME=@TableName and COLUMN_NAME=@ColumnName and table_schema=@dbName;");
query.Parameters.Add(new QueryParameter("@TableName", DbType.String, tableName));
query.Parameters.Add(new QueryParameter("@ColumnName", DbType.String, columnName));
query.Parameters.Add(new QueryParameter("@dbName", DbType.String, this.dbName));
return (Select(query).Rows.Count > 0);
}
/// <summary>
/// Compact the database
/// << may only apply to Access databases >>
/// </summary>
public override bool CompactDatabase()
{
return true;
}
/// <summary>
/// Executes a non-query statement
/// </summary>
/// <param name="nonQueryStatement">Query to execute</param>
/// <returns>An integer</returns>
public override int ExecuteNonQuery(Query nonQueryStatement)
{
#region Input Validation
if (nonQueryStatement == null)
{
throw new ArgumentNullException("query");
}
#endregion
//Logger.Log(nonQueryStatement);
IDbConnection conn = this.GetConnection(connectionString);
IDbCommand command = GetCommand(nonQueryStatement.SqlStatement, conn, nonQueryStatement.Parameters);
try
{
OpenConnection(conn);
return command.ExecuteNonQuery();
}
finally
{
CloseConnection(conn);
}
}
/// <summary>
/// Executes a SQL statement and returns total records affected.
/// </summary>
/// <param name="nonQueryStatement">The query to be executed against the database.</param>
/// <param name="transaction">The transaction to be performed at a data source.</param>
public override int ExecuteNonQuery(Query nonQueryStatement, System.Data.IDbTransaction transaction)
{
#region Input Validation
if (nonQueryStatement == null)
{
throw new ArgumentNullException("query");
}
if (transaction == null)
{
throw new ArgumentNullException("transaction");
}
#endregion
//Logger.Log(nonQueryStatement);
IDbCommand command = GetCommand(nonQueryStatement.SqlStatement, transaction, nonQueryStatement.Parameters);
try
{
// do not try to open connection, we are inside a transaction
return command.ExecuteNonQuery();
}
finally
{
// do not close connection, we are inside a transaction
}
}
/// <summary>
/// Executes a scalar query against the database
/// </summary>
/// <param name="scalarStatement">The query to be executed against the database</param>
/// <returns></returns>
public override object ExecuteScalar(Query scalarStatement)
{
#region Input Validation
if (scalarStatement == null)
{
throw new ArgumentNullException("query");
}
#endregion
object result;
IDbConnection conn = GetConnection(connectionString);
IDbCommand command = GetCommand(scalarStatement.SqlStatement, conn, scalarStatement.Parameters);
try
{
OpenConnection(conn);
//Logger.Log(scalarStatement);
result = command.ExecuteScalar();
}
finally
{
CloseConnection(conn);
}
return result;
}
/// <summary>
/// Executes a scalar query against the database using an existing transaction
/// </summary>
/// <param name="scalarStatement">The query to be executed against the database</param>
/// <param name="transaction">Null is allowed</param>
/// <returns></returns>
public override object ExecuteScalar(Query scalarStatement, System.Data.IDbTransaction transaction)
{
#region Input Validation
if (scalarStatement == null)
{
throw new ArgumentNullException("query");
}
if (transaction == null)
{
throw new ArgumentNullException("transaction");
}
#endregion
object result;
IDbCommand command = GetCommand(scalarStatement.SqlStatement, transaction, scalarStatement.Parameters);
try
{
// do not open connection, we are inside a transaction
result = command.ExecuteScalar();
}
finally
{
// do not close connection, we are inside a transaction
}
return result;
}
/// <summary>
/// Delete a specific table in the database
/// </summary>
/// <param name="tableName">Name of the table</param>
/// <returns>Boolean</returns>
public override bool DeleteTable(string tableName)
{
Query query = this.CreateQuery("Drop Table @Name");
query.Parameters.Add(new QueryParameter("@Name", DbType.String, tableName));
return (ExecuteNonQuery(query) > 0);
}
/// <summary>
/// Delete a specific column in the database
/// </summary>
/// <param name="tableName">Name of the table</param>
/// <param name="columnName">Name of the column</param>
/// <returns>Boolean</returns>
public override bool DeleteColumn(string tableName, string columnName)
{
Query query = this.CreateQuery("ALTER TABLE " + tableName + " DROP COLUMN " + columnName);
return (ExecuteNonQuery(query) > 0);
}
/// <summary>
/// Gets a value indicating whether or not a specific table exists in the database
/// </summary>
/// <param name="tableName">Name of the table</param>
/// <returns>Boolean</returns>
public override bool TableExists(string tableName)
{
Query query = this.CreateQuery("select * from information_schema.tables where TABLE_NAME=@Name and TABLE_SCHEMA=@DatabaseName");
query.Parameters.Add(new QueryParameter("@Name", DbType.String, tableName));
query.Parameters.Add(new QueryParameter("@DatabaseName", DbType.String, this.DbName));
try
{
if (Select(query).Rows.Count > 0)
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
throw new System.ApplicationException("Error checking table status.", ex);
}
}
/// <summary>
/// Gets column schema information about an MySQL table
/// </summary>
/// <param name="tableName">Name of the table</param>
/// <returns>DataTable with schema information</returns>
public override Epi.DataSets.TableColumnSchema.ColumnsDataTable GetTableColumnSchema(string tableName)
{
DataTable table = this.GetSchema("Columns", tableName);
DataTable tableToMerge = table.Copy();
tableToMerge.Rows.Clear();
string isNullableCol = table.Rows[0].ItemArray[6].ToString();
if (isNullableCol.Equals("YES"))
{
}
else
{
tableToMerge.Rows[0].ItemArray[6] = "false";
tableToMerge.Rows[0].ItemArray[6] = Boolean.Parse(tableToMerge.Rows[0].ItemArray[6].ToString());
}
//string datatype = table.Rows[0].ItemArray[7].ToString();
DataSets.TableColumnSchema tableColumnSchema = new Epi.DataSets.TableColumnSchema();
//string dc = tableColumnSchema.Columns.IS_NULLABLEColumn.DataType.FullName;
tableColumnSchema.Merge(tableToMerge);
return tableColumnSchema.Columns;
}
/// <summary>
/// Gets column schema information about an OLE table
/// </summary>
/// <param name="tableName">Name of the table</param>
/// <returns>DataTable with schema information</returns>
public override DataSets.ANSI.TableColumnSchema.ColumnsDataTable GetTableColumnSchemaANSI(string tableName)
{
try
{
DataTable table = this.GetSchema("Columns", tableName);
// IS_NULLABLE and DATA_TYPE are different data types for non OleDb DataTables.
DataSets.ANSI.TableColumnSchema tableColumnSchema = new Epi.DataSets.ANSI.TableColumnSchema();
tableColumnSchema.Merge(table, false, MissingSchemaAction.Ignore);
return tableColumnSchema.Columns;
}
catch (Exception ex)
{
throw new GeneralException("Could not get table column schema for." + tableName, ex);
}
}
/// <summary>
/// Gets the selected schema of the table specified in tableName
/// </summary>
/// <param name="collectionName"></param>
/// <param name="tableName"></param>
/// <returns>DataTable with schema information</returns>
///
private DataTable GetSchema(string collectionName, string tableName)
{
NpgsqlConnection conn = this.GetNativeConnection();
try
{
OpenConnection(conn);
return conn.GetSchema(collectionName, new string[] { null, null, tableName, null });
}
finally
{
CloseConnection(conn);
}
}
/// <summary>
/// Gets the selected schema of the table specified in tableName
/// </summary>
/// <param name="collectionName"></param>
/// <returns>DataTable with schema information</returns>
private DataTable GetSchema(string collectionName)
{
NpgsqlConnection conn = this.GetNativeConnection();
try
{
OpenConnection(conn);
return conn.GetSchema(collectionName, new string[] { null, null, null });
}
finally
{
CloseConnection(conn);
}
}
/// <summary>
/// Gets Primary_Keys schema information about a MySQL table
/// </summary>
/// <param name="tableName">Name of the table</param>
/// <returns>DataTable with schema information</returns>
public override Epi.DataSets.TableKeysSchema.Primary_KeysDataTable GetTableKeysSchema(string tableName)
{
DataSets.TableKeysSchema schema = new Epi.DataSets.TableKeysSchema();
NpgsqlConnection conn = this.GetNativeConnection();
bool alreadyOpen = (conn.State != ConnectionState.Closed);
try
{
if (!alreadyOpen)
{
OpenConnection(conn);
}
string query = "select KU.TABLE_CATALOG, KU.TABLE_SCHEMA, KU.TABLE_NAME, COLUMN_NAME, " +
"0 as COLUMN_PROPID, ORDINAL_POSITION as ORDINAL, KU.CONSTRAINT_NAME as PK_NAME " +
"from INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC " +
"inner join " +
"INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU " +
"on TC.CONSTRAINT_TYPE = 'primary key' and " +
"TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME " +
"where KU.TABLE_NAME = '" + tableName +
"' order by KU.ORDINAL_POSITION;";
NpgsqlDataAdapter da = new NpgsqlDataAdapter(query, conn);
//Logger.Log(query);
da.Fill(schema.Primary_Keys);
da.Dispose();
}
catch (Exception ex)
{
throw new GeneralException("Unable to obtain primary keys schema.", ex);
}
finally
{
if (!alreadyOpen && conn.State != ConnectionState.Closed)
{
CloseConnection(conn);
}
}
return schema.Primary_Keys;
}
/// <summary>
/// Gets the contents of a table
/// </summary>
/// <param name="tableName">Name of the table</param>
/// <returns>Datatable containing the table data</returns>
public override System.Data.DataTable GetTableData(string tableName)
{
return GetTableData(tableName, string.Empty, string.Empty);
}
/// <summary>
/// Returns contents of a table.
/// </summary>
/// <param name="tableName"></param>
/// <param name="columnNames">Comma delimited string of column names and ASC/DESC order</param>
public override System.Data.DataTable GetTableData(string tableName, string columnNames)
{
return GetTableData(tableName, columnNames, string.Empty);
}
/// <summary>
/// Returns contents of a table.
/// </summary>
/// <param name="tableName"></param>
/// <param name="columnNames"></param>
/// <param name="sortCriteria">Comma delimited string of column names and ASC/DESC order</param>
/// <returns>DataTable</returns>
public override System.Data.DataTable GetTableData(string tableName, string columnNames, string sortCriteria)
{
#region Input Validation
if (tableName == null)
{
throw new ArgumentNullException("tableName");
}
#endregion
try
{
if (string.IsNullOrEmpty(columnNames))
{
columnNames = Epi.StringLiterals.STAR;
}
string queryString = "select " + columnNames + " from [" + tableName + "]";
if (!string.IsNullOrEmpty(sortCriteria))
{
queryString += " order by " + sortCriteria;
}
Query query = this.CreateQuery(queryString);
return Select(query);
}
finally
{
}
}
/// <summary>
/// Returns contents of a table with only the top two rows.
/// </summary>
/// <param name="tableName">The name of the table to query</param>
/// <returns>DataTable</returns>
public override DataTable GetTopTwoTable(string tableName)
{
#region Input Validation
if (tableName == null)
{
throw new ArgumentNullException("tableName");
}
#endregion
try
{
string queryString = "select * from " + tableName + " limit 2";
Query query = this.CreateQuery(queryString);
return Select(query);
}
finally
{
}
}
/// <summary>
/// Create a reader from a table
/// </summary>
/// <param name="tableName">name of table</param>
/// <returns>IDataReader reader</returns>
public override System.Data.IDataReader GetTableDataReader(string tableName)
{
#region Input Validation
if (tableName == null)
{
throw new ArgumentNullException("tableName");
}
#endregion
Query query = this.CreateQuery("select * from " + tableName);
return this.ExecuteReader(query);
}
public override IDataReader GetTableDataReader(string tableName, string sortColumnName)
{
Query query = this.CreateQuery("select * from " + tableName + " ORDER BY " + sortColumnName);
return this.ExecuteReader(query);
}
/// <summary>
/// Executes a query and returns a stream of rows
/// </summary>
/// <param name="selectQuery">The query to be executed against the database</param>
/// <returns>A data reader object</returns>
public override System.Data.IDataReader ExecuteReader(Query selectQuery)
{
#region Input Validation
if (selectQuery == null)
{
throw new ArgumentNullException("SelectQuery");
}
#endregion
return ExecuteReader(selectQuery, CommandBehavior.Default);
}
/// <summary>
/// Executes a query and returns a stream of rows
/// </summary>
/// <param name="selectQuery">The query to be executed against the database</param>
/// <param name="commandBehavior"></param>
/// <returns>A data reader object</returns>
public override System.Data.IDataReader ExecuteReader(Query selectQuery, CommandBehavior commandBehavior)
{
#region Input Validation
if (selectQuery == null)
{
throw new ArgumentNullException("SelectQuery");
}
#endregion
IDbConnection connection = GetConnection();
try
{
OpenConnection(connection);
IDbCommand command = GetCommand(selectQuery.SqlStatement, connection, selectQuery.Parameters);
return command.ExecuteReader(commandBehavior);
}
catch (Exception ex)
{
throw new System.ApplicationException("Could not execute reader", ex);
}
finally
{
}
}
/// <summary>
/// Get the column names for a table
/// </summary>
/// <param name="tableName">Table name</param>
/// <returns>List of column names</returns>
public override List<string> GetTableColumnNames(string tableName)
{
//DataTable table = this.GetSchema("COLUMNS", tableName);
//List<string> list = new List<string>();
//foreach (DataRow row in table.Rows)
//{
// list.Add(row["COLUMN_NAME"].ToString());
//}
//return list;
DataTable table = this.GetTopTwoTable(tableName);
List<string> list = new List<string>();
foreach (DataColumn column in table.Columns)
{
list.Add(column.ColumnName);
}
return list;
}
/// <summary>
/// </summary>
/// <param name="tableName"></param>
/// <returns></returns>
public override Dictionary<string, int> GetTableColumnNameTypePairs(string tableName)
{
DataTable table = this.GetSchema("COLUMNS", tableName);
Dictionary<string, int> dictionary = new Dictionary<string, int>();
foreach (DataRow row in table.Rows)
{
dictionary.Add((string)row["COLUMN_NAME"], (int)row["DATA_TYPE"]);
}
return dictionary;
}
/// <summary>
/// Get ColumnNames by table name
/// </summary>
/// <param name="tableName">Table Name</param>
/// <returns>DataView</returns>
public override System.Data.DataView GetTextColumnNames(string tableName)
{
return new DataView(this.GetSchema("Columns", tableName));
}
/// <summary>
/// Opens a database connection and begins a new transaction
/// </summary>
/// <returns>A specialized transaction object based on the current database engine type</returns>
public override System.Data.IDbTransaction OpenTransaction()
{
IDbConnection connection = GetConnection();
OpenConnection(connection);
return connection.BeginTransaction();
}
/// <summary>
/// Opens a database connection and begins a new transaction
/// </summary>
/// <param name="isolationLevel">The transaction locking behavior for the connection</param>
/// <returns>A specialized transaction object based on the current database engine type</returns>
public override System.Data.IDbTransaction OpenTransaction(System.Data.IsolationLevel isolationLevel)
{
IDbConnection connection = GetConnection();
OpenConnection(connection);
return connection.BeginTransaction(isolationLevel);
}
/// <summary>
/// Close a specific connection if state is not already closed
/// </summary>
/// <param name="transaction"></param>
public override void CloseTransaction(System.Data.IDbTransaction transaction)
{
#region Input Validation
if (transaction == null)
{
throw new ArgumentNullException("Transaction cannot be null.", "transaction");
}
#endregion
CloseConnection(transaction.Connection);
}
/// <summary>
/// Gets the names of all tables in the database
/// </summary>
/// <returns>Names of all tables in the database</returns>
public override List<string> GetTableNames()
{
List<string> tableNames = new List<string>();
DataTable schemaTable = Select(this.CreateQuery("select tablename from pg_catalog.pg_tables where schemaname not in ('pg_catalog', 'information_schema')"));
foreach (DataRow row in schemaTable.Rows)
{
tableNames.Add(row[0].ToString());
}
//Option 1
//DataTable schemaViews = Select(this.CreateQuery("select viewname from pg_catalog.pg_views where schemaname not in ('pg_catalog', 'information_schema')"));
//Option 2 does not include system views in the result
DataTable schemaViews = Select(this.CreateQuery("select table_name from INFORMATION_SCHEMA.views WHERE table_schema = ANY (current_schemas(false))"));
foreach (DataRow row in schemaViews.Rows)
{
tableNames.Add(row[0].ToString());
}
return tableNames;
}
/// <summary>
/// Create MySQL query object
/// </summary>
/// <param name="ansiSqlStatement">Query string</param>
/// <returns>Query</returns>
public override Query CreateQuery(string ansiSqlStatement)
{
return new PostgreSQLQuery(ansiSqlStatement);
}
/// <summary>
/// Opens specific connection if state is not already opened
/// </summary>
/// <param name="conn"></param>
protected void OpenConnection(IDbConnection conn)
{
try
{
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
}
catch (Exception ex)
{
throw new System.ApplicationException("Error opening connection.", ex);
}
}
/// <summary>
/// Close a specific connection if state is not already closed
/// </summary>
/// <param name="conn"></param>
protected void CloseConnection(IDbConnection conn)
{
try
{
if (conn != null)
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
}
}
}
catch (Exception ex)
{
conn = null;
throw new System.ApplicationException("Error closing connection.", ex);
}
}
/// <summary>
/// Gets the MySQL version of a generic DbType
/// </summary>
/// <returns>MySQL version of the generic DbType</returns>
public NpgsqlDbType CovertToNativeDbType(DbType dbType)
{
switch (dbType)
{
case DbType.AnsiString:
return NpgsqlDbType.Text;
case DbType.AnsiStringFixedLength:
return NpgsqlDbType.Text;
case DbType.Binary:
return NpgsqlDbType.Bit;
case DbType.Boolean:
return NpgsqlDbType.Bit;
case DbType.Byte:
return NpgsqlDbType.Text;
case DbType.Currency:
return NpgsqlDbType.Double;
case DbType.Date:
return NpgsqlDbType.Date;
case DbType.DateTime:
return NpgsqlDbType.Timestamp;//.DateTime;
case DbType.Decimal:
return NpgsqlDbType.Double;//.Decimal;
case DbType.Double:
return NpgsqlDbType.Double;
case DbType.Guid:
return NpgsqlDbType.Text;
case DbType.Int16:
return NpgsqlDbType.Smallint;//.Int16;
case DbType.Int32:
return NpgsqlDbType.Integer;//.Int32;
case DbType.Int64:
return NpgsqlDbType.Bigint;//.Int64;
case DbType.Object:
return NpgsqlDbType.Varchar;//.VarBinary;
case DbType.SByte:
return NpgsqlDbType.Integer;
case DbType.Single:
return NpgsqlDbType.Double;//.Float;
case DbType.String:
return NpgsqlDbType.Text;
case DbType.StringFixedLength:
return NpgsqlDbType.Text;
case DbType.Time:
return NpgsqlDbType.Time;
case DbType.UInt16:
return NpgsqlDbType.Smallint;
case DbType.UInt32:
return NpgsqlDbType.Integer;
case DbType.UInt64:
return NpgsqlDbType.Bigint;
case DbType.VarNumeric:
return NpgsqlDbType.Double;
default:
return NpgsqlDbType.Text;
}
}
/// <summary>
/// Gets a new command using an existing transaction
/// </summary>
/// <param name="sqlStatement">The query to be executed against the database</param>
/// <param name="transaction">Transction</param>
/// <param name="parameters">parameters">Parameters for the query to be executed</param>
/// <returns>An MySQL command object</returns>
protected virtual IDbCommand GetCommand(string sqlStatement, IDbTransaction transaction, List<QueryParameter> parameters)
{
#region Input Validation
if (string.IsNullOrEmpty(sqlStatement))
{
throw new ArgumentNullException("sqlStatement");
}
if (parameters == null)
{
throw new ArgumentNullException("Parameters");
}
#endregion
IDbCommand command = this.GetNativeCommand(transaction);
command.CommandText = sqlStatement;
foreach (QueryParameter parameter in parameters)
{
command.Parameters.Add(this.ConvertToNativeParameter(parameter));
}
return command;
}
/// <summary>
/// Gets a new command using an existing connection
/// </summary>
/// <param name="sqlStatement">The query to be executed against the database</param>
/// <param name="connection">Connection</param>
/// <param name="parameters">Parameters for the query to be executed</param>
/// <returns></returns>
protected virtual IDbCommand GetCommand(string sqlStatement, IDbConnection connection, List<QueryParameter> parameters)
{
#region Input Validation
if (string.IsNullOrEmpty(sqlStatement))
{
throw new ArgumentNullException("sqlStatement");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
#endregion
IDbCommand command = connection.CreateCommand();
command.CommandText = sqlStatement;
foreach (QueryParameter parameter in parameters)
{
command.Parameters.Add(this.ConvertToNativeParameter(parameter));
}
return command;
}
/// <summary>
/// Gets the code table names for the project.
/// </summary>
/// <param name="project"><see cref="Epi.Project"/></param>
/// <returns><see cref="System.Data.DataTable"/></returns>
public override DataTable GetCodeTableNamesForProject(Project project)
{
List<string> tables = project.GetDataTableList();
DataSets.TableSchema.TablesDataTable codeTables = project.GetCodeTableList();
foreach (DataSets.TableSchema.TablesRow row in codeTables)
{
tables.Add(row.TABLE_NAME);
}
DataView dataView = codeTables.DefaultView;
return codeTables;
}
/// <summary>
/// Gets a list of code tables.
/// </summary>
/// <param name="db"></param>
/// <returns></returns>
public override Epi.DataSets.TableSchema.TablesDataTable GetCodeTableList(IDbDriver db)
{
Epi.DataSets.TableSchema.TablesDataTable table = db.GetTableSchema();
DataRow[] rowsFiltered = table.Select("TABLE_NAME not like 'code%'");
//remove tables that don't start with "code"
foreach (DataRow rowFiltered in rowsFiltered)
{
table.Rows.Remove(rowFiltered);
}
//remove the code tables that are not for the current database
DataRow[] rowsFilteredSchema = table.Select("TABLE_SCHEMA<>'" + db.DbName + "'");
foreach (DataRow rowFilteredSchema in rowsFilteredSchema)
{
table.Rows.Remove(rowFilteredSchema);
}
return table;
}
/// <summary>
/// Identity which type of database drive is in use.
/// </summary>
/// <returns>MYSQL</returns>
public override string IdentifyDatabase()
{
return "POSTGRESQL";
}
/// <summary>
/// Inserts the string in escape characters. [] for SQL server and `` for MySQL etc.
/// </summary>
/// <param name="str">string</param>
/// <returns>string</returns>
public override string InsertInEscape(string str)
{
//string newString = string.Empty;
//if (!str.StartsWith(StringLiterals.BACK_TICK))
//{
// newString = StringLiterals.BACK_TICK;
//}
//newString += str;
//if (!str.EndsWith(StringLiterals.BACK_TICK))
//{
// newString += StringLiterals.BACK_TICK;
//}
//return newString;
return str;
}
/// <summary>
/// Provides a database frieldly string representation of date.
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public override string FormatDate(DateTime dt)
{
string formattedString = dt.ToString("u");
// Remove time part of the string.
formattedString = formattedString.Remove(formattedString.IndexOf(StringLiterals.SPACE));
return Util.InsertInSingleQuotes(formattedString);
}
/// <summary>
/// Provides a database frieldly string representation of date.
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public override string FormatTime(DateTime dt)
{
string formattedString = dt.ToString("u");
// Remove the date part
formattedString = formattedString.Remove(0, formattedString.IndexOf(StringLiterals.SPACE));
// Remove the trailing 'Z' character.
formattedString = formattedString.Remove(formattedString.Length - 1);
return Util.InsertInSingleQuotes(formattedString);
}
/// <summary>
/// Provides a database frieldly string representation of date.
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public override string FormatDateTime(DateTime dt)
{
string formattedString = dt.ToString("u");
// Remove the trailing 'Z' character.
formattedString = formattedString.Remove(formattedString.Length - 1);
return Util.InsertInSingleQuotes(formattedString);
}
/// <summary>
/// Convert Query to String format for EnterWebService
/// </summary>
/// <param name="pValue"></param>
/// <returns>Sql query in string form</returns>
private string ConvertQueryToString(Query pValue)
{
string result = pValue.SqlStatement;
foreach (QueryParameter parameter in pValue.Parameters)
{
switch (parameter.DbType)
{
case DbType.Currency:
case DbType.Byte:
case DbType.Decimal:
case DbType.Double:
case DbType.Int16:
case DbType.Int32:
case DbType.Int64:
case DbType.SByte:
case DbType.UInt16:
case DbType.UInt32:
case DbType.UInt64:
case DbType.Boolean:
result = Regex.Replace(result, parameter.ParameterName, parameter.Value.ToString(), RegexOptions.IgnoreCase);
break;
default:
result = Regex.Replace(result, parameter.ParameterName, "'" + parameter.Value.ToString() + "'", RegexOptions.IgnoreCase);
break;
}
}
return result;
}
public override string SyntaxTrue
{
get { return "'TRUE'"; }
}
public override string SyntaxFalse
{
get { return "'FALSE'"; }
}
public override System.Data.Common.DbDataAdapter GetDbAdapter(string p)
{
throw new NotImplementedException();
}
public override System.Data.Common.DbCommandBuilder GetDbCommandBuilder(System.Data.Common.DbDataAdapter Adapter)
{
throw new NotImplementedException();
}
public override bool InsertBulkRows(string pSelectSQL, System.Data.Common.DbDataReader pDataReader, SetGadgetStatusHandler pStatusDelegate = null, CheckForCancellationHandler pCancellationDelegate = null)
{
throw new NotImplementedException();
}
public override bool Insert_1_Row(string pSelectSQL, System.Data.Common.DbDataReader pDataReader)
{
throw new NotImplementedException();
}
public override bool Update_1_Row(string pSelectSQL, string pKeyString, System.Data.Common.DbDataReader pDataReader)
{
throw new NotImplementedException();
}
public override System.Data.Common.DbCommand GetCommand(string pKeyString, DataTable pDataTable)
{
throw new NotImplementedException();
}
}
}
| |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Vevo;
using Vevo.DataAccessLib.Cart;
using Vevo.Domain;
using Vevo.Domain.Orders;
using Vevo.Shared.Utilities;
using Vevo.WebUI;
using Vevo.Domain.Products;
using Vevo.Domain.Stores;
public partial class AdminAdvanced_Components_OrderItemDetails : AdminAdvancedBaseUserControl
{
#region Private
private enum Mode { Add, Edit };
private Mode _mode = Mode.Add;
private string _orderID;
private string CurrentOrderID
{
get
{
if (_orderID == null)
{
if (IsEditMode())
{
_orderID = GetCurrentOrderIDByOrderItemID( CurrentOrderItemID );
}
else
{
_orderID = MainContext.QueryString["OrderID"];
}
}
return _orderID;
}
}
private string CurrentOrderItemID
{
get
{
return MainContext.QueryString["OrderItemID"];
}
}
//private string GetOrderEditLink()
//{
// return Page.ResolveUrl( "OrdersEdit.aspx?OrderID=" + CurrentOrderID );
//}
private void ClearInputField()
{
uxQuantityText.Text = "";
uxNameText.Text = "";
uxSkuText.Text = "";
uxUnitPriceText.Text = "";
uxDownloadCountText.Text = "";
}
private void PopulateControl()
{
ClearInputField();
OrderItem orderItem = DataAccessContext.OrderItemRepository.GetOne( CurrentOrderItemID );
uxQuantityText.Text = orderItem.Quantity.ToString();
uxNameText.Text = orderItem.Name;
uxSkuText.Text = orderItem.Sku;
uxUnitPriceText.Text = orderItem.UnitPrice.ToString( "f2" );
uxDownloadCountText.Text = orderItem.DownloadCount.ToString();
IsItemDownloadable( orderItem.ProductID );
}
private void IsItemDownloadable( string ProductID )
{
Product product = DataAccessContext.ProductRepository.GetOne( StoreContext.Culture, ProductID, new StoreRetriever().GetCurrentStoreID() );
bool IsDownloadable = product.IsDownloadable;
if (!IsDownloadable)
{
DownloadCountPanel.Visible = false;
}
}
private string GetCurrentOrderIDByOrderItemID( string OrderItemID )
{
OrderItem orderItem = DataAccessContext.OrderItemRepository.GetOne( CurrentOrderItemID );
return orderItem.OrderID;
}
private OrderItem LoadOrderItemDataFromGui( OrderItem orderItem )
{
orderItem.OrderID = CurrentOrderID;
orderItem.Quantity = ConvertUtilities.ToInt32( uxQuantityText.Text );
orderItem.Name = uxNameText.Text;
orderItem.Sku = uxSkuText.Text;
orderItem.UnitPrice = ConvertUtilities.ToDecimal( uxUnitPriceText.Text );
orderItem.DownloadCount = ConvertUtilities.ToInt32( uxDownloadCountText.Text );
return orderItem;
}
protected void checkDownloadCount( object source, ServerValidateEventArgs args )
{
int count = ConvertUtilities.ToInt32( uxDownloadCountText.Text );
bool IsVisible = DownloadCountPanel.Visible;
if (IsVisible && count < 0)
{
args.IsValid = false;
}
}
private void CreateNewOrderItem()
{
OrderItem orderItem = LoadOrderItemDataFromGui( new OrderItem() );
DataAccessContext.OrderItemRepository.Save( orderItem );
}
private void UpdateCurrentOrderItem()
{
OrderItem orderItem = DataAccessContext.OrderItemRepository.GetOne( CurrentOrderItemID );
orderItem = LoadOrderItemDataFromGui( orderItem );
DataAccessContext.OrderItemRepository.Save( orderItem );
}
private void RefreshOrderPricing()
{
OrderEditService orderEditService = new OrderEditService();
orderEditService.RefreshOrderAmount( CurrentOrderID );
}
#endregion
#region Protected
protected void Page_Load( object sender, EventArgs e )
{
if (!MainContext.IsPostBack)
{
if (IsEditMode())
{
PopulateControl();
}
uxOrderIDdisplayLable.Text = CurrentOrderID;
}
}
protected void Page_PreRender( object sender, EventArgs e )
{
if (IsEditMode())
{
if (!MainContext.IsPostBack)
{
if (IsAdminModifiable())
{
uxUpdateButton.Visible = true;
}
else
{
uxUpdateButton.Visible = false;
}
uxAddButton.Visible = false;
}
}
else
{
if (IsAdminModifiable())
{
uxAddButton.Visible = true;
uxUpdateButton.Visible = false;
}
else
{
MainContext.RedirectMainControl( "OrderList.ascx" );
}
}
}
protected void uxAddButton_Click( object sender, EventArgs e )
{
try
{
if (Page.IsValid)
{
CreateNewOrderItem();
RefreshOrderPricing();
ClearInputField();
MainContext.RedirectMainControl( "OrdersEdit.ascx", String.Format( "OrderID={0}", CurrentOrderID ) );
//uxMessage.DisplayMessage( Resources.OrderItemMessage.AddSuccess );
}
}
catch (Exception ex)
{
uxMessage.DisplayException( ex );
}
}
protected void uxUpdateButton_Click( object sender, EventArgs e )
{
try
{
if (Page.IsValid)
{
UpdateCurrentOrderItem();
RefreshOrderPricing();
MainContext.RedirectMainControl( "OrdersEdit.ascx", String.Format( "OrderID={0}", CurrentOrderID ) );
//uxMessage.DisplayMessage( Resources.OrderItemMessage.UpdateSuccess );
}
}
catch (Exception ex)
{
uxMessage.DisplayException( ex );
}
}
protected void uxOrderLink_Click( object sender, EventArgs e )
{
MainContext.RedirectMainControl( "OrdersEdit.ascx", String.Format( "OrderID={0}", CurrentOrderID ) );
}
#endregion
#region Public Methods
public bool IsEditMode()
{
return (_mode == Mode.Edit);
}
public void SetEditMode()
{
_mode = Mode.Edit;
}
#endregion
}
| |
// Copyright (c) Oleg Zudov. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// This file is based on or incorporates material from the project Selenium, licensed under the Apache License, Version 2.0. More info in THIRD-PARTY-NOTICES file.
using System;
using System.Globalization;
using System.Text;
using System.Threading.Tasks;
using Zu.AsyncWebDriver.Remote;
namespace Zu.AsyncWebDriver
{
public static class TaskStringExtensions
{
public static async Task<int> CompareTo(this Task<string> task, object value)
{
var el = await task.ConfigureAwait(false);
return el.CompareTo(value);
}
public static async Task<int> CompareTo(this Task<string> task, String strB)
{
var el = await task.ConfigureAwait(false);
return el.CompareTo(strB);
}
public static async Task<bool> Contains(this Task<string> task, String value)
{
var el = await task.ConfigureAwait(false);
return el.Contains(value);
}
public static async Task CopyTo(this Task<string> task, int sourceIndex, char[] destination, int destinationIndex, int count)
{
var el = await task.ConfigureAwait(false);
el.CopyTo(sourceIndex, destination, destinationIndex, count);
}
public static async Task<bool> EndsWith(this Task<string> task, String value)
{
var el = await task.ConfigureAwait(false);
return el.EndsWith(value);
}
public static async Task<bool> EndsWith(this Task<string> task, String value, StringComparison comparisonType)
{
var el = await task.ConfigureAwait(false);
return el.EndsWith(value, comparisonType);
}
public static async Task<bool> EndsWith(this Task<string> task, String value, bool ignoreCase, CultureInfo culture)
{
var el = await task.ConfigureAwait(false);
return el.EndsWith(value, ignoreCase, culture);
}
public static async Task<CharEnumerator> GetEnumerator(this Task<string> task)
{
var el = await task.ConfigureAwait(false);
return el.GetEnumerator();
}
public static async Task<TypeCode> GetTypeCode(this Task<string> task)
{
var el = await task.ConfigureAwait(false);
return el.GetTypeCode();
}
public static async Task<int> IndexOf(this Task<string> task, char value, int startIndex, int count)
{
var el = await task.ConfigureAwait(false);
return el.IndexOf(value, startIndex, count);
}
public static async Task<int> IndexOf(this Task<string> task, char value, int startIndex)
{
var el = await task.ConfigureAwait(false);
return el.IndexOf(value, startIndex);
}
public static async Task<int> IndexOf(this Task<string> task, String value)
{
var el = await task.ConfigureAwait(false);
return el.IndexOf(value);
}
public static async Task<int> IndexOf(this Task<string> task, String value, int startIndex)
{
var el = await task.ConfigureAwait(false);
return el.IndexOf(value, startIndex);
}
public static async Task<int> IndexOf(this Task<string> task, String value, int startIndex, int count)
{
var el = await task.ConfigureAwait(false);
return el.IndexOf(value, startIndex, count);
}
public static async Task<int> IndexOf(this Task<string> task, String value, StringComparison comparisonType)
{
var el = await task.ConfigureAwait(false);
return el.IndexOf(value, comparisonType);
}
public static async Task<int> IndexOf(this Task<string> task, String value, int startIndex, StringComparison comparisonType)
{
var el = await task.ConfigureAwait(false);
return el.IndexOf(value, startIndex, comparisonType);
}
public static async Task<int> IndexOf(this Task<string> task, char value)
{
var el = await task.ConfigureAwait(false);
return el.IndexOf(value);
}
public static async Task<int> IndexOf(this Task<string> task, String value, int startIndex, int count, StringComparison comparisonType)
{
var el = await task.ConfigureAwait(false);
return el.IndexOf(value, startIndex, count, comparisonType);
}
public static async Task<int> IndexOfAny(this Task<string> task, char[] anyOf, int startIndex, int count)
{
var el = await task.ConfigureAwait(false);
return el.IndexOfAny(anyOf, startIndex, count);
}
public static async Task<int> IndexOfAny(this Task<string> task, char[] anyOf, int startIndex)
{
var el = await task.ConfigureAwait(false);
return el.IndexOfAny(anyOf, startIndex);
}
public static async Task<int> IndexOfAny(this Task<string> task, char[] anyOf)
{
var el = await task.ConfigureAwait(false);
return el.IndexOfAny(anyOf);
}
public static async Task<String> Insert(this Task<string> task, int startIndex, String value)
{
var el = await task.ConfigureAwait(false);
return el.Insert(startIndex, value);
}
public static async Task<bool> IsNormalized(this Task<string> task)
{
var el = await task.ConfigureAwait(false);
return el.IsNormalized();
}
public static async Task<bool> IsNormalized(this Task<string> task, NormalizationForm normalizationForm)
{
var el = await task.ConfigureAwait(false);
return el.IsNormalized(normalizationForm);
}
public static async Task<int> LastIndexOf(this Task<string> task, String value, int startIndex, int count, StringComparison comparisonType)
{
var el = await task.ConfigureAwait(false);
return el.LastIndexOf(value, startIndex, count, comparisonType);
}
public static async Task<int> LastIndexOf(this Task<string> task, char value, int startIndex, int count)
{
var el = await task.ConfigureAwait(false);
return el.LastIndexOf(value, startIndex, count);
}
public static async Task<int> LastIndexOf(this Task<string> task, char value, int startIndex)
{
var el = await task.ConfigureAwait(false);
return el.LastIndexOf(value, startIndex);
}
public static async Task<int> LastIndexOf(this Task<string> task, char value)
{
var el = await task.ConfigureAwait(false);
return el.LastIndexOf(value);
}
public static async Task<int> LastIndexOf(this Task<string> task, String value, int startIndex)
{
var el = await task.ConfigureAwait(false);
return el.LastIndexOf(value, startIndex);
}
public static async Task<int> LastIndexOf(this Task<string> task, String value, int startIndex, StringComparison comparisonType)
{
var el = await task.ConfigureAwait(false);
return el.LastIndexOf(value, startIndex, comparisonType);
}
public static async Task<int> LastIndexOf(this Task<string> task, String value, int startIndex, int count)
{
var el = await task.ConfigureAwait(false);
return el.LastIndexOf(value, startIndex, count);
}
public static async Task<int> LastIndexOf(this Task<string> task, String value, StringComparison comparisonType)
{
var el = await task.ConfigureAwait(false);
return el.LastIndexOf(value);
}
public static async Task<int> LastIndexOf(this Task<string> task, String value)
{
var el = await task.ConfigureAwait(false);
return el.LastIndexOf(value);
}
public static async Task<int> LastIndexOfAny(this Task<string> task, char[] anyOf)
{
var el = await task.ConfigureAwait(false);
return el.LastIndexOfAny(anyOf);
}
public static async Task<int> LastIndexOfAny(this Task<string> task, char[] anyOf, int startIndex)
{
var el = await task.ConfigureAwait(false);
return el.LastIndexOfAny(anyOf, startIndex);
}
public static async Task<int> LastIndexOfAny(this Task<string> task, char[] anyOf, int startIndex, int count)
{
var el = await task.ConfigureAwait(false);
return el.LastIndexOfAny(anyOf, startIndex, count);
}
public static async Task<String> Normalize(this Task<string> task)
{
var el = await task.ConfigureAwait(false);
return el.Normalize();
}
public static async Task<String> Normalize(this Task<string> task, NormalizationForm normalizationForm)
{
var el = await task.ConfigureAwait(false);
return el.Normalize(normalizationForm);
}
public static async Task<String> PadLeft(this Task<string> task, int totalWidth, char paddingChar)
{
var el = await task.ConfigureAwait(false);
return el.PadLeft(totalWidth, paddingChar);
}
public static async Task<String> PadLeft(this Task<string> task, int totalWidth)
{
var el = await task.ConfigureAwait(false);
return el.PadLeft(totalWidth);
}
public static async Task<String> PadRight(this Task<string> task, int totalWidth, char paddingChar)
{
var el = await task.ConfigureAwait(false);
return el.PadRight(totalWidth, paddingChar);
}
public static async Task<String> PadRight(this Task<string> task, int totalWidth)
{
var el = await task.ConfigureAwait(false);
return el.PadRight(totalWidth);
}
public static async Task<String> Remove(this Task<string> task, int startIndex)
{
var el = await task.ConfigureAwait(false);
return el.Remove(startIndex);
}
public static async Task<String> Remove(this Task<string> task, int startIndex, int count)
{
var el = await task.ConfigureAwait(false);
return el.Remove(startIndex, count);
}
public static async Task<String> Replace(this Task<string> task, String oldValue, String newValue)
{
var el = await task.ConfigureAwait(false);
return el.Replace(oldValue, newValue);
}
public static async Task<String> Replace(this Task<string> task, char oldChar, char newChar)
{
var el = await task.ConfigureAwait(false);
return el.Replace(oldChar, newChar);
}
public static async Task<String[]> Split(this Task<string> task, params char[] separator)
{
var el = await task.ConfigureAwait(false);
return el.Split(separator);
}
public static async Task<String[]> Split(this Task<string> task, char[] separator, int count)
{
var el = await task.ConfigureAwait(false);
return el.Split(separator, count);
}
public static async Task<String[]> Split(this Task<string> task, char[] separator, StringSplitOptions options)
{
var el = await task.ConfigureAwait(false);
return el.Split(separator, options);
}
public static async Task<String[]> Split(this Task<string> task, char[] separator, int count, StringSplitOptions options)
{
var el = await task.ConfigureAwait(false);
return el.Split(separator, count, options);
}
public static async Task<String[]> Split(this Task<string> task, String[] separator, StringSplitOptions options)
{
var el = await task.ConfigureAwait(false);
return el.Split(separator, options);
}
public static async Task<String[]> Split(this Task<string> task, String[] separator, int count, StringSplitOptions options)
{
var el = await task.ConfigureAwait(false);
return el.Split(separator, count, options);
}
public static async Task<bool> StartsWith(this Task<string> task, String value, StringComparison comparisonType)
{
var el = await task.ConfigureAwait(false);
return el.StartsWith(value, comparisonType);
}
public static async Task<bool> StartsWith(this Task<string> task, String value, bool ignoreCase, CultureInfo culture)
{
var el = await task.ConfigureAwait(false);
return el.StartsWith(value, ignoreCase, culture);
}
public static async Task<bool> StartsWith(this Task<string> task, String value)
{
var el = await task.ConfigureAwait(false);
return el.StartsWith(value);
}
public static async Task<String> Substring(this Task<string> task, int startIndex, int length)
{
var el = await task.ConfigureAwait(false);
return el.Substring(startIndex, length);
}
public static async Task<String> Substring(this Task<string> task, int startIndex)
{
var el = await task.ConfigureAwait(false);
return el.Substring(startIndex);
}
public static async Task<char[]> ToCharArray(this Task<string> task, int startIndex, int length)
{
var el = await task.ConfigureAwait(false);
return el.ToCharArray(startIndex, length);
}
public static async Task<char[]> ToCharArray(this Task<string> task)
{
var el = await task.ConfigureAwait(false);
return el.ToCharArray();
}
public static async Task<String> ToLower(this Task<string> task, CultureInfo culture)
{
var el = await task.ConfigureAwait(false);
return el.ToLower(culture);
}
public static async Task<String> ToLower(this Task<string> task)
{
var el = await task.ConfigureAwait(false);
return el.ToLower();
}
public static async Task<String> ToLowerInvariant(this Task<string> task)
{
var el = await task.ConfigureAwait(false);
return el.ToLowerInvariant();
}
public static async Task<String> ToUpper(this Task<string> task)
{
var el = await task.ConfigureAwait(false);
return el.ToUpper();
}
public static async Task<String> ToUpper(this Task<string> task, CultureInfo culture)
{
var el = await task.ConfigureAwait(false);
return el.ToUpper(culture);
}
public static async Task<String> ToUpperInvariant(this Task<string> task)
{
var el = await task.ConfigureAwait(false);
return el.ToUpperInvariant();
}
public static async Task<String> Trim(this Task<string> task, params char[] trimChars)
{
var el = await task.ConfigureAwait(false);
return el.Trim(trimChars);
}
public static async Task<String> Trim(this Task<string> task)
{
var el = await task.ConfigureAwait(false);
return el.Trim();
}
public static async Task<String> TrimEnd(this Task<string> task, params char[] trimChars)
{
var el = await task.ConfigureAwait(false);
return el.TrimEnd(trimChars);
}
public static async Task<String> TrimStart(this Task<string> task, params char[] trimChars)
{
var el = await task.ConfigureAwait(false);
return el.TrimStart(trimChars);
}
}
public class TaskStringExtensionsTest
{
public async Task Method()
{
var parent = new AsyncWebElement(null, null);
var count = await parent.FindElement(By.TagName("div")).Text().ToLower().ConfigureAwait(false);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
#if FEATURE_COM
using System;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
using Marshal = System.Runtime.InteropServices.Marshal;
using VarEnum = System.Runtime.InteropServices.VarEnum;
namespace Microsoft.Scripting.ComInterop {
/// <summary>
/// The parameter description of a method defined in a type library
/// </summary>
public class ComParamDesc {
# region private fields
private readonly bool _isOut; // is an output parameter?
private readonly bool _isOpt; // is an optional parameter?
private readonly bool _byRef; // is a reference or pointer parameter?
private readonly bool _isArray;
private readonly VarEnum _vt;
private readonly string _name;
private readonly Type _type;
private readonly object _defaultValue;
# endregion
# region ctor
/// <summary>
/// Creates a representation for the paramter of a COM method
/// </summary>
internal ComParamDesc(ref ELEMDESC elemDesc, string name) {
// Ensure _defaultValue is set to DBNull.Value regardless of whether or not the
// default value is extracted from the parameter description. Failure to do so
// yields a runtime exception in the ToString() function.
_defaultValue = DBNull.Value;
if (!String.IsNullOrEmpty(name)) {
// This is a parameter, not a return value
_isOut = (elemDesc.desc.paramdesc.wParamFlags & PARAMFLAG.PARAMFLAG_FOUT) != 0;
_isOpt = (elemDesc.desc.paramdesc.wParamFlags & PARAMFLAG.PARAMFLAG_FOPT) != 0;
// TODO: The PARAMDESCEX struct has a memory issue that needs to be resolved. For now, we ignore it.
//_defaultValue = PARAMDESCEX.GetDefaultValue(ref elemDesc.desc.paramdesc);
}
_name = name;
_vt = (VarEnum)elemDesc.tdesc.vt;
TYPEDESC typeDesc = elemDesc.tdesc;
while (true) {
if (_vt == VarEnum.VT_PTR) {
_byRef = true;
} else if (_vt == VarEnum.VT_ARRAY) {
_isArray = true;
} else {
break;
}
TYPEDESC childTypeDesc = (TYPEDESC)Marshal.PtrToStructure(typeDesc.lpValue, typeof(TYPEDESC));
_vt = (VarEnum)childTypeDesc.vt;
typeDesc = childTypeDesc;
}
VarEnum vtWithoutByref = _vt;
if ((_vt & VarEnum.VT_BYREF) != 0) {
vtWithoutByref = (_vt & ~VarEnum.VT_BYREF);
_byRef = true;
}
_type = GetTypeForVarEnum(vtWithoutByref);
}
/// <summary>
/// Creates a representation for the return value of a COM method
/// TODO: Return values should be represented by a different type
/// </summary>
internal ComParamDesc(ref ELEMDESC elemDesc)
: this(ref elemDesc, String.Empty) {
}
//internal struct PARAMDESCEX {
// private ulong _cByte;
// private Variant _varDefaultValue;
// internal void Dummy() {
// _cByte = 0;
// throw Error.MethodShouldNotBeCalled();
// }
// internal static object GetDefaultValue(ref PARAMDESC paramdesc) {
// if ((paramdesc.wParamFlags & PARAMFLAG.PARAMFLAG_FHASDEFAULT) == 0) {
// return DBNull.Value;
// }
// PARAMDESCEX varValue = (PARAMDESCEX)Marshal.PtrToStructure(paramdesc.lpVarValue, typeof(PARAMDESCEX));
// if (varValue._cByte != (ulong)(Marshal.SizeOf((typeof(PARAMDESCEX))))) {
// throw Error.DefaultValueCannotBeRead();
// }
// return varValue._varDefaultValue.ToObject();
// }
//}
private static Type GetTypeForVarEnum(VarEnum vt) {
Type type;
switch (vt) {
// VarEnums which can be used in VARIANTs, but which cannot occur in a TYPEDESC
case VarEnum.VT_EMPTY:
case VarEnum.VT_NULL:
case VarEnum.VT_RECORD:
throw new InvalidOperationException(string.Format("Unexpected VarEnum {0}.", vt));
// VarEnums which are not used in VARIANTs, but which can occur in a TYPEDESC
case VarEnum.VT_VOID:
type = null;
break;
#if DISABLE // TODO: WTypes.h indicates that these cannot be used in VARIANTs, but Type.InvokeMember seems to allow it
case VarEnum.VT_I8:
case VarEnum.UI8:
#endif
case VarEnum.VT_HRESULT:
type = typeof(int);
break;
case ((VarEnum)37): // VT_INT_PTR:
case VarEnum.VT_PTR:
type = typeof(IntPtr);
break;
case ((VarEnum)38): // VT_UINT_PTR:
type = typeof(UIntPtr);
break;
case VarEnum.VT_SAFEARRAY:
case VarEnum.VT_CARRAY:
type = typeof(Array);
break;
case VarEnum.VT_LPSTR:
case VarEnum.VT_LPWSTR:
type = typeof(string);
break;
case VarEnum.VT_USERDEFINED:
type = typeof(object);
break;
// For VarEnums that can be used in VARIANTs and well as TYPEDESCs, just use VarEnumSelector
default:
type = VarEnumSelector.GetManagedMarshalType(vt);
break;
}
return type;
}
public override string ToString() {
StringBuilder result = new StringBuilder();
if (_isOpt) {
result.Append("[Optional] ");
}
if (_isOut) {
result.Append("[out]");
}
result.Append(_type.Name);
if (_isArray) {
result.Append("[]");
}
if (_byRef) {
result.Append("&");
}
result.Append(" ");
result.Append(_name);
if (_defaultValue != DBNull.Value) {
result.Append("=");
result.Append(_defaultValue);
}
return result.ToString();
}
# endregion
# region properties
public bool IsOut {
get { return _isOut; }
}
public bool IsOptional {
get { return _isOpt; }
}
public bool ByReference {
get { return _byRef; }
}
public bool IsArray {
get { return _isArray; }
}
public Type ParameterType {
get {
return _type;
}
}
/// <summary>
/// DBNull.Value if there is no default value
/// </summary>
internal object DefaultValue {
get {
return _defaultValue;
}
}
# endregion
}
}
#endif
| |
using System;
using System.Configuration;
using System.Collections;
using System.Globalization;
using System.Data;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.Caching;
using System.Xml;
/// <summary>
/// Summary description for DataReferensi
/// </summary>
public class DataReferensi
{
public DataReferensi()
{
//
// TODO: Add constructor logic here
//
}
#region # GET DATA REFERENSI PROPINSI
public static DataTable GetPropinsiData()
{
string cacheKey = "SIMRS_Propinsi";
if (HttpRuntime.Cache[cacheKey] == null)
{
BkNet.DataAccess.Propinsi myObj = new BkNet.DataAccess.Propinsi();
DataTable objData = myObj.GetList();
HttpRuntime.Cache.Insert(cacheKey, objData);
}
return (DataTable)HttpRuntime.Cache[cacheKey];
}
public static string GetPropinsiFunction(string action, string option)
{
DataTable Data = GetPropinsiData();
string textOption = Resources.GetString("Referensi", "SelectAll");
string textOptionKab = Resources.GetString("Referensi", "SelectAll");
if (option.ToUpper() == "SELECT")
{
textOption = Resources.GetString("Referensi", "SelectProp");
textOptionKab = Resources.GetString("Referensi", "SelectKab");
}
string jsFunction = "";
//Draw Function
jsFunction += "<script language=\"javascript\" type=\"text/javascript\">";
jsFunction += "\n var propinsidata = new Array; \n";
int k = 0;
jsFunction += "\n propinsidata[" + k + "] = new Array( '','','');";
foreach (DataRow dr in Data.Rows)
{
k++;
jsFunction += "\n propinsidata[" + k + "] = new Array( '" + dr["Id"].ToString() + "','" + dr["Kode"].ToString() + "','" + dr["Nama"].ToString() + "');";
}
jsFunction += "\n\n function ChangePropinsiList( propinsidata, listname ,source, key, orig_key, orig_val, display, option) { ";
jsFunction += "\n var list = document.getElementById(listname); ";
jsFunction += "\n for (i in list.options.length) { ";
jsFunction += "\n list.options[i] = null; ";
jsFunction += "\n } ";
jsFunction += "\n i = 0; ";
jsFunction += "\n for (x in source) { ";
jsFunction += "\n if (source[x][0] == key) { ";
jsFunction += "\n opt = new Option(); ";
jsFunction += "\n opt.value = source[x][1]; ";
jsFunction += "\n if(source[x][1] == ''){ ";
jsFunction += "\n opt.text = '" + textOptionKab + "' ; ";
jsFunction += "\n }else {";
jsFunction += "\n if(display.toUpperCase() == 'CODE') ";
jsFunction += "\n opt.text = source[x][2]; ";
jsFunction += "\n else if(display.toUpperCase() == 'NAME') ";
jsFunction += "\n opt.text = source[x][3]; ";
jsFunction += "\n else ";
jsFunction += "\n opt.text = source[x][2] + ' ['+source[x][3]+ ']'; ";
jsFunction += "\n } ";
jsFunction += "\n if ((orig_key == key && orig_val == opt.value) || i == 0) { ";
jsFunction += "\n opt.selected = true; ";
jsFunction += "\n } ";
jsFunction += "\n list.options[i++] = opt; ";
jsFunction += "\n } ";
jsFunction += "\n } ";
jsFunction += "\n if (i == 0) { ";
jsFunction += "\n opt = new Option(); ";
jsFunction += "\n opt.value = ''; ";
jsFunction += "\n opt.text = '" + textOptionKab + "' ; ";
jsFunction += "\n list.options[i++] = opt; ";
jsFunction += "\n } ";
jsFunction += "\n list.length = i; ";
if (action.ToUpper() == "FILTER")
{
jsFunction += "\n for (y in propinsidata) { ";
jsFunction += "\n if (propinsidata[y][0] == key) { ";
jsFunction += "\n document.getElementById('PropinsiNama').value = propinsidata[y][2] ; ";
jsFunction += "\n break; ";
jsFunction += "\n } ";
jsFunction += "\n } ";
}
jsFunction += "\n ChangeKabupatenKotaList( kabupatenkotadata, 'LokasiId' ,lokasidata, list.options[list.selectedIndex].value, 0, 0, display, option,''); ";
jsFunction += "\n } ";
jsFunction += "\n</script>";
return jsFunction;
}
public static string DrawPropinsiList(string PropinsiId)
{
string display = "";
string action = "Filter";
string option = "SelectAll";
return DrawPropinsiList(PropinsiId, display, action, option);
}
public static string DrawPropinsiList(string PropinsiId, string display)
{
string action = "";
string option = "SelectAll";
return DrawPropinsiList(PropinsiId, display, action, option);
}
public static string DrawPropinsiList(string PropinsiId, string display, string action)
{
string option = "SelectAll";
return DrawPropinsiList(PropinsiId, display, action, option);
}
public static string DrawPropinsiList(string PropinsiId, string display, string action, string option)
{
DataTable dt = GetPropinsiData();
DataView dv = dt.DefaultView;
if (display.ToUpper() == "NAME")
dv.Sort = " Nama ASC";
else
dv.Sort = " Kode ASC";
string jscript = "";
jscript = "onchange=\"ChangePropinsiList( propinsidata, 'KabupatenKotaId',kabupatenkotadata, document.getElementById('PropinsiId').options[document.getElementById('PropinsiId').selectedIndex].value, 0, 0,'" + display + "','" + option + "');\"";
string textOption = Resources.GetString("Referensi", "SelectAll");
if (option.ToUpper() == "SELECT")
{
textOption = Resources.GetString("Referensi", "SelectProp");
}
string itemText = "";
string itemNama = "";
string listData = "";
listData += "\n <SELECT id=\"PropinsiId\" name=\"PropinsiId\" " + jscript + ">";
listData += "\n <OPTION value=\"\">" + textOption + "</OPTION>";
for (int k = 0; k < dv.Count; k++)
{
if (display.ToUpper() == "CODE")
itemText = dv[k]["Kode"].ToString();
else if (display.ToUpper() == "NAME")
itemText = dv[k]["Nama"].ToString();
else
itemText = dv[k]["Kode"].ToString() + " [" + dv[k]["Nama"].ToString() + "]";
if (dv[k]["Id"].ToString() == PropinsiId.ToString())
{
itemNama = dv[k]["Nama"].ToString();
listData += "\n <OPTION value=\"" + dv[k]["Id"].ToString() + "\" selected>" + itemText + "</OPTION>";
}
else
{
listData += "\n <OPTION value=\"" + dv[k]["Id"].ToString() + "\">" + itemText + "</OPTION>";
}
}
listData += "</SELECT>";
if (action.ToUpper() == "FILTER")
{
listData += "<input type=\"hidden\" name=\"PropinsiNama\" id=\"PropinsiNama\" value=\"" + itemNama + "\" >";
}
return listData;
}
#endregion
#region #GET DATA REFERENSI KABUPATEN/KOTA
public static DataTable GetKabupatenKotaData()
{
string cacheKey = "SIMRS_KabupatenKota";
if (HttpRuntime.Cache[cacheKey] == null)
{
BkNet.DataAccess.KabupatenKota myObj = new BkNet.DataAccess.KabupatenKota();
DataTable objData = myObj.SelectAll();
HttpRuntime.Cache.Insert(cacheKey, objData);
}
return (DataTable)HttpRuntime.Cache[cacheKey];
}
public static string GetKabupatenKotaFunction(string display, string action, string option, string displayLokasi)
{
DataTable dt = GetKabupatenKotaData();
DataView dv = dt.DefaultView;
dv.Sort = " PropinsiId ASC ";
if (display.ToUpper() == "NAME")
dv.Sort += ", Nama ASC";
else
dv.Sort += ", Kode ASC";
string textOption = Resources.GetString("Referensi", "SelectAll");
string textOptionLok = Resources.GetString("Referensi", "SelectAll");
if (option.ToUpper() == "SELECT")
{
textOption = Resources.GetString("Referensi", "SelectKab");
textOptionLok = Resources.GetString("Referensi", "SelectLokasi");
}
string jsFunction = "";
//Draw Function
jsFunction += "<script language=\"javascript\" type=\"text/javascript\">";
jsFunction += "\n var kabupatenkotadata = new Array; \n";
int k = 0;
string OldParentId = "";
string NewParentId = "";
jsFunction += "\n kabupatenkotadata[" + k + "] = new Array( '" + NewParentId + "','','','');";
k++;
for (int i = 0; i < dv.Count; i++)
{
NewParentId = dv[i]["PropinsiId"].ToString();
if (NewParentId != OldParentId)
{
jsFunction += "\n kabupatenkotadata[" + k + "] = new Array( '" + NewParentId + "','','','');";
k++;
}
jsFunction += "\n kabupatenkotadata[" + k + "] = new Array( '" + dv[i]["PropinsiId"].ToString() + "','" + dv[i]["Id"].ToString() + "','" + dv[i]["Kode"].ToString() + "','" + dv[i]["Nama"].ToString() + "');";
k++;
OldParentId = NewParentId;
}
jsFunction += "\n\n function ChangeKabupatenKotaList( kabupatenkotadata, listname ,source, key, orig_key, orig_val, display, option,displayLokasi) { ";
jsFunction += "\n var list = document.getElementById(listname); ";
jsFunction += "\n for (i in list.options.length) { ";
jsFunction += "\n list.options[i] = null; ";
jsFunction += "\n } ";
jsFunction += "\n i = 0; ";
jsFunction += "\n for (x in source) { ";
jsFunction += "\n if (source[x][0] == key) { ";
jsFunction += "\n opt = new Option(); ";
jsFunction += "\n opt.value = source[x][1]; ";
jsFunction += "\n if(source[x][1] == ''){ ";
jsFunction += "\n opt.text = '" + textOptionLok + "' ; ";
jsFunction += "\n }else {";
jsFunction += "\n if(displayLokasi.toUpperCase() == 'CODE') ";
jsFunction += "\n opt.text = source[x][2]; ";
jsFunction += "\n else if(displayLokasi.toUpperCase() == 'NAME') ";
jsFunction += "\n opt.text = source[x][3]; ";
jsFunction += "\n else ";
jsFunction += "\n opt.text = source[x][2] + ' ['+source[x][3]+ ']'; ";
jsFunction += "\n } ";
jsFunction += "\n if ((orig_key == key && orig_val == opt.value) || i == 0) { ";
jsFunction += "\n opt.selected = true; ";
jsFunction += "\n } ";
jsFunction += "\n list.options[i++] = opt; ";
jsFunction += "\n } ";
jsFunction += "\n } ";
jsFunction += "\n if (i == 0) { ";
jsFunction += "\n opt = new Option(); ";
jsFunction += "\n opt.value = ''; ";
jsFunction += "\n opt.text = '" + textOptionLok + "' ; ";
jsFunction += "\n list.options[i++] = opt; ";
jsFunction += "\n } ";
jsFunction += "\n list.length = i; ";
if (action.ToUpper() == "FILTER")
{
jsFunction += "\n for (y in kabupatenkotadata) { ";
jsFunction += "\n if (kabupatenkotadata[y][1] == key) { ";
jsFunction += "\n document.getElementById('KabupatenKotaNama').value = kabupatenkotadata[y][3] ; ";
jsFunction += "\n break; ";
jsFunction += "\n } ";
jsFunction += "\n } ";
}
if (action.ToUpper() == "FORMATKODE")
{
jsFunction += "\n ChangeFormatLokasiAset(list.options[list.selectedIndex].value , lokasidata, 'KodeLokasi');";
}
jsFunction += "\n } ";
jsFunction += "\n</script>";
return jsFunction;
}
public static string DrawKabupatenKotaList()
{
string PropinsiId = "";
string KabupatenKotaId = "";
string display = "";
string action = "";
string option = "SelectAll";
string displayLokasi = "";
return DrawKabupatenKotaList(PropinsiId, KabupatenKotaId, display, action, option, displayLokasi);
}
public static string DrawKabupatenKotaList(string PropinsiId)
{
string KabupatenKotaId = "";
string display = "";
string action = "";
string option = "SelectAll";
string displayLokasi = "";
return DrawKabupatenKotaList(PropinsiId, KabupatenKotaId, display, action, option, displayLokasi);
}
public static string DrawKabupatenKotaList(string PropinsiId, string KabupatenKotaId)
{
string display = "";
string action = "";
string option = "SelectAll";
string displayLokasi = "";
return DrawKabupatenKotaList(PropinsiId, KabupatenKotaId, display, action, option, displayLokasi);
}
public static string DrawKabupatenKotaList(string PropinsiId, string KabupatenKotaId, string display)
{
string action = "";
string option = "SelectAll";
string displayLokasi = "";
return DrawKabupatenKotaList(PropinsiId, KabupatenKotaId, display, action, option, displayLokasi);
}
public static string DrawKabupatenKotaList(string PropinsiId, string KabupatenKotaId, string display, string action)
{
string option = "SelectAll";
string displayLokasi = "";
return DrawKabupatenKotaList(PropinsiId, KabupatenKotaId, display, action, option, displayLokasi);
}
public static string DrawKabupatenKotaList(string PropinsiId, string KabupatenKotaId, string display, string action, string option)
{
string displayLokasi = "";
return DrawKabupatenKotaList(PropinsiId, KabupatenKotaId, display, action, option, displayLokasi);
}
public static string DrawKabupatenKotaList(string PropinsiId, string KabupatenKotaId, string display, string action, string option, string displayLokasi)
{
BkNet.DataAccess.KabupatenKota obj = new BkNet.DataAccess.KabupatenKota();
if (PropinsiId != "")
obj.PropinsiId = int.Parse(PropinsiId);
DataTable dt = obj.GetListWPropinsiIdLogic();
DataView dv = dt.DefaultView;
if (display.ToUpper() == "NAME")
dv.Sort = " Nama ASC";
else
dv.Sort = " Kode ASC";
string jscript = "";
jscript = "onchange=\"ChangeKabupatenKotaList( kabupatenkotadata, 'LokasiId',lokasidata, document.getElementById('KabupatenKotaId').options[document.getElementById('KabupatenKotaId').selectedIndex].value, 0, 0,'" + display + "','" + option + "','" + displayLokasi + "');\"";
string textOption = Resources.GetString("Referensi", "SelectAll");
if (option.ToUpper() == "SELECT")
{
textOption = Resources.GetString("Referensi", "SelectKab");
}
string itemText = "";
string itemNama = "";
string listData = "";
listData += "\n <SELECT id=\"KabupatenKotaId\" name=\"KabupatenKotaId\" " + jscript + ">";
listData += "\n <OPTION value=\"\">" + textOption + "</OPTION>";
for (int k = 0; k < dv.Count; k++)
{
if (display.ToUpper() == "CODE")
itemText = dv[k]["Kode"].ToString();
else if (display.ToUpper() == "NAME")
itemText = dv[k]["Nama"].ToString();
else
itemText = dv[k]["Kode"].ToString() + " [" + dv[k]["Nama"].ToString() + "]";
if (dv[k]["Id"].ToString() == KabupatenKotaId.ToString())
{
itemNama = dv[k]["Nama"].ToString();
listData += "\n <OPTION value=\"" + dv[k]["Id"].ToString() + "\" selected>" + itemText + "</OPTION>";
}
else
{
listData += "\n <OPTION value=\"" + dv[k]["Id"].ToString() + "\">" + itemText + "</OPTION>";
}
}
listData += "</SELECT>";
if (action.ToUpper() == "FILTER")
{
listData += "<input type=\"hidden\" name=\"KabupatenKotaNama\" id=\"KabupatenKotaNama\" value=\"" + itemNama + "\" >";
}
return listData;
}
#endregion
}
| |
using System;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Collections.Concurrent;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using MessageStream2;
using System.IO;
using DarkMultiPlayerCommon;
namespace DarkMultiPlayerServer
{
public class ClientHandler
{
//No point support IPv6 until KSP enables it on their windows builds.
private static TcpListener TCPServer;
private static ReadOnlyCollection<ClientObject> clients = new List<ClientObject>().AsReadOnly();
//When a client hits 100kb on the send queue, DMPServer will throw out old duplicate messages
private const int OPTIMIZE_QUEUE_LIMIT = 100 * 1024;
public static void ThreadMain()
{
try
{
clients = new List<ClientObject>().AsReadOnly();
Messages.WarpControl.Reset();
Messages.Chat.Reset();
Messages.ScreenshotLibrary.Reset();
SetupTCPServer();
while (Server.serverRunning)
{
//Process current clients
foreach (ClientObject client in clients)
{
Messages.Heartbeat.CheckHeartBeat(client);
}
//Check timers
NukeKSC.CheckTimer();
Dekessler.CheckTimer();
Messages.WarpControl.CheckTimer();
//Run plugin update
DMPPluginHandler.FireOnUpdate();
Thread.Sleep(10);
}
}
catch (Exception e)
{
DarkLog.Error("Fatal error thrown, exception: " + e);
Server.ShutDown("Crashed!");
}
try
{
long disconnectTime = DateTime.UtcNow.Ticks;
bool sendingHighPriotityMessages = true;
while (sendingHighPriotityMessages)
{
if ((DateTime.UtcNow.Ticks - disconnectTime) > 50000000)
{
DarkLog.Debug("Shutting down with " + Server.playerCount + " players, " + clients.Count + " connected clients");
break;
}
sendingHighPriotityMessages = false;
foreach (ClientObject client in clients)
{
if (client.authenticated && (client.sendMessageQueueHigh.Count > 0))
{
sendingHighPriotityMessages = true;
}
}
Thread.Sleep(10);
}
ShutdownTCPServer();
}
catch (Exception e)
{
DarkLog.Fatal("Fatal error thrown during shutdown, exception: " + e);
throw;
}
}
private static void SetupTCPServer()
{
try
{
IPAddress bindAddress = IPAddress.Parse(Settings.settingsStore.address);
TCPServer = new TcpListener(new IPEndPoint(bindAddress, Settings.settingsStore.port));
try
{
if (System.Net.Sockets.Socket.OSSupportsIPv6)
{
//Windows defaults to v6 only, but this option does not exist in mono so it has to be in a try/catch block along with the casted int.
if (Environment.OSVersion.Platform != PlatformID.MacOSX && Environment.OSVersion.Platform != PlatformID.Unix)
{
TCPServer.Server.SetSocketOption(SocketOptionLevel.IPv6, (SocketOptionName)27, 0);
}
}
}
catch
{
//Don't care - On linux and mac this throws because it's already set, and on windows it just works.
}
TCPServer.Start(4);
TCPServer.BeginAcceptTcpClient(new AsyncCallback(NewClientCallback), null);
}
catch (Exception e)
{
DarkLog.Normal("Error setting up server, Exception: " + e);
Server.serverRunning = false;
}
Server.serverStarting = false;
}
private static void ShutdownTCPServer()
{
TCPServer.Stop();
}
private static void NewClientCallback(IAsyncResult ar)
{
if (Server.serverRunning)
{
try
{
TcpClient newClient = TCPServer.EndAcceptTcpClient(ar);
SetupClient(newClient);
DarkLog.Normal("New client connection from " + newClient.Client.RemoteEndPoint);
}
catch
{
DarkLog.Normal("Error accepting client!");
}
TCPServer.BeginAcceptTcpClient(new AsyncCallback(NewClientCallback), null);
}
}
private static void SetupClient(TcpClient newClientConnection)
{
ClientObject newClientObject = new ClientObject();
newClientObject.subspace = Messages.WarpControl.GetLatestSubspace();
newClientObject.playerStatus = new PlayerStatus();
newClientObject.connectionStatus = ConnectionStatus.CONNECTED;
newClientObject.endpoint = newClientConnection.Client.RemoteEndPoint.ToString();
newClientObject.ipAddress = (newClientConnection.Client.RemoteEndPoint as IPEndPoint).Address;
//Keep the connection reference
newClientObject.connection = newClientConnection;
StartReceivingIncomingMessages(newClientObject);
StartSendingOutgoingMessages(newClientObject);
DMPPluginHandler.FireOnClientConnect(newClientObject);
Messages.Handshake.SendHandshakeChallange(newClientObject);
lock (clients)
{
List<ClientObject> newList = new List<ClientObject>(clients);
newList.Add(newClientObject);
clients = newList.AsReadOnly();
Server.playerCount = GetActiveClientCount();
Server.players = GetActivePlayerNames();
DarkLog.Debug("Online players is now: " + Server.playerCount + ", connected: " + clients.Count);
}
}
public static int GetActiveClientCount()
{
int authenticatedCount = 0;
foreach (ClientObject client in clients)
{
if (client.authenticated)
{
authenticatedCount++;
}
}
return authenticatedCount;
}
public static string GetActivePlayerNames()
{
string playerString = "";
foreach (ClientObject client in clients)
{
if (client.authenticated)
{
if (playerString != "")
{
playerString += ", ";
}
playerString += client.playerName;
}
}
return playerString;
}
private static void StartSendingOutgoingMessages(ClientObject client)
{
Thread clientSendThread = new Thread(new ParameterizedThreadStart(SendOutgoingMessages));
clientSendThread.IsBackground = true;
clientSendThread.Start(client);
}
//ParameterizedThreadStart takes an object
private static void SendOutgoingMessages(object client)
{
SendOutgoingMessages((ClientObject)client);
}
private static void SendOutgoingMessages(ClientObject client)
{
while (client.connectionStatus == ConnectionStatus.CONNECTED)
{
ServerMessage message = null;
if (message == null && client.sendMessageQueueHigh.Count > 0)
{
client.sendMessageQueueHigh.TryDequeue(out message);
}
//Don't send low or split during server shutdown.
if (Server.serverRunning)
{
if (message == null && client.sendMessageQueueSplit.Count > 0)
{
client.sendMessageQueueSplit.TryDequeue(out message);
}
if (message == null && client.sendMessageQueueLow.Count > 0)
{
client.sendMessageQueueLow.TryDequeue(out message);
//Splits large messages to higher priority messages can get into the queue faster
SplitAndRewriteMessage(client, ref message);
}
}
if (message != null)
{
SendNetworkMessage(client, message);
}
else
{
//Give the chance for the thread to terminate
client.sendEvent.WaitOne(1000);
}
}
}
private static void SplitAndRewriteMessage(ClientObject client, ref ServerMessage message)
{
if (message == null)
{
return;
}
if (message.data == null)
{
return;
}
if (message.data.Length > Common.SPLIT_MESSAGE_LENGTH)
{
ServerMessage newSplitMessage = new ServerMessage();
newSplitMessage.type = ServerMessageType.SPLIT_MESSAGE;
int splitBytesLeft = message.data.Length;
using (MessageWriter mw = new MessageWriter())
{
mw.Write<int>((int)message.type);
mw.Write<int>(message.data.Length);
byte[] firstSplit = new byte[Common.SPLIT_MESSAGE_LENGTH];
Array.Copy(message.data, 0, firstSplit, 0, Common.SPLIT_MESSAGE_LENGTH);
mw.Write<byte[]>(firstSplit);
splitBytesLeft -= Common.SPLIT_MESSAGE_LENGTH;
newSplitMessage.data = mw.GetMessageBytes();
//SPLIT_MESSAGE metadata header length.
client.bytesQueuedOut += 8;
client.sendMessageQueueSplit.Enqueue(newSplitMessage);
}
while (splitBytesLeft > 0)
{
ServerMessage currentSplitMessage = new ServerMessage();
currentSplitMessage.type = ServerMessageType.SPLIT_MESSAGE;
currentSplitMessage.data = new byte[Math.Min(splitBytesLeft, Common.SPLIT_MESSAGE_LENGTH)];
Array.Copy(message.data, message.data.Length - splitBytesLeft, currentSplitMessage.data, 0, currentSplitMessage.data.Length);
splitBytesLeft -= currentSplitMessage.data.Length;
//SPLIT_MESSAGE network frame header length.
client.bytesQueuedOut += 8;
client.sendMessageQueueSplit.Enqueue(currentSplitMessage);
}
client.sendMessageQueueSplit.TryDequeue(out message);
}
}
private static void SendNetworkMessage(ClientObject client, ServerMessage message)
{
//Write the send times down in SYNC_TIME_REPLY packets
if (message.type == ServerMessageType.SYNC_TIME_REPLY)
{
try
{
using (MessageWriter mw = new MessageWriter())
{
using (MessageReader mr = new MessageReader(message.data))
{
client.bytesQueuedOut += 8;
//Client send time
mw.Write<long>(mr.Read<long>());
//Server receive time
mw.Write<long>(mr.Read<long>());
//Server send time
mw.Write<long>(DateTime.UtcNow.Ticks);
message.data = mw.GetMessageBytes();
}
}
}
catch (Exception e)
{
DarkLog.Debug("Error rewriting SYNC_TIME packet, Exception " + e);
}
}
//Continue sending
byte[] messageBytes = Common.PrependNetworkFrame((int)message.type, message.data);
client.lastSendTime = Server.serverClock.ElapsedMilliseconds;
client.bytesQueuedOut -= messageBytes.Length;
client.bytesSent += messageBytes.Length;
if (client.connectionStatus == ConnectionStatus.CONNECTED)
{
try
{
client.connection.GetStream().Write(messageBytes, 0, messageBytes.Length);
}
catch (Exception e)
{
HandleDisconnectException("Send Network Message", client, e);
return;
}
}
DMPPluginHandler.FireOnMessageSent(client, message);
if (message.type == ServerMessageType.CONNECTION_END)
{
using (MessageReader mr = new MessageReader(message.data))
{
string reason = mr.Read<string>();
DarkLog.Normal("Disconnecting client " + client.playerName + ", sent CONNECTION_END (" + reason + ") to endpoint " + client.endpoint);
client.disconnectClient = true;
DisconnectClient(client);
}
}
if (message.type == ServerMessageType.HANDSHAKE_REPLY)
{
using (MessageReader mr = new MessageReader(message.data))
{
int response = mr.Read<int>();
string reason = mr.Read<string>();
if (response != 0)
{
DarkLog.Normal("Disconnecting client " + client.playerName + ", sent HANDSHAKE_REPLY (" + reason + ") to endpoint " + client.endpoint);
client.disconnectClient = true;
DisconnectClient(client);
}
}
}
}
private static void StartReceivingIncomingMessages(ClientObject client)
{
client.lastReceiveTime = Server.serverClock.ElapsedMilliseconds;
//Allocate byte for header
client.receiveMessage = new ClientMessage();
client.receiveMessage.data = new byte[8];
client.receiveMessageBytesLeft = client.receiveMessage.data.Length;
try
{
client.connection.GetStream().BeginRead(client.receiveMessage.data, client.receiveMessage.data.Length - client.receiveMessageBytesLeft, client.receiveMessageBytesLeft, new AsyncCallback(ReceiveCallback), client);
}
catch (Exception e)
{
HandleDisconnectException("Start Receive", client, e);
}
}
private static void ReceiveCallback(IAsyncResult ar)
{
ClientObject client = (ClientObject)ar.AsyncState;
int bytesRead = 0;
try
{
bytesRead = client.connection.GetStream().EndRead(ar);
}
catch (Exception e)
{
HandleDisconnectException("ReceiveCallback", client, e);
return;
}
client.bytesReceived += bytesRead;
client.receiveMessageBytesLeft -= bytesRead;
if (client.receiveMessageBytesLeft == 0)
{
//We either have the header or the message data, let's do something
if (!client.isReceivingMessage)
{
//We have the header
using (MessageReader mr = new MessageReader(client.receiveMessage.data))
{
int messageType = mr.Read<int>();
int messageLength = mr.Read<int>();
if (messageType < 0 || messageType > (Enum.GetNames(typeof(ClientMessageType)).Length - 1))
{
//Malformed message, most likely from a non DMP-client.
Messages.ConnectionEnd.SendConnectionEnd(client, "Invalid DMP message. Disconnected.");
DarkLog.Normal("Invalid DMP message from " + client.endpoint);
//Returning from ReceiveCallback will break the receive loop and stop processing any further messages.
return;
}
client.receiveMessage.type = (ClientMessageType)messageType;
if (messageLength == 0)
{
//Null message, handle it.
client.receiveMessage.data = null;
HandleMessage(client, client.receiveMessage);
client.receiveMessage.type = 0;
client.receiveMessage.data = new byte[8];
client.receiveMessageBytesLeft = client.receiveMessage.data.Length;
}
else
{
if (messageLength > 0 && messageLength < Common.MAX_MESSAGE_SIZE)
{
client.isReceivingMessage = true;
client.receiveMessage.data = new byte[messageLength];
client.receiveMessageBytesLeft = client.receiveMessage.data.Length;
}
else
{
//Malformed message, most likely from a non DMP-client.
Messages.ConnectionEnd.SendConnectionEnd(client, "Invalid DMP message. Disconnected.");
DarkLog.Normal("Invalid DMP message from " + client.endpoint);
//Returning from ReceiveCallback will break the receive loop and stop processing any further messages.
return;
}
}
}
}
else
{
//We have the message data to a non-null message, handle it
client.isReceivingMessage = false;
#if !DEBUG
try
{
#endif
HandleMessage(client, client.receiveMessage);
#if !DEBUG
}
catch (Exception e)
{
HandleDisconnectException("ReceiveCallback", client, e);
return;
}
#endif
client.receiveMessage.type = 0;
client.receiveMessage.data = new byte[8];
client.receiveMessageBytesLeft = client.receiveMessage.data.Length;
}
}
if (client.connectionStatus == ConnectionStatus.CONNECTED)
{
client.lastReceiveTime = Server.serverClock.ElapsedMilliseconds;
try
{
client.connection.GetStream().BeginRead(client.receiveMessage.data, client.receiveMessage.data.Length - client.receiveMessageBytesLeft, client.receiveMessageBytesLeft, new AsyncCallback(ReceiveCallback), client);
}
catch (Exception e)
{
HandleDisconnectException("ReceiveCallback", client, e);
return;
}
}
}
private static void HandleDisconnectException(string location, ClientObject client, Exception e)
{
lock (client.disconnectLock)
{
if (!client.disconnectClient && client.connectionStatus != ConnectionStatus.DISCONNECTED)
{
if (e.InnerException != null)
{
DarkLog.Normal("Client " + client.playerName + " disconnected in " + location + ", endpoint " + client.endpoint + ", error: " + e.Message + " (" + e.InnerException.Message + ")");
}
else
{
DarkLog.Normal("Client " + client.playerName + " disconnected in " + location + ", endpoint " + client.endpoint + ", error: " + e.Message);
}
}
DisconnectClient(client);
}
}
internal static void DisconnectClient(ClientObject client)
{
lock (client.disconnectLock)
{
//Remove clients from list
if (clients.Contains(client))
{
List<ClientObject> newList = new List<ClientObject>(clients);
newList.Remove(client);
clients = newList.AsReadOnly();
Server.playerCount = GetActiveClientCount();
Server.players = GetActivePlayerNames();
DarkLog.Debug("Online players is now: " + Server.playerCount + ", connected: " + clients.Count);
if (!Settings.settingsStore.keepTickingWhileOffline && clients.Count == 0)
{
Messages.WarpControl.HoldSubspace();
}
Messages.WarpControl.DisconnectPlayer(client.playerName);
}
//Disconnect
if (client.connectionStatus != ConnectionStatus.DISCONNECTED)
{
DMPPluginHandler.FireOnClientDisconnect(client);
if (client.playerName != null)
{
Messages.Chat.RemovePlayer(client.playerName);
}
client.connectionStatus = ConnectionStatus.DISCONNECTED;
if (client.authenticated)
{
ServerMessage newMessage = new ServerMessage();
newMessage.type = ServerMessageType.PLAYER_DISCONNECT;
using (MessageWriter mw = new MessageWriter())
{
mw.Write<string>(client.playerName);
newMessage.data = mw.GetMessageBytes();
}
SendToAll(client, newMessage, true);
LockSystem.fetch.ReleasePlayerLocks(client.playerName);
}
try
{
if (client.connection != null)
{
client.connection.GetStream().Close();
client.connection.Close();
}
}
catch (Exception e)
{
DarkLog.Debug("Error closing client connection: " + e.Message);
}
Server.lastPlayerActivity = Server.serverClock.ElapsedMilliseconds;
}
}
}
internal static void HandleMessage(ClientObject client, ClientMessage message)
{
//Prevent plugins from dodging SPLIT_MESSAGE. If they are modified, every split message will be broken.
if (message.type != ClientMessageType.SPLIT_MESSAGE)
{
DMPPluginHandler.FireOnMessageReceived(client, message);
if (message.handled)
{
//a plugin has handled this message and requested suppression of the default DMP behavior
return;
}
}
//Clients can only send HEARTBEATS, HANDSHAKE_REQUEST or CONNECTION_END's until they are authenticated.
if (!client.authenticated && !(message.type == ClientMessageType.HEARTBEAT || message.type == ClientMessageType.HANDSHAKE_RESPONSE || message.type == ClientMessageType.CONNECTION_END))
{
Messages.ConnectionEnd.SendConnectionEnd(client, "You must authenticate before attempting to send a " + message.type.ToString() + " message");
return;
}
#if !DEBUG
try
{
#endif
switch (message.type)
{
case ClientMessageType.HEARTBEAT:
//Don't do anything for heartbeats, they just keep the connection alive
break;
case ClientMessageType.HANDSHAKE_RESPONSE:
Messages.Handshake.HandleHandshakeResponse(client, message.data);
break;
case ClientMessageType.CHAT_MESSAGE:
Messages.Chat.HandleChatMessage(client, message.data);
break;
case ClientMessageType.PLAYER_STATUS:
Messages.PlayerStatus.HandlePlayerStatus(client, message.data);
break;
case ClientMessageType.PLAYER_COLOR:
Messages.PlayerColor.HandlePlayerColor(client, message.data);
break;
case ClientMessageType.SCENARIO_DATA:
Messages.ScenarioData.HandleScenarioModuleData(client, message.data);
break;
case ClientMessageType.SYNC_TIME_REQUEST:
Messages.SyncTimeRequest.HandleSyncTimeRequest(client, message.data);
break;
case ClientMessageType.KERBALS_REQUEST:
Messages.KerbalsRequest.HandleKerbalsRequest(client);
break;
case ClientMessageType.KERBAL_PROTO:
Messages.KerbalProto.HandleKerbalProto(client, message.data);
break;
case ClientMessageType.VESSELS_REQUEST:
Messages.VesselRequest.HandleVesselsRequest(client, message.data);
break;
case ClientMessageType.VESSEL_PROTO:
Messages.VesselProto.HandleVesselProto(client, message.data);
break;
case ClientMessageType.VESSEL_UPDATE:
Messages.VesselUpdate.HandleVesselUpdate(client, message.data);
break;
case ClientMessageType.VESSEL_REMOVE:
Messages.VesselRemove.HandleVesselRemoval(client, message.data);
break;
case ClientMessageType.CRAFT_LIBRARY:
Messages.CraftLibrary.HandleCraftLibrary(client, message.data);
break;
case ClientMessageType.SCREENSHOT_LIBRARY:
Messages.ScreenshotLibrary.HandleScreenshotLibrary(client, message.data);
break;
case ClientMessageType.FLAG_SYNC:
Messages.FlagSync.HandleFlagSync(client, message.data);
break;
case ClientMessageType.PING_REQUEST:
Messages.PingRequest.HandlePingRequest(client, message.data);
break;
case ClientMessageType.MOTD_REQUEST:
Messages.MotdRequest.HandleMotdRequest(client);
break;
case ClientMessageType.WARP_CONTROL:
Messages.WarpControl.HandleWarpControl(client, message.data);
break;
case ClientMessageType.LOCK_SYSTEM:
Messages.LockSystem.HandleLockSystemMessage(client, message.data);
break;
case ClientMessageType.MOD_DATA:
Messages.ModData.HandleModDataMessage(client, message.data);
break;
case ClientMessageType.SPLIT_MESSAGE:
Messages.SplitMessage.HandleSplitMessage(client, message.data);
break;
case ClientMessageType.CONNECTION_END:
Messages.ConnectionEnd.HandleConnectionEnd(client, message.data);
break;
default:
DarkLog.Debug("Unhandled message type " + message.type);
Messages.ConnectionEnd.SendConnectionEnd(client, "Unhandled message type " + message.type);
#if DEBUG
throw new NotImplementedException("Message type not implemented");
#else
break;
#endif
}
#if !DEBUG
}
catch (Exception e)
{
DarkLog.Debug("Error handling " + message.type + " from " + client.playerName + ", exception: " + e);
Messages.ConnectionEnd.SendConnectionEnd(client, "Server failed to process " + message.type + " message");
}
#endif
}
//Call with null client to send to all clients. Also called from Dekessler and NukeKSC.
public static void SendToAll(ClientObject ourClient, ServerMessage message, bool highPriority)
{
foreach (ClientObject otherClient in clients)
{
if (ourClient != otherClient)
{
SendToClient(otherClient, message, highPriority);
}
}
}
//Call with null client to send to all clients. Auto selects wether to use the compressed or decompressed message.
public static void SendToAllAutoCompressed(ClientObject ourClient, ServerMessage compressed, ServerMessage decompressed, bool highPriority)
{
foreach (ClientObject otherClient in clients)
{
if (ourClient != otherClient)
{
if (otherClient.compressionEnabled && (compressed != null))
{
SendToClient(otherClient, compressed, highPriority);
}
else
{
SendToClient(otherClient, decompressed, highPriority);
}
}
}
}
public static void SendToClient(ClientObject client, ServerMessage message, bool highPriority)
{
//Because we dodge the queue, we need to lock it up again...
lock (client.sendLock)
{
if (message == null)
{
return;
}
//All messages have an 8 byte header
client.bytesQueuedOut += 8;
if (message.data != null)
{
//Count the payload if we have one.
client.bytesQueuedOut += message.data.Length;
}
if (highPriority)
{
client.sendMessageQueueHigh.Enqueue(message);
}
else
{
client.sendMessageQueueLow.Enqueue(message);
//If we need to optimize
if (client.bytesQueuedOut > OPTIMIZE_QUEUE_LIMIT)
{
//And we haven't optimized in the last 5 seconds
long currentTime = DateTime.UtcNow.Ticks;
long optimizedBytes = 0;
if ((currentTime - client.lastQueueOptimizeTime) > 50000000)
{
client.lastQueueOptimizeTime = currentTime;
DarkLog.Debug("Optimizing " + client.playerName + " (" + client.bytesQueuedOut + " bytes queued)");
//Create a temporary filter list
List<ServerMessage> oldClientMessagesToSend = new List<ServerMessage>();
List<ServerMessage> newClientMessagesToSend = new List<ServerMessage>();
//Steal all the messages from the queue and put them into a list
ServerMessage stealMessage = null;
while (client.sendMessageQueueLow.TryDequeue(out stealMessage))
{
oldClientMessagesToSend.Add(stealMessage);
}
//Clear the client send queue
List<string> seenProtovesselUpdates = new List<string>();
List<string> seenPositionUpdates = new List<string>();
//Iterate backwards over the list
oldClientMessagesToSend.Reverse();
foreach (ServerMessage currentMessage in oldClientMessagesToSend)
{
if (currentMessage.type != ServerMessageType.VESSEL_PROTO && currentMessage.type != ServerMessageType.VESSEL_UPDATE)
{
//Message isn't proto or position, don't skip it.
newClientMessagesToSend.Add(currentMessage);
}
else
{
//Message is proto or position
if (currentMessage.type == ServerMessageType.VESSEL_PROTO)
{
using (MessageReader mr = new MessageReader(currentMessage.data))
{
//Don't care about the send time, it's already the latest in the queue.
mr.Read<double>();
string vesselID = mr.Read<string>();
if (!seenProtovesselUpdates.Contains(vesselID))
{
seenProtovesselUpdates.Add(vesselID);
newClientMessagesToSend.Add(currentMessage);
}
else
{
optimizedBytes += 8 + currentMessage.data.Length;
}
}
}
if (currentMessage.type == ServerMessageType.VESSEL_UPDATE)
{
using (MessageReader mr = new MessageReader(currentMessage.data))
{
//Don't care about the send time, it's already the latest in the queue.
mr.Read<double>();
string vesselID = mr.Read<string>();
if (!seenPositionUpdates.Contains(vesselID))
{
seenPositionUpdates.Add(vesselID);
newClientMessagesToSend.Add(currentMessage);
}
else
{
//8 byte message header plus payload
optimizedBytes += 8 + currentMessage.data.Length;
}
}
}
}
}
//Flip it back to the right order
newClientMessagesToSend.Reverse();
foreach (ServerMessage putBackMessage in newClientMessagesToSend)
{
client.sendMessageQueueLow.Enqueue(putBackMessage);
}
float optimizeTime = (DateTime.UtcNow.Ticks - currentTime) / 10000f;
client.bytesQueuedOut -= optimizedBytes;
DarkLog.Debug("Optimized " + optimizedBytes + " bytes in " + Math.Round(optimizeTime, 3) + " ms.");
}
}
}
client.sendEvent.Set();
}
}
public static ClientObject[] GetClients()
{
List<ClientObject> returnArray = new List<ClientObject>(clients);
return returnArray.ToArray();
}
public static bool ClientConnected(ClientObject client)
{
return clients.Contains(client);
}
public static ClientObject GetClientByName(string playerName)
{
ClientObject findClient = null;
foreach (ClientObject testClient in clients)
{
if (testClient.authenticated && testClient.playerName == playerName)
{
findClient = testClient;
break;
}
}
return findClient;
}
public static ClientObject GetClientByIP(IPAddress ipAddress)
{
ClientObject findClient = null;
foreach (ClientObject testClient in clients)
{
if (testClient.authenticated && testClient.ipAddress == ipAddress)
{
findClient = testClient;
break;
}
}
return findClient;
}
public static ClientObject GetClientByPublicKey(string publicKey)
{
ClientObject findClient = null;
foreach (ClientObject testClient in clients)
{
if (testClient.authenticated && testClient.publicKey == publicKey)
{
findClient = testClient;
break;
}
}
return findClient;
}
}
public class ClientObject
{
public bool authenticated;
public byte[] challange;
public string playerName = "Unknown";
public string clientVersion;
public bool isBanned;
public IPAddress ipAddress;
public string publicKey;
//subspace tracking
public int subspace = -1;
public float subspaceRate = 1f;
//vessel tracking
public string activeVessel = "";
//connection
public string endpoint;
public TcpClient connection;
//Send buffer
public long lastSendTime;
public ConcurrentQueue<ServerMessage> sendMessageQueueHigh = new ConcurrentQueue<ServerMessage>();
public ConcurrentQueue<ServerMessage> sendMessageQueueSplit = new ConcurrentQueue<ServerMessage>();
public ConcurrentQueue<ServerMessage> sendMessageQueueLow = new ConcurrentQueue<ServerMessage>();
public long lastReceiveTime;
public bool disconnectClient;
//Receive buffer
public bool isReceivingMessage;
public int receiveMessageBytesLeft;
public ClientMessage receiveMessage;
//Receive split buffer
public bool isReceivingSplitMessage;
public int receiveSplitMessageBytesLeft;
public ClientMessage receiveSplitMessage;
//State tracking
public ConnectionStatus connectionStatus;
public PlayerStatus playerStatus;
public float[] playerColor;
//Network traffic tracking
public long bytesQueuedOut = 0;
public long bytesSent = 0;
public long bytesReceived = 0;
public long lastQueueOptimizeTime = 0;
//Send lock
public AutoResetEvent sendEvent = new AutoResetEvent(false);
public object sendLock = new object();
public object disconnectLock = new object();
//Compression
public bool compressionEnabled = false;
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Collections.Generic;
using Microsoft.Protocols.TestTools.StackSdk.Messages;
using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Cifs;
namespace Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb
{
/// <summary>
/// Packets for SmbNtCreateAndx Response
/// </summary>
public class SmbNtCreateAndxResponsePacket : Cifs.SmbNtCreateAndxResponsePacket
{
#region Const
/// <summary>
/// in TD: WordCount, This field SHOULD be 0x32.<para/>
/// and windows feature: Windows-based servers set this field to 0x2A.<para/>
/// so, if there is 16(0x32 - 0x2A) bytes more in channel, need to unmarshal the additional data.
/// </summary>
private const int WINDOWS_BEHAVIOR_ADDITIONAL_DATA_LENGTH = 16;
/// <summary>
/// The word count for this response MUST be 0x2A (42). WordCount in this case is not used as the count of
/// parameter words but is just a number.
/// </summary>
private const int CREATE_EXTENDED_INFORMATION_RESPONSE_LENGTH = 42;
#endregion
#region Fields
private SMB_COM_NT_CREATE_ANDX_Response_SMB_Parameters smbParameters;
#endregion
#region Properties
/// <summary>
/// get or set the Smb_Parameters:SMB_COM_TREE_CONNECT_ANDX_Response_SMB_Parameters
/// </summary>
public new SMB_COM_NT_CREATE_ANDX_Response_SMB_Parameters SmbParameters
{
get
{
return this.smbParameters;
}
set
{
this.smbParameters = value;
base.SmbParameters = SmbMessageUtils.ConvertSmbComCreatePacketPayload(this.smbParameters);
}
}
#endregion
#region Convert from base class
/// <summary>
/// initialize packet from base packet.
/// </summary>
/// <param name = "packet">the base packet to initialize this packet. </param>
public SmbNtCreateAndxResponsePacket(Cifs.SmbNtCreateAndxResponsePacket packet)
: base(packet)
{
this.smbParameters = SmbMessageUtils.ConvertSmbComCreatePacketPayload(base.SmbParameters);
}
#endregion
#region override methods
/// <summary>
/// to unmarshal the SmbParameters struct from a channel.
/// </summary>
/// <param name="channel">the channel started with SmbParameters.</param>
/// <returns>the size in bytes of the SmbParameters.</returns>
protected override int ReadParametersFromChannel(Channel channel)
{
this.smbParametersBlock = channel.Read<SmbParameters>();
if (channel.Stream.Position <= channel.Stream.Length - WINDOWS_BEHAVIOR_ADDITIONAL_DATA_LENGTH)
{
byte[] data = CifsMessageUtils.ToBytesArray<ushort>(this.smbParametersBlock.Words);
this.smbParametersBlock.Words = CifsMessageUtils.ToTypeArray<ushort>(
ArrayUtility.ConcatenateArrays<byte>(
data, channel.ReadBytes(WINDOWS_BEHAVIOR_ADDITIONAL_DATA_LENGTH)));
}
this.DecodeParameters();
int sizeOfWordCount = sizeof(byte);
int sizeOfWords = this.smbParametersBlock.WordCount * sizeof(ushort);
return sizeOfWordCount + sizeOfWords;
}
/// <summary>
/// Encode the struct of SMB_COM_TREE_CONNECT_ANDX_Response_SMB_Parameters into the struct of SmbParameters
/// </summary>
protected override void EncodeParameters()
{
List<byte> bytes = new List<byte>();
bytes.AddRange(TypeMarshal.ToBytes<SmbCommand>(this.smbParameters.AndXCommand));
bytes.AddRange(TypeMarshal.ToBytes<byte>(this.smbParameters.AndXReserved));
bytes.AddRange(TypeMarshal.ToBytes<ushort>(this.smbParameters.AndXOffset));
bytes.AddRange(TypeMarshal.ToBytes<OplockLevelValue>(this.smbParameters.OplockLevel));
bytes.AddRange(TypeMarshal.ToBytes<ushort>(this.smbParameters.FID));
bytes.AddRange(TypeMarshal.ToBytes<uint>(this.smbParameters.CreationAction));
bytes.AddRange(TypeMarshal.ToBytes<Cifs.FileTime>(this.smbParameters.CreateTime));
bytes.AddRange(TypeMarshal.ToBytes<Cifs.FileTime>(this.smbParameters.LastAccessTime));
bytes.AddRange(TypeMarshal.ToBytes<Cifs.FileTime>(this.smbParameters.LastWriteTime));
bytes.AddRange(TypeMarshal.ToBytes<Cifs.FileTime>(this.smbParameters.LastChangeTime));
bytes.AddRange(TypeMarshal.ToBytes<uint>(this.smbParameters.ExtFileAttributes));
bytes.AddRange(TypeMarshal.ToBytes<ulong>(this.smbParameters.AllocationSize));
bytes.AddRange(TypeMarshal.ToBytes<ulong>(this.smbParameters.EndOfFile));
bytes.AddRange(TypeMarshal.ToBytes<FileTypeValue>(this.smbParameters.ResourceType));
bytes.AddRange(TypeMarshal.ToBytes<SMB_NMPIPE_STATUS>(this.smbParameters.NMPipeStatus_or_FileStatusFlags));
bytes.AddRange(TypeMarshal.ToBytes<byte>(this.smbParameters.Directory));
if (this.smbParameters.VolumeGUID != null)
{
bytes.AddRange(this.smbParameters.VolumeGUID);
}
if (this.smbParameters.FileId != null)
{
bytes.AddRange(this.smbParameters.FileId);
}
if (this.smbParameters.MaximalAccessRights != null)
{
bytes.AddRange(this.smbParameters.MaximalAccessRights);
}
if (this.smbParameters.GuestMaximalAccessRights != null)
{
bytes.AddRange(this.smbParameters.GuestMaximalAccessRights);
}
this.smbParametersBlock.WordCount = (byte)this.smbParameters.WordCount;
this.smbParametersBlock.Words = CifsMessageUtils.ToTypeArray<ushort>(bytes.ToArray());
}
/// <summary>
/// to decode the smb parameters: from the general SmbParameters to the concrete Smb Parameters.
/// </summary>
protected override void DecodeParameters()
{
// When a client requests extended information, the word count must be 42
if (this.smbParametersBlock.WordCount == CREATE_EXTENDED_INFORMATION_RESPONSE_LENGTH)
{
SMB_COM_NT_CREATE_ANDX_Response_SMB_Parameters param =
new SMB_COM_NT_CREATE_ANDX_Response_SMB_Parameters();
using (MemoryStream stream = new MemoryStream(
CifsMessageUtils.ToBytesArray<ushort>(this.smbParametersBlock.Words)))
{
using (Channel channel = new Channel(null, stream))
{
param.WordCount = this.smbParametersBlock.WordCount;
param.AndXCommand = channel.Read<SmbCommand>();
param.AndXReserved = channel.Read<byte>();
param.AndXOffset = channel.Read<ushort>();
param.OplockLevel = channel.Read<OplockLevelValue>();
param.FID = channel.Read<ushort>();
param.CreationAction = channel.Read<uint>();
param.CreateTime = channel.Read<Cifs.FileTime>();
param.LastAccessTime = channel.Read<Cifs.FileTime>();
param.LastWriteTime = channel.Read<Cifs.FileTime>();
param.LastChangeTime = channel.Read<Cifs.FileTime>();
param.ExtFileAttributes = channel.Read<uint>();
param.AllocationSize = channel.Read<ulong>();
param.EndOfFile = channel.Read<ulong>();
param.ResourceType = channel.Read<FileTypeValue>();
param.NMPipeStatus_or_FileStatusFlags = channel.Read<SMB_NMPIPE_STATUS>();
param.Directory = channel.Read<byte>();
// VolumeGUID (16 bytes), td defines this length
param.VolumeGUID = channel.ReadBytes(CifsMessageUtils.GetSize<Guid>(new Guid()));
// if there is more 16 bytes in the channel.
if (channel.Stream.Position <= channel.Stream.Length - WINDOWS_BEHAVIOR_ADDITIONAL_DATA_LENGTH)
{
// FileId (8 bytes), td defines this length
param.FileId = channel.ReadBytes(sizeof(ulong));
// MaximalAccessRights (4 bytes), td defines this length
param.MaximalAccessRights = channel.ReadBytes(sizeof(uint));
// GuestMaximalAccessRights (4 bytes), td defines this length
param.GuestMaximalAccessRights = channel.ReadBytes(sizeof(uint));
}
}
}
this.SmbParameters = param;
}
else
{
base.DecodeParameters();
this.smbParameters = SmbMessageUtils.ConvertSmbComCreatePacketPayload(base.SmbParameters);
}
}
/// <summary>
/// override the marshal method of smb parameter.<para/>
/// in the create response, the WordCount is not equal to Words.Count.
/// </summary>
/// <param name="channel">
/// a Channel to write data to.
/// </param>
protected override void WriteSmbParameter(Channel channel)
{
channel.Write<byte>((byte)CREATE_EXTENDED_INFORMATION_RESPONSE_LENGTH);
channel.WriteBytes(Cifs.CifsMessageUtils.ToBytesArray<ushort>(this.smbParametersBlock.Words));
}
#endregion
#region Constructor
/// <summary>
/// Constructor.
/// </summary>
public SmbNtCreateAndxResponsePacket()
: base()
{
}
/// <summary>
/// Constructor: Create a request directly from a buffer.
/// </summary>
public SmbNtCreateAndxResponsePacket(byte[] data)
: base(data)
{
}
/// <summary>
/// Deep copy constructor.
/// </summary>
public SmbNtCreateAndxResponsePacket(SmbNtCreateAndxResponsePacket packet)
: base(packet)
{
}
#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.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
namespace System.Collections.Immutable
{
public sealed partial class ImmutableSortedSet<T>
{
/// <summary>
/// A node in the AVL tree storing this set.
/// </summary>
[DebuggerDisplay("{_key}")]
internal sealed class Node : IBinaryTree<T>, IEnumerable<T>
{
/// <summary>
/// The default empty node.
/// </summary>
internal static readonly Node EmptyNode = new Node();
/// <summary>
/// The key associated with this node.
/// </summary>
private readonly T _key;
/// <summary>
/// A value indicating whether this node has been frozen (made immutable).
/// </summary>
/// <remarks>
/// Nodes must be frozen before ever being observed by a wrapping collection type
/// to protect collections from further mutations.
/// </remarks>
private bool _frozen;
/// <summary>
/// The depth of the tree beneath this node.
/// </summary>
private byte _height; // AVL tree max height <= ~1.44 * log2(maxNodes + 2)
/// <summary>
/// The number of elements contained by this subtree starting at this node.
/// </summary>
/// <remarks>
/// If this node would benefit from saving 4 bytes, we could have only a few nodes
/// scattered throughout the graph actually record the count of nodes beneath them.
/// Those without the count could query their descendants, which would often short-circuit
/// when they hit a node that *does* include a count field.
/// </remarks>
private int _count;
/// <summary>
/// The left tree.
/// </summary>
private Node _left;
/// <summary>
/// The right tree.
/// </summary>
private Node _right;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableSortedSet{T}.Node"/> class
/// that is pre-frozen.
/// </summary>
private Node()
{
Contract.Ensures(this.IsEmpty);
_frozen = true; // the empty node is *always* frozen.
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableSortedSet{T}.Node"/> class
/// that is not yet frozen.
/// </summary>
/// <param name="key">The value stored by this node.</param>
/// <param name="left">The left branch.</param>
/// <param name="right">The right branch.</param>
/// <param name="frozen">Whether this node is prefrozen.</param>
private Node(T key, Node left, Node right, bool frozen = false)
{
Requires.NotNullAllowStructs(key, nameof(key));
Requires.NotNull(left, nameof(left));
Requires.NotNull(right, nameof(right));
Debug.Assert(!frozen || (left._frozen && right._frozen));
_key = key;
_left = left;
_right = right;
_height = checked((byte)(1 + Math.Max(left._height, right._height)));
_count = 1 + left._count + right._count;
_frozen = frozen;
}
/// <summary>
/// Gets a value indicating whether this instance is empty.
/// </summary>
/// <value>
/// <c>true</c> if this instance is empty; otherwise, <c>false</c>.
/// </value>
public bool IsEmpty
{
get { return _left == null; }
}
/// <summary>
/// Gets the height of the tree beneath this node.
/// </summary>
public int Height
{
get { return _height; }
}
/// <summary>
/// Gets the left branch of this node.
/// </summary>
public Node Left
{
get { return _left; }
}
/// <summary>
/// Gets the left branch of this node.
/// </summary>
IBinaryTree IBinaryTree.Left
{
get { return _left; }
}
/// <summary>
/// Gets the right branch of this node.
/// </summary>
public Node Right
{
get { return _right; }
}
/// <summary>
/// Gets the right branch of this node.
/// </summary>
IBinaryTree IBinaryTree.Right
{
get { return _right; }
}
/// <summary>
/// Gets the left branch of this node.
/// </summary>
IBinaryTree<T> IBinaryTree<T>.Left
{
get { return _left; }
}
/// <summary>
/// Gets the right branch of this node.
/// </summary>
IBinaryTree<T> IBinaryTree<T>.Right
{
get { return _right; }
}
/// <summary>
/// Gets the value represented by the current node.
/// </summary>
public T Value { get { return _key; } }
/// <summary>
/// Gets the number of elements contained by this subtree starting at this node.
/// </summary>
public int Count
{
get { return _count; }
}
/// <summary>
/// Gets the key.
/// </summary>
internal T Key
{
get { return _key; }
}
/// <summary>
/// Gets the maximum value in the collection, as defined by the comparer.
/// </summary>
/// <value>The maximum value in the set.</value>
internal T Max
{
get
{
if (this.IsEmpty)
{
return default(T);
}
Node n = this;
while (!n._right.IsEmpty)
{
n = n._right;
}
return n._key;
}
}
/// <summary>
/// Gets the minimum value in the collection, as defined by the comparer.
/// </summary>
/// <value>The minimum value in the set.</value>
internal T Min
{
get
{
if (this.IsEmpty)
{
return default(T);
}
Node n = this;
while (!n._left.IsEmpty)
{
n = n._left;
}
return n._key;
}
}
/// <summary>
/// Gets the element of the set at the given index.
/// </summary>
/// <param name="index">The 0-based index of the element in the set to return.</param>
/// <returns>The element at the given position.</returns>
internal T this[int index]
{
get
{
Requires.Range(index >= 0 && index < this.Count, nameof(index));
if (index < _left._count)
{
return _left[index];
}
if (index > _left._count)
{
return _right[index - _left._count - 1];
}
return _key;
}
}
#region IEnumerable<T> Members
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
[ExcludeFromCodeCoverage] // internal and never called, but here for the interface.
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return this.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
[ExcludeFromCodeCoverage] // internal and never called, but here for the interface.
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <param name="builder">The builder, if applicable.</param>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
internal Enumerator GetEnumerator(Builder builder)
{
return new Enumerator(this, builder);
}
/// <summary>
/// See the <see cref="ICollection{T}"/> interface.
/// </summary>
internal void CopyTo(T[] array, int arrayIndex)
{
Requires.NotNull(array, nameof(array));
Requires.Range(arrayIndex >= 0, nameof(arrayIndex));
Requires.Range(array.Length >= arrayIndex + this.Count, nameof(arrayIndex));
foreach (var item in this)
{
array[arrayIndex++] = item;
}
}
/// <summary>
/// See the <see cref="ICollection{T}"/> interface.
/// </summary>
internal void CopyTo(Array array, int arrayIndex)
{
Requires.NotNull(array, nameof(array));
Requires.Range(arrayIndex >= 0, nameof(arrayIndex));
Requires.Range(array.Length >= arrayIndex + this.Count, nameof(arrayIndex));
foreach (var item in this)
{
array.SetValue(item, arrayIndex++);
}
}
/// <summary>
/// Adds the specified key to the tree.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="comparer">The comparer.</param>
/// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param>
/// <returns>The new tree.</returns>
internal Node Add(T key, IComparer<T> comparer, out bool mutated)
{
Requires.NotNullAllowStructs(key, nameof(key));
Requires.NotNull(comparer, nameof(comparer));
if (this.IsEmpty)
{
mutated = true;
return new Node(key, this, this);
}
else
{
Node result = this;
int compareResult = comparer.Compare(key, _key);
if (compareResult > 0)
{
var newRight = _right.Add(key, comparer, out mutated);
if (mutated)
{
result = this.Mutate(right: newRight);
}
}
else if (compareResult < 0)
{
var newLeft = _left.Add(key, comparer, out mutated);
if (mutated)
{
result = this.Mutate(left: newLeft);
}
}
else
{
mutated = false;
return this;
}
return mutated ? MakeBalanced(result) : result;
}
}
/// <summary>
/// Removes the specified key from the tree.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="comparer">The comparer.</param>
/// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param>
/// <returns>The new tree.</returns>
internal Node Remove(T key, IComparer<T> comparer, out bool mutated)
{
Requires.NotNullAllowStructs(key, nameof(key));
Requires.NotNull(comparer, nameof(comparer));
if (this.IsEmpty)
{
mutated = false;
return this;
}
else
{
Node result = this;
int compare = comparer.Compare(key, _key);
if (compare == 0)
{
// We have a match.
mutated = true;
// If this is a leaf, just remove it
// by returning Empty. If we have only one child,
// replace the node with the child.
if (_right.IsEmpty && _left.IsEmpty)
{
result = EmptyNode;
}
else if (_right.IsEmpty && !_left.IsEmpty)
{
result = _left;
}
else if (!_right.IsEmpty && _left.IsEmpty)
{
result = _right;
}
else
{
// We have two children. Remove the next-highest node and replace
// this node with it.
var successor = _right;
while (!successor._left.IsEmpty)
{
successor = successor._left;
}
bool dummyMutated;
var newRight = _right.Remove(successor._key, comparer, out dummyMutated);
result = successor.Mutate(left: _left, right: newRight);
}
}
else if (compare < 0)
{
var newLeft = _left.Remove(key, comparer, out mutated);
if (mutated)
{
result = this.Mutate(left: newLeft);
}
}
else
{
var newRight = _right.Remove(key, comparer, out mutated);
if (mutated)
{
result = this.Mutate(right: newRight);
}
}
return result.IsEmpty ? result : MakeBalanced(result);
}
}
/// <summary>
/// Determines whether the specified key is in this tree.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="comparer">The comparer.</param>
/// <returns>
/// <c>true</c> if the tree contains the specified key; otherwise, <c>false</c>.
/// </returns>
[Pure]
internal bool Contains(T key, IComparer<T> comparer)
{
Requires.NotNullAllowStructs(key, nameof(key));
Requires.NotNull(comparer, nameof(comparer));
return !this.Search(key, comparer).IsEmpty;
}
/// <summary>
/// Freezes this node and all descendant nodes so that any mutations require a new instance of the nodes.
/// </summary>
internal void Freeze()
{
// If this node is frozen, all its descendants must already be frozen.
if (!_frozen)
{
_left.Freeze();
_right.Freeze();
_frozen = true;
}
}
/// <summary>
/// Searches for the specified key.
/// </summary>
/// <param name="key">The key to search for.</param>
/// <param name="comparer">The comparer.</param>
/// <returns>The matching node, or <see cref="EmptyNode"/> if no match was found.</returns>
[Pure]
internal Node Search(T key, IComparer<T> comparer)
{
Requires.NotNullAllowStructs(key, nameof(key));
Requires.NotNull(comparer, nameof(comparer));
if (this.IsEmpty)
{
return this;
}
else
{
int compare = comparer.Compare(key, _key);
if (compare == 0)
{
return this;
}
else if (compare > 0)
{
return _right.Search(key, comparer);
}
else
{
return _left.Search(key, comparer);
}
}
}
/// <summary>
/// Searches for the specified key.
/// </summary>
/// <param name="key">The key to search for.</param>
/// <param name="comparer">The comparer.</param>
/// <returns>The matching node, or <see cref="EmptyNode"/> if no match was found.</returns>
[Pure]
internal int IndexOf(T key, IComparer<T> comparer)
{
Requires.NotNullAllowStructs(key, nameof(key));
Requires.NotNull(comparer, nameof(comparer));
if (this.IsEmpty)
{
return -1;
}
else
{
int compare = comparer.Compare(key, _key);
if (compare == 0)
{
return _left.Count;
}
else if (compare > 0)
{
int result = _right.IndexOf(key, comparer);
bool missing = result < 0;
if (missing)
{
result = ~result;
}
result = _left.Count + 1 + result;
if (missing)
{
result = ~result;
}
return result;
}
else
{
return _left.IndexOf(key, comparer);
}
}
}
/// <summary>
/// Returns an <see cref="IEnumerable{T}"/> that iterates over this
/// collection in reverse order.
/// </summary>
/// <returns>
/// An enumerator that iterates over the <see cref="ImmutableSortedSet{T}"/>
/// in reverse order.
/// </returns>
[Pure]
internal IEnumerator<T> Reverse()
{
return new Enumerator(this, reverse: true);
}
#region Tree balancing methods
/// <summary>
/// AVL rotate left operation.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>The rotated tree.</returns>
private static Node RotateLeft(Node tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
Contract.Ensures(Contract.Result<Node>() != null);
if (tree._right.IsEmpty)
{
return tree;
}
var right = tree._right;
return right.Mutate(left: tree.Mutate(right: right._left));
}
/// <summary>
/// AVL rotate right operation.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>The rotated tree.</returns>
private static Node RotateRight(Node tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
Contract.Ensures(Contract.Result<Node>() != null);
if (tree._left.IsEmpty)
{
return tree;
}
var left = tree._left;
return left.Mutate(right: tree.Mutate(left: left._right));
}
/// <summary>
/// AVL rotate double-left operation.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>The rotated tree.</returns>
private static Node DoubleLeft(Node tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
Contract.Ensures(Contract.Result<Node>() != null);
if (tree._right.IsEmpty)
{
return tree;
}
Node rotatedRightChild = tree.Mutate(right: RotateRight(tree._right));
return RotateLeft(rotatedRightChild);
}
/// <summary>
/// AVL rotate double-right operation.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>The rotated tree.</returns>
private static Node DoubleRight(Node tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
Contract.Ensures(Contract.Result<Node>() != null);
if (tree._left.IsEmpty)
{
return tree;
}
Node rotatedLeftChild = tree.Mutate(left: RotateLeft(tree._left));
return RotateRight(rotatedLeftChild);
}
/// <summary>
/// Returns a value indicating whether the tree is in balance.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>0 if the tree is in balance, a positive integer if the right side is heavy, or a negative integer if the left side is heavy.</returns>
[Pure]
private static int Balance(Node tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
return tree._right._height - tree._left._height;
}
/// <summary>
/// Determines whether the specified tree is right heavy.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>
/// <c>true</c> if [is right heavy] [the specified tree]; otherwise, <c>false</c>.
/// </returns>
[Pure]
private static bool IsRightHeavy(Node tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
return Balance(tree) >= 2;
}
/// <summary>
/// Determines whether the specified tree is left heavy.
/// </summary>
[Pure]
private static bool IsLeftHeavy(Node tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
return Balance(tree) <= -2;
}
/// <summary>
/// Balances the specified tree.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>A balanced tree.</returns>
[Pure]
private static Node MakeBalanced(Node tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
Contract.Ensures(Contract.Result<Node>() != null);
if (IsRightHeavy(tree))
{
return Balance(tree._right) < 0 ? DoubleLeft(tree) : RotateLeft(tree);
}
if (IsLeftHeavy(tree))
{
return Balance(tree._left) > 0 ? DoubleRight(tree) : RotateRight(tree);
}
return tree;
}
#endregion
/// <summary>
/// Creates a node tree that contains the contents of a list.
/// </summary>
/// <param name="items">An indexable list with the contents that the new node tree should contain.</param>
/// <param name="start">The starting index within <paramref name="items"/> that should be captured by the node tree.</param>
/// <param name="length">The number of elements from <paramref name="items"/> that should be captured by the node tree.</param>
/// <returns>The root of the created node tree.</returns>
[Pure]
internal static Node NodeTreeFromList(IOrderedCollection<T> items, int start, int length)
{
Requires.NotNull(items, nameof(items));
Debug.Assert(start >= 0);
Debug.Assert(length >= 0);
if (length == 0)
{
return EmptyNode;
}
int rightCount = (length - 1) / 2;
int leftCount = (length - 1) - rightCount;
Node left = NodeTreeFromList(items, start, leftCount);
Node right = NodeTreeFromList(items, start + leftCount + 1, rightCount);
return new Node(items[start + leftCount], left, right, true);
}
/// <summary>
/// Creates a node mutation, either by mutating this node (if not yet frozen) or by creating a clone of this node
/// with the described changes.
/// </summary>
/// <param name="left">The left branch of the mutated node.</param>
/// <param name="right">The right branch of the mutated node.</param>
/// <returns>The mutated (or created) node.</returns>
private Node Mutate(Node left = null, Node right = null)
{
if (_frozen)
{
return new Node(_key, left ?? _left, right ?? _right);
}
else
{
if (left != null)
{
_left = left;
}
if (right != null)
{
_right = right;
}
_height = checked((byte)(1 + Math.Max(_left._height, _right._height)));
_count = 1 + _left._count + _right._count;
return this;
}
}
}
}
}
| |
using System;
using System.IO;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Date;
namespace Org.BouncyCastle.Bcpg.OpenPgp
{
/// <remarks>A PGP signature object.</remarks>
public class PgpSignature
{
public const int BinaryDocument = 0x00;
public const int CanonicalTextDocument = 0x01;
public const int StandAlone = 0x02;
public const int DefaultCertification = 0x10;
public const int NoCertification = 0x11;
public const int CasualCertification = 0x12;
public const int PositiveCertification = 0x13;
public const int SubkeyBinding = 0x18;
public const int PrimaryKeyBinding = 0x19;
public const int DirectKey = 0x1f;
public const int KeyRevocation = 0x20;
public const int SubkeyRevocation = 0x28;
public const int CertificationRevocation = 0x30;
public const int Timestamp = 0x40;
private readonly SignaturePacket sigPck;
private readonly int signatureType;
private readonly TrustPacket trustPck;
private ISigner sig;
private byte lastb; // Initial value anything but '\r'
internal PgpSignature(
BcpgInputStream bcpgInput)
: this((SignaturePacket)bcpgInput.ReadPacket())
{
}
internal PgpSignature(
SignaturePacket sigPacket)
: this(sigPacket, null)
{
}
internal PgpSignature(
SignaturePacket sigPacket,
TrustPacket trustPacket)
{
if (sigPacket == null)
throw new ArgumentNullException("sigPacket");
this.sigPck = sigPacket;
this.signatureType = sigPck.SignatureType;
this.trustPck = trustPacket;
}
private void GetSig()
{
this.sig = SignerUtilities.GetSigner(
PgpUtilities.GetSignatureName(sigPck.KeyAlgorithm, sigPck.HashAlgorithm));
}
/// <summary>The OpenPGP version number for this signature.</summary>
public int Version
{
get { return sigPck.Version; }
}
/// <summary>The key algorithm associated with this signature.</summary>
public PublicKeyAlgorithmTag KeyAlgorithm
{
get { return sigPck.KeyAlgorithm; }
}
/// <summary>The hash algorithm associated with this signature.</summary>
public HashAlgorithmTag HashAlgorithm
{
get { return sigPck.HashAlgorithm; }
}
public void InitVerify(
PgpPublicKey pubKey)
{
lastb = 0;
if (sig == null)
{
GetSig();
}
try
{
sig.Init(false, pubKey.GetKey());
}
catch (InvalidKeyException e)
{
throw new PgpException("invalid key.", e);
}
}
public void Update(
byte b)
{
if (signatureType == CanonicalTextDocument)
{
doCanonicalUpdateByte(b);
}
else
{
sig.Update(b);
}
}
private void doCanonicalUpdateByte(
byte b)
{
if (b == '\r')
{
doUpdateCRLF();
}
else if (b == '\n')
{
if (lastb != '\r')
{
doUpdateCRLF();
}
}
else
{
sig.Update(b);
}
lastb = b;
}
private void doUpdateCRLF()
{
sig.Update((byte)'\r');
sig.Update((byte)'\n');
}
public void Update(
params byte[] bytes)
{
Update(bytes, 0, bytes.Length);
}
public void Update(
byte[] bytes,
int off,
int length)
{
if (signatureType == CanonicalTextDocument)
{
int finish = off + length;
for (int i = off; i != finish; i++)
{
doCanonicalUpdateByte(bytes[i]);
}
}
else
{
sig.BlockUpdate(bytes, off, length);
}
}
public bool Verify()
{
byte[] trailer = GetSignatureTrailer();
sig.BlockUpdate(trailer, 0, trailer.Length);
return sig.VerifySignature(GetSignature());
}
private void UpdateWithIdData(
int header,
byte[] idBytes)
{
this.Update(
(byte) header,
(byte)(idBytes.Length >> 24),
(byte)(idBytes.Length >> 16),
(byte)(idBytes.Length >> 8),
(byte)(idBytes.Length));
this.Update(idBytes);
}
private void UpdateWithPublicKey(
PgpPublicKey key)
{
byte[] keyBytes = GetEncodedPublicKey(key);
this.Update(
(byte) 0x99,
(byte)(keyBytes.Length >> 8),
(byte)(keyBytes.Length));
this.Update(keyBytes);
}
/// <summary>
/// Verify the signature as certifying the passed in public key as associated
/// with the passed in user attributes.
/// </summary>
/// <param name="userAttributes">User attributes the key was stored under.</param>
/// <param name="key">The key to be verified.</param>
/// <returns>True, if the signature matches, false otherwise.</returns>
public bool VerifyCertification(
PgpUserAttributeSubpacketVector userAttributes,
PgpPublicKey key)
{
UpdateWithPublicKey(key);
//
// hash in the userAttributes
//
try
{
MemoryStream bOut = new MemoryStream();
foreach (UserAttributeSubpacket packet in userAttributes.ToSubpacketArray())
{
packet.Encode(bOut);
}
UpdateWithIdData(0xd1, bOut.ToArray());
}
catch (IOException e)
{
throw new PgpException("cannot encode subpacket array", e);
}
this.Update(sigPck.GetSignatureTrailer());
return sig.VerifySignature(this.GetSignature());
}
/// <summary>
/// Verify the signature as certifying the passed in public key as associated
/// with the passed in ID.
/// </summary>
/// <param name="id">ID the key was stored under.</param>
/// <param name="key">The key to be verified.</param>
/// <returns>True, if the signature matches, false otherwise.</returns>
public bool VerifyCertification(
string id,
PgpPublicKey key)
{
UpdateWithPublicKey(key);
//
// hash in the id
//
UpdateWithIdData(0xb4, Strings.ToByteArray(id));
Update(sigPck.GetSignatureTrailer());
return sig.VerifySignature(GetSignature());
}
/// <summary>Verify a certification for the passed in key against the passed in master key.</summary>
/// <param name="masterKey">The key we are verifying against.</param>
/// <param name="pubKey">The key we are verifying.</param>
/// <returns>True, if the certification is valid, false otherwise.</returns>
public bool VerifyCertification(
PgpPublicKey masterKey,
PgpPublicKey pubKey)
{
UpdateWithPublicKey(masterKey);
UpdateWithPublicKey(pubKey);
Update(sigPck.GetSignatureTrailer());
return sig.VerifySignature(GetSignature());
}
/// <summary>Verify a key certification, such as revocation, for the passed in key.</summary>
/// <param name="pubKey">The key we are checking.</param>
/// <returns>True, if the certification is valid, false otherwise.</returns>
public bool VerifyCertification(
PgpPublicKey pubKey)
{
if (SignatureType != KeyRevocation
&& SignatureType != SubkeyRevocation)
{
throw new InvalidOperationException("signature is not a key signature");
}
UpdateWithPublicKey(pubKey);
Update(sigPck.GetSignatureTrailer());
return sig.VerifySignature(GetSignature());
}
public int SignatureType
{
get { return sigPck.SignatureType; }
}
/// <summary>The ID of the key that created the signature.</summary>
public long KeyId
{
get { return sigPck.KeyId; }
}
[Obsolete("Use 'CreationTime' property instead")]
public DateTime GetCreationTime()
{
return CreationTime;
}
/// <summary>The creation time of this signature.</summary>
public DateTime CreationTime
{
get { return DateTimeUtilities.UnixMsToDateTime(sigPck.CreationTime); }
}
public byte[] GetSignatureTrailer()
{
return sigPck.GetSignatureTrailer();
}
/// <summary>
/// Return true if the signature has either hashed or unhashed subpackets.
/// </summary>
public bool HasSubpackets
{
get
{
return sigPck.GetHashedSubPackets() != null
|| sigPck.GetUnhashedSubPackets() != null;
}
}
public PgpSignatureSubpacketVector GetHashedSubPackets()
{
return createSubpacketVector(sigPck.GetHashedSubPackets());
}
public PgpSignatureSubpacketVector GetUnhashedSubPackets()
{
return createSubpacketVector(sigPck.GetUnhashedSubPackets());
}
private PgpSignatureSubpacketVector createSubpacketVector(SignatureSubpacket[] pcks)
{
return pcks == null ? null : new PgpSignatureSubpacketVector(pcks);
}
public byte[] GetSignature()
{
MPInteger[] sigValues = sigPck.GetSignature();
byte[] signature;
if (sigValues != null)
{
if (sigValues.Length == 1) // an RSA signature
{
signature = sigValues[0].Value.ToByteArrayUnsigned();
}
else
{
try
{
signature = new DerSequence(
new DerInteger(sigValues[0].Value),
new DerInteger(sigValues[1].Value)).GetEncoded();
}
catch (IOException e)
{
throw new PgpException("exception encoding DSA sig.", e);
}
}
}
else
{
signature = sigPck.GetSignatureBytes();
}
return signature;
}
// TODO Handle the encoding stuff by subclassing BcpgObject?
public byte[] GetEncoded()
{
MemoryStream bOut = new MemoryStream();
Encode(bOut);
return bOut.ToArray();
}
public void Encode(
Stream outStream)
{
BcpgOutputStream bcpgOut = BcpgOutputStream.Wrap(outStream);
bcpgOut.WritePacket(sigPck);
if (trustPck != null)
{
bcpgOut.WritePacket(trustPck);
}
}
private byte[] GetEncodedPublicKey(
PgpPublicKey pubKey)
{
try
{
return pubKey.publicPk.GetEncodedContents();
}
catch (IOException e)
{
throw new PgpException("exception preparing key.", e);
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.