context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
#region License
// Copyright (c) 2010-2019, Mark Final
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of BuildAMation nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion // License
using System.Linq;
namespace XcodeBuilder
{
/// <summary>
/// Support classes for Xcode projet generation
/// </summary>
static partial class Support
{
private static void
AddModuleDirectoryCreationShellCommands(
Bam.Core.Module module,
Bam.Core.StringArray shellCommandLines)
{
foreach (var dir in module.OutputDirectories)
{
var escapedDir = Bam.Core.IOWrapper.EscapeSpacesInPath(dir.ToString());
shellCommandLines.Add($"[[ ! -d {escapedDir} ]] && mkdir -p {escapedDir}");
}
}
private static void
AddNewerThanPreamble(
Bam.Core.Module module,
Bam.Core.StringArray shellCommandLines)
{
if (!module.GeneratedPaths.Any())
{
return;
}
var condition_text = new System.Text.StringBuilder();
condition_text.Append("if [[ ");
var last_output = module.GeneratedPaths.Values.Last();
foreach (var output in module.GeneratedPaths.Values)
{
var output_path = Bam.Core.IOWrapper.EscapeSpacesInPath(output.ToString());
condition_text.Append($"! -e {output_path} ");
foreach (var (inputModule, inputPathKey) in module.InputModulePaths)
{
if (!inputModule.GeneratedPaths.Any())
{
continue;
}
var input_path = Bam.Core.IOWrapper.EscapeSpacesInPath(inputModule.GeneratedPaths[inputPathKey].ToString());
condition_text.Append($"|| {input_path} -nt {output_path} ");
}
if (output != last_output)
{
condition_text.Append("|| ");
}
}
condition_text.AppendLine("]]");
shellCommandLines.Add(condition_text.ToString());
shellCommandLines.Add("then");
}
private static void
AddNewerThanPostamble(
Bam.Core.Module module,
Bam.Core.StringArray shellCommandLines)
{
if (!module.GeneratedPaths.Any())
{
return;
}
shellCommandLines.Add("fi");
}
private static void
AddRedirectToFile(
Bam.Core.TokenizedString outputFile,
Bam.Core.StringArray shellCommandLines)
{
var command = shellCommandLines.Last();
shellCommandLines.Remove(command);
var redirectedCommand = command + $" > {outputFile.ToString()}";
shellCommandLines.Add(redirectedCommand);
}
static private void
AddModuleCommandLineShellCommand(
Bam.Core.Module module,
Bam.Core.StringArray shellCommandLines,
bool allowNonZeroSuccessfulExitCodes)
{
if (null == module.Tool)
{
throw new Bam.Core.Exception(
$"Command line tool passed with module '{module.ToString()}' is invalid"
);
}
System.Diagnostics.Debug.Assert(module.Tool is Bam.Core.ICommandLineTool);
var args = new Bam.Core.StringArray();
if (module.WorkingDirectory != null)
{
args.Add(
$"cd {module.WorkingDirectory.ToStringQuoteIfNecessary()} &&"
);
}
var tool = module.Tool as Bam.Core.ICommandLineTool;
args.Add(CommandLineProcessor.Processor.StringifyTool(tool));
args.AddRange(
CommandLineProcessor.NativeConversion.Convert(
module.Settings,
module
)
);
args.Add(CommandLineProcessor.Processor.TerminatingArgs(tool));
if (allowNonZeroSuccessfulExitCodes)
{
args.Add("|| true");
}
shellCommandLines.Add(args.ToString(' '));
}
private static void
GetTargetAndConfiguration(
Bam.Core.Module module,
out Target target,
out Configuration configuration)
{
var encapsulating = module.EncapsulatingModule;
#if D_PACKAGE_PUBLISHER
if (encapsulating is Publisher.Collation asCollation)
{
asCollation.ForEachAnchor(
(collation, anchor, customData) =>
{
encapsulating = anchor.SourceModule;
},
null
);
}
#endif
var workspace = Bam.Core.Graph.Instance.MetaData as XcodeBuilder.WorkspaceMeta;
target = workspace.EnsureTargetExists(encapsulating);
configuration = target.GetConfiguration(encapsulating);
}
/// <summary>
/// Add pre build commands to the target.
/// </summary>
/// <param name="module">Module associated with</param>
/// <param name="target">Target to add the commands to</param>
/// <param name="configuration">Configuration within the Target</param>
/// <param name="commandLine">Command line to add</param>
/// <param name="outputPaths">Any output paths to add.</param>
public static void
AddPreBuildCommands(
Bam.Core.Module module,
Target target,
Configuration configuration,
string commandLine,
Bam.Core.TokenizedStringArray outputPaths = null)
{
var shellCommandLines = new Bam.Core.StringArray();
AddModuleDirectoryCreationShellCommands(module, shellCommandLines);
AddNewerThanPreamble(module, shellCommandLines);
shellCommandLines.Add($"\techo {commandLine}");
shellCommandLines.Add($"\t{commandLine}");
AddNewerThanPostamble(module, shellCommandLines);
target.AddPreBuildCommands(
shellCommandLines,
configuration,
outputPaths
);
}
/// <summary>
/// Add a pre build step corresponding to a command line tool.
/// </summary>
/// <param name="module">Module associated with</param>
/// <param name="target">Target written to</param>
/// <param name="configuration">Configuration written to</param>
/// <param name="checkForNewer">Perform a newer check on files</param>
/// <param name="allowNonZeroSuccessfulExitCodes">Allow a non-zero exit code to be successful</param>
/// <param name="addOrderOnlyDependencyOnTool">Adding an order only dependency</param>
/// <param name="outputPaths">Add output paths</param>
/// <param name="redirectToFile">Redirect to a file</param>
public static void
AddPreBuildStepForCommandLineTool(
Bam.Core.Module module,
out Target target,
out Configuration configuration,
bool checkForNewer,
bool allowNonZeroSuccessfulExitCodes,
bool addOrderOnlyDependencyOnTool = false,
Bam.Core.TokenizedStringArray outputPaths = null,
Bam.Core.TokenizedString redirectToFile = null)
{
GetTargetAndConfiguration(
module,
out target,
out configuration
);
var shellCommandLines = new Bam.Core.StringArray();
AddModuleDirectoryCreationShellCommands(module, shellCommandLines);
if (checkForNewer)
{
AddNewerThanPreamble(module, shellCommandLines);
}
AddModuleCommandLineShellCommand(
module,
shellCommandLines,
allowNonZeroSuccessfulExitCodes
);
if (null != redirectToFile)
{
AddRedirectToFile(redirectToFile, shellCommandLines);
}
if (checkForNewer)
{
AddNewerThanPostamble(module, shellCommandLines);
}
target.AddPreBuildCommands(
shellCommandLines,
configuration,
outputPaths
);
if (addOrderOnlyDependencyOnTool)
{
var tool = module.Tool;
#if D_PACKAGE_PUBLISHER
// note the custom handler here, which checks to see if we're running a tool
// that has been collated
if (tool is Publisher.CollatedCommandLineTool)
{
tool = (tool as Publisher.ICollatedObject).SourceModule;
}
#endif
if (tool.MetaData is Target toolTarget)
{
target.Requires(toolTarget);
}
}
}
/// <summary>
/// Add a prebuild step for command line tool.
/// </summary>
/// <param name="module">Module associated with</param>
/// <param name="target">Target written to</param>
/// <param name="configuration">Configuration written to</param>
/// <param name="inputFileType">The file type of the input</param>
/// <param name="checkForNewer">Is there a check for a newer file?</param>
/// <param name="allowNonZeroSuccessfulExitCodes">Allow non-zero exit codes to be successful</param>
/// <param name="addOrderOnlyDependencyOnTool">Add an order only dependency</param>
/// <param name="outputPaths">Add output paths</param>
public static void
AddPreBuildStepForCommandLineTool(
Bam.Core.Module module,
out Target target,
out Configuration configuration,
FileReference.EFileType inputFileType,
bool checkForNewer,
bool allowNonZeroSuccessfulExitCodes,
bool addOrderOnlyDependencyOnTool = false,
Bam.Core.TokenizedStringArray outputPaths = null)
{
AddPreBuildStepForCommandLineTool(
module,
out target,
out configuration,
checkForNewer,
allowNonZeroSuccessfulExitCodes,
addOrderOnlyDependencyOnTool: addOrderOnlyDependencyOnTool,
outputPaths: outputPaths
);
foreach (var (inputModule,inputPathKey) in module.InputModulePaths)
{
target.EnsureFileOfTypeExists(
inputModule.GeneratedPaths[inputPathKey],
inputFileType
);
}
}
/// <summary>
/// Add post build commands
/// </summary>
/// <param name="module">Module associated with</param>
/// <param name="target">Target added to</param>
/// <param name="configuration">Configuration added to</param>
/// <param name="customCommands">Custom command lines</param>
public static void
AddPostBuildCommands(
Bam.Core.Module module,
Target target,
Configuration configuration,
Bam.Core.StringArray customCommands)
{
var shellCommandLines = new Bam.Core.StringArray();
AddModuleDirectoryCreationShellCommands(module, shellCommandLines);
shellCommandLines.AddRange(customCommands);
target.AddPostBuildCommands(
shellCommandLines,
configuration
);
}
/// <summary>
/// Add a post build step for a command line tool
/// </summary>
/// <param name="module">Module associated with</param>
/// <param name="moduleToAddBuildStepTo">Module to add the build step to</param>
/// <param name="target">Target written to</param>
/// <param name="configuration">Configuration written to</param>
/// <param name="redirectToFile">Is the output redirected to file?</param>
public static void
AddPostBuildStepForCommandLineTool(
Bam.Core.Module module,
Bam.Core.Module moduleToAddBuildStepTo,
out Target target,
out Configuration configuration,
Bam.Core.TokenizedString redirectToFile = null)
{
GetTargetAndConfiguration(
moduleToAddBuildStepTo,
out target,
out configuration
);
var shellCommandLines = new Bam.Core.StringArray();
AddModuleDirectoryCreationShellCommands(module, shellCommandLines);
AddNewerThanPreamble(module, shellCommandLines);
AddModuleCommandLineShellCommand(
module,
shellCommandLines,
false
);
if (null != redirectToFile)
{
AddRedirectToFile(redirectToFile, shellCommandLines);
}
AddNewerThanPostamble(module, shellCommandLines);
target.AddPostBuildCommands(
shellCommandLines,
configuration
);
}
}
}
| |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace DocuSign.eSign.Model
{
/// <summary>
///
/// </summary>
[DataContract]
public class Zip : IEquatable<Zip>
{
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="useDash4", EmitDefaultValue=false)]
public string UseDash4 { get; set; }
/// <summary>
/// A regular expressionn used to validate input for the tab.
/// </summary>
/// <value>A regular expressionn used to validate input for the tab.</value>
[DataMember(Name="validationPattern", EmitDefaultValue=false)]
public string ValidationPattern { get; set; }
/// <summary>
/// The message displayed if the custom tab fails input validation (either custom of embedded).
/// </summary>
/// <value>The message displayed if the custom tab fails input validation (either custom of embedded).</value>
[DataMember(Name="validationMessage", EmitDefaultValue=false)]
public string ValidationMessage { get; set; }
/// <summary>
/// When set to **true**, this custom tab is shared.
/// </summary>
/// <value>When set to **true**, this custom tab is shared.</value>
[DataMember(Name="shared", EmitDefaultValue=false)]
public string Shared { get; set; }
/// <summary>
/// Optional element for field markup. When set to **true**, the signer is required to initial when they modify a shared field.
/// </summary>
/// <value>Optional element for field markup. When set to **true**, the signer is required to initial when they modify a shared field.</value>
[DataMember(Name="requireInitialOnSharedChange", EmitDefaultValue=false)]
public string RequireInitialOnSharedChange { get; set; }
/// <summary>
/// When set to **true**, the sender must populate the tab before an envelope can be sent using the template. \n\nThis value tab can only be changed by modifying (PUT) the template. \n\nTabs with a `senderRequired` value of true cannot be deleted from an envelope.
/// </summary>
/// <value>When set to **true**, the sender must populate the tab before an envelope can be sent using the template. \n\nThis value tab can only be changed by modifying (PUT) the template. \n\nTabs with a `senderRequired` value of true cannot be deleted from an envelope.</value>
[DataMember(Name="senderRequired", EmitDefaultValue=false)]
public string SenderRequired { get; set; }
/// <summary>
/// When set to **true** and shared is true, information must be entered in this field to complete the envelope.
/// </summary>
/// <value>When set to **true** and shared is true, information must be entered in this field to complete the envelope.</value>
[DataMember(Name="requireAll", EmitDefaultValue=false)]
public string RequireAll { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
/// <summary>
/// Specifies the value of the tab.
/// </summary>
/// <value>Specifies the value of the tab.</value>
[DataMember(Name="value", EmitDefaultValue=false)]
public string Value { get; set; }
/// <summary>
/// The initial value of the tab when it was sent to the recipient.
/// </summary>
/// <value>The initial value of the tab when it was sent to the recipient.</value>
[DataMember(Name="originalValue", EmitDefaultValue=false)]
public string OriginalValue { get; set; }
/// <summary>
/// Width of the tab in pixels.
/// </summary>
/// <value>Width of the tab in pixels.</value>
[DataMember(Name="width", EmitDefaultValue=false)]
public int? Width { get; set; }
/// <summary>
/// When set to **true**, the signer is required to fill out this tab
/// </summary>
/// <value>When set to **true**, the signer is required to fill out this tab</value>
[DataMember(Name="required", EmitDefaultValue=false)]
public string Required { get; set; }
/// <summary>
/// When set to **true**, the signer cannot change the data of the custom tab.
/// </summary>
/// <value>When set to **true**, the signer cannot change the data of the custom tab.</value>
[DataMember(Name="locked", EmitDefaultValue=false)]
public string Locked { get; set; }
/// <summary>
/// When set to **true**, the field appears normally while the recipient is adding or modifying the information in the field, but the data is not visible (the characters are hidden by asterisks) to any other signer or the sender.\n\nWhen an envelope is completed the information is available to the sender through the Form Data link in the DocuSign Console.\n\nThis setting applies only to text boxes and does not affect list boxes, radio buttons, or check boxes.
/// </summary>
/// <value>When set to **true**, the field appears normally while the recipient is adding or modifying the information in the field, but the data is not visible (the characters are hidden by asterisks) to any other signer or the sender.\n\nWhen an envelope is completed the information is available to the sender through the Form Data link in the DocuSign Console.\n\nThis setting applies only to text boxes and does not affect list boxes, radio buttons, or check boxes.</value>
[DataMember(Name="concealValueOnDocument", EmitDefaultValue=false)]
public string ConcealValueOnDocument { get; set; }
/// <summary>
/// When set to **true**, disables the auto sizing of single line text boxes in the signing screen when the signer enters data. If disabled users will only be able enter as much data as the text box can hold. By default this is false. This property only affects single line text boxes.
/// </summary>
/// <value>When set to **true**, disables the auto sizing of single line text boxes in the signing screen when the signer enters data. If disabled users will only be able enter as much data as the text box can hold. By default this is false. This property only affects single line text boxes.</value>
[DataMember(Name="disableAutoSize", EmitDefaultValue=false)]
public string DisableAutoSize { get; set; }
/// <summary>
/// An optional value that describes the maximum length of the property when the property is a string.
/// </summary>
/// <value>An optional value that describes the maximum length of the property when the property is a string.</value>
[DataMember(Name="maxLength", EmitDefaultValue=false)]
public int? MaxLength { get; set; }
/// <summary>
/// The label string associated with the tab.
/// </summary>
/// <value>The label string associated with the tab.</value>
[DataMember(Name="tabLabel", EmitDefaultValue=false)]
public string TabLabel { get; set; }
/// <summary>
/// The font to be used for the tab value. Supported Fonts: Arial, Arial, ArialNarrow, Calibri, CourierNew, Garamond, Georgia, Helvetica, LucidaConsole, Tahoma, TimesNewRoman, Trebuchet, Verdana, MSGothic, MSMincho, Default.
/// </summary>
/// <value>The font to be used for the tab value. Supported Fonts: Arial, Arial, ArialNarrow, Calibri, CourierNew, Garamond, Georgia, Helvetica, LucidaConsole, Tahoma, TimesNewRoman, Trebuchet, Verdana, MSGothic, MSMincho, Default.</value>
[DataMember(Name="font", EmitDefaultValue=false)]
public string Font { get; set; }
/// <summary>
/// When set to **true**, the information in the tab is bold.
/// </summary>
/// <value>When set to **true**, the information in the tab is bold.</value>
[DataMember(Name="bold", EmitDefaultValue=false)]
public string Bold { get; set; }
/// <summary>
/// When set to **true**, the information in the tab is italic.
/// </summary>
/// <value>When set to **true**, the information in the tab is italic.</value>
[DataMember(Name="italic", EmitDefaultValue=false)]
public string Italic { get; set; }
/// <summary>
/// When set to **true**, the information in the tab is underlined.
/// </summary>
/// <value>When set to **true**, the information in the tab is underlined.</value>
[DataMember(Name="underline", EmitDefaultValue=false)]
public string Underline { get; set; }
/// <summary>
/// The font color used for the information in the tab.\n\nPossible values are: Black, BrightBlue, BrightRed, DarkGreen, DarkRed, Gold, Green, NavyBlue, Purple, or White.
/// </summary>
/// <value>The font color used for the information in the tab.\n\nPossible values are: Black, BrightBlue, BrightRed, DarkGreen, DarkRed, Gold, Green, NavyBlue, Purple, or White.</value>
[DataMember(Name="fontColor", EmitDefaultValue=false)]
public string FontColor { get; set; }
/// <summary>
/// The font size used for the information in the tab.\n\nPossible values are: Size7, Size8, Size9, Size10, Size11, Size12, Size14, Size16, Size18, Size20, Size22, Size24, Size26, Size28, Size36, Size48, or Size72.
/// </summary>
/// <value>The font size used for the information in the tab.\n\nPossible values are: Size7, Size8, Size9, Size10, Size11, Size12, Size14, Size16, Size18, Size20, Size22, Size24, Size26, Size28, Size36, Size48, or Size72.</value>
[DataMember(Name="fontSize", EmitDefaultValue=false)]
public string FontSize { get; set; }
/// <summary>
/// Specifies the document ID number that the tab is placed on. This must refer to an existing Document's ID attribute.
/// </summary>
/// <value>Specifies the document ID number that the tab is placed on. This must refer to an existing Document's ID attribute.</value>
[DataMember(Name="documentId", EmitDefaultValue=false)]
public string DocumentId { get; set; }
/// <summary>
/// Unique for the recipient. It is used by the tab element to indicate which recipient is to sign the Document.
/// </summary>
/// <value>Unique for the recipient. It is used by the tab element to indicate which recipient is to sign the Document.</value>
[DataMember(Name="recipientId", EmitDefaultValue=false)]
public string RecipientId { get; set; }
/// <summary>
/// Specifies the page number on which the tab is located.
/// </summary>
/// <value>Specifies the page number on which the tab is located.</value>
[DataMember(Name="pageNumber", EmitDefaultValue=false)]
public string PageNumber { get; set; }
/// <summary>
/// This indicates the horizontal offset of the object on the page. DocuSign uses 72 DPI when determining position.
/// </summary>
/// <value>This indicates the horizontal offset of the object on the page. DocuSign uses 72 DPI when determining position.</value>
[DataMember(Name="xPosition", EmitDefaultValue=false)]
public string XPosition { get; set; }
/// <summary>
/// This indicates the vertical offset of the object on the page. DocuSign uses 72 DPI when determining position.
/// </summary>
/// <value>This indicates the vertical offset of the object on the page. DocuSign uses 72 DPI when determining position.</value>
[DataMember(Name="yPosition", EmitDefaultValue=false)]
public string YPosition { get; set; }
/// <summary>
/// Anchor text information for a radio button.
/// </summary>
/// <value>Anchor text information for a radio button.</value>
[DataMember(Name="anchorString", EmitDefaultValue=false)]
public string AnchorString { get; set; }
/// <summary>
/// Specifies the X axis location of the tab, in achorUnits, relative to the anchorString.
/// </summary>
/// <value>Specifies the X axis location of the tab, in achorUnits, relative to the anchorString.</value>
[DataMember(Name="anchorXOffset", EmitDefaultValue=false)]
public string AnchorXOffset { get; set; }
/// <summary>
/// Specifies the Y axis location of the tab, in achorUnits, relative to the anchorString.
/// </summary>
/// <value>Specifies the Y axis location of the tab, in achorUnits, relative to the anchorString.</value>
[DataMember(Name="anchorYOffset", EmitDefaultValue=false)]
public string AnchorYOffset { get; set; }
/// <summary>
/// Specifies units of the X and Y offset. Units could be pixels, millimeters, centimeters, or inches.
/// </summary>
/// <value>Specifies units of the X and Y offset. Units could be pixels, millimeters, centimeters, or inches.</value>
[DataMember(Name="anchorUnits", EmitDefaultValue=false)]
public string AnchorUnits { get; set; }
/// <summary>
/// When set to **true**, this tab is ignored if anchorString is not found in the document.
/// </summary>
/// <value>When set to **true**, this tab is ignored if anchorString is not found in the document.</value>
[DataMember(Name="anchorIgnoreIfNotPresent", EmitDefaultValue=false)]
public string AnchorIgnoreIfNotPresent { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="anchorCaseSensitive", EmitDefaultValue=false)]
public string AnchorCaseSensitive { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="anchorMatchWholeWord", EmitDefaultValue=false)]
public string AnchorMatchWholeWord { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="anchorHorizontalAlignment", EmitDefaultValue=false)]
public string AnchorHorizontalAlignment { get; set; }
/// <summary>
/// The unique identifier for the tab. The tabid can be retrieved with the [ML:GET call].
/// </summary>
/// <value>The unique identifier for the tab. The tabid can be retrieved with the [ML:GET call].</value>
[DataMember(Name="tabId", EmitDefaultValue=false)]
public string TabId { get; set; }
/// <summary>
/// When set to **true**, the sender cannot change any attributes of the recipient. Used only when working with template recipients.
/// </summary>
/// <value>When set to **true**, the sender cannot change any attributes of the recipient. Used only when working with template recipients.</value>
[DataMember(Name="templateLocked", EmitDefaultValue=false)]
public string TemplateLocked { get; set; }
/// <summary>
/// When set to **true**, the sender may not remove the recipient. Used only when working with template recipients.
/// </summary>
/// <value>When set to **true**, the sender may not remove the recipient. Used only when working with template recipients.</value>
[DataMember(Name="templateRequired", EmitDefaultValue=false)]
public string TemplateRequired { get; set; }
/// <summary>
/// For conditional fields this is the TabLabel of the parent tab that controls this tab's visibility.
/// </summary>
/// <value>For conditional fields this is the TabLabel of the parent tab that controls this tab's visibility.</value>
[DataMember(Name="conditionalParentLabel", EmitDefaultValue=false)]
public string ConditionalParentLabel { get; set; }
/// <summary>
/// For conditional fields, this is the value of the parent tab that controls the tab's visibility.\n\nIf the parent tab is a Checkbox, Radio button, Optional Signature, or Optional Initial use \"on\" as the value to show that the parent tab is active.
/// </summary>
/// <value>For conditional fields, this is the value of the parent tab that controls the tab's visibility.\n\nIf the parent tab is a Checkbox, Radio button, Optional Signature, or Optional Initial use \"on\" as the value to show that the parent tab is active.</value>
[DataMember(Name="conditionalParentValue", EmitDefaultValue=false)]
public string ConditionalParentValue { get; set; }
/// <summary>
/// The DocuSign generated custom tab ID for the custom tab to be applied. This can only be used when adding new tabs for a recipient. When used, the new tab inherits all the custom tab properties.
/// </summary>
/// <value>The DocuSign generated custom tab ID for the custom tab to be applied. This can only be used when adding new tabs for a recipient. When used, the new tab inherits all the custom tab properties.</value>
[DataMember(Name="customTabId", EmitDefaultValue=false)]
public string CustomTabId { get; set; }
/// <summary>
/// Gets or Sets MergeField
/// </summary>
[DataMember(Name="mergeField", EmitDefaultValue=false)]
public MergeField MergeField { get; set; }
/// <summary>
/// Indicates the envelope status. Valid values are:\n\n* sent - The envelope is sent to the recipients. \n* created - The envelope is saved as a draft and can be modified and sent later.
/// </summary>
/// <value>Indicates the envelope status. Valid values are:\n\n* sent - The envelope is sent to the recipients. \n* created - The envelope is saved as a draft and can be modified and sent later.</value>
[DataMember(Name="status", EmitDefaultValue=false)]
public string Status { get; set; }
/// <summary>
/// Gets or Sets ErrorDetails
/// </summary>
[DataMember(Name="errorDetails", EmitDefaultValue=false)]
public ErrorDetails ErrorDetails { 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 Zip {\n");
sb.Append(" UseDash4: ").Append(UseDash4).Append("\n");
sb.Append(" ValidationPattern: ").Append(ValidationPattern).Append("\n");
sb.Append(" ValidationMessage: ").Append(ValidationMessage).Append("\n");
sb.Append(" Shared: ").Append(Shared).Append("\n");
sb.Append(" RequireInitialOnSharedChange: ").Append(RequireInitialOnSharedChange).Append("\n");
sb.Append(" SenderRequired: ").Append(SenderRequired).Append("\n");
sb.Append(" RequireAll: ").Append(RequireAll).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" Value: ").Append(Value).Append("\n");
sb.Append(" OriginalValue: ").Append(OriginalValue).Append("\n");
sb.Append(" Width: ").Append(Width).Append("\n");
sb.Append(" Required: ").Append(Required).Append("\n");
sb.Append(" Locked: ").Append(Locked).Append("\n");
sb.Append(" ConcealValueOnDocument: ").Append(ConcealValueOnDocument).Append("\n");
sb.Append(" DisableAutoSize: ").Append(DisableAutoSize).Append("\n");
sb.Append(" MaxLength: ").Append(MaxLength).Append("\n");
sb.Append(" TabLabel: ").Append(TabLabel).Append("\n");
sb.Append(" Font: ").Append(Font).Append("\n");
sb.Append(" Bold: ").Append(Bold).Append("\n");
sb.Append(" Italic: ").Append(Italic).Append("\n");
sb.Append(" Underline: ").Append(Underline).Append("\n");
sb.Append(" FontColor: ").Append(FontColor).Append("\n");
sb.Append(" FontSize: ").Append(FontSize).Append("\n");
sb.Append(" DocumentId: ").Append(DocumentId).Append("\n");
sb.Append(" RecipientId: ").Append(RecipientId).Append("\n");
sb.Append(" PageNumber: ").Append(PageNumber).Append("\n");
sb.Append(" XPosition: ").Append(XPosition).Append("\n");
sb.Append(" YPosition: ").Append(YPosition).Append("\n");
sb.Append(" AnchorString: ").Append(AnchorString).Append("\n");
sb.Append(" AnchorXOffset: ").Append(AnchorXOffset).Append("\n");
sb.Append(" AnchorYOffset: ").Append(AnchorYOffset).Append("\n");
sb.Append(" AnchorUnits: ").Append(AnchorUnits).Append("\n");
sb.Append(" AnchorIgnoreIfNotPresent: ").Append(AnchorIgnoreIfNotPresent).Append("\n");
sb.Append(" AnchorCaseSensitive: ").Append(AnchorCaseSensitive).Append("\n");
sb.Append(" AnchorMatchWholeWord: ").Append(AnchorMatchWholeWord).Append("\n");
sb.Append(" AnchorHorizontalAlignment: ").Append(AnchorHorizontalAlignment).Append("\n");
sb.Append(" TabId: ").Append(TabId).Append("\n");
sb.Append(" TemplateLocked: ").Append(TemplateLocked).Append("\n");
sb.Append(" TemplateRequired: ").Append(TemplateRequired).Append("\n");
sb.Append(" ConditionalParentLabel: ").Append(ConditionalParentLabel).Append("\n");
sb.Append(" ConditionalParentValue: ").Append(ConditionalParentValue).Append("\n");
sb.Append(" CustomTabId: ").Append(CustomTabId).Append("\n");
sb.Append(" MergeField: ").Append(MergeField).Append("\n");
sb.Append(" Status: ").Append(Status).Append("\n");
sb.Append(" ErrorDetails: ").Append(ErrorDetails).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as Zip);
}
/// <summary>
/// Returns true if Zip instances are equal
/// </summary>
/// <param name="other">Instance of Zip to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(Zip other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.UseDash4 == other.UseDash4 ||
this.UseDash4 != null &&
this.UseDash4.Equals(other.UseDash4)
) &&
(
this.ValidationPattern == other.ValidationPattern ||
this.ValidationPattern != null &&
this.ValidationPattern.Equals(other.ValidationPattern)
) &&
(
this.ValidationMessage == other.ValidationMessage ||
this.ValidationMessage != null &&
this.ValidationMessage.Equals(other.ValidationMessage)
) &&
(
this.Shared == other.Shared ||
this.Shared != null &&
this.Shared.Equals(other.Shared)
) &&
(
this.RequireInitialOnSharedChange == other.RequireInitialOnSharedChange ||
this.RequireInitialOnSharedChange != null &&
this.RequireInitialOnSharedChange.Equals(other.RequireInitialOnSharedChange)
) &&
(
this.SenderRequired == other.SenderRequired ||
this.SenderRequired != null &&
this.SenderRequired.Equals(other.SenderRequired)
) &&
(
this.RequireAll == other.RequireAll ||
this.RequireAll != null &&
this.RequireAll.Equals(other.RequireAll)
) &&
(
this.Name == other.Name ||
this.Name != null &&
this.Name.Equals(other.Name)
) &&
(
this.Value == other.Value ||
this.Value != null &&
this.Value.Equals(other.Value)
) &&
(
this.OriginalValue == other.OriginalValue ||
this.OriginalValue != null &&
this.OriginalValue.Equals(other.OriginalValue)
) &&
(
this.Width == other.Width ||
this.Width != null &&
this.Width.Equals(other.Width)
) &&
(
this.Required == other.Required ||
this.Required != null &&
this.Required.Equals(other.Required)
) &&
(
this.Locked == other.Locked ||
this.Locked != null &&
this.Locked.Equals(other.Locked)
) &&
(
this.ConcealValueOnDocument == other.ConcealValueOnDocument ||
this.ConcealValueOnDocument != null &&
this.ConcealValueOnDocument.Equals(other.ConcealValueOnDocument)
) &&
(
this.DisableAutoSize == other.DisableAutoSize ||
this.DisableAutoSize != null &&
this.DisableAutoSize.Equals(other.DisableAutoSize)
) &&
(
this.MaxLength == other.MaxLength ||
this.MaxLength != null &&
this.MaxLength.Equals(other.MaxLength)
) &&
(
this.TabLabel == other.TabLabel ||
this.TabLabel != null &&
this.TabLabel.Equals(other.TabLabel)
) &&
(
this.Font == other.Font ||
this.Font != null &&
this.Font.Equals(other.Font)
) &&
(
this.Bold == other.Bold ||
this.Bold != null &&
this.Bold.Equals(other.Bold)
) &&
(
this.Italic == other.Italic ||
this.Italic != null &&
this.Italic.Equals(other.Italic)
) &&
(
this.Underline == other.Underline ||
this.Underline != null &&
this.Underline.Equals(other.Underline)
) &&
(
this.FontColor == other.FontColor ||
this.FontColor != null &&
this.FontColor.Equals(other.FontColor)
) &&
(
this.FontSize == other.FontSize ||
this.FontSize != null &&
this.FontSize.Equals(other.FontSize)
) &&
(
this.DocumentId == other.DocumentId ||
this.DocumentId != null &&
this.DocumentId.Equals(other.DocumentId)
) &&
(
this.RecipientId == other.RecipientId ||
this.RecipientId != null &&
this.RecipientId.Equals(other.RecipientId)
) &&
(
this.PageNumber == other.PageNumber ||
this.PageNumber != null &&
this.PageNumber.Equals(other.PageNumber)
) &&
(
this.XPosition == other.XPosition ||
this.XPosition != null &&
this.XPosition.Equals(other.XPosition)
) &&
(
this.YPosition == other.YPosition ||
this.YPosition != null &&
this.YPosition.Equals(other.YPosition)
) &&
(
this.AnchorString == other.AnchorString ||
this.AnchorString != null &&
this.AnchorString.Equals(other.AnchorString)
) &&
(
this.AnchorXOffset == other.AnchorXOffset ||
this.AnchorXOffset != null &&
this.AnchorXOffset.Equals(other.AnchorXOffset)
) &&
(
this.AnchorYOffset == other.AnchorYOffset ||
this.AnchorYOffset != null &&
this.AnchorYOffset.Equals(other.AnchorYOffset)
) &&
(
this.AnchorUnits == other.AnchorUnits ||
this.AnchorUnits != null &&
this.AnchorUnits.Equals(other.AnchorUnits)
) &&
(
this.AnchorIgnoreIfNotPresent == other.AnchorIgnoreIfNotPresent ||
this.AnchorIgnoreIfNotPresent != null &&
this.AnchorIgnoreIfNotPresent.Equals(other.AnchorIgnoreIfNotPresent)
) &&
(
this.AnchorCaseSensitive == other.AnchorCaseSensitive ||
this.AnchorCaseSensitive != null &&
this.AnchorCaseSensitive.Equals(other.AnchorCaseSensitive)
) &&
(
this.AnchorMatchWholeWord == other.AnchorMatchWholeWord ||
this.AnchorMatchWholeWord != null &&
this.AnchorMatchWholeWord.Equals(other.AnchorMatchWholeWord)
) &&
(
this.AnchorHorizontalAlignment == other.AnchorHorizontalAlignment ||
this.AnchorHorizontalAlignment != null &&
this.AnchorHorizontalAlignment.Equals(other.AnchorHorizontalAlignment)
) &&
(
this.TabId == other.TabId ||
this.TabId != null &&
this.TabId.Equals(other.TabId)
) &&
(
this.TemplateLocked == other.TemplateLocked ||
this.TemplateLocked != null &&
this.TemplateLocked.Equals(other.TemplateLocked)
) &&
(
this.TemplateRequired == other.TemplateRequired ||
this.TemplateRequired != null &&
this.TemplateRequired.Equals(other.TemplateRequired)
) &&
(
this.ConditionalParentLabel == other.ConditionalParentLabel ||
this.ConditionalParentLabel != null &&
this.ConditionalParentLabel.Equals(other.ConditionalParentLabel)
) &&
(
this.ConditionalParentValue == other.ConditionalParentValue ||
this.ConditionalParentValue != null &&
this.ConditionalParentValue.Equals(other.ConditionalParentValue)
) &&
(
this.CustomTabId == other.CustomTabId ||
this.CustomTabId != null &&
this.CustomTabId.Equals(other.CustomTabId)
) &&
(
this.MergeField == other.MergeField ||
this.MergeField != null &&
this.MergeField.Equals(other.MergeField)
) &&
(
this.Status == other.Status ||
this.Status != null &&
this.Status.Equals(other.Status)
) &&
(
this.ErrorDetails == other.ErrorDetails ||
this.ErrorDetails != null &&
this.ErrorDetails.Equals(other.ErrorDetails)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.UseDash4 != null)
hash = hash * 57 + this.UseDash4.GetHashCode();
if (this.ValidationPattern != null)
hash = hash * 57 + this.ValidationPattern.GetHashCode();
if (this.ValidationMessage != null)
hash = hash * 57 + this.ValidationMessage.GetHashCode();
if (this.Shared != null)
hash = hash * 57 + this.Shared.GetHashCode();
if (this.RequireInitialOnSharedChange != null)
hash = hash * 57 + this.RequireInitialOnSharedChange.GetHashCode();
if (this.SenderRequired != null)
hash = hash * 57 + this.SenderRequired.GetHashCode();
if (this.RequireAll != null)
hash = hash * 57 + this.RequireAll.GetHashCode();
if (this.Name != null)
hash = hash * 57 + this.Name.GetHashCode();
if (this.Value != null)
hash = hash * 57 + this.Value.GetHashCode();
if (this.OriginalValue != null)
hash = hash * 57 + this.OriginalValue.GetHashCode();
if (this.Width != null)
hash = hash * 57 + this.Width.GetHashCode();
if (this.Required != null)
hash = hash * 57 + this.Required.GetHashCode();
if (this.Locked != null)
hash = hash * 57 + this.Locked.GetHashCode();
if (this.ConcealValueOnDocument != null)
hash = hash * 57 + this.ConcealValueOnDocument.GetHashCode();
if (this.DisableAutoSize != null)
hash = hash * 57 + this.DisableAutoSize.GetHashCode();
if (this.MaxLength != null)
hash = hash * 57 + this.MaxLength.GetHashCode();
if (this.TabLabel != null)
hash = hash * 57 + this.TabLabel.GetHashCode();
if (this.Font != null)
hash = hash * 57 + this.Font.GetHashCode();
if (this.Bold != null)
hash = hash * 57 + this.Bold.GetHashCode();
if (this.Italic != null)
hash = hash * 57 + this.Italic.GetHashCode();
if (this.Underline != null)
hash = hash * 57 + this.Underline.GetHashCode();
if (this.FontColor != null)
hash = hash * 57 + this.FontColor.GetHashCode();
if (this.FontSize != null)
hash = hash * 57 + this.FontSize.GetHashCode();
if (this.DocumentId != null)
hash = hash * 57 + this.DocumentId.GetHashCode();
if (this.RecipientId != null)
hash = hash * 57 + this.RecipientId.GetHashCode();
if (this.PageNumber != null)
hash = hash * 57 + this.PageNumber.GetHashCode();
if (this.XPosition != null)
hash = hash * 57 + this.XPosition.GetHashCode();
if (this.YPosition != null)
hash = hash * 57 + this.YPosition.GetHashCode();
if (this.AnchorString != null)
hash = hash * 57 + this.AnchorString.GetHashCode();
if (this.AnchorXOffset != null)
hash = hash * 57 + this.AnchorXOffset.GetHashCode();
if (this.AnchorYOffset != null)
hash = hash * 57 + this.AnchorYOffset.GetHashCode();
if (this.AnchorUnits != null)
hash = hash * 57 + this.AnchorUnits.GetHashCode();
if (this.AnchorIgnoreIfNotPresent != null)
hash = hash * 57 + this.AnchorIgnoreIfNotPresent.GetHashCode();
if (this.AnchorCaseSensitive != null)
hash = hash * 57 + this.AnchorCaseSensitive.GetHashCode();
if (this.AnchorMatchWholeWord != null)
hash = hash * 57 + this.AnchorMatchWholeWord.GetHashCode();
if (this.AnchorHorizontalAlignment != null)
hash = hash * 57 + this.AnchorHorizontalAlignment.GetHashCode();
if (this.TabId != null)
hash = hash * 57 + this.TabId.GetHashCode();
if (this.TemplateLocked != null)
hash = hash * 57 + this.TemplateLocked.GetHashCode();
if (this.TemplateRequired != null)
hash = hash * 57 + this.TemplateRequired.GetHashCode();
if (this.ConditionalParentLabel != null)
hash = hash * 57 + this.ConditionalParentLabel.GetHashCode();
if (this.ConditionalParentValue != null)
hash = hash * 57 + this.ConditionalParentValue.GetHashCode();
if (this.CustomTabId != null)
hash = hash * 57 + this.CustomTabId.GetHashCode();
if (this.MergeField != null)
hash = hash * 57 + this.MergeField.GetHashCode();
if (this.Status != null)
hash = hash * 57 + this.Status.GetHashCode();
if (this.ErrorDetails != null)
hash = hash * 57 + this.ErrorDetails.GetHashCode();
return hash;
}
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="WeakEventManager.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// Description: Base class for event managers in the "weak event listener"
// pattern.
//
//---------------------------------------------------------------------------
/***************************************************************************\
The standard mechanism for listening to events contains an inherent
potential memory leak. This class (and its derived classes) and the
related class WeakEventTable provide a workaround.
The leak occurs when all the following conditions hold:
a. Object A wants to listen to an event Foo from object B.
b. A uses an instance method (not a static method) as its event handler.
c. A's lifetime should not depend on B's.
d. A does not know when to stop listening (or A should keep listening
as long as it lives).
Normally, A listens by adding an event handler to B's Foo event:
B.Foo += new FooEventHandler(OnFoo);
but the handler contains a strong reference to A, and thus B now effectively
has a strong reference to A. Because of (d), this reference keeps A
alive at least as long as B, which is a leak because of (c).
The solution to this kind of leak is to introduce an intermediate "proxy"
object P with the following properties:
1. P does the actual listening to B.
2. P maintains a list of "real listeners" such as A, using weak references.
3. When P receives an event, it forwards it to the real listeners that
are still alive.
4. P's lifetime is expected to be as long as the app (or Dispatcher).
This replaces the strong reference from B to A by a strong reference from
B to P and a weak reference from P to A. Thus B's lifetime will not affect A's.
The only object that can leak is P, but this is OK because of (d).
In the implementation of this idea, the role of P is played by a singleton
instance of a class derived from WeakEventManager. There is one such class
for each event declaration. The global WeakEventTable keeps track of the
manager instances.
The implementation also fulfills the following additional requirements:
5. Events can be raised (and hence delivered) on any thread.
6. Each event is delivered to all the listeners present at the time
P receives the event, even if a listener modifies the list (e.g.
by removing itself or another listener, or adding a new listener).
7. P does not hold a strong reference to the event source B.
8. P automatically purges its list of dead entries (where either the
source or the listener has died and been GC'd). This is done
frequently enough to avoid large "leaks" of entries that are
dead but not yet discovered, but not so frequently that the cost
of purging becomes a noticeable perf hit.
9. New events can be easily added to the system, by defining a new
derived class and implementing a few simple methods.
\***************************************************************************/
using System;
using System.Diagnostics; // Debug
using System.Collections; // Hashtable
using System.Collections.Generic; // List<T>
using System.Reflection; // MethodInfo
using System.Threading; // Interlocked
using System.Security; // [SecuritySafeCritical]
using System.Security.Permissions; // [ReflectionPermission]
using System.Windows; // SR
using System.Windows.Threading; // DispatcherObject
using MS.Utility; // FrugalList
using MS.Internal; // Invariant
using MS.Internal.WindowsBase; // [FriendAccessAllowed]
namespace System.Windows
{
//
// See WeakEventManagerTemplate.cs for instructions on how to subclass
// this abstract base class.
//
/// <summary>
/// This base class provides common functionality for event managers,
/// in support of the "weak event listener" pattern.
/// </summary>
public abstract class WeakEventManager : DispatcherObject
{
#region Constructors
//
// Constructors
//
/// <summary>
/// Create a new instance of WeakEventManager.
/// </summary>
protected WeakEventManager()
{
_table = WeakEventTable.CurrentWeakEventTable;
}
// initialize static fields
static WeakEventManager()
{
s_DeliverEventMethodInfo = typeof(WeakEventManager).GetMethod("DeliverEvent", BindingFlags.NonPublic | BindingFlags.Instance);
}
#endregion Constructors
#region Protected Properties
//
// Protected Properties
//
/// <summary>
/// Take a read-lock on the table, and return the IDisposable.
/// Queries to the table should occur within a
/// "using (ReadLock) { ... }" clause, except for queries
/// that are already within a write lock.
/// </summary>
protected IDisposable ReadLock
{
get { return Table.ReadLock; }
}
/// <summary>
/// Take a write-lock on the table, and return the IDisposable.
/// All modifications to the table should occur within a
/// "using (WriteLock) { ... }" clause.
/// </summary>
protected IDisposable WriteLock
{
get { return Table.WriteLock; }
}
/// <summary>
/// The data associated with the given source. Subclasses chose
/// what to store here; most commonly it is a ListenerList - a list
/// of weak references to listeners.
/// </summary>
protected object this[object source]
{
get { return Table[this, source]; }
set { Table[this, source] = value; }
}
/// <summary>
/// MethodInfo for the DeliverEvent method - used by generic WeakEventManager.
/// </summary>
internal static MethodInfo DeliverEventMethodInfo
{
get { return s_DeliverEventMethodInfo; }
}
#endregion Protected Properties
#region Protected Methods
//
// Protected Methods
//
/// <summary>
/// Return a new list to hold listeners to the event.
/// </summary>
protected virtual ListenerList NewListenerList()
{
return new ListenerList();
}
/// <summary>
/// Listen to the given source for the event.
/// </summary>
protected abstract void StartListening(object source);
/// <summary>
/// Stop listening to the given source for the event.
/// </summary>
protected abstract void StopListening(object source);
/// <summary>
/// Get the current manager for the given manager type.
/// </summary>
protected static WeakEventManager GetCurrentManager(Type managerType)
{
WeakEventTable table = WeakEventTable.CurrentWeakEventTable;
return table[managerType];
}
/// <summary>
/// Set the current manager for the given manager type.
/// </summary>
protected static void SetCurrentManager(Type managerType, WeakEventManager manager)
{
WeakEventTable table = WeakEventTable.CurrentWeakEventTable;
table[managerType] = manager;
}
/// <summary>
/// Get the current manager for the given event.
/// </summary>
internal static WeakEventManager GetCurrentManager(Type eventSourceType, string eventName)
{
WeakEventTable table = WeakEventTable.CurrentWeakEventTable;
return table[eventSourceType, eventName];
}
/// <summary>
/// Set the current manager for the given event.
/// </summary>
internal static void SetCurrentManager(Type eventSourceType, string eventName, WeakEventManager manager)
{
WeakEventTable table = WeakEventTable.CurrentWeakEventTable;
table[eventSourceType, eventName] = manager;
}
/// <summary>
/// Discard the data associated with the given source
/// </summary>
protected void Remove(object source)
{
Table.Remove(this, source);
}
/// <summary>
/// Add a listener to the given source for the event.
/// </summary>
protected void ProtectedAddListener(object source, IWeakEventListener listener)
{
if (listener == null)
throw new ArgumentNullException("listener");
AddListener(source, listener, null);
}
/// <summary>
/// Remove a listener to the given source for the event.
/// </summary>
protected void ProtectedRemoveListener(object source, IWeakEventListener listener)
{
if (listener == null)
throw new ArgumentNullException("listener");
RemoveListener(source, listener, null);
}
/// <summary>
/// Add a handler to the given source for the event.
/// </summary>
protected void ProtectedAddHandler(object source, Delegate handler)
{
if (handler == null)
throw new ArgumentNullException("handler");
AddListener(source, null, handler);
}
/// <summary>
/// Remove a handler to the given source for the event.
/// </summary>
protected void ProtectedRemoveHandler(object source, Delegate handler)
{
if (handler == null)
throw new ArgumentNullException("handler");
RemoveListener(source, null, handler);
}
private void AddListener(object source, IWeakEventListener listener, Delegate handler)
{
object sourceKey = (source != null) ? source : StaticSource;
using (Table.WriteLock)
{
ListenerList list = (ListenerList)Table[this, sourceKey];
if (list == null)
{
// no entry in the table - add a new one
list = NewListenerList();
Table[this, sourceKey] = list;
// listen for the desired event
StartListening(source);
}
// make sure list is ready for writing
if (ListenerList.PrepareForWriting(ref list))
{
Table[this, source] = list;
}
// add a target to the list of listeners
if (handler != null)
{
list.AddHandler(handler);
}
else
{
list.Add(listener);
}
// schedule a cleanup pass (heuristic (b) described above)
ScheduleCleanup();
}
}
private void RemoveListener(object source, object target, Delegate handler)
{
object sourceKey = (source != null) ? source : StaticSource;
using (Table.WriteLock)
{
ListenerList list = (ListenerList)Table[this, sourceKey];
if (list != null)
{
// make sure list is ready for writing
if (ListenerList.PrepareForWriting(ref list))
{
Table[this, sourceKey] = list;
}
// remove the target from the list of listeners
if (handler != null)
{
list.RemoveHandler(handler);
}
else
{
list.Remove((IWeakEventListener)target);
}
// after removing the last listener, stop listening
if (list.IsEmpty)
{
Table.Remove(this, sourceKey);
StopListening(source);
}
}
}
}
/// <summary>
/// Deliver an event to each listener.
/// </summary>
protected void DeliverEvent(object sender, EventArgs args)
{
ListenerList list;
object sourceKey = (sender != null) ? sender : StaticSource;
// get the list of listeners
using (Table.ReadLock)
{
list = (ListenerList)Table[this, sourceKey];
if (list == null)
{
list = ListenerList.Empty;
}
// mark the list "in use", even outside the read lock,
// so that any writers will know not to modify it (they'll
// modify a clone intead).
list.BeginUse();
}
// deliver the event, being sure to undo the effect of BeginUse().
try
{
DeliverEventToList(sender, args, list);
}
finally
{
list.EndUse();
}
}
/// <summary>
/// Deliver an event to the listeners on the given list
/// </summary>
protected void DeliverEventToList(object sender, EventArgs args, ListenerList list)
{
bool foundStaleEntries = list.DeliverEvent(sender, args, this.GetType());
// if we found stale entries, schedule a cleanup (heuristic b)
if (foundStaleEntries)
{
ScheduleCleanup();
}
}
/// <summary>
/// Schedule a cleanup pass.
/// </summary>
protected void ScheduleCleanup()
{
Table.ScheduleCleanup();
}
/// <summary>
/// Remove dead entries from the data for the given source. Returns true if
/// some entries were actually removed.
/// </summary>
protected virtual bool Purge(object source, object data, bool purgeAll)
{
bool foundDirt = false;
bool removeList = purgeAll || source == null;
// remove dead entries from the list
if (!removeList)
{
ListenerList list = (ListenerList)data;
if (ListenerList.PrepareForWriting(ref list) && source != null)
{
Table[this, source] = list;
}
if (list.Purge())
foundDirt = true;
removeList = list.IsEmpty;
}
// if the list is no longer needed, stop listening to the event
if (removeList)
{
if (source != null) // source may have been GC'd
{
StopListening(source);
// remove the list completely (in the purgeAll case, we'll do it later)
if (!purgeAll)
{
Table.Remove(this, source);
foundDirt = true;
}
}
}
return foundDirt;
}
#endregion Protected Methods
#region Internal Methods
//
// Internal Methods
//
// this should only be called by WeakEventTable
internal bool PurgeInternal(object source, object data, bool purgeAll)
{
return Purge(source, data, purgeAll);
}
// for use by test programs (e.g. leak detectors) that want to force
// a cleanup pass.
[FriendAccessAllowed] // defined in Base, used by Framework
internal static bool Cleanup()
{
return WeakEventTable.Cleanup();
}
// for use by test programs (e.g. perf tests) that want to disable
// cleanup passes temporarily.
[FriendAccessAllowed] // defined in Base, used by Framework
internal static void SetCleanupEnabled(bool value)
{
WeakEventTable.CurrentWeakEventTable.IsCleanupEnabled = value;
}
#endregion Internal Methods
#region Private Properties
//
// Private Properties
//
private WeakEventTable Table
{
get { return _table; }
}
#endregion Private Properties
#region Private Fields
//
// Private Fields
//
private WeakEventTable _table;
private static readonly object StaticSource = new NamedObject("StaticSource");
private static MethodInfo s_DeliverEventMethodInfo;
#endregion Private Fields
#region ListenerList
internal struct Listener
{
public Listener(object target)
{
if (target == null)
target = StaticSource;
_target = new WeakReference(target);
_handler = null;
}
public Listener(object target, Delegate handler)
{
_target = new WeakReference(target);
_handler = new WeakReference(handler);
}
public bool Matches(object target, Delegate handler)
{
return Object.ReferenceEquals(target, Target) &&
Object.Equals(handler, Handler);
}
public object Target { get { return _target.Target; } }
public Delegate Handler { get { return (_handler != null) ? (Delegate)_handler.Target : null; } }
public bool HasHandler { get { return _handler != null; } }
WeakReference _target;
WeakReference _handler;
}
/// <summary>
/// This class implements the most common data that a simple manager
/// might want to store for a given source: a list of weak references
/// to the listeners.
/// </summary>
protected class ListenerList
{
/// <summary>
/// Create a new instance of ListenerList.
/// </summary>
public ListenerList()
{
_list = new FrugalObjectList<Listener>();
}
/// <summary>
/// Create a new instance of ListenerList, with given capacity.
/// </summary>
public ListenerList(int capacity)
{
_list = new FrugalObjectList<Listener>(capacity);
}
/// <summary>
/// Return the listener at the given index.
/// </summary>
public IWeakEventListener this[int index]
{
get { return (IWeakEventListener)_list[index].Target; }
}
internal Listener GetListener(int index)
{
return _list[index];
}
/// <summary>
/// Return the number of listeners.
/// </summary>
public int Count
{
get { return _list.Count; }
}
/// <summary>
/// Return true if there are no listeners.
/// </summary>
public bool IsEmpty
{
get { return _list.Count == 0; }
}
/// <summary>
/// An empty list of listeners.
/// </summary>
public static ListenerList Empty
{
get { return s_empty; }
}
/// <summary>
/// Add the given listener to the list.
/// </summary>
public void Add(IWeakEventListener listener)
{
Invariant.Assert(_users == 0, "Cannot modify a ListenerList that is in use");
_list.Add(new Listener(listener));
}
/// <summary>
/// Remove the given listener from the list.
/// </summary>
public void Remove(IWeakEventListener listener)
{
Invariant.Assert(_users == 0, "Cannot modify a ListenerList that is in use");
for (int i=_list.Count-1; i>=0; --i)
{
if (_list[i].Target == listener)
{
_list.RemoveAt(i);
break;
}
}
}
public void AddHandler(Delegate handler)
{
Invariant.Assert(_users == 0, "Cannot modify a ListenerList that is in use");
object target = handler.Target;
if (target == null)
target = StaticSource;
// add a record to the main list
_list.Add(new Listener(target, handler));
AddHandlerToCWT(target, handler);
}
void AddHandlerToCWT(object target, Delegate handler)
{
// add the handler to the CWT - this keeps the handler alive throughout
// the lifetime of the target, without prolonging the lifetime of
// the target
object value;
if (!_cwt.TryGetValue(target, out value))
{
// 99% case - the target only listens once
_cwt.Add(target, handler);
}
else
{
// 1% case - the target listens multiple times
// we store the delegates in a list
List<Delegate> list = value as List<Delegate>;
if (list == null)
{
// lazily allocate the list, and add the old handler
Delegate oldHandler = value as Delegate;
list = new List<Delegate>();
list.Add(oldHandler);
// install the list as the CWT value
_cwt.Remove(target);
_cwt.Add(target, list);
}
// add the new handler to the list
list.Add(handler);
}
}
public void RemoveHandler(Delegate handler)
{
Invariant.Assert(_users == 0, "Cannot modify a ListenerList that is in use");
object value;
object target = handler.Target;
if (target == null)
target = StaticSource;
// remove the record from the main list
for (int i=_list.Count-1; i>=0; --i)
{
if (_list[i].Matches(target, handler))
{
_list.RemoveAt(i);
break;
}
}
// remove the handler from the CWT
if (_cwt.TryGetValue(target, out value))
{
List<Delegate> list = value as List<Delegate>;
if (list == null)
{
// 99% case - the target is removing its single handler
_cwt.Remove(target);
}
else
{
// 1% case - the target had multiple handlers, and is removing one
list.Remove(handler);
if (list.Count == 0)
{
_cwt.Remove(target);
}
}
}
else
{
// target has been GC'd. This probably can't happen, since the
// target initiates the Remove. But if it does, there's nothing
// to do - the target is removed from the CWT automatically,
// and the weak-ref in the main list will be removed
// at the next Purge.
}
}
/// <summary>
/// Add the given listener to the list.
/// </summary>
internal void Add(Listener listener)
{
Invariant.Assert(_users == 0, "Cannot modify a ListenerList that is in use");
// no need to add if the listener has been GC'd
object target = listener.Target;
if (target == null)
return;
_list.Add(listener);
if (listener.HasHandler)
{
AddHandlerToCWT(target, listener.Handler);
}
}
/// <summary>
/// If the given list is in use (which means an event is currently
/// being delivered), replace it with a clone. The existing
/// users will finish delivering the event to the original list,
/// without interference from changes to the new list.
/// </summary>
/// <returns>
/// True if the list was cloned. Callers will probably want to
/// insert the new list in their own data structures.
/// </returns>
public static bool PrepareForWriting(ref ListenerList list)
{
bool inUse = list.BeginUse();
list.EndUse();
if (inUse)
{
list = list.Clone();
}
return inUse;
}
public virtual bool DeliverEvent(object sender, EventArgs args, Type managerType)
{
bool foundStaleEntries = false;
for (int k=0, n=Count; k<n; ++k)
{
Listener listener = GetListener(k);
foundStaleEntries |= DeliverEvent(ref listener, sender, args, managerType);
}
return foundStaleEntries;
}
internal bool DeliverEvent(ref Listener listener, object sender, EventArgs args, Type managerType)
{
object target = listener.Target;
bool entryIsStale = (target == null);
if (!entryIsStale)
{
if (listener.HasHandler)
{
EventHandler handler = (EventHandler)listener.Handler;
if (handler != null)
{
handler(sender, args);
}
}
else
{
// legacy (4.0)
IWeakEventListener iwel = target as IWeakEventListener;
if (iwel != null)
{
bool handled = iwel.ReceiveWeakEvent(managerType, sender, args);
// if the event isn't handled, something is seriously wrong. This
// means a listener registered to receive the event, but refused to
// handle it when it was delivered. Such a listener is coded incorrectly.
if (!handled)
{
Invariant.Assert(handled,
SR.Get(SRID.ListenerDidNotHandleEvent),
SR.Get(SRID.ListenerDidNotHandleEventDetail, iwel.GetType(), managerType));
}
}
}
}
return entryIsStale;
}
/// <summary>
/// Purge the list of stale entries. Returns true if any stale
/// entries were purged.
/// </summary>
public bool Purge()
{
Invariant.Assert(_users == 0, "Cannot modify a ListenerList that is in use");
bool foundDirt = false;
for (int j=_list.Count-1; j>=0; --j)
{
if (_list[j].Target == null)
{
_list.RemoveAt(j);
foundDirt = true;
}
}
return foundDirt;
}
/// <summary>
/// Return a copy of the list.
/// </summary>
public virtual ListenerList Clone()
{
ListenerList result = new ListenerList();
CopyTo(result);
return result;
}
protected void CopyTo(ListenerList newList)
{
IWeakEventListener iwel;
for (int k=0, n=Count; k<n; ++k)
{
Listener listener = GetListener(k);
if (listener.Target != null)
{
if (listener.HasHandler)
{
Delegate handler = listener.Handler;
if (handler != null)
{
newList.AddHandler(handler);
}
}
else if ((iwel = listener.Target as IWeakEventListener) != null)
{
newList.Add(iwel);
}
}
}
}
/// <summary>
/// Mark the list as 'in use'. An event manager should call BeginUse()
/// before iterating through the list to deliver an event to the listeners,
/// and should call EndUse() when it is done. This prevents another
/// user from modifying the list while the iteration is in progress.
/// </summary>
/// <returns> True if the list is already in use.</returns>
public bool BeginUse()
{
return (Interlocked.Increment(ref _users) != 1);
}
/// <summary>
/// Undo the effect of BeginUse().
/// </summary>
public void EndUse()
{
Interlocked.Decrement(ref _users);
}
private FrugalObjectList<Listener> _list; // list of listeners
private int _users; // number of active users
private System.Runtime.CompilerServices.ConditionalWeakTable<object, object>
_cwt = new System.Runtime.CompilerServices.ConditionalWeakTable<object, object>();
private static ListenerList s_empty = new ListenerList();
}
protected class ListenerList<TEventArgs> : ListenerList
where TEventArgs : EventArgs
{
public ListenerList() : base() {}
public ListenerList(int capacity) : base(capacity) {}
public override bool DeliverEvent(object sender, EventArgs e, Type managerType)
{
TEventArgs args = (TEventArgs)e;
bool foundStaleEntries = false;
for (int k=0, n=Count; k<n; ++k)
{
Listener listener = GetListener(k);
if (listener.Target != null)
{
EventHandler<TEventArgs> handler = (EventHandler<TEventArgs>)listener.Handler;
if (handler != null)
{
handler(sender, args);
}
else
{
// legacy (4.0)
foundStaleEntries |= base.DeliverEvent(ref listener, sender, e, managerType);
}
}
else
{
foundStaleEntries = true;
}
}
return foundStaleEntries;
}
public override ListenerList Clone()
{
ListenerList<TEventArgs> result = new ListenerList<TEventArgs>();
CopyTo(result);
return result;
}
}
#endregion ListenerList
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
//using System.ComponentModel.DataAnnotations;
//using System.Data;
//using System.Data.Entity.SqlServer;
using System.Linq;
using System.Reflection;
using EntityFramework.MappingAPI.Exceptions;
using EntityFramework.MappingAPI.Extensions;
using EntityFramework.MappingAPI.Mappings;
#if EF6
using System.Data.Entity.Core.Metadata.Edm;
#else
using System.Data.Metadata.Edm;
#endif
namespace EntityFramework.MappingAPI.Mappers
{
internal abstract class MapperBase
{
/// <summary>
///
/// </summary>
protected EntityContainer EntityContainer { get; private set; }
/// <summary>
/// The magic box
/// </summary>
protected readonly MetadataWorkspace MetadataWorkspace;
/// <summary>
/// Table mappings dictionary where key is entity type full name.
/// </summary>
protected readonly Dictionary<string, EntityMap> _entityMaps = new Dictionary<string, EntityMap>();
/// <summary>
/// Primary keys of tables.
/// Key is table name (in db).
/// Values is array of entity property names that are primary keys
/// </summary>
private readonly Dictionary<string, string[]> _pks = new Dictionary<string, string[]>();
/// <summary>
/// Foreign keys map
/// Key is fk ref
/// Value is pk ref
/// </summary>
private readonly Dictionary<EdmMember, EdmMember> _fks = new Dictionary<EdmMember, EdmMember>();
private Dictionary<string, TphData> _tphData;
protected virtual Dictionary<string, TphData> GetTphData()
{
var entitySetMaps = (IEnumerable<object>)MetadataWorkspace
.GetItemCollection(DataSpace.CSSpace)[0]
.GetPrivateFieldValue("EntitySetMaps");
var data = new Dictionary<string, TphData>();
foreach (var entitySetMap in entitySetMaps)
{
var props = new List<EdmMember>();
var navProps = new List<NavigationProperty>();
var discriminators = new Dictionary<string, object>();
var typeMappings = (IEnumerable<object>)entitySetMap.GetPrivateFieldValue("TypeMappings");
// make sure that the baseType appear last in the list
typeMappings = typeMappings
.OrderBy(tm => ((IEnumerable<object>)tm.GetPrivateFieldValue("IsOfTypes")).Count());
foreach (var typeMapping in typeMappings)
{
var types = (IEnumerable<EdmType>)typeMapping.GetPrivateFieldValue("Types");
var isOfypes = (IEnumerable<EdmType>)typeMapping.GetPrivateFieldValue("IsOfTypes");
var mappingFragments = (IEnumerable<object>)typeMapping.GetPrivateFieldValue("MappingFragments");
// if isOfType.length > 0, then it is base type of TPH
// must merge properties with siblings
foreach (EntityType type in isOfypes)
{
var identity = type.ToString();
if (!data.ContainsKey(identity))
data[identity] = new TphData();
data[identity].NavProperties = navProps.ToArray();
data[identity].Properties = props.ToArray();
data[identity].Discriminators = discriminators;
}
foreach (EntityType type in types)
{
var identity = type.ToString();
if (!data.ContainsKey(identity))
data[identity] = new TphData();
// type.Properties gets properties including inherited properties
var tmp = new List<EdmMember>(type.Properties);
foreach (var navProp in type.NavigationProperties)
{
var associationType = navProp.RelationshipType as AssociationType;
if (associationType != null)
{
// if entity does not contain id property i.e has only reference object for a fk
if (associationType.ReferentialConstraints.Count == 0)
{
tmp.Add(navProp);
}
}
}
data[identity].NavProperties = type.NavigationProperties.ToArray();
data[identity].Properties = tmp.ToArray();
foreach (var prop in type.Properties)
{
if (!props.Contains(prop))
props.Add(prop);
}
foreach (var navProp in type.NavigationProperties)
{
if (!navProps.Contains(navProp))
navProps.Add(navProp);
}
foreach (var fragment in mappingFragments)
{
var conditionProperties = (IEnumerable)fragment.GetPrivateFieldValue("m_conditionProperties");
foreach (var conditionalProperty in conditionProperties)
{
var columnName = ((EdmProperty)conditionalProperty.GetPrivateFieldValue("Key")).Name;
var value = conditionalProperty.GetPrivateFieldValue("Value").GetPrivateFieldValue("Value");
data[identity].Discriminators[columnName] = value;
discriminators[columnName] = value;
}
}
}
}
}
return data;
}
public Dictionary<string, TphData> TphData
{
get
{
if (_tphData != null)
return _tphData;
_tphData = GetTphData();
return _tphData;
}
}
/// <summary>
/// Type name and Edm.EntityType map for EF4 and EF5
/// </summary>
/// <returns></returns>
protected virtual Dictionary<string, EntityType> GetTypeMappingsEf4()
{
var entityTypes = MetadataWorkspace.GetItems(DataSpace.CSpace).OfType<EntityType>();
var clrTypes = MetadataWorkspace.GetItems(DataSpace.OSpace)
.Select(x => x.ToString())
.ToDictionary(x => x.Substring(x.LastIndexOf('.') + 1));
// can be matched by name because classes with same name from different namespaces can not be used
// http://entityframework.codeplex.com/workitem/714
var typeMappings = new Dictionary<string, EntityType>();
foreach (var entityType in entityTypes)
{
if (entityType.Name == "EdmMetadata")
{
continue;
}
var key = clrTypes[entityType.Name];
typeMappings[key] = entityType;
}
return typeMappings;
}
/// <summary>
/// Type name and Edm.EntityType map for EF6+
/// Key is type full name (Also OSpace item fullname and OCSpace identity)
/// Value is EntityType from CSpace
/// </summary>
/// <returns></returns>
protected virtual Dictionary<string, EntityType> GetTypeMappingsEf6()
{
return MetadataWorkspace.GetItems(DataSpace.OCSpace)
.Select(x => new { identity = x.ToString().Split(':'), edmItem = x.GetPrivateFieldValue("EdmItem") as EntityType })
.Where(x => x.edmItem != null)
.ToDictionary(x => x.identity[0], x => x.edmItem);
}
private Dictionary<string, EntityType> _typeMappings;
/// <summary>
/// Type name and Edm.EntityType map.
/// Key is type full name (Also OSpace item fullname).
/// Value is EntityType from CSpace.
/// </summary>
/// <returns></returns>
public Dictionary<string, EntityType> TypeMappings
{
get
{
if (_typeMappings != null)
{
return _typeMappings;
}
#if EF6
_typeMappings = GetTypeMappingsEf6();
#else
_typeMappings = GetTypeMappingsEf4();
#endif
return _typeMappings;
}
}
/// <summary>
///
/// </summary>
/// <param name="metadataWorkspace"></param>
/// <param name="entityContainer">Code first or DB first entityContainer</param>
protected MapperBase(MetadataWorkspace metadataWorkspace, EntityContainer entityContainer)
{
MetadataWorkspace = metadataWorkspace;
EntityContainer = entityContainer;
var relations = MetadataWorkspace.GetItems(DataSpace.CSpace).OfType<AssociationType>();
foreach (var associationType in relations)
{
foreach (var referentialConstraint in associationType.ReferentialConstraints)
{
for (int i = 0; i < referentialConstraint.ToProperties.Count; ++i)
{
_fks[referentialConstraint.ToProperties[i]] = referentialConstraint.FromProperties[i];
}
}
}
}
/*
/// <summary>
///
/// </summary>
/// <param name="typeFullName"></param>
/// <param name="entitySet"></param>
/// <returns></returns>
protected abstract string GetTableName(string typeFullName, EntitySet entitySet);
*/
/// <summary>
///
/// </summary>
/// <param name="typeFullName"></param>
/// <param name="tableName"></param>
/// <param name="schema"></param>
/// <returns></returns>
internal EntityMap RegEntity(string typeFullName, string tableName, string schema)
{
var entityType = TryGetRefObjectType(typeFullName);
var entityMapType = typeof (EntityMap<>);
var genericType = entityMapType.MakeGenericType(entityType);
var entityMap = (EntityMap)Activator.CreateInstance(genericType);
entityMap.TypeFullName = typeFullName;
entityMap.TableName = tableName;
entityMap.Schema = schema;
entityMap.Type = entityType;
_entityMaps.Add(typeFullName, entityMap);
return entityMap;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
private Type TryGetRefObjectType(string typeFullName)
{
foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
{
var t = a.GetType(typeFullName);
if (t != null)
return t;
}
return null;
}
protected class PrepareMappingRes
{
public string TableName { get; set; }
public EntitySet StorageEntitySet { get; set; }
public bool IsRoot { get; set; }
public EdmType BaseEdmType { get; set; }
}
protected abstract PrepareMappingRes PrepareMapping(string typeFullName, EdmType edmitem);
/// <summary>
///
/// </summary>
/// <param name="typeFullName"></param>
/// <param name="edmItem"></param>
public EntityMap MapEntity(string typeFullName, EdmType edmItem)
{
var identity = edmItem.FullName;
if (!TphData.ContainsKey(identity))
{
return null;
}
var prepareMappingRes = PrepareMapping(typeFullName, edmItem);
if (prepareMappingRes == null){return null;}
var storageEntitySet = prepareMappingRes.StorageEntitySet;
var tableName = prepareMappingRes.TableName;
var isRoot = prepareMappingRes.IsRoot;
var baseEdmType = prepareMappingRes.BaseEdmType;
var entityMap = RegEntity(typeFullName, tableName, storageEntitySet.Schema);
entityMap.IsRoot = isRoot;
entityMap.EdmType = edmItem;
entityMap.ParentEdmType = entityMap.IsRoot ? null : baseEdmType;
_pks[tableName] = storageEntitySet.ElementType.KeyMembers.Select(x => x.Name).ToArray();
entityMap.IsTph = TphData[identity].Discriminators.Count > 0;
string prefix = null;
int i = 0;
var propertiesToMap = this.GetPropertiesToMapOld(entityMap, storageEntitySet.ElementType.Properties);
foreach (var edmProperty in propertiesToMap) {
MapProperty(entityMap, edmProperty, ref i, ref prefix);
}
// create navigation properties
foreach (var navigationProperty in TphData[identity].NavProperties)
{
var associationType = navigationProperty.RelationshipType as AssociationType;
if (associationType == null || associationType.ReferentialConstraints.Count == 0)
{
continue;
}
var to = associationType.ReferentialConstraints[0].ToProperties[0];
var propertyMap = entityMap.Properties.Cast<PropertyMap>()
.FirstOrDefault(x => x.EdmMember == to);
if (propertyMap != null)
{
propertyMap.NavigationPropertyName = navigationProperty.Name;
if (entityMap.Prop(navigationProperty.Name) == null)
{
var navigationPropertyMap = entityMap.MapProperty(navigationProperty.Name, propertyMap.ColumnName);
navigationPropertyMap.IsNavigationProperty = true;
navigationPropertyMap.ForeignKeyPropertyName = propertyMap.PropertyName;
navigationPropertyMap.ForeignKey = propertyMap;
propertyMap.NavigationProperty = navigationPropertyMap;
}
}
}
// create discriminators
foreach (var discriminator in TphData[identity].Discriminators)
{
var propertyMap = entityMap.MapDiscriminator(discriminator.Key, discriminator.Value);
entityMap.AddDiscriminator(propertyMap);
}
return entityMap;
}
/// <summary>
/// Gets properties that are ment for given type.
/// TPH columns are ordered by hierarchy and type name.
/// First columns are from base class. Derived types, which name starts with 'A', columns are before type, which name starts with 'B' etc.
/// So the logic is to include all properties inherited from base types and exclude all already bound properties from siblings.
/// </summary>
/// <param name="entityMap"></param>
/// <param name="properties"></param>
/// <returns></returns>
private IEnumerable<EdmProperty> GetOwnEdmTypeProperties(EntityMap entityMap, IEnumerable<EdmProperty> properties)
{
if (entityMap.IsRoot)
{
return properties;
}
var edmType = entityMap.EdmType as EntityType;
var edmTypeProperties = edmType.Properties;
return edmTypeProperties.Select(edmProperty => properties.FirstOrDefault(baseEdmProperty => baseEdmProperty.Name == edmProperty.Name) ?? edmProperty);
}
private IEnumerable<EdmProperty> GetPropertiesToMapOld(EntityMap entityMap, IEnumerable<EdmProperty> properties)
{
if (entityMap.IsRoot)
{
return properties;
}
if(entityMap.IsTph)
{
var preferedNames = properties.SelectMany(p => p.MetadataProperties.Where(mp => mp.Name == "PreferredName")).Select(mpp => mpp.Value);
if(preferedNames.Count() != preferedNames.Distinct().Count()) throw new ProperyOverrideNotSupported("Propery override not supported!",entityMap.Type);
}
var parentEdmType = entityMap.ParentEdmType;
var include = new List<EdmProperty>(this.GetOwnEdmTypeProperties(entityMap, properties));
var exclude = new List<EdmProperty>();
while (true)
{
var parent = _entityMaps.Values.FirstOrDefault(x => x.EdmType == parentEdmType);
if (parent == null)
{
break;
}
include.AddRange(parent.Properties.Cast<PropertyMap>().Select(x => x.EdmProperty));
exclude.AddRange(_entityMaps.Values.Where(x => x.ParentEdmType == parentEdmType)
.SelectMany(x => x.Properties)
.Cast<PropertyMap>()
.Select(x => x.EdmProperty));
parentEdmType = parent.ParentEdmType;
}
return properties.Where(edmProperty => include.Contains(edmProperty) || !exclude.Contains(edmProperty)).ToList();
}
/// <summary>
///
/// </summary>
/// <param name="entityMap"></param>
/// <param name="edmProperty"></param>
/// <param name="i"></param>
/// <param name="prefix"></param>
private void MapProperty(EntityMap entityMap, EdmProperty edmProperty, ref int i, ref string prefix)
{
var identity = entityMap.EdmType.FullName;
var entityMembers = TphData[identity].Properties;
var columnName = edmProperty.Name;
EdmMember edmMember;
if(entityMembers.Length <= i)
{
if(prefix != null) { edmMember = entityMembers[i-1]; }
else
{ return; }
}
else
{
edmMember = entityMembers[i];
}
// check if is complex type
if (string.IsNullOrEmpty(prefix) && edmMember.TypeUsage.EdmType.GetType() == typeof(ComplexType))
{
prefix = edmMember.Name;
++i;
}
string propName;
if (prefix != null)
{
if (columnName.StartsWith(prefix + "_"))
{
propName = columnName.Replace('_', '.');
}
else
{
prefix = null;
propName = edmMember.Name;
++i;
}
}
else
{
propName = entityMembers[i++].Name;
}
var propInfo = entityMap.Type.GetProperty(propName, '.');
if (propInfo == null)
{
// entity does not contain such property
return;
}
PropertyMap propertyMap;
try
{
/*
var mi = SqlProviderServices.Instance.GetType().GetMethod("GetSqlDbType", BindingFlags.NonPublic | BindingFlags.Static);
var parameterInfos = mi.GetParameters();
var parameters = new List<object>();
parameters.Add(edmProperty.TypeUsage);
parameters.Add(false);
parameters.Add(SqlVersion);
parameters.Add(null);
parameters.Add(null);
parameters.Add(null);
parameters.Add(null);
SqlDbType sqlDbType = (SqlDbType) mi.Invoke(null, parameters.ToArray());
*/
propertyMap = entityMap.MapProperty(propName, columnName);
propertyMap.EdmProperty = edmProperty;
propertyMap.EdmMember = edmMember;
propertyMap.IsNavigationProperty = edmMember is NavigationProperty;
propertyMap.IsFk = propertyMap.IsNavigationProperty || _fks.ContainsKey(edmMember);
if (propertyMap.IsFk && _fks.ContainsKey(edmMember))
{
propertyMap.FkTargetEdmMember = _fks[edmMember];
entityMap.AddFk(propertyMap);
}
}
catch (Exception ex)
{
var errorMessage = string.Format("Failed to map propName {0} to column {1} on table {2} ({3})",
propName,
columnName,
entityMap.TableName,
entityMap.TypeFullName);
throw new Exception(errorMessage, ex);
}
if (_pks[entityMap.TableName].Contains(columnName))
{
propertyMap.IsPk = true;
entityMap.AddPk(propertyMap);
}
foreach (var facet in edmProperty.TypeUsage.Facets)
{
//System.Data.Entity.Core.Common.DbProviderManifest.ScaleFacetName
switch (facet.Name)
{
case "SRID":
try
{
propertyMap.SRID = (int?)facet.Value;
}
catch
{
// nothing to do
}
break;
case "IsStrict":
propertyMap.IsStrict = facet.Value != null && (bool)facet.Value;
break;
case "Unicode":
propertyMap.Unicode = facet.Value != null && (bool)facet.Value;
break;
case "FixedLength":
propertyMap.FixedLength = facet.Value != null && (bool)facet.Value;
break;
case "Precision":
propertyMap.Precision = (byte)facet.Value;
break;
case "Scale":
propertyMap.Scale = (byte)facet.Value;
break;
case "Nullable":
propertyMap.IsRequired = !(bool)facet.Value;
break;
case "DefaultValue":
propertyMap.DefaultValue = facet.Value;
break;
case "StoreGeneratedPattern":
propertyMap.IsIdentity = (StoreGeneratedPattern)facet.Value == StoreGeneratedPattern.Identity;
propertyMap.Computed = (StoreGeneratedPattern)facet.Value == StoreGeneratedPattern.Computed;
break;
case "MaxLength":
if (facet.Value == null)
{
propertyMap.MaxLength = int.MaxValue;
}
else
{
int result;
var val = facet.Value.ToString();
if (!Int32.TryParse(val, out result))
{
if (val == "Max")
{
propertyMap.MaxLength = int.MaxValue;
}
}
propertyMap.MaxLength = result;
}
break;
}
}
}
/// <summary>
///
/// </summary>
public void BindForeignKeys()
{
var fks = _entityMaps.Values.SelectMany(x => x.Fks);
var pks = _entityMaps.Values.SelectMany(x => x.Pks);
// can't use ToDictionary, because tph tables share mappings
var pkDict = new Dictionary<EdmMember, PropertyMap>();
foreach (PropertyMap columnMapping in pks)
{
pkDict[columnMapping.EdmMember] = columnMapping;
}
foreach (PropertyMap fkCol in fks)
{
fkCol.FkTargetColumn = pkDict[fkCol.FkTargetEdmMember];
}
}
}
}
| |
/*
Copyright 2006 - 2010 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.IO;
using System.Net;
using System.Threading;
using System.Collections;
using System.Net.Sockets;
using OpenSource.Utilities;
namespace OpenSource.UPnP
{
/// <summary>
/// An event based AsyncSocket Object
/// </summary>
public sealed class AsyncSocket
{
public class StopReadException : Exception
{
public StopReadException()
: base("User initiated StopRead")
{
}
}
private Thread StopThread = null;
private bool SentDisconnect = false;
public void StopReading()
{
StopThread = Thread.CurrentThread;
}
/// <summary>
/// The number of bytes read
/// </summary>
public int BufferReadLength = 0;
/// <summary>
/// The index to begin reading
/// <para>
/// setting the BeginPointer equal to the BufferSize has
/// the same result as setting it to zero
/// </para>
/// </summary>
public int BufferBeginPointer = 0;
internal int BufferEndPointer = 0;
/// <summary>
/// The size of the data chunk
/// </summary>
public int BufferSize = 0;
private Socket MainSocket;
private IPEndPoint endpoint_local;
private object SendLock;
private AsyncCallback ReceiveCB;
private AsyncCallback SendCB;
private AsyncCallback ConnectCB;
private int PendingBytesSent;
private object CountLock;
private long TotalBytesSent;
private EndPoint rEP;
private Byte[] MainBuffer;
private Queue SendQueue;
public delegate void OnReceiveHandler(AsyncSocket sender, Byte[] buffer, int HeadPointer, int BufferSize, int BytesRead, IPEndPoint source, IPEndPoint remote);
private WeakEvent OnReceiveEvent = new WeakEvent();
/// <summary>
/// This is triggered when there is data to be processed
/// </summary>
public event OnReceiveHandler OnReceive
{
add
{
OnReceiveEvent.Register(value);
}
remove
{
OnReceiveEvent.UnRegister(value);
}
}
public delegate void OnSendReadyHandler(object Tag);
private WeakEvent OnSendReadyEvent = new WeakEvent();
/// <summary>
/// This is triggered when the SendQueue is ready for more
/// </summary>
public event OnSendReadyHandler OnSendReady
{
add
{
OnSendReadyEvent.Register(value);
}
remove
{
OnSendReadyEvent.UnRegister(value);
}
}
public delegate void ConnectHandler(AsyncSocket sender);
private WeakEvent OnConnectEvent = new WeakEvent();
private WeakEvent OnConnectFailedEvent = new WeakEvent();
private WeakEvent OnDisconnectEvent = new WeakEvent();
/// <summary>
/// This is triggered when a Connection attempt was successful
/// </summary>
public event ConnectHandler OnConnect
{
add
{
OnConnectEvent.Register(value);
}
remove
{
OnConnectEvent.UnRegister(value);
}
}
/// <summary>
/// This is triggered when a Connection attempt failed
/// </summary>
public event ConnectHandler OnConnectFailed
{
add
{
OnConnectFailedEvent.Register(value);
}
remove
{
OnConnectFailedEvent.UnRegister(value);
}
}
/// <summary>
/// This is triggered when the underlying socket closed
/// </summary>
public event ConnectHandler OnDisconnect
{
add
{
OnDisconnectEvent.Register(value);
}
remove
{
OnDisconnectEvent.UnRegister(value);
}
}
private EndPoint LocalEP;
private EndPoint RemoteEP;
private Stream _WriteStream = null;
private struct SendInfo
{
public Byte[] buffer;
public int offset;
public int count;
public object Tag;
public IPEndPoint dest;
}
/// <summary>
/// Creates a new AsyncSocket, with a stream object to write to
/// </summary>
/// <param name="WriteStream">The Stream to use</param>
public AsyncSocket(Stream WriteStream)
{
_WriteStream = WriteStream;
MainBuffer = new byte[4096];
}
/// <summary>
/// Creates a new AsyncSocket, with a fixed size buffer to write to
/// </summary>
/// <param name="BufferSize">Size of buffer</param>
public AsyncSocket(int BufferSize)
{
MainBuffer = new byte[BufferSize];
}
/// <summary>
/// Attaches this AsyncSocket to a new Socket instance, using the given info.
/// </summary>
/// <param name="local">Local interface to use</param>
/// <param name="PType">Protocol Type</param>
public void Attach(IPEndPoint local, ProtocolType PType)
{
endpoint_local = local;
TotalBytesSent = 0;
LocalEP = (EndPoint)local;
Init();
MainSocket = null;
if (PType == ProtocolType.Tcp)
{
MainSocket = new Socket(local.AddressFamily, SocketType.Stream, PType);
}
if (PType == ProtocolType.Udp)
{
MainSocket = new Socket(local.AddressFamily, SocketType.Dgram, PType);
MainSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
}
if (MainSocket != null)
{
MainSocket.Bind(local);
System.Reflection.PropertyInfo pi = MainSocket.GetType().GetProperty("UseOnlyOverlappedIO");
if (pi != null)
{
pi.SetValue(MainSocket, true, null);
}
}
else
{
throw (new Exception(PType.ToString() + " not supported"));
}
}
/// <summary>
/// Attach this AsyncSocket to an existing Socket
/// </summary>
/// <param name="UseThisSocket">The Socket</param>
public void Attach(Socket UseThisSocket)
{
endpoint_local = (IPEndPoint)UseThisSocket.LocalEndPoint;
TotalBytesSent = 0;
LocalEP = UseThisSocket.LocalEndPoint;
if (UseThisSocket.SocketType == SocketType.Stream)
{
RemoteEP = UseThisSocket.RemoteEndPoint;
endpoint_local = (IPEndPoint)UseThisSocket.LocalEndPoint;
}
else
{
RemoteEP = null;
}
MainSocket = UseThisSocket;
System.Reflection.PropertyInfo pi = MainSocket.GetType().GetProperty("UseOnlyOverlappedIO");
if (pi != null)
{
pi.SetValue(MainSocket, true, null);
}
Init();
}
public void SetTTL(int TTL)
{
MainSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, TTL);
}
/// <summary>
/// Join a multicast group
/// </summary>
/// <param name="local">Interface to use</param>
/// <param name="MulticastAddress">MulticastAddress to join</param>
public void AddMembership(IPEndPoint local, IPAddress MulticastAddress)
{
try
{
MainSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastLoopback, 1);
}
catch (Exception ex)
{
OpenSource.Utilities.EventLogger.Log(ex);
// This will only fail if the network stack does not support this
// Which means you are probably running Win9x
}
try
{
MainSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(MulticastAddress));
}
catch (Exception ex)
{
OpenSource.Utilities.EventLogger.Log(ex);
OpenSource.Utilities.EventLogger.Log(this, System.Diagnostics.EventLogEntryType.Error, "Cannot AddMembership to IPAddress: " + MulticastAddress.ToString());
}
try
{
MainSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, local.Address.GetAddressBytes());
}
catch (Exception ex)
{
OpenSource.Utilities.EventLogger.Log(ex);
OpenSource.Utilities.EventLogger.Log(this, System.Diagnostics.EventLogEntryType.Error, "Cannot Set Multicast Interface to IPAddress: " + local.Address.ToString());
}
}
/// <summary>
/// Leave a multicast group
/// </summary>
/// <param name="MulticastAddress">Multicast Address to leave</param>
public void DropMembership(IPAddress MulticastAddress)
{
MainSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.DropMembership, new MulticastOption(MulticastAddress));
}
/// <summary>
/// Number of bytes in the send queue pending
/// </summary>
public int Pending
{
get { return (PendingBytesSent); }
}
/// <summary>
/// Total bytes send
/// </summary>
public long Total
{
get { return (TotalBytesSent); }
}
/// <summary>
/// The Local EndPoint
/// </summary>
public EndPoint LocalEndPoint
{
get
{
if (MainSocket.LocalEndPoint != null)
{
return ((IPEndPoint)MainSocket.LocalEndPoint);
}
else
{
return (endpoint_local);
}
}
}
/// <summary>
/// The Remote EndPoint
/// </summary>
public EndPoint RemoteEndPoint
{
get { return (MainSocket.RemoteEndPoint); }
}
/// <summary>
/// Connect to a remote socket
/// </summary>
/// <param name="Remote">IPEndPoint to connect to</param>
public void Connect(IPEndPoint Remote)
{
if (MainSocket.SocketType != SocketType.Stream)
{
throw (new Exception("Cannot connect a non StreamSocket"));
}
System.Reflection.PropertyInfo pi = MainSocket.GetType().GetProperty("UseOnlyOverlappedIO");
if (pi != null)
{
pi.SetValue(MainSocket, true, null);
}
MainSocket.BeginConnect(Remote, ConnectCB, null);
}
private void HandleConnect(IAsyncResult result)
{
bool IsOK = false;
Exception xx;
try
{
MainSocket.EndConnect(result);
IsOK = true;
RemoteEP = MainSocket.RemoteEndPoint;
}
catch (Exception x)
{
OpenSource.Utilities.EventLogger.Log(x);
xx = x;
}
if ((IsOK == true) && (MainSocket.Connected == true))
{
OnConnectEvent.Fire(this);
}
else
{
OnConnectFailedEvent.Fire(this);
}
}
/// <summary>
/// Start AsyncReads
/// </summary>
/// <returns>Successfully started</returns>
public void Begin()
{
bool Disconnect = false;
IPEndPoint src, from;
if (MainSocket.SocketType == SocketType.Stream)
{
from = (IPEndPoint)MainSocket.RemoteEndPoint;
}
else
{
from = (IPEndPoint)rEP;
}
try
{
src = (IPEndPoint)MainSocket.LocalEndPoint;
}
catch (Exception ex)
{
OpenSource.Utilities.EventLogger.Log(ex);
src = new IPEndPoint(IPAddress.Any, 0);
}
while ((BufferBeginPointer != 0) &&
(BufferBeginPointer != BufferEndPointer))
{
Array.Copy(MainBuffer, BufferBeginPointer, MainBuffer, 0, BufferEndPointer - BufferBeginPointer);
BufferEndPointer = BufferEndPointer - BufferBeginPointer;
BufferBeginPointer = 0;
BufferSize = BufferEndPointer;
try
{
OnReceiveEvent.Fire(this, MainBuffer, BufferBeginPointer, BufferSize, 0, src, from);
}
catch (AsyncSocket.StopReadException ex)
{
OpenSource.Utilities.EventLogger.Log(ex);
return;
}
if (StopThread != null)
{
if (Thread.CurrentThread.GetHashCode() == StopThread.GetHashCode())
{
StopThread = null;
return;
}
}
}
try
{
if (MainSocket.SocketType == SocketType.Stream)
{
MainSocket.BeginReceive(MainBuffer, BufferEndPointer, BufferReadLength, SocketFlags.None, ReceiveCB, null);
}
else
{
MainSocket.BeginReceiveFrom(MainBuffer, BufferEndPointer, BufferReadLength, SocketFlags.None, ref rEP, ReceiveCB, null);
}
}
catch (Exception ex)
{
OpenSource.Utilities.EventLogger.Log(ex);
Disconnect = true;
}
if (Disconnect == true)
{
bool OK = false;
lock (this)
{
if (SentDisconnect == false)
{
OK = true;
SentDisconnect = true;
}
}
if (OK == true)
{
MainSocket = null;
}
if (Disconnect == true && OK == true) OnDisconnectEvent.Fire(this);
}
}
private void Init()
{
BufferReadLength = MainBuffer.Length;
CountLock = new object();
PendingBytesSent = 0;
SendLock = new object();
SendQueue = new Queue();
ReceiveCB = new AsyncCallback(HandleReceive);
SendCB = new AsyncCallback(HandleSend);
ConnectCB = new AsyncCallback(HandleConnect);
rEP = (EndPoint)new IPEndPoint(0, 0);
}
/// <summary>
/// Closes the socket
/// </summary>
public void Close()
{
//SendLock.WaitOne();
//SendResult = null;
//SendLock.ReleaseMutex();
if (MainSocket != null)
{
try
{
MainSocket.Shutdown(SocketShutdown.Both);
MainSocket.Close();
}
catch (Exception ex)
{
OpenSource.Utilities.EventLogger.Log(ex);
}
}
}
/*
public bool Sync_Send(byte[] buffer)
{
return Sync_Send(buffer, 0, buffer.Length);
}
public bool Sync_Send(byte[] buffer, int offset, int count)
{
if (MainSocket == null) return false;
try
{
MainSocket.Send(buffer, offset, count, SocketFlags.None);
return true;
}
catch (Exception e)
{
OpenSource.Utilities.EventLogger.Log(e);
return false;
}
}
*/
/// <summary>
/// Asynchronously send bytes
/// </summary>
/// <param name="buffer"></param>
public void Send(Byte[] buffer)
{
Send(buffer, null);
}
/// <summary>
/// Asynchronously send bytes
/// </summary>
/// <param name="buffer"></param>
/// <param name="Tag"></param>
public void Send(Byte[] buffer, object Tag)
{
Send(buffer, 0, buffer.Length, Tag);
}
/// <summary>
/// Asyncronously send bytes
/// </summary>
/// <param name="buffer"></param>
/// <param name="offset"></param>
/// <param name="length"></param>
/// <param name="Tag"></param>
public void Send(Byte[] buffer, int offset, int length, object Tag)
{
Send(buffer, offset, length, null, Tag);
}
public void Send(Byte[] buffer, int offset, int length, IPEndPoint dest)
{
Send(buffer, offset, length, dest, null);
}
/// <summary>
/// Asynchronously send a UDP payload
/// </summary>
/// <param name="buffer"></param>
/// <param name="offset"></param>
/// <param name="length"></param>
/// <param name="dest"></param>
/// <param name="Tag"></param>
public void Send(Byte[] buffer, int offset, int length, IPEndPoint dest, object Tag)
{
bool Disconnect = false;
SendInfo SI;
lock (SendLock)
{
lock (CountLock)
{
if (PendingBytesSent > 0)
{
SI = new SendInfo();
SI.buffer = buffer;
SI.offset = offset;
SI.count = length;
SI.dest = dest;
SI.Tag = Tag;
SendQueue.Enqueue(SI);
}
else
{
PendingBytesSent += length;
try
{
if (MainSocket.SocketType == SocketType.Stream)
{
MainSocket.BeginSend(buffer, offset, length, SocketFlags.None, SendCB, Tag);
}
else
{
MainSocket.BeginSendTo(buffer, offset, length, SocketFlags.None, dest, SendCB, Tag);
}
}
catch (Exception ex)
{
OpenSource.Utilities.EventLogger.Log(ex);
OpenSource.Utilities.EventLogger.Log(this, System.Diagnostics.EventLogEntryType.Error, "Send Failure [Normal for non-pipelined connection]");
Disconnect = true;
}
}
}
}
if (Disconnect == true)
{
bool OK = false;
lock (this)
{
if (SentDisconnect == false)
{
OK = true;
SentDisconnect = true;
}
}
if (OK == true)
{
this.MainSocket = null;
OnDisconnectEvent.Fire(this);
}
}
}
private void HandleSend(IAsyncResult result)
{
int sent = 0;
bool Ready = false;
bool Disconnect = false;
try
{
SendInfo SI;
lock (SendLock)
{
if (null != MainSocket)
{
try
{
if (MainSocket.SocketType == SocketType.Stream)
{
sent = MainSocket.EndSend(result);
}
else
{
sent = MainSocket.EndSendTo(result);
}
}
catch (Exception ex)
{
OpenSource.Utilities.EventLogger.Log(ex);
Disconnect = true;
}
lock (CountLock)
{
PendingBytesSent -= sent;
TotalBytesSent += sent;
}
if (SendQueue.Count > 0)
{
SI = (SendInfo)SendQueue.Dequeue();
try
{
if (MainSocket.SocketType == SocketType.Stream)
{
MainSocket.BeginSend(SI.buffer, SI.offset, SI.count, SocketFlags.None, SendCB, SI.Tag);
}
else
{
MainSocket.BeginSendTo(SI.buffer, SI.offset, SI.count, SocketFlags.None, SI.dest, SendCB, SI.Tag);
}
}
catch (Exception ex)
{
OpenSource.Utilities.EventLogger.Log(ex);
OpenSource.Utilities.EventLogger.Log(this, System.Diagnostics.EventLogEntryType.Error, "Send Failure [Normal for non-pipelined connection]");
Disconnect = true;
}
}
else
{
Ready = true;
}
}
else
{
OpenSource.Utilities.EventLogger.Log(this, System.Diagnostics.EventLogEntryType.Warning, "Socket closed while waiting to send to "+RemoteEP.ToString());
Disconnect = true;
}
}
if (Disconnect == true)
{
bool OK = false;
lock (this)
{
if (SentDisconnect == false)
{
OK = true;
SentDisconnect = true;
}
}
if (OK == true)
{
MainSocket = null;
}
if (OK == true) OnDisconnectEvent.Fire(this);
}
else
{
if (Ready == true)
{
OnSendReadyEvent.Fire(result.AsyncState);
}
}
}
catch (Exception ex)
{
OpenSource.Utilities.EventLogger.Log(ex);
}
}
private void HandleReceive(IAsyncResult result)
{
int BytesReceived = 0;
IPEndPoint from;
IPEndPoint src;
bool Disconnect = false;
try
{
if (MainSocket.SocketType == SocketType.Stream)
{
from = (IPEndPoint)MainSocket.RemoteEndPoint;
BytesReceived = MainSocket.EndReceive(result);
}
else
{
BytesReceived = MainSocket.EndReceiveFrom(result, ref rEP);
from = (IPEndPoint)rEP;
}
}
catch (Exception ex)
{
// Socket Error
bool _OK = false;
OpenSource.Utilities.EventLogger.Log(ex);
lock (this)
{
if (SentDisconnect == false)
{
_OK = true;
SentDisconnect = true;
}
}
if (_OK == true)
{
MainSocket = null;
}
if (_OK == true) OnDisconnectEvent.Fire(this);
return;
}
// OpenSource.Utilities.EventLogger.Log(this,System.Diagnostics.EventLogEntryType.Information,"BytesRead: " + BytesReceived.ToString() + " BytesRequested: "+this.BufferReadLength.ToString());
if (BytesReceived <= 0)
{
Disconnect = true;
}
if (BytesReceived != 0)
{
try
{
src = (IPEndPoint)MainSocket.LocalEndPoint;
}
catch (Exception ex)
{
OpenSource.Utilities.EventLogger.Log(ex);
src = new IPEndPoint(IPAddress.Any, 0);
}
BufferEndPointer += BytesReceived;
BufferSize = BufferEndPointer - BufferBeginPointer;
BufferReadLength = MainBuffer.Length - BufferEndPointer;
if (_WriteStream == null)
{
try
{
OnReceiveEvent.Fire(this, MainBuffer, BufferBeginPointer, BufferSize, BytesReceived, src, from);
}
catch (AsyncSocket.StopReadException ex)
{
OpenSource.Utilities.EventLogger.Log(ex);
return;
}
}
else
{
_WriteStream.Write(MainBuffer, 0, BytesReceived);
BufferBeginPointer = BufferEndPointer;
BufferReadLength = MainBuffer.Length;
}
while ((BufferBeginPointer != 0) &&
(BufferBeginPointer != BufferEndPointer))
{
Array.Copy(MainBuffer, BufferBeginPointer, MainBuffer, 0, BufferEndPointer - BufferBeginPointer);
BufferEndPointer = BufferEndPointer - BufferBeginPointer;
BufferBeginPointer = 0;
BufferSize = BufferEndPointer;
try
{
OnReceiveEvent.Fire(this, MainBuffer, BufferBeginPointer, BufferSize, 0, src, from);
}
catch (AsyncSocket.StopReadException ex)
{
OpenSource.Utilities.EventLogger.Log(ex);
return;
}
if (StopThread != null)
{
if (Thread.CurrentThread.GetHashCode() == StopThread.GetHashCode())
{
StopThread = null;
return;
}
}
}
if (BufferBeginPointer == BufferEndPointer)
{
// ResetBuffer then continue reading
BufferBeginPointer = 0;
BufferEndPointer = 0;
}
if (StopThread != null)
{
if (Thread.CurrentThread.GetHashCode() == StopThread.GetHashCode())
{
StopThread = null;
return;
}
}
try
{
if (MainSocket != null && MainSocket.Connected)
{
if (MainSocket.SocketType == SocketType.Stream)
{
MainSocket.BeginReceive(MainBuffer, BufferEndPointer, BufferReadLength, SocketFlags.None, ReceiveCB, MainSocket);
}
else
{
MainSocket.BeginReceiveFrom(MainBuffer, BufferEndPointer, BufferReadLength, SocketFlags.None, ref rEP, ReceiveCB, MainSocket);
}
}
else
{
Disconnect = true;
}
}
catch (Exception ex)
{
OpenSource.Utilities.EventLogger.Log(ex);
Disconnect = true;
}
}
if (Disconnect == true)
{
bool OK = false;
lock (this)
{
if (SentDisconnect == false)
{
OK = true;
SentDisconnect = true;
}
}
if (OK == true)
{
MainSocket = null;
}
if (Disconnect == true && OK == true) OnDisconnectEvent.Fire(this);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Reflection;
using System.IO;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
namespace System.Text
{
// Our input file data structures look like:
//
// Header structure looks like:
// struct NLSPlusHeader
// {
// WORD[16] filename; // 32 bytes
// WORD[4] version; // 8 bytes = 40 // e.g.: 3, 2, 0, 0
// WORD count; // 2 bytes = 42 // Number of code page indexes that will follow
// }
//
// Each code page section looks like:
// struct NLSCodePageIndex
// {
// WORD[16] codePageName; // 32 bytes
// WORD codePage; // +2 bytes = 34
// WORD byteCount; // +2 bytes = 36
// DWORD offset; // +4 bytes = 40 // Bytes from beginning of FILE.
// }
//
// Each code page then has its own header
// struct NLSCodePage
// {
// WORD[16] codePageName; // 32 bytes
// WORD[4] version; // 8 bytes = 40 // e.g.: 3.2.0.0
// WORD codePage; // 2 bytes = 42
// WORD byteCount; // 2 bytes = 44 // 1 or 2 byte code page (SBCS or DBCS)
// WORD unicodeReplace; // 2 bytes = 46 // default replacement unicode character
// WORD byteReplace; // 2 bytes = 48 // default replacement byte(s)
// BYTE[] data; // data section
// }
internal abstract class BaseCodePageEncoding : EncodingNLS
{
internal const String CODE_PAGE_DATA_FILE_NAME = "codepages.nlp";
protected int dataTableCodePage;
// Variables to help us allocate/mark our memory section correctly
protected int iExtraBytes = 0;
// Our private unicode-to-bytes best-fit-array, and vice versa.
protected char[] arrayUnicodeBestFit = null;
protected char[] arrayBytesBestFit = null;
[System.Security.SecuritySafeCritical] // static constructors should be safe to call
static BaseCodePageEncoding()
{
}
[System.Security.SecurityCritical] // auto-generated
internal BaseCodePageEncoding(int codepage)
: this(codepage, codepage)
{
}
[System.Security.SecurityCritical] // auto-generated
internal BaseCodePageEncoding(int codepage, int dataCodePage)
: base(codepage, new InternalEncoderBestFitFallback(null), new InternalDecoderBestFitFallback(null))
{
SetFallbackEncoding();
// Remember number of code pagess that we'll be using the table for.
dataTableCodePage = dataCodePage;
LoadCodePageTables();
}
internal BaseCodePageEncoding(int codepage, int dataCodePage, EncoderFallback enc, DecoderFallback dec)
: base(codepage, enc, dec)
{
// Remember number of code pages that we'll be using the table for.
dataTableCodePage = dataCodePage;
LoadCodePageTables();
}
// Just a helper as we cannot use 'this' when calling 'base(...)'
private void SetFallbackEncoding()
{
(EncoderFallback as InternalEncoderBestFitFallback).encoding = this;
(DecoderFallback as InternalDecoderBestFitFallback).encoding = this;
}
//
// This is the header for the native data table that we load from CODE_PAGE_DATA_FILE_NAME.
//
// Explicit layout is used here since a syntax like char[16] can not be used in sequential layout.
[StructLayout(LayoutKind.Explicit)]
internal struct CodePageDataFileHeader
{
[FieldOffset(0)]
internal char TableName; // WORD[16]
[FieldOffset(0x20)]
internal ushort Version; // WORD[4]
[FieldOffset(0x28)]
internal short CodePageCount; // WORD
[FieldOffset(0x2A)]
internal short unused1; // Add an unused WORD so that CodePages is aligned with DWORD boundary.
}
private const int CODEPAGE_DATA_FILE_HEADER_SIZE = 44;
[StructLayout(LayoutKind.Explicit, Pack = 2)]
internal unsafe struct CodePageIndex
{
[FieldOffset(0)]
internal char CodePageName; // WORD[16]
[FieldOffset(0x20)]
internal short CodePage; // WORD
[FieldOffset(0x22)]
internal short ByteCount; // WORD
[FieldOffset(0x24)]
internal int Offset; // DWORD
}
[StructLayout(LayoutKind.Explicit)]
internal unsafe struct CodePageHeader
{
[FieldOffset(0)]
internal char CodePageName; // WORD[16]
[FieldOffset(0x20)]
internal ushort VersionMajor; // WORD
[FieldOffset(0x22)]
internal ushort VersionMinor; // WORD
[FieldOffset(0x24)]
internal ushort VersionRevision;// WORD
[FieldOffset(0x26)]
internal ushort VersionBuild; // WORD
[FieldOffset(0x28)]
internal short CodePage; // WORD
[FieldOffset(0x2a)]
internal short ByteCount; // WORD // 1 or 2 byte code page (SBCS or DBCS)
[FieldOffset(0x2c)]
internal char UnicodeReplace; // WORD // default replacement unicode character
[FieldOffset(0x2e)]
internal ushort ByteReplace; // WORD // default replacement bytes
}
private const int CODEPAGE_HEADER_SIZE = 48;
// Initialize our global stuff
private static byte[] s_codePagesDataHeader = new byte[CODEPAGE_DATA_FILE_HEADER_SIZE];
protected static Stream s_codePagesEncodingDataStream = GetEncodingDataStream(CODE_PAGE_DATA_FILE_NAME);
protected static readonly Object s_streamLock = new Object(); // this lock used when reading from s_codePagesEncodingDataStream
// Real variables
protected byte[] m_codePageHeader = new byte[CODEPAGE_HEADER_SIZE];
protected int m_firstDataWordOffset;
protected int m_dataSize;
// Safe handle wrapper around section map view
[System.Security.SecurityCritical] // auto-generated
protected SafeAllocHHandle safeNativeMemoryHandle = null;
internal static Stream GetEncodingDataStream(String tableName)
{
Debug.Assert(tableName != null, "table name can not be null");
// NOTE: We must reflect on a public type that is exposed in the contract here
// (i.e. CodePagesEncodingProvider), otherwise we will not get a reference to
// the right assembly.
Stream stream = typeof(CodePagesEncodingProvider).GetTypeInfo().Assembly.GetManifestResourceStream(tableName);
if (stream == null)
{
// We can not continue if we can't get the resource.
throw new InvalidOperationException();
}
// Read the header
stream.Read(s_codePagesDataHeader, 0, s_codePagesDataHeader.Length);
return stream;
}
// We need to load tables for our code page
[System.Security.SecurityCritical] // auto-generated
private unsafe void LoadCodePageTables()
{
if (!FindCodePage(dataTableCodePage))
{
// Didn't have one
throw new NotSupportedException(SR.Format(SR.NotSupported_NoCodepageData, CodePage));
}
// We had it, so load it
LoadManagedCodePage();
}
// Look up the code page pointer
[System.Security.SecurityCritical] // auto-generated
private unsafe bool FindCodePage(int codePage)
{
Debug.Assert(m_codePageHeader != null && m_codePageHeader.Length == CODEPAGE_HEADER_SIZE, "m_codePageHeader expected to match in size the struct CodePageHeader");
// Loop through all of the m_pCodePageIndex[] items to find our code page
byte[] codePageIndex = new byte[sizeof(CodePageIndex)];
lock (s_streamLock)
{
// seek to the first CodePageIndex entry
s_codePagesEncodingDataStream.Seek(CODEPAGE_DATA_FILE_HEADER_SIZE, SeekOrigin.Begin);
int codePagesCount;
fixed (byte* pBytes = s_codePagesDataHeader)
{
CodePageDataFileHeader* pDataHeader = (CodePageDataFileHeader*)pBytes;
codePagesCount = pDataHeader->CodePageCount;
}
fixed (byte* pBytes = codePageIndex)
{
CodePageIndex* pCodePageIndex = (CodePageIndex*)pBytes;
for (int i = 0; i < codePagesCount; i++)
{
s_codePagesEncodingDataStream.Read(codePageIndex, 0, codePageIndex.Length);
if (pCodePageIndex->CodePage == codePage)
{
// Found it!
long position = s_codePagesEncodingDataStream.Position;
s_codePagesEncodingDataStream.Seek((long)pCodePageIndex->Offset, SeekOrigin.Begin);
s_codePagesEncodingDataStream.Read(m_codePageHeader, 0, m_codePageHeader.Length);
m_firstDataWordOffset = (int)s_codePagesEncodingDataStream.Position; // stream now pointing to the codepage data
if (i == codePagesCount - 1) // last codepage
{
m_dataSize = (int)(s_codePagesEncodingDataStream.Length - pCodePageIndex->Offset - m_codePageHeader.Length);
}
else
{
// Read Next codepage data to get the offset and then calculate the size
s_codePagesEncodingDataStream.Seek(position, SeekOrigin.Begin);
int currentOffset = pCodePageIndex->Offset;
s_codePagesEncodingDataStream.Read(codePageIndex, 0, codePageIndex.Length);
m_dataSize = pCodePageIndex->Offset - currentOffset - m_codePageHeader.Length;
}
return true;
}
}
}
}
// Couldn't find it
return false;
}
// Get our code page byte count
[System.Security.SecurityCritical] // auto-generated
internal static unsafe int GetCodePageByteSize(int codePage)
{
// Loop through all of the m_pCodePageIndex[] items to find our code page
byte[] codePageIndex = new byte[sizeof(CodePageIndex)];
lock (s_streamLock)
{
// seek to the first CodePageIndex entry
s_codePagesEncodingDataStream.Seek(CODEPAGE_DATA_FILE_HEADER_SIZE, SeekOrigin.Begin);
int codePagesCount;
fixed (byte* pBytes = s_codePagesDataHeader)
{
CodePageDataFileHeader* pDataHeader = (CodePageDataFileHeader*)pBytes;
codePagesCount = pDataHeader->CodePageCount;
}
fixed (byte* pBytes = codePageIndex)
{
CodePageIndex* pCodePageIndex = (CodePageIndex*)pBytes;
for (int i = 0; i < codePagesCount; i++)
{
s_codePagesEncodingDataStream.Read(codePageIndex, 0, codePageIndex.Length);
if (pCodePageIndex->CodePage == codePage)
{
Debug.Assert(pCodePageIndex->ByteCount == 1 || pCodePageIndex->ByteCount == 2,
"[BaseCodePageEncoding] Code page (" + codePage + ") has invalid byte size (" + pCodePageIndex->ByteCount + ") in table");
// Return what it says for byte count
return pCodePageIndex->ByteCount;
}
}
}
}
// Couldn't find it
return 0;
}
// We have a managed code page entry, so load our tables
[System.Security.SecurityCritical]
protected abstract unsafe void LoadManagedCodePage();
// Allocate memory to load our code page
[System.Security.SecurityCritical] // auto-generated
protected unsafe byte* GetNativeMemory(int iSize)
{
if (safeNativeMemoryHandle == null)
{
byte* pNativeMemory = (byte*)Marshal.AllocHGlobal(iSize);
Debug.Assert(pNativeMemory != null);
safeNativeMemoryHandle = new SafeAllocHHandle((IntPtr)pNativeMemory);
}
return (byte*)safeNativeMemoryHandle.DangerousGetHandle();
}
[System.Security.SecurityCritical]
protected abstract unsafe void ReadBestFitTable();
[System.Security.SecuritySafeCritical]
internal char[] GetBestFitUnicodeToBytesData()
{
// Read in our best fit table if necessary
if (arrayUnicodeBestFit == null) ReadBestFitTable();
Debug.Assert(arrayUnicodeBestFit != null, "[BaseCodePageEncoding.GetBestFitUnicodeToBytesData]Expected non-null arrayUnicodeBestFit");
// Normally we don't have any best fit data.
return arrayUnicodeBestFit;
}
[System.Security.SecuritySafeCritical]
internal char[] GetBestFitBytesToUnicodeData()
{
// Read in our best fit table if necessary
if (arrayBytesBestFit == null) ReadBestFitTable();
Debug.Assert(arrayBytesBestFit != null, "[BaseCodePageEncoding.GetBestFitBytesToUnicodeData]Expected non-null arrayBytesBestFit");
// Normally we don't have any best fit data.
return arrayBytesBestFit;
}
// During the AppDomain shutdown the Encoding class may have already finalized, making the memory section
// invalid. We detect that by validating the memory section handle then re-initializing the memory
// section by calling LoadManagedCodePage() method and eventually the mapped file handle and
// the memory section pointer will get finalized one more time.
[System.Security.SecurityCritical] // auto-generated
internal unsafe void CheckMemorySection()
{
if (safeNativeMemoryHandle != null && safeNativeMemoryHandle.DangerousGetHandle() == IntPtr.Zero)
{
LoadManagedCodePage();
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Threading;
using Microsoft.Research.Joins;
using Microsoft.Research.Joins.Patterns;
using Microsoft.Research.Joins.BitMasks;
using Microsoft.Research.Joins.Paper.Bag;
namespace Microsoft.Research.Joins.Paper {
internal partial class Join<IntSet, MsgArray> {
#warning "this might be faster if it wasn't an interface method"
#region TryClaim
partial class Chord<A,R> {
//++ Chan[] Chans; // channels in this chord, ordered by channel id.
internal override
// try to claim enough messages -- including myMsg -- to fire
bool TryClaim(ref MsgArray claims, Chan myChan, Msg myMsg,
out bool sawClaimed) {
sawClaimed = false;
// first locate enough pending messages to fire the chord
foreach (var chan in Chans)
if (chan == myChan) claims[chan.id] = myMsg;
else {
Msg msg = chan.FindPendingMsg(out sawClaimed);
if (msg.IsNull) return false;
claims[chan.id] = msg;
}
#if true
// now try to claim the messages we found
foreach (var chan in Chans) {
if (!claims[chan.id].TryClaim()) {
// another thread got a message before we did; revert
foreach(var claimed in Chans) {
if (claimed == chan) break;
var claim = claims[claimed.id];
claim.Status = Stat.PENDING;
}
sawClaimed = true; // there may be CLAIMED messages
return false;
}
} // success: each chan, claims[chan.id].Status == Stat.CLAIMED
#else
// now try to claim the messages we found
for(int i = 0; i < Chans.Length; i++)
{
var chan = Chans[i];
if (!claims[chan.id].TryClaim())
{
// another thread got a message before we did; revert
for (int j = i - 1; j >= 0; j--)
{ var claimed = Chans[j];
var claim = claims[claimed.id];
claim.Status = Stat.PENDING;
}
sawClaimed = true; // there may be CLAIMED messages
return false;
}
} // success: each chan, claims[chan.id].Status == Stat.CLAIMED
#endif
return true;
}
}
#endregion TryClaim
}
internal partial class Join<IntSet, MsgArray> {
static Chan ChannelOf(Msg msg) {
// Debug.Assert(!msg.IsNull);
#warning "TODO: remove this cast by making msg.Chan strongly typed (SegmentedBag must be nested)"
return (Chan)msg.Chan();
}
}
internal
#region Resolve
partial class Join<IntSet,MsgArray> {
// resolves myMsg, which was already added to its channel's bag.
// returns null: if no chord is firable or myMsg is consumed
// o/w : a firable chord and sufficient claimed messages in claims
static Chord Resolve(ref MsgArray claims, Chan chan, Msg myMsg) {
var backoff = new Backoff();
while (true) {
bool retry = false, sawClaimed;
foreach (var chord in chan.Chords) {
if (chord.TryClaim(ref claims, chan, myMsg, out sawClaimed))
return chord;
retry |= sawClaimed;
}
if (!retry || myMsg.IsConsumed
|| myMsg.IsWoken) return null;
backoff.Once();
}
}
}
#endregion Resolve
#region Send
partial class Join<IntSet,MsgArray> {
static void AsyncSend<A>(Chan<A> chan, A a) {
HandleAsyncMsg(chan, chan.AddPendingMsg(a));
}
// resolve myMsg (which is asynchronous) and respond accordingly
static void HandleAsyncMsg(Chan myChan, Msg myMsg) {
MsgArray claims = new MsgArray();
var chord = Resolve(ref claims, myChan, myMsg);
if (chord == null) return; // no chord to fire; nothing to do
if (chord.IsAsync) { // completely asynchronous chord
foreach (var ch in chord.Chans) claims[ch.id].Consume();
chord.FireAsync(ref claims); // fire in a new thread!
}
else { // synchronous chord: wake a synchronous waiter
bool foundSleeper = false;
foreach (var chan in chord.Chans) {
var claim = claims[chan.id];
if (chan.IsSync && !foundSleeper) {
foundSleeper = true;
claim.AsyncWaker = myMsg; // transfer responsibility
claim.Status = Stat.WOKEN;
claim.Signal.Set();
}
else claim.Status = Stat.PENDING; // relinquish message
}
}
}
// create a message with payload a, and block until chord fired
static R SyncSend<R, A>(Chan<A> chan, A a, bool fastpath) {
MsgArray claims = new MsgArray();
Msg waker = Msg.Null;
Chord chord = (fastpath) ? FastPath(ref claims, chan, a) : null;
if (chord == null) {
var backoff = new Backoff();
Msg myMsg = chan.AddPendingMsg(a);
while (true) {
chord = Resolve(ref claims, chan, myMsg);
if (chord != null) break; // claimed a chord; break to fire
if (!waker.IsNull) // resend our last async waker
RetryAsync(waker);
myMsg.Signal.Block(chan.SpinCount);
if (myMsg.IsConsumed) // rendezvous: chord already fired
return myMsg.GetResult<R>();
waker = myMsg.AsyncWaker; // record waker to retry later
myMsg.Status = Stat.PENDING;
backoff.Once();
}
}
// consume all claims
foreach (var ch in chord.Chans) claims[ch.id].Consume();
if (!waker.IsNull) // resend our last async waker
RetryAsync(waker); // *after* consuming our own message
try {
R r = chord.FireSync<R>(ref claims);
foreach (var other in chord.Chans)
if (other.IsSync && other != chan) {// synchronous rendezvous
claims[other.id].SetResult(r); // transfer computed result
claims[other.id].Signal.Set();
}
return r;
}
catch (Exception e) {
foreach (var other in chord.Chans)
if (other.IsSync && other != chan) {// synchronous rendezvous
claims[other.id].SetException(e); // transfer computed exception
claims[other.id].Signal.Set();
}
throw;
}
}
static void RetryAsync(Msg myMsg) {
if (!myMsg.IsConsumed) HandleAsyncMsg(ChannelOf(myMsg),myMsg);
}
static Chord FastPath<A>(ref MsgArray claims, Chan<A> chan, A a) {
var chord = Resolve(ref claims, chan, Msg.Null);
if (chord != null) ThreadStatic<A>.Value = a;
return chord;
}
}
#endregion Send
partial class Join<IntSet,MsgArray> {
#region Fastpath
#endregion Fastpath
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics.Contracts;
using System.Diagnostics;
namespace System.IO.Compression
{
internal class WrappedStream : Stream
{
#region fields
private readonly Stream _baseStream;
private readonly Boolean _closeBaseStream;
// Delegate that will be invoked on stream disposing
private readonly Action<ZipArchiveEntry> _onClosed;
// Instance that will be passed to _onClose delegate
private readonly ZipArchiveEntry _zipArchiveEntry;
private Boolean _isDisposed;
#endregion
#region constructors
internal WrappedStream(Stream baseStream, Boolean closeBaseStream)
: this(baseStream, closeBaseStream, null, null)
{ }
private WrappedStream(Stream baseStream, Boolean closeBaseStream, ZipArchiveEntry entry, Action<ZipArchiveEntry> onClosed)
{
_baseStream = baseStream;
_closeBaseStream = closeBaseStream;
_onClosed = onClosed;
_zipArchiveEntry = entry;
_isDisposed = false;
}
internal WrappedStream(Stream baseStream, ZipArchiveEntry entry, Action<ZipArchiveEntry> onClosed)
: this(baseStream, false, entry, onClosed)
{ }
#endregion
#region properties
public override long Length
{
get
{
ThrowIfDisposed();
return _baseStream.Length;
}
}
public override long Position
{
get
{
ThrowIfDisposed();
return _baseStream.Position;
}
set
{
ThrowIfDisposed();
ThrowIfCantSeek();
_baseStream.Position = value;
}
}
public override bool CanRead { get { return !_isDisposed && _baseStream.CanRead; } }
public override bool CanSeek { get { return !_isDisposed && _baseStream.CanSeek; } }
public override bool CanWrite { get { return !_isDisposed && _baseStream.CanWrite; } }
#endregion
#region methods
private void ThrowIfDisposed()
{
if (_isDisposed)
throw new ObjectDisposedException(this.GetType().ToString(), SR.HiddenStreamName);
}
private void ThrowIfCantRead()
{
if (!CanRead)
throw new NotSupportedException(SR.ReadingNotSupported);
}
private void ThrowIfCantWrite()
{
if (!CanWrite)
throw new NotSupportedException(SR.WritingNotSupported);
}
private void ThrowIfCantSeek()
{
if (!CanSeek)
throw new NotSupportedException(SR.SeekingNotSupported);
}
public override int Read(byte[] buffer, int offset, int count)
{
ThrowIfDisposed();
ThrowIfCantRead();
return _baseStream.Read(buffer, offset, count);
}
public override long Seek(long offset, SeekOrigin origin)
{
ThrowIfDisposed();
ThrowIfCantSeek();
return _baseStream.Seek(offset, origin);
}
public override void SetLength(long value)
{
ThrowIfDisposed();
ThrowIfCantSeek();
ThrowIfCantWrite();
_baseStream.SetLength(value);
}
public override void Write(byte[] buffer, int offset, int count)
{
ThrowIfDisposed();
ThrowIfCantWrite();
_baseStream.Write(buffer, offset, count);
}
public override void Flush()
{
ThrowIfDisposed();
ThrowIfCantWrite();
_baseStream.Flush();
}
protected override void Dispose(bool disposing)
{
if (disposing && !_isDisposed)
{
if (_onClosed != null)
_onClosed(_zipArchiveEntry);
if (_closeBaseStream)
_baseStream.Dispose();
_isDisposed = true;
}
base.Dispose(disposing);
}
#endregion
}
internal class SubReadStream : Stream
{
#region fields
private readonly long _startInSuperStream;
private long _positionInSuperStream;
private readonly long _endInSuperStream;
private readonly Stream _superStream;
private Boolean _canRead;
private Boolean _isDisposed;
#endregion
#region constructors
public SubReadStream(Stream superStream, long startPosition, long maxLength)
{
_startInSuperStream = startPosition;
_positionInSuperStream = startPosition;
_endInSuperStream = startPosition + maxLength;
_superStream = superStream;
_canRead = true;
_isDisposed = false;
}
#endregion
#region properties
public override long Length
{
get
{
Contract.Ensures(Contract.Result<Int64>() >= 0);
ThrowIfDisposed();
return _endInSuperStream - _startInSuperStream;
}
}
public override long Position
{
get
{
Contract.Ensures(Contract.Result<Int64>() >= 0);
ThrowIfDisposed();
return _positionInSuperStream - _startInSuperStream;
}
set
{
ThrowIfDisposed();
throw new NotSupportedException(SR.SeekingNotSupported);
}
}
public override bool CanRead { get { return _superStream.CanRead && _canRead; } }
public override bool CanSeek { get { return false; } }
public override bool CanWrite { get { return false; } }
#endregion
#region methods
private void ThrowIfDisposed()
{
if (_isDisposed)
throw new ObjectDisposedException(this.GetType().ToString(), SR.HiddenStreamName);
}
private void ThrowIfCantRead()
{
if (!CanRead)
throw new NotSupportedException(SR.ReadingNotSupported);
}
public override int Read(byte[] buffer, int offset, int count)
{
//parameter validation sent to _superStream.Read
int origCount = count;
ThrowIfDisposed();
ThrowIfCantRead();
if (_superStream.Position != _positionInSuperStream)
_superStream.Seek(_positionInSuperStream, SeekOrigin.Begin);
if (_positionInSuperStream + count > _endInSuperStream)
count = (int)(_endInSuperStream - _positionInSuperStream);
Debug.Assert(count >= 0);
Debug.Assert(count <= origCount);
int ret = _superStream.Read(buffer, offset, count);
_positionInSuperStream += ret;
return ret;
}
public override long Seek(long offset, SeekOrigin origin)
{
ThrowIfDisposed();
throw new NotSupportedException(SR.SeekingNotSupported);
}
public override void SetLength(long value)
{
ThrowIfDisposed();
throw new NotSupportedException(SR.SetLengthRequiresSeekingAndWriting);
}
public override void Write(byte[] buffer, int offset, int count)
{
ThrowIfDisposed();
throw new NotSupportedException(SR.WritingNotSupported);
}
public override void Flush()
{
ThrowIfDisposed();
throw new NotSupportedException(SR.WritingNotSupported);
}
// Close the stream for reading. Note that this does NOT close the superStream (since
// the substream is just 'a chunk' of the super-stream
protected override void Dispose(bool disposing)
{
if (disposing && !_isDisposed)
{
_canRead = false;
_isDisposed = true;
}
base.Dispose(disposing);
}
#endregion
}
internal class CheckSumAndSizeWriteStream : Stream
{
#region fields
private readonly Stream _baseStream;
private readonly Stream _baseBaseStream;
private Int64 _position;
private UInt32 _checksum;
private readonly Boolean _leaveOpenOnClose;
private Boolean _canWrite;
private Boolean _isDisposed;
private Boolean _everWritten;
//this is the position in BaseBaseStream
private Int64 _initialPosition;
private readonly ZipArchiveEntry _zipArchiveEntry;
private readonly EventHandler _onClose;
// Called when the stream is closed.
// parameters are initialPosition, currentPosition, checkSum, baseBaseStream, zipArchiveEntry and onClose handler
private readonly Action<Int64, Int64, UInt32, Stream, ZipArchiveEntry, EventHandler> _saveCrcAndSizes;
#endregion
#region constructors
/* parameters to saveCrcAndSizes are
* initialPosition (initialPosition in baseBaseStream),
* currentPosition (in this CheckSumAndSizeWriteStream),
* checkSum (of data passed into this CheckSumAndSizeWriteStream),
* baseBaseStream it's a backingStream, passed here so as to avoid closure allocation,
* zipArchiveEntry passed here so as to avoid closure allocation,
* onClose handler passed here so as to avoid closure allocation
*/
public CheckSumAndSizeWriteStream(Stream baseStream, Stream baseBaseStream, Boolean leaveOpenOnClose,
ZipArchiveEntry entry, EventHandler onClose,
Action<Int64, Int64, UInt32, Stream, ZipArchiveEntry, EventHandler> saveCrcAndSizes)
{
_baseStream = baseStream;
_baseBaseStream = baseBaseStream;
_position = 0;
_checksum = 0;
_leaveOpenOnClose = leaveOpenOnClose;
_canWrite = true;
_isDisposed = false;
_initialPosition = 0;
_zipArchiveEntry = entry;
_onClose = onClose;
_saveCrcAndSizes = saveCrcAndSizes;
}
#endregion
#region properties
public override Int64 Length
{
get
{
ThrowIfDisposed();
throw new NotSupportedException(SR.SeekingNotSupported);
}
}
public override Int64 Position
{
get
{
Contract.Ensures(Contract.Result<Int64>() >= 0);
ThrowIfDisposed();
return _position;
}
set
{
ThrowIfDisposed();
throw new NotSupportedException(SR.SeekingNotSupported);
}
}
public override Boolean CanRead { get { return false; } }
public override Boolean CanSeek { get { return false; } }
public override Boolean CanWrite { get { return _canWrite; } }
#endregion
#region methods
private void ThrowIfDisposed()
{
if (_isDisposed)
throw new ObjectDisposedException(this.GetType().ToString(), SR.HiddenStreamName);
}
public override Int32 Read(Byte[] buffer, Int32 offset, Int32 count)
{
ThrowIfDisposed();
throw new NotSupportedException(SR.ReadingNotSupported);
}
public override Int64 Seek(Int64 offset, SeekOrigin origin)
{
ThrowIfDisposed();
throw new NotSupportedException(SR.SeekingNotSupported);
}
public override void SetLength(Int64 value)
{
ThrowIfDisposed();
throw new NotSupportedException(SR.SetLengthRequiresSeekingAndWriting);
}
public override void Write(Byte[] buffer, Int32 offset, Int32 count)
{
//we can't pass the argument checking down a level
if (buffer == null)
throw new ArgumentNullException("buffer");
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", SR.ArgumentNeedNonNegative);
if (count < 0)
throw new ArgumentOutOfRangeException("count", SR.ArgumentNeedNonNegative);
if ((buffer.Length - offset) < count)
throw new ArgumentException(SR.OffsetLengthInvalid);
Contract.EndContractBlock();
//if we're not actually writing anything, we don't want to trigger as if we did write something
ThrowIfDisposed();
Debug.Assert(CanWrite);
if (count == 0)
return;
if (!_everWritten)
{
_initialPosition = _baseBaseStream.Position;
_everWritten = true;
}
_checksum = Crc32Helper.UpdateCrc32(_checksum, buffer, offset, count);
_baseStream.Write(buffer, offset, count);
_position += count;
}
public override void Flush()
{
ThrowIfDisposed();
//assume writeable if not disposed
Debug.Assert(CanWrite);
_baseStream.Flush();
}
protected override void Dispose(Boolean disposing)
{
if (disposing && !_isDisposed)
{
// if we never wrote through here, save the position
if (!_everWritten)
_initialPosition = _baseBaseStream.Position;
if (!_leaveOpenOnClose)
_baseStream.Dispose(); // Close my super-stream (flushes the last data)
if (_saveCrcAndSizes != null)
_saveCrcAndSizes(_initialPosition, Position, _checksum, _baseBaseStream, _zipArchiveEntry, _onClose);
_isDisposed = true;
}
base.Dispose(disposing);
}
#endregion
}
}
| |
/*
Copyright (c) Microsoft Corporation
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License
at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER
EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF
TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace Microsoft.Research.Tools
{
/// <summary>
/// A data grid that filters the contents.
/// </summary>
public partial class FilteredDataGridView : UserControl
{
IDGVData data;
/// <summary>
/// If true apply the complement of the current filter.
/// </summary>
bool complementFilter;
/// <summary>
/// Create a filtered data
/// </summary>
public FilteredDataGridView()
{
this.complementFilter = false;
this.InitializeComponent();
ToolTip tip = new ToolTip();
tip.SetToolTip(this.button_drop, "Remove the rows matching the filter string");
tip.SetToolTip(this.button_filter, "Keep the rows matching the filter string");
tip.SetToolTip(this.button_X, "Remove all applied filters");
tip.SetToolTip(this.textBox_filter, "String to perform filtering on");
}
/// <summary>
/// Bind to the data source.
/// </summary>
/// <param name="dataSource">Value to set data to.</param>
public void SetDataSource(IDGVData dataSource)
{
this.data = dataSource;
this.dataGridView.DataSource = dataSource.VisibleItems;
this.ApplyFilter(this.complementFilter, false);
this.data.ItemsChanged += this.ItemsChanged;
this.data.ItemAppended += this.ItemAdded;
}
/// <summary>
/// Delegate called by DGV then a new item is added.
/// </summary>
/// <param name="sender">Unused.</param>
/// <param name="e">Unused.</param>
public void ItemAdded(object sender, EventArgs e)
{
this.ApplyFilter(this.complementFilter, true);
}
/// <summary>
/// Delegate called by DGV when the items change.
/// </summary>
/// <param name="sender">Unused.</param>
/// <param name="e">Unused.</param>
public void ItemsChanged(object sender, EventArgs e)
{
this.ApplyFilter(this.complementFilter, false);
}
/// <summary>
/// Handle to the datagridview in the form.
/// </summary>
public DataGridView DataGridView { get { return this.dataGridView; } }
/// <summary>
/// Used clicked the button to filter the data displayed.
/// </summary>
/// <param name="sender">Unused.</param>
/// <param name="e">Unused.</param>
private void button_filter_Click(object sender, EventArgs e)
{
this.complementFilter = false;
this.ApplyFilter(false, false);
}
/// <summary>
/// Used clicked button to remove filter.
/// </summary>
/// <param name="sender">Unused.</param>
/// <param name="e">Unused.</param>
private void button_X_Click(object sender, EventArgs e)
{
this.textBox_filter.Text = "";
this.complementFilter = false;
this.data.RemoveFilter();
if (this.ViewChanged != null)
this.ViewChanged(this, EventArgs.Empty);
}
/// <summary>
/// Apply the current filter.
/// <param name="complement">If true, complement the selection.</param>
/// <param name="lastOnly">Only filter the last value.</param>
/// </summary>
public void ApplyFilter(bool complement, bool lastOnly)
{
int firstIndex = lastOnly ? this.DataGridView.Rows.Count - 1 : 0;
int lastIndex = this.DataGridView.Rows.Count;
this.data.Filter(this.textBox_filter.Text, this.DataGridView, firstIndex, lastIndex, complement);
if (this.ViewChanged != null)
this.ViewChanged(this, EventArgs.Empty);
}
/// <summary>
/// User pressed a key in the filter textbox.
/// </summary>
/// <param name="sender">Unused.</param>
/// <param name="e">Key description.</param>
private void textBox_filter_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
this.ApplyFilter(false, false);
}
/// <summary>
/// Invoked when a cell needs to be formatted.
/// </summary>
public event DataGridViewCellFormattingEventHandler CellFormatting;
/// <summary>
/// Invoked when a cell has been double-clicked.
/// </summary>
public event DataGridViewCellMouseEventHandler CellMouseDoubleClick;
/// <summary>
/// Invoked when the view has been changed.
/// </summary>
public event EventHandler ViewChanged;
private void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (this.CellFormatting != null)
this.CellFormatting(sender, e);
}
private void dataGridView_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (this.CellMouseDoubleClick != null)
this.CellMouseDoubleClick(sender, e);
}
/// <summary>
/// Right mouse button clicked in a row of the datagrid.
/// </summary>
/// <param name="sender">Unused.</param>
/// <param name="e">Event describing the mouse click.</param>
private void dataGridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Right && e.ColumnIndex >= 0 && e.RowIndex >= 0)
{
if (this.DataGridView.Rows[e.RowIndex].Selected == false)
{
this.DataGridView.ClearSelection();
this.DataGridView.Rows[e.RowIndex].Selected = true;
}
this.DataGridView.CurrentCell = this.DataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex];
}
}
/// <summary>
/// Redo the last sort; return true if there was a last sort.
/// </summary>
/// <returns>False if the data was never sorted.</returns>
public bool RedoSort()
{
bool sorted = this.data.RedoSort();
if (this.ViewChanged != null)
this.ViewChanged(this, EventArgs.Empty);
return sorted;
}
/// <summary>
/// Drop the text from the grid.
/// </summary>
/// <param name="sender">Unused.</param>
/// <param name="e">Unused.</param>
private void button_drop_Click(object sender, EventArgs e)
{
this.complementFilter = true;
this.ApplyFilter(true, false);
}
}
/// <summary>
/// Untyped interface for data bound to a filtered data grid view.
/// </summary>
public interface IDGVData
{
/// <summary>
/// Items to display; should be a BindingList.
/// </summary>
object VisibleItems { get; }
/// <summary>
/// Perform filtering with this text.
/// </summary>
/// <param name="text">Text to find.</param>
/// <param name="grid">Data grid where text is sought.</param>
/// <returns>Number of matches.</returns>
/// <param name="complement">If true then complement the selection.</param>
/// <param name="endIndex">Last index to filter.</param>
/// <param name="startIndex">First index to filter.</param>
int Filter(string text, DataGridView grid, int startIndex, int endIndex, bool complement);
/// <summary>
/// Remove any filter applied.
/// </summary>
/// <returns>The number of items.</returns>
int RemoveFilter();
/// <summary>
/// Event raised when the list changes.
/// </summary>
event EventHandler ItemsChanged;
/// <summary>
/// An item has been added.
/// </summary>
event EventHandler ItemAppended;
/// <summary>
/// Redo the sort as done the last time.
/// Return true if there was a previous sort.
/// </summary>
bool RedoSort();
}
/// <summary>
/// Data for a filtered data grid view; can't have a type parameter in a form, so we segregate it here.
/// </summary>
/// <typeparam name="T"></typeparam>
public class DGVData<T> : IDGVData
{
/// <summary>
/// Data items which are filtered.
/// </summary>
List<T> dataItems;
/// <summary>
/// Items displayed.
/// </summary>
BindingListSortable<T> visibleItems;
/// <summary>
/// If true filtering is case sensitive.
/// </summary>
public bool CaseSensitive { get; set; }
/// <summary>
/// Number of visible items.
/// </summary>
public int VisibleItemCount { get { return this.visibleItems.Count; } }
/// <summary>
/// Items that are visible: a binding list sortable.
/// </summary>
public object VisibleItems { get { return this.visibleItems; } }
/// <summary>
/// Clear the contents.
/// </summary>
public void Clear()
{
this.visibleItems.Clear();
this.dataItems.Clear();
}
/// <summary>
/// Delegate called when the items change.
/// </summary>
public event EventHandler ItemsChanged;
/// <summary>
/// Delegate called when an item is added.
/// </summary>
public event EventHandler ItemAppended;
/// <summary>
/// Raise the changed event if required.
/// </summary>
private void OnChanged()
{
if (this.ItemsChanged != null)
this.ItemsChanged(this, EventArgs.Empty);
}
/// <summary>
/// Raise the changed event if required.
/// </summary>
private void OnItemAppended()
{
if (this.ItemAppended != null)
this.ItemAppended(this, EventArgs.Empty);
}
/// <summary>
/// Create an empty DGVData object.
/// </summary>
public DGVData()
{
this.visibleItems = new BindingListSortable<T>();
this.dataItems = new List<T>();
this.OnChanged();
}
/// <summary>
/// Redo the last sorting operation.
/// </summary>
public bool RedoSort()
{
return this.visibleItems.RedoSort();
}
/// <summary>
/// Set the items to display.
/// </summary>
/// <param name="items">Collection of items to display.</param>
public void SetItems(IEnumerable<T> items)
{
this.Clear();
this.dataItems.AddRange(items);
this.RemoveFilter();
this.OnChanged();
}
/// <summary>
/// True if the text is found in any cell of the row.
/// </summary>
/// <param name="tofind">Text to search.</param>
/// <param name="row">A datagridview row with arbitrary contents.</param>
/// <returns>True if any cell contains the text.</returns>
/// <param name="caseSensitive">If true, do a case-sensitive match.</param>
private static bool DataGridViewRowMatches(string tofind, DataGridViewRow row, bool caseSensitive)
{
for (int i = 0; i < row.Cells.Count; i++)
{
var cell = row.Cells[i];
if (!cell.Visible) continue;
object inside = cell.FormattedValue;
string text = inside as string;
if (text == null)
continue;
if (!caseSensitive)
text = text.ToLower();
if (text.Contains(tofind))
return true;
}
return false;
}
/// <summary>
/// Return the list of all indices of rows matching a specified string.
/// </summary>
/// <param name="tofind">String to find in a datagridview.</param>
/// <param name="grid">Datagrid view to search.</param>
/// <returns>A list with all matching row indices.</returns>
/// <param name="caseSensitive">If true do a case-sensitive match.</param>
/// <param name="exclusive">If true, return the complement of the set.</param>
public static List<int> DataGridViewRowIndicesMatching(string tofind, DataGridView grid, bool caseSensitive, bool exclusive, int startIndex, int endIndex)
{
if (!caseSensitive)
tofind = tofind.ToLower();
List<int> retval = new List<int>();
for (int i = Math.Max(0, startIndex); i < Math.Min(grid.Rows.Count, endIndex); i++)
{
var row = grid.Rows[i];
bool matches = DataGridViewRowMatches(tofind, row, caseSensitive);
if (matches ^ exclusive)
retval.Add(i);
}
return retval;
}
/// <summary>
/// Return the list of all indices of rows matching a specified string.
/// </summary>
/// <param name="tofind">String to find in a datagridview.</param>
/// <param name="grid">Datagrid view to search.</param>
/// <returns>A list with all matching row indices.</returns>
/// <param name="caseSensitive">If true do a case-sensitive match.</param>
/// <param name="exclusive">If true, return the complement of the set.</param>
public static List<int> DataGridViewRowIndicesMatching(string tofind, DataGridView grid, bool caseSensitive, bool exclusive)
{
return DataGridViewRowIndicesMatching(tofind, grid, caseSensitive, exclusive, 0, grid.Rows.Count);
}
/// <summary>
/// Stop filtering jobs; return number of jobs.
/// </summary>
public int RemoveFilter()
{
if (this.dataItems == null)
return 0;
this.visibleItems.RaiseListChangedEvents = false;
this.visibleItems.Clear();
foreach (var ji in this.dataItems)
this.visibleItems.Add(ji);
this.visibleItems.RaiseListChangedEvents = true;
this.visibleItems.RedoSort();
this.visibleItems.ResetBindings();
return this.dataItems.Count;
}
/// <summary>
/// Apply the filter. Return the number of matches. If the filter is empty do not do anything.
/// <param name="datagrid">Data grid to filter.</param>
/// <param name="filter">Text to fine.</param>
/// <param name="complement">If true complement the selection.</param>
/// <param name="startIndex">First index to filter.</param>
/// <param name="endIndex">Last index to filter.</param>
/// </summary>
public int Filter(string filter, DataGridView datagrid, int startIndex, int endIndex, bool complement)
{
int matches = datagrid.Rows.Count;
if (filter == "")
this.RemoveFilter();
List<int> toRemove = DataGridViewRowIndicesMatching(filter, datagrid, this.CaseSensitive, !complement, startIndex, endIndex);
matches -= toRemove.Count;
this.visibleItems.RaiseListChangedEvents = false;
toRemove.Sort();
toRemove.Reverse(); // do it backwards to keep indices unchanged
foreach (int index in toRemove)
{
this.visibleItems.RemoveAt(index);
}
this.visibleItems.RaiseListChangedEvents = true;
this.visibleItems.ResetBindings();
return matches;
}
/// <summary>
/// Add a new item to the data grid view.
/// </summary>
/// <param name="item">Item to add.</param>
public void AddItem(T item)
{
this.dataItems.Add(item);
this.OnItemAppended();
}
}
}
| |
#if !UNITY_WINRT || UNITY_EDITOR || UNITY_WP8
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Utilities;
using System.Collections;
using System.Globalization;
namespace Newtonsoft.Json.Linq
{
/// <summary>
/// Contains the LINQ to JSON extension methods.
/// </summary>
public static class LinqExtensions
{
/// <summary>
/// Returns a collection of tokens that contains the ancestors of every token in the source collection.
/// </summary>
/// <typeparam name="T">The type of the objects in source, constrained to <see cref="JToken"/>.</typeparam>
/// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param>
/// <returns>An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the ancestors of every node in the source collection.</returns>
public static IJEnumerable<JToken> Ancestors<T>(this IEnumerable<T> source) where T : JToken
{
ValidationUtils.ArgumentNotNull(source, "source");
return source.SelectMany(j => j.Ancestors()).AsJEnumerable();
}
//TODO
//public static IEnumerable<JObject> AncestorsAndSelf<T>(this IEnumerable<T> source) where T : JObject
//{
// ValidationUtils.ArgumentNotNull(source, "source");
// return source.SelectMany(j => j.AncestorsAndSelf());
//}
/// <summary>
/// Returns a collection of tokens that contains the descendants of every token in the source collection.
/// </summary>
/// <typeparam name="T">The type of the objects in source, constrained to <see cref="JContainer"/>.</typeparam>
/// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param>
/// <returns>An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the descendants of every node in the source collection.</returns>
public static IJEnumerable<JToken> Descendants<T>(this IEnumerable<T> source) where T : JContainer
{
ValidationUtils.ArgumentNotNull(source, "source");
return source.SelectMany(j => j.Descendants()).AsJEnumerable();
}
//TODO
//public static IEnumerable<JObject> DescendantsAndSelf<T>(this IEnumerable<T> source) where T : JContainer
//{
// ValidationUtils.ArgumentNotNull(source, "source");
// return source.SelectMany(j => j.DescendantsAndSelf());
//}
/// <summary>
/// Returns a collection of child properties of every object in the source collection.
/// </summary>
/// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JObject"/> that contains the source collection.</param>
/// <returns>An <see cref="IEnumerable{T}"/> of <see cref="JProperty"/> that contains the properties of every object in the source collection.</returns>
public static IJEnumerable<JProperty> Properties(this IEnumerable<JObject> source)
{
ValidationUtils.ArgumentNotNull(source, "source");
return source.SelectMany(d => d.Properties()).AsJEnumerable();
}
/// <summary>
/// Returns a collection of child values of every object in the source collection with the given key.
/// </summary>
/// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param>
/// <param name="key">The token key.</param>
/// <returns>An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the values of every node in the source collection with the given key.</returns>
public static IJEnumerable<JToken> Values(this IEnumerable<JToken> source, object key)
{
return Values<JToken, JToken>(source, key).AsJEnumerable();
}
/// <summary>
/// Returns a collection of child values of every object in the source collection.
/// </summary>
/// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param>
/// <returns>An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the values of every node in the source collection.</returns>
public static IJEnumerable<JToken> Values(this IEnumerable<JToken> source)
{
return source.Values(null);
}
/// <summary>
/// Returns a collection of converted child values of every object in the source collection with the given key.
/// </summary>
/// <typeparam name="U">The type to convert the values to.</typeparam>
/// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param>
/// <param name="key">The token key.</param>
/// <returns>An <see cref="IEnumerable{T}"/> that contains the converted values of every node in the source collection with the given key.</returns>
public static IEnumerable<U> Values<U>(this IEnumerable<JToken> source, object key)
{
return Values<JToken, U>(source, key);
}
/// <summary>
/// Returns a collection of converted child values of every object in the source collection.
/// </summary>
/// <typeparam name="U">The type to convert the values to.</typeparam>
/// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param>
/// <returns>An <see cref="IEnumerable{T}"/> that contains the converted values of every node in the source collection.</returns>
public static IEnumerable<U> Values<U>(this IEnumerable<JToken> source)
{
return Values<JToken, U>(source, null);
}
/// <summary>
/// Converts the value.
/// </summary>
/// <typeparam name="U">The type to convert the value to.</typeparam>
/// <param name="value">A <see cref="JToken"/> cast as a <see cref="IEnumerable{T}"/> of <see cref="JToken"/>.</param>
/// <returns>A converted value.</returns>
public static U Value<U>(this IEnumerable<JToken> value)
{
return value.Value<JToken, U>();
}
/// <summary>
/// Converts the value.
/// </summary>
/// <typeparam name="T">The source collection type.</typeparam>
/// <typeparam name="U">The type to convert the value to.</typeparam>
/// <param name="value">A <see cref="JToken"/> cast as a <see cref="IEnumerable{T}"/> of <see cref="JToken"/>.</param>
/// <returns>A converted value.</returns>
public static U Value<T, U>(this IEnumerable<T> value) where T : JToken
{
ValidationUtils.ArgumentNotNull(value, "source");
JToken token = value as JToken;
if (token == null)
throw new ArgumentException("Source value must be a JToken.");
return token.Convert<JToken, U>();
}
internal static IEnumerable<U> Values<T, U>(this IEnumerable<T> source, object key) where T : JToken
{
ValidationUtils.ArgumentNotNull(source, "source");
foreach (JToken token in source)
{
if (key == null)
{
if (token is JValue)
{
yield return Convert<JValue, U>((JValue)token);
}
else
{
foreach (JToken t in token.Children())
{
yield return t.Convert<JToken, U>(); ;
}
}
}
else
{
JToken value = token[key];
if (value != null)
yield return value.Convert<JToken, U>();
}
}
yield break;
}
//TODO
//public static IEnumerable<T> InDocumentOrder<T>(this IEnumerable<T> source) where T : JObject;
//public static IEnumerable<JToken> Children<T>(this IEnumerable<T> source) where T : JToken
//{
// ValidationUtils.ArgumentNotNull(source, "source");
// return source.SelectMany(c => c.Children());
//}
/// <summary>
/// Returns a collection of child tokens of every array in the source collection.
/// </summary>
/// <typeparam name="T">The source collection type.</typeparam>
/// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param>
/// <returns>An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the values of every node in the source collection.</returns>
public static IJEnumerable<JToken> Children<T>(this IEnumerable<T> source) where T : JToken
{
return Children<T, JToken>(source).AsJEnumerable();
}
/// <summary>
/// Returns a collection of converted child tokens of every array in the source collection.
/// </summary>
/// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param>
/// <typeparam name="U">The type to convert the values to.</typeparam>
/// <typeparam name="T">The source collection type.</typeparam>
/// <returns>An <see cref="IEnumerable{T}"/> that contains the converted values of every node in the source collection.</returns>
public static IEnumerable<U> Children<T, U>(this IEnumerable<T> source) where T : JToken
{
ValidationUtils.ArgumentNotNull(source, "source");
return source.SelectMany(c => c.Children()).Convert<JToken, U>();
}
internal static IEnumerable<U> Convert<T, U>(this IEnumerable<T> source) where T : JToken
{
ValidationUtils.ArgumentNotNull(source, "source");
foreach (JToken token in source)
{
yield return Convert<JToken, U>(token);
}
}
internal static U Convert<T, U>(this T token) where T : JToken
{
if (token == null)
return default(U);
if (token is U
// don't want to cast JValue to its interfaces, want to get the internal value
&& typeof(U) != typeof(IComparable) && typeof(U) != typeof(IFormattable))
{
// HACK
return (U)(object)token;
}
else
{
JValue value = token as JValue;
if (value == null)
throw new InvalidCastException("Cannot cast {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, token.GetType(), typeof(T)));
if (value.Value is U)
return (U)value.Value;
Type targetType = typeof(U);
if (ReflectionUtils.IsNullableType(targetType))
{
if (value.Value == null)
return default(U);
targetType = Nullable.GetUnderlyingType(targetType);
}
return (U)System.Convert.ChangeType(value.Value, targetType, CultureInfo.InvariantCulture);
}
}
//TODO
//public static void Remove<T>(this IEnumerable<T> source) where T : JContainer;
/// <summary>
/// Returns the input typed as <see cref="IJEnumerable{T}"/>.
/// </summary>
/// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param>
/// <returns>The input typed as <see cref="IJEnumerable{T}"/>.</returns>
public static IJEnumerable<JToken> AsJEnumerable(this IEnumerable<JToken> source)
{
return source.AsJEnumerable<JToken>();
}
/// <summary>
/// Returns the input typed as <see cref="IJEnumerable{T}"/>.
/// </summary>
/// <typeparam name="T">The source collection type.</typeparam>
/// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param>
/// <returns>The input typed as <see cref="IJEnumerable{T}"/>.</returns>
public static IJEnumerable<T> AsJEnumerable<T>(this IEnumerable<T> source) where T : JToken
{
if (source == null)
return null;
else if (source is IJEnumerable<T>)
return (IJEnumerable<T>)source;
else
return new JEnumerable<T>(source);
}
}
}
#endif
| |
//------------------------------------------------------------------------------
// <copyright file="DbConnectionStringBuilder.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Data.Common {
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Diagnostics.CodeAnalysis;
public class DbConnectionStringBuilder : System.Collections.IDictionary, ICustomTypeDescriptor {
// keyword->value currently listed in the connection string
private Dictionary<string,object> _currentValues;
// cached connectionstring to avoid constant rebuilding
// and to return a user's connectionstring as is until editing occurs
private string _connectionString = "";
private PropertyDescriptorCollection _propertyDescriptors;
private bool _browsableConnectionString = true;
private readonly bool UseOdbcRules;
private static int _objectTypeCount; // Bid counter
internal readonly int _objectID = System.Threading.Interlocked.Increment(ref _objectTypeCount);
public DbConnectionStringBuilder() {
}
public DbConnectionStringBuilder(bool useOdbcRules) {
UseOdbcRules = useOdbcRules;
}
private ICollection Collection {
get { return (ICollection)CurrentValues; }
}
private IDictionary Dictionary {
get { return (IDictionary)CurrentValues; }
}
private Dictionary<string,object> CurrentValues {
get {
Dictionary<string,object> values = _currentValues;
if (null == values) {
values = new Dictionary<string,object>(StringComparer.OrdinalIgnoreCase);
_currentValues = values;
}
return values;
}
}
object System.Collections.IDictionary.this[object keyword] {
// delegate to this[string keyword]
get { return this[ObjectToString(keyword)]; }
set { this[ObjectToString(keyword)] = value; }
}
[Browsable(false)]
public virtual object this[string keyword] {
get {
Bid.Trace("<comm.DbConnectionStringBuilder.get_Item|API> %d#, keyword='%ls'\n", ObjectID, keyword);
ADP.CheckArgumentNull(keyword, "keyword");
object value;
if (CurrentValues.TryGetValue(keyword, out value)) {
return value;
}
throw ADP.KeywordNotSupported(keyword);
}
set {
ADP.CheckArgumentNull(keyword, "keyword");
bool flag = false;
if (null != value) {
string keyvalue = DbConnectionStringBuilderUtil.ConvertToString(value);
DbConnectionOptions.ValidateKeyValuePair(keyword, keyvalue);
flag = CurrentValues.ContainsKey(keyword);
// store keyword/value pair
CurrentValues[keyword] = keyvalue;
}
else {
flag = Remove(keyword);
}
_connectionString = null;
if (flag) {
_propertyDescriptors = null;
}
}
}
[Browsable(false)]
[DesignOnly(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[EditorBrowsableAttribute(EditorBrowsableState.Never)]
public bool BrowsableConnectionString {
get {
return _browsableConnectionString;
}
set {
_browsableConnectionString = value;
_propertyDescriptors = null;
}
}
[RefreshPropertiesAttribute(RefreshProperties.All)]
[ResCategoryAttribute(Res.DataCategory_Data)]
[ResDescriptionAttribute(Res.DbConnectionString_ConnectionString)]
public string ConnectionString {
get {
Bid.Trace("<comm.DbConnectionStringBuilder.get_ConnectionString|API> %d#\n", ObjectID);
string connectionString = _connectionString;
if (null == connectionString) {
StringBuilder builder = new StringBuilder();
foreach(string keyword in Keys) {
object value;
if (ShouldSerialize(keyword) && TryGetValue(keyword, out value)) {
string keyvalue = (null != value) ? Convert.ToString(value, CultureInfo.InvariantCulture) : (string)null;
AppendKeyValuePair(builder, keyword, keyvalue, UseOdbcRules);
}
}
connectionString = builder.ToString();
_connectionString = connectionString;
}
return connectionString;
}
set {
Bid.Trace("<comm.DbConnectionStringBuilder.set_ConnectionString|API> %d#\n", ObjectID);
DbConnectionOptions constr = new DbConnectionOptions(value, null, UseOdbcRules);
string originalValue = ConnectionString;
Clear();
try {
for(NameValuePair pair = constr.KeyChain; null != pair; pair = pair.Next) {
if (null != pair.Value) {
this[pair.Name] = pair.Value;
}
else {
Remove(pair.Name);
}
}
_connectionString = null;
}
catch(ArgumentException) { // restore original string
ConnectionString = originalValue;
_connectionString = originalValue;
throw;
}
}
}
[Browsable(false)]
public virtual int Count {
get { return CurrentValues.Count; }
}
[Browsable(false)]
public bool IsReadOnly {
get { return false; }
}
[Browsable(false)]
public virtual bool IsFixedSize {
get { return false; }
}
bool System.Collections.ICollection.IsSynchronized {
get { return Collection.IsSynchronized; }
}
[Browsable(false)]
public virtual ICollection Keys {
get {
Bid.Trace("<comm.DbConnectionStringBuilder.Keys|API> %d#\n", ObjectID);
return Dictionary.Keys;
}
}
internal int ObjectID {
get {
return _objectID;
}
}
object System.Collections.ICollection.SyncRoot {
get { return Collection.SyncRoot; }
}
[Browsable(false)]
public virtual ICollection Values {
get {
Bid.Trace("<comm.DbConnectionStringBuilder.Values|API> %d#\n", ObjectID);
System.Collections.Generic.ICollection<string> keys = (System.Collections.Generic.ICollection<string>)Keys;
System.Collections.Generic.IEnumerator<string> keylist = keys.GetEnumerator();
object[] values = new object[keys.Count];
for(int i = 0; i < values.Length; ++i) {
keylist.MoveNext();
values[i] = this[keylist.Current];
Debug.Assert(null != values[i], "null value " + keylist.Current);
}
return new System.Data.Common.ReadOnlyCollection<object>(values);
}
}
void System.Collections.IDictionary.Add(object keyword, object value) {
Add(ObjectToString(keyword), value);
}
public void Add(string keyword, object value) {
this[keyword] = value;
}
public static void AppendKeyValuePair(StringBuilder builder, string keyword, string value) {
DbConnectionOptions.AppendKeyValuePairBuilder(builder, keyword, value, false);
}
public static void AppendKeyValuePair(StringBuilder builder, string keyword, string value, bool useOdbcRules) {
DbConnectionOptions.AppendKeyValuePairBuilder(builder, keyword, value, useOdbcRules);
}
public virtual void Clear() {
Bid.Trace("<comm.DbConnectionStringBuilder.Clear|API>\n");
_connectionString = "";
_propertyDescriptors = null;
CurrentValues.Clear();
}
protected internal void ClearPropertyDescriptors() {
_propertyDescriptors = null;
}
// does the keyword exist as a strongly typed keyword or as a stored value
bool System.Collections.IDictionary.Contains(object keyword) {
return ContainsKey(ObjectToString(keyword));
}
public virtual bool ContainsKey(string keyword) {
ADP.CheckArgumentNull(keyword, "keyword");
return CurrentValues.ContainsKey(keyword);
}
void ICollection.CopyTo(Array array, int index) {
Bid.Trace("<comm.DbConnectionStringBuilder.ICollection.CopyTo|API> %d#\n", ObjectID);
Collection.CopyTo(array, index);
}
public virtual bool EquivalentTo(DbConnectionStringBuilder connectionStringBuilder) {
ADP.CheckArgumentNull(connectionStringBuilder, "connectionStringBuilder");
Bid.Trace("<comm.DbConnectionStringBuilder.EquivalentTo|API> %d#, connectionStringBuilder=%d#\n", ObjectID, connectionStringBuilder.ObjectID);
if ((GetType() != connectionStringBuilder.GetType()) || (CurrentValues.Count != connectionStringBuilder.CurrentValues.Count)) {
return false;
}
object value;
foreach(KeyValuePair<string, object> entry in CurrentValues) {
if (!connectionStringBuilder.CurrentValues.TryGetValue(entry.Key, out value) || !entry.Value.Equals(value)) {
return false;
}
}
return true;
}
IEnumerator System.Collections.IEnumerable.GetEnumerator() {
Bid.Trace("<comm.DbConnectionStringBuilder.IEnumerable.GetEnumerator|API> %d#\n", ObjectID);
return Collection.GetEnumerator();
}
IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator() {
Bid.Trace("<comm.DbConnectionStringBuilder.IDictionary.GetEnumerator|API> %d#\n", ObjectID);
return Dictionary.GetEnumerator();
}
[SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly", Justification = "See Dev11 bug 875012")]
private string ObjectToString(object keyword) {
try {
return (string)keyword;
}
catch(InvalidCastException) {
//
throw new ArgumentException("keyword", "not a string");
}
}
void System.Collections.IDictionary.Remove(object keyword) {
Remove(ObjectToString(keyword));
}
public virtual bool Remove(string keyword) {
Bid.Trace("<comm.DbConnectionStringBuilder.Remove|API> %d#, keyword='%ls'\n", ObjectID, keyword);
ADP.CheckArgumentNull(keyword, "keyword");
if (CurrentValues.Remove(keyword)) {
_connectionString = null;
_propertyDescriptors = null;
return true;
}
return false;
}
// does the keyword exist as a stored value or something that should always be persisted
public virtual bool ShouldSerialize(string keyword) {
ADP.CheckArgumentNull(keyword, "keyword");
return CurrentValues.ContainsKey(keyword);
}
public override string ToString() {
return ConnectionString;
}
public virtual bool TryGetValue(string keyword, out object value) {
ADP.CheckArgumentNull(keyword, "keyword");
return CurrentValues.TryGetValue(keyword, out value);
}
internal Attribute[] GetAttributesFromCollection(AttributeCollection collection) {
Attribute[] attributes = new Attribute[collection.Count];
collection.CopyTo(attributes, 0);
return attributes;
}
private PropertyDescriptorCollection GetProperties() {
PropertyDescriptorCollection propertyDescriptors = _propertyDescriptors;
if (null == propertyDescriptors) {
IntPtr hscp;
Bid.ScopeEnter(out hscp, "<comm.DbConnectionStringBuilder.GetProperties|INFO> %d#", ObjectID);
try {
Hashtable descriptors = new Hashtable(StringComparer.OrdinalIgnoreCase);
GetProperties(descriptors);
PropertyDescriptor[] properties = new PropertyDescriptor[descriptors.Count];
descriptors.Values.CopyTo(properties, 0);
propertyDescriptors = new PropertyDescriptorCollection(properties);
_propertyDescriptors = propertyDescriptors;
}
finally {
Bid.ScopeLeave(ref hscp);
}
}
return propertyDescriptors;
}
protected virtual void GetProperties(Hashtable propertyDescriptors) {
IntPtr hscp;
Bid.ScopeEnter(out hscp, "<comm.DbConnectionStringBuilder.GetProperties|API> %d#", ObjectID);
try {
// show all strongly typed properties (not already added)
// except ConnectionString iff BrowsableConnectionString
Attribute[] attributes;
foreach(PropertyDescriptor reflected in TypeDescriptor.GetProperties(this, true)) {
if (ADP.ConnectionString != reflected.Name) {
string displayName = reflected.DisplayName;
if (!propertyDescriptors.ContainsKey(displayName)) {
attributes = GetAttributesFromCollection(reflected.Attributes);
PropertyDescriptor descriptor = new DbConnectionStringBuilderDescriptor(reflected.Name,
reflected.ComponentType, reflected.PropertyType, reflected.IsReadOnly, attributes);
propertyDescriptors[displayName] = descriptor;
}
// else added by derived class first
}
else if (BrowsableConnectionString) {
propertyDescriptors[ADP.ConnectionString] = reflected;
}
else {
propertyDescriptors.Remove(ADP.ConnectionString);
}
}
// all keywords in Keys list that do not have strongly typed property, ODBC case
// ignore 'Workaround Oracle Bug 914652' via IsFixedSize
if (!IsFixedSize) {
attributes = null;
foreach(string keyword in Keys) {
if (!propertyDescriptors.ContainsKey(keyword)) {
object value = this[keyword];
Type vtype;
if (null != value) {
vtype = value.GetType();
if (typeof(string) == vtype) {
int tmp1;
if (Int32.TryParse((string)value, out tmp1)) {
vtype = typeof(Int32);
}
else {
bool tmp2;
if (Boolean.TryParse((string)value, out tmp2)) {
vtype = typeof(Boolean);
}
}
}
}
else {
vtype = typeof(string);
}
Attribute[] useAttributes = attributes;
if (StringComparer.OrdinalIgnoreCase.Equals(DbConnectionStringKeywords.Password, keyword) ||
StringComparer.OrdinalIgnoreCase.Equals(DbConnectionStringSynonyms.Pwd, keyword)) {
useAttributes = new Attribute[] {
BrowsableAttribute.Yes,
PasswordPropertyTextAttribute.Yes,
new ResCategoryAttribute(Res.DataCategory_Security),
RefreshPropertiesAttribute.All,
};
}
else if (null == attributes) {
attributes = new Attribute[] {
BrowsableAttribute.Yes,
RefreshPropertiesAttribute.All,
};
useAttributes = attributes;
}
PropertyDescriptor descriptor = new DbConnectionStringBuilderDescriptor(keyword,
this.GetType(), vtype, false, useAttributes);
propertyDescriptors[keyword] = descriptor;
}
}
}
}
finally {
Bid.ScopeLeave(ref hscp);
}
}
private PropertyDescriptorCollection GetProperties(Attribute[] attributes) {
PropertyDescriptorCollection propertyDescriptors = GetProperties();
if ((null == attributes) || (0 == attributes.Length)) {
// Basic case has no filtering
return propertyDescriptors;
}
// Create an array that is guaranteed to hold all attributes
PropertyDescriptor[] propertiesArray = new PropertyDescriptor[propertyDescriptors.Count];
// Create an index to reference into this array
int index = 0;
// Iterate over each property
foreach (PropertyDescriptor property in propertyDescriptors) {
// Identify if this property's attributes match the specification
bool match = true;
foreach (Attribute attribute in attributes) {
Attribute attr = property.Attributes[attribute.GetType()];
if ((attr == null && !attribute.IsDefaultAttribute()) || !attr.Match(attribute)) {
match = false;
break;
}
}
// If this property matches, add it to the array
if (match) {
propertiesArray[index] = property;
index++;
}
}
// Create a new array that only contains the filtered properties
PropertyDescriptor[] filteredPropertiesArray = new PropertyDescriptor[index];
Array.Copy(propertiesArray, filteredPropertiesArray, index);
return new PropertyDescriptorCollection(filteredPropertiesArray);
}
string ICustomTypeDescriptor.GetClassName() {
return TypeDescriptor.GetClassName(this, true);
}
string ICustomTypeDescriptor.GetComponentName() {
return TypeDescriptor.GetComponentName(this, true);
}
AttributeCollection ICustomTypeDescriptor.GetAttributes() {
return TypeDescriptor.GetAttributes(this, true);
}
object ICustomTypeDescriptor.GetEditor(Type editorBaseType) {
return TypeDescriptor.GetEditor(this, editorBaseType, true);
}
TypeConverter ICustomTypeDescriptor.GetConverter() {
return TypeDescriptor.GetConverter(this, true);
}
PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() {
return TypeDescriptor.GetDefaultProperty(this, true);
}
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() {
return GetProperties();
}
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) {
return GetProperties(attributes);
}
EventDescriptor ICustomTypeDescriptor.GetDefaultEvent() {
return TypeDescriptor.GetDefaultEvent(this, true);
}
EventDescriptorCollection ICustomTypeDescriptor.GetEvents() {
return TypeDescriptor.GetEvents(this, true);
}
EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes) {
return TypeDescriptor.GetEvents(this, attributes, true);
}
object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) {
return this;
}
}
}
| |
// -------------------------------------
// Domain : Avariceonline.com
// Author : Nicholas Ventimiglia
// Product : Unity3d Foundation
// Published : 2015
// -------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Text;
using Foundation.Server.Api;
using Foundation.Tasks;
using FullSerializer;
using UnityEngine;
namespace Foundation.Server
{
/// <summary>
/// A http client which returns UnityTasks's
/// </summary>
public class HttpService
{
#region Settings
/// <summary>
/// content type Header. Default value of "application/json"
/// </summary>
public string ContentType = "application/json";
/// <summary>
/// Accept Header. Default value of "application/json"
/// </summary>
public string Accept = "application/json";
/// <summary>
/// timeout in seconds
/// </summary>
public int Timeout = 11;
#endregion
#region session
/// <summary>
/// Key used to acquire the session server side. Add to header.
/// </summary>
public static string SessionToken { get; set; }
/// <summary>
/// Key used to acquire the session server side. Add to header.
/// </summary>
public static string AuthorizationToken { get; set; }
/// <summary>
/// Is authorized
/// </summary>
public static bool IsAuthenticated
{
get { return !string.IsNullOrEmpty(AuthorizationToken); }
}
/// <summary>
/// Load session from disk
/// </summary>
public static void LoadSession()
{
SessionToken = PlayerPrefs.GetString("HttpSession:SessionToken", string.Empty);
AuthorizationToken = PlayerPrefs.GetString("HttpSession:AuthorizationToken", string.Empty);
}
/// <summary>
/// Saves to prefs
/// </summary>
public static void SaveSession()
{
PlayerPrefs.SetString("HttpSession:SessionToken", SessionToken);
PlayerPrefs.SetString("HttpSession:AuthorizationToken", AuthorizationToken);
PlayerPrefs.Save();
}
/// <summary>
/// Delete session
/// </summary>
public static void ClearSession()
{
SessionToken = AuthorizationToken = string.Empty;
SaveSession();
}
static HttpService()
{
LoadSession();
}
#endregion
#region public interface
//Callbacks
/// <summary>
/// Begins the Http request
/// </summary>
/// <param name="url"></param>
/// <param name="callback"></param>
/// <returns></returns>
public void GetAsync(string url, Action<Response> callback)
{
TaskManager.StartRoutine(GetAsync(callback.FromJsonResponse(), url));
}
/// <summary>
/// Begins the Http request
/// </summary>
/// <param name="url"></param>
/// <param name="callback"></param>
/// <returns></returns>
public void GetAsync<T>(string url, Action<Response<T>> callback)
{
TaskManager.StartRoutine(GetAsync(callback.FromJsonResponse(), url));
}
/// <summary>
/// Begins the Http request
/// </summary>
/// <param name="url"></param>
/// <param name="callback"></param>
/// <returns></returns>
public void PostAsync(string url, Action<Response> callback)
{
TaskManager.StartRoutine(PostAsync(callback.FromJsonResponse(), url, null));
}
/// <summary>
/// Begins the Http request
/// </summary>
/// <param name="url"></param>
/// <param name="content"></param>
/// <returns></returns>
public void PostAsync(string url, string content, Action<Response> callback)
{
TaskManager.StartRoutine(PostAsync(callback.FromJsonResponse(), url, content));
}
/// <summary>
/// Begins the Http request
/// </summary>
/// <param name="url"></param>
/// <param name="callback"></param>
/// <returns></returns>
public void PostAsync<T>(string url, Action<Response<T>> callback)
{
TaskManager.StartRoutine(PostAsync(callback.FromJsonResponse(), url, null));
}
/// <summary>
/// Begins the Http request
/// </summary>
/// <param name="url"></param>
/// <param name="content"></param>
/// <param name="callback"></param>
/// <returns></returns>
public void PostAsync<T>(string url, string content, Action<Response<T>> callback)
{
TaskManager.StartRoutine(PostAsync(callback.FromJsonResponse(), url, content));
}
// Async
/// <summary>
/// Begins the Http request
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public UnityTask GetAsync(string url)
{
var state = new UnityTask();
TaskManager.StartRoutine(GetAsync(state.FromJsonResponse(), url));
return state;
}
/// <summary>
/// Begins the Http request
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public UnityTask<T> GetAsync<T>(string url)
{
var state = new UnityTask<T>();
TaskManager.StartRoutine(GetAsync(state.FromJsonResponse(), url));
return state;
}
/// <summary>
/// Begins the Http request
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public UnityTask PostAsync(string url)
{
var state = new UnityTask();
TaskManager.StartRoutine(PostAsync(state.FromJsonResponse(), url, null));
return state;
}
/// <summary>
/// Begins the Http request
/// </summary>
/// <param name="url"></param>
/// <param name="content"></param>
/// <returns></returns>
public UnityTask PostAsync(string url, string content)
{
var state = new UnityTask();
TaskManager.StartRoutine(PostAsync(state.FromJsonResponse(), url, content));
return state;
}
/// <summary>
/// Begins the Http request
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public UnityTask<T> PostAsync<T>(string url)
{
var state = new UnityTask<T>();
TaskManager.StartRoutine(PostAsync(state.FromJsonResponse(), url, null));
return state;
}
/// <summary>
/// Begins the Http request
/// </summary>
/// <param name="url"></param>
/// <param name="content"></param>
/// <returns></returns>
public UnityTask<T> PostAsync<T>(string url, string content)
{
var state = new UnityTask<T>();
TaskManager.StartRoutine(PostAsync(state.FromJsonResponse(), url, content));
return state;
}
#endregion
#region internal
Dictionary<WWW, Action<Response<string>>> _pendingCalls = new Dictionary<WWW, Action<Response<string>>>();
// Callbacks
IEnumerator GetAsync(Action<Response<string>> task, string url)
{
WWW www;
try
{
www = new WWW(url);
}
catch (Exception ex)
{
Debug.LogException(ex);
task(new Response<string>
{
Exception = ex
});
yield break;
}
yield return TaskManager.StartRoutine(HandleWWWAsync(task, www));
}
IEnumerator PostAsync(Action<Response<string>> task, string url, string content)
{
var headers = new Dictionary<string, string>
{
{"Accept", Accept},
{"Content-Type", ContentType},
{APIConstants.AUTHORIZATION, AuthorizationToken},
{APIConstants.SESSION, SessionToken},
{APIConstants.APPLICATIONID, ServerConfig.Instance.Key}
};
WWW www;
try
{
www = new WWW(url, content == null ? new byte[1] : Encoding.UTF8.GetBytes(content), headers);
}
catch (Exception ex)
{
Debug.LogException(ex);
task(new Response<string>
{
Exception = ex
});
yield break;
}
yield return TaskManager.StartRoutine(HandleWWWAsync(task, www));
}
IEnumerator TimeoutResponse(Action<Response<string>> task, WWW www)
{
yield return new WaitForSeconds(Timeout);
if (_pendingCalls.ContainsKey(www))
{
_pendingCalls.Remove(www);
task(new Response<string>
{
Exception = new Exception("Request timed out"),
Metadata = new HttpMetadata {Message = "Request timed out", StatusCode = HttpStatusCode.RequestTimeout}
});
}
}
IEnumerator HandleWWWAsync(Action<Response<string>> task, WWW www)
{
if (!www.isDone)
{
_pendingCalls.Add(www, task);
TaskManager.StartRoutine(TimeoutResponse(task, www));
yield return www;
}
//Timeout
if (!_pendingCalls.ContainsKey(www))
{
yield break;
}
_pendingCalls.Remove(www);
HttpMetadata meta;
if (www.responseHeaders.ContainsKey("MESSAGE"))
{
var error = www.responseHeaders["MESSAGE"];
meta = JsonSerializer.Deserialize<HttpMetadata>(error);
meta.StatusCode = GetCode(www);
}
else
{
meta = new HttpMetadata {StatusCode = GetCode(www) };
}
if (!string.IsNullOrEmpty(www.error))
{
if (!string.IsNullOrEmpty(meta.Message))
{
task(new Response<string>
{
Metadata = meta,
Exception = new HttpException(meta.Message, meta.StatusCode, meta.ModelState)
});
}
else
{
task(new Response<string>
{
Metadata = meta,
Exception = new Exception(RemoveReturn(www.error))
});
}
}
else
{
if (www.responseHeaders.ContainsKey(APIConstants.AUTHORIZATION))
{
AuthorizationToken = www.responseHeaders[APIConstants.AUTHORIZATION];
}
if (www.responseHeaders.ContainsKey(APIConstants.SESSION))
{
SessionToken = www.responseHeaders[APIConstants.SESSION];
}
SaveSession();
task(new Response<string>
{
Metadata = meta,
Result = www.text,
});
}
}
HttpStatusCode GetCode(WWW www)
{
if (!www.responseHeaders.ContainsKey("STATUS"))
{
return 0;
}
var code = www.responseHeaders["STATUS"].Split(' ')[1];
return (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), code);
}
string RemoveReturn(string s)
{
return s.Replace("\r", "");
}
#endregion
}
}
| |
// ---------------------------------------------------------------------------
// <copyright file="OofSettings.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// ---------------------------------------------------------------------------
//-----------------------------------------------------------------------
// <summary>Defines the OofSettings class.</summary>
//-----------------------------------------------------------------------
namespace Microsoft.Exchange.WebServices.Data
{
using System;
using System.Collections.Generic;
using System.Text;
/// <summary>
/// Represents a user's Out of Office (OOF) settings.
/// </summary>
public sealed class OofSettings : ComplexProperty, ISelfValidate
{
private OofState state;
private OofExternalAudience externalAudience;
private OofExternalAudience allowExternalOof;
private TimeWindow duration;
private OofReply internalReply;
private OofReply externalReply;
/// <summary>
/// Serializes an OofReply. Emits an empty OofReply in case the one passed in is null.
/// </summary>
/// <param name="oofReply">The oof reply.</param>
/// <param name="writer">The writer.</param>
/// <param name="xmlElementName">Name of the XML element.</param>
private void SerializeOofReply(
OofReply oofReply,
EwsServiceXmlWriter writer,
string xmlElementName)
{
if (oofReply != null)
{
oofReply.WriteToXml(writer, xmlElementName);
}
else
{
OofReply.WriteEmptyReplyToXml(writer, xmlElementName);
}
}
/// <summary>
/// Initializes a new instance of OofSettings.
/// </summary>
public OofSettings()
: base()
{
}
/// <summary>
/// Tries to read element from XML.
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns>True if appropriate element was read.</returns>
internal override bool TryReadElementFromXml(EwsServiceXmlReader reader)
{
switch (reader.LocalName)
{
case XmlElementNames.OofState:
this.state = reader.ReadValue<OofState>();
return true;
case XmlElementNames.ExternalAudience:
this.externalAudience = reader.ReadValue<OofExternalAudience>();
return true;
case XmlElementNames.Duration:
this.duration = new TimeWindow();
this.duration.LoadFromXml(reader);
return true;
case XmlElementNames.InternalReply:
this.internalReply = new OofReply();
this.internalReply.LoadFromXml(reader, reader.LocalName);
return true;
case XmlElementNames.ExternalReply:
this.externalReply = new OofReply();
this.externalReply.LoadFromXml(reader, reader.LocalName);
return true;
default:
return false;
}
}
/// <summary>
/// Loads from json.
/// </summary>
/// <param name="jsonProperty">The json property.</param>
/// <param name="service"></param>
internal override void LoadFromJson(JsonObject jsonProperty, ExchangeService service)
{
foreach (string key in jsonProperty.Keys)
{
switch (key)
{
case XmlElementNames.OofState:
this.state = jsonProperty.ReadEnumValue<OofState>(key);
break;
case XmlElementNames.ExternalAudience:
this.externalAudience = jsonProperty.ReadEnumValue<OofExternalAudience>(key);
break;
case XmlElementNames.Duration:
this.duration = new TimeWindow();
this.duration.LoadFromJson(jsonProperty.ReadAsJsonObject(key), service);
break;
case XmlElementNames.InternalReply:
this.internalReply = new OofReply();
this.internalReply.LoadFromJson(jsonProperty.ReadAsJsonObject(key), service);
break;
case XmlElementNames.ExternalReply:
this.externalReply = new OofReply();
this.externalReply.LoadFromJson(jsonProperty.ReadAsJsonObject(key), service);
break;
default:
break;
}
}
}
/// <summary>
/// Writes elements to XML.
/// </summary>
/// <param name="writer">The writer.</param>
internal override void WriteElementsToXml(EwsServiceXmlWriter writer)
{
base.WriteElementsToXml(writer);
writer.WriteElementValue(
XmlNamespace.Types,
XmlElementNames.OofState,
this.State);
writer.WriteElementValue(
XmlNamespace.Types,
XmlElementNames.ExternalAudience,
this.ExternalAudience);
if (this.Duration != null && this.State == OofState.Scheduled)
{
this.Duration.WriteToXml(writer, XmlElementNames.Duration);
}
this.SerializeOofReply(
this.InternalReply,
writer,
XmlElementNames.InternalReply);
this.SerializeOofReply(
this.ExternalReply,
writer,
XmlElementNames.ExternalReply);
}
internal override object InternalToJson(ExchangeService service)
{
JsonObject jsonProperty = new JsonObject();
jsonProperty.Add(XmlElementNames.OofState, this.State);
jsonProperty.Add(XmlElementNames.ExternalAudience, this.ExternalAudience);
if (this.Duration != null && this.State == OofState.Scheduled)
{
jsonProperty.Add(XmlElementNames.Duration, this.Duration.InternalToJson(service));
}
if (this.InternalReply != null)
{
jsonProperty.Add(XmlElementNames.InternalReply, this.InternalReply.InternalToJson(service));
}
if (this.ExternalReply != null)
{
jsonProperty.Add(XmlElementNames.ExternalReply, this.ExternalReply.InternalToJson(service));
}
return jsonProperty;
}
/// <summary>
/// Gets or sets the user's OOF state.
/// </summary>
/// <value>The user's OOF state.</value>
public OofState State
{
get { return this.state; }
set { this.state = value; }
}
/// <summary>
/// Gets or sets a value indicating who should receive external OOF messages.
/// </summary>
public OofExternalAudience ExternalAudience
{
get { return this.externalAudience; }
set { this.externalAudience = value; }
}
/// <summary>
/// Gets or sets the duration of the OOF status when State is set to OofState.Scheduled.
/// </summary>
public TimeWindow Duration
{
get { return this.duration; }
set { this.duration = value; }
}
/// <summary>
/// Gets or sets the OOF response sent other users in the user's domain or trusted domain.
/// </summary>
public OofReply InternalReply
{
get { return this.internalReply; }
set { this.internalReply = value; }
}
/// <summary>
/// Gets or sets the OOF response sent to addresses outside the user's domain or trusted domain.
/// </summary>
public OofReply ExternalReply
{
get { return this.externalReply; }
set { this.externalReply = value; }
}
/// <summary>
/// Gets a value indicating the authorized external OOF notifications.
/// </summary>
public OofExternalAudience AllowExternalOof
{
get { return this.allowExternalOof; }
internal set { this.allowExternalOof = value; }
}
#region ISelfValidate Members
/// <summary>
/// Validates this instance.
/// </summary>
void ISelfValidate.Validate()
{
if (this.State == OofState.Scheduled)
{
if (this.Duration == null)
{
throw new ArgumentException(Strings.DurationMustBeSpecifiedWhenScheduled);
}
EwsUtilities.ValidateParam(this.Duration, "Duration");
}
}
#endregion
}
}
| |
// <copyright file="TypesParserTest.cs" company="Fubar Development Junker">
// Copyright (c) 2016 Fubar Development Junker. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
using System;
using System.Collections.Generic;
using System.IO;
using NodaTime;
using Xunit;
namespace BeanIO.Parser.Types
{
public class TypesParserTest : ParserTest
{
[Fact]
public void TestObjectHandlers()
{
var factory = NewStreamFactory("types.xml");
var reader = factory.CreateReader("t1", LoadReader("t1_valid.txt"));
try
{
var record = Assert.IsType<ObjectRecord>(reader.Read());
Assert.Equal((byte)10, record.ByteValue);
Assert.Equal((short)10, record.ShortValue);
Assert.Equal(-10, record.IntegerValue);
Assert.Equal(10, record.LongValue);
Assert.Equal(10.1f, record.FloatValue);
Assert.Equal(-10.1, record.DoubleValue);
Assert.Equal('A', record.CharacterValue);
Assert.Equal("ABC", record.StringValue);
Assert.Equal(new LocalDate(1970, 1, 1), record.DateValue);
Assert.True(record.BooleanValue);
Assert.Equal(10m, record.DecimalValue);
Assert.Equal(new Guid("fbd9d2be-35dc-41fb-abc9-f4b4c8757eb5"), record.Id);
Assert.Equal(new Uri("http://www.google.com"), record.Url);
Assert.Equal(TypeEnum.ONE, record.Enum1);
Assert.Equal(TypeEnum.TWO, record.Enum2);
var text = new StringWriter();
factory.CreateWriter("t1", text).Write(record);
Assert.Equal(
"10,10,-10,10,10.1,-10.1,A,ABC,010170,True,10," +
"fbd9d2be-35dc-41fb-abc9-f4b4c8757eb5,http://www.google.com/,ONE,two" + LineSeparator,
text.ToString());
record = Assert.IsType<ObjectRecord>(reader.Read());
Assert.Null(record.ByteValue);
Assert.Null(record.ShortValue);
Assert.Null(record.IntegerValue);
Assert.Null(record.LongValue);
Assert.Null(record.FloatValue);
Assert.Null(record.DoubleValue);
Assert.Null(record.CharacterValue);
Assert.Equal(string.Empty, record.StringValue);
Assert.Null(record.DateValue);
Assert.Null(record.BooleanValue);
Assert.Null(record.DecimalValue);
Assert.Null(record.Id);
Assert.Null(record.Url);
Assert.Null(record.Enum1);
Assert.Null(record.Enum2);
text = new StringWriter();
factory.CreateWriter("t1", text).Write(record);
Assert.Equal(
",,,,,,,,,,,,,," + LineSeparator,
text.ToString());
}
finally
{
reader.Close();
}
}
[Fact]
public void TestPrimitiveHandlers()
{
var factory = NewStreamFactory("types.xml");
var reader = factory.CreateReader("t2", LoadReader("t2_valid.txt"));
try
{
var record = Assert.IsType<PrimitiveRecord>(reader.Read());
Assert.Equal((byte)10, record.ByteValue);
Assert.Equal((short)10, record.ShortValue);
Assert.Equal(-10, record.IntegerValue);
Assert.Equal(10, record.LongValue);
Assert.Equal(10.1f, record.FloatValue);
Assert.Equal(-10.1, record.DoubleValue);
Assert.Equal('A', record.CharacterValue);
Assert.True(record.BooleanValue);
Assert.Equal(10.1m, record.DecimalValue);
var text = new StringWriter();
factory.CreateWriter("t2", text).Write(record);
Assert.Equal(
"10,10,-10,10,10.1,-10.1,A,True,10.1" + LineSeparator,
text.ToString());
record = Assert.IsType<PrimitiveRecord>(reader.Read());
Assert.Equal((byte)0, record.ByteValue);
Assert.Equal((short)0, record.ShortValue);
Assert.Equal(0, record.IntegerValue);
Assert.Equal(0, record.LongValue);
Assert.Equal(0, record.FloatValue);
Assert.Equal(0, record.DoubleValue);
Assert.Equal('x', record.CharacterValue);
Assert.False(record.BooleanValue);
Assert.Equal(0, record.DecimalValue);
text = new StringWriter();
factory.CreateWriter("t2", text).Write(record);
Assert.Equal(
"0,0,0,0,0,0,x,False,0" + LineSeparator,
text.ToString());
}
finally
{
reader.Close();
}
}
[Fact]
public void TestStreamTypeHandler()
{
var factory = NewStreamFactory("types.xml");
var reader = factory.CreateReader("t3", LoadReader("t3_valid.txt"));
try
{
var record = Assert.IsType<ObjectRecord>(reader.Read());
Assert.Equal(new LocalDate(1970, 1, 1), record.DateValue);
var text = new StringWriter();
factory.CreateWriter("t3", text).Write(record);
Assert.Equal(
"01-01-1970" + LineSeparator,
text.ToString());
}
finally
{
reader.Close();
}
}
[Fact]
public void TestNamedTypeHandler()
{
var factory = NewStreamFactory("types.xml");
var reader = factory.CreateReader("t4", LoadReader("t4_valid.txt"));
try
{
var map = Assert.IsType<Dictionary<string, object>>(reader.Read());
Assert.Equal(new LocalTime(12, 0), map["dateValue"]);
var text = new StringWriter();
factory.CreateWriter("t4", text).Write(map);
Assert.Equal(
"12:00:00" + LineSeparator,
text.ToString());
}
finally
{
reader.Close();
}
}
[Fact]
public void TestStringTypeHandler()
{
var factory = NewStreamFactory("types.xml");
var reader = factory.CreateReader("t5", LoadReader("t5_valid.txt"));
try
{
var map = Assert.IsType<Dictionary<string, object>>(reader.Read());
Assert.Equal(string.Empty, map["field"]);
var text = new StringWriter();
factory.CreateWriter("t5", text).Write(map);
Assert.Equal(
string.Empty + LineSeparator,
text.ToString());
map = Assert.IsType<Dictionary<string, object>>(reader.Read());
Assert.Equal("Text", map["field"]);
}
finally
{
reader.Close();
}
}
[Fact]
public void TestNullPrimitive()
{
var factory = NewStreamFactory("types.xml");
var reader = factory.CreateReader("t6", new StringReader("\n"));
var record = Assert.IsType<PrimitiveRecord>(reader.Read());
Assert.Equal(0, record.IntegerValue);
}
[Fact(Skip = "There is no ParseExact for numeric types")]
public void TestFormats()
{
var factory = NewStreamFactory("types.xml");
var reader = factory.CreateReader("t7", LoadReader("t7_valid.txt"));
try
{
var record = Assert.IsType<ObjectRecord>(reader.Read());
Assert.Equal((byte)1, record.ByteValue);
Assert.Equal((short)2, record.ShortValue);
Assert.Equal(-3, record.IntegerValue);
Assert.Equal(4, record.LongValue);
Assert.Equal(5.1f, record.FloatValue);
Assert.Equal(-6.1, record.DoubleValue);
Assert.Equal(new LocalDate(2011, 1, 1), record.DateValue);
Assert.Equal(10.5m, record.DecimalValue);
var text = new StringWriter();
factory.CreateWriter("t7", text).Write(record);
Assert.Equal(
"1x,2x,-3x,4x,5.10x,-6.10x,2011-01-01,10.50x" + LineSeparator,
text.ToString());
}
finally
{
reader.Close();
}
}
[Fact]
public void TestFormatSpecificTypeHandler()
{
var factory = NewStreamFactory("types.xml");
var reader = factory.CreateReader("t8", LoadReader("t8_valid.txt"));
try
{
var record = Assert.IsType<ObjectRecord>(reader.Read());
Assert.Equal(new LocalDate(2000, 1, 1), record.DateValue);
var text = new StringWriter();
factory.CreateWriter("t8", text).Write(record);
Assert.Equal(
"2000-01-01" + LineSeparator,
text.ToString());
}
finally
{
reader.Close();
}
}
}
}
| |
// 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.Concurrent;
using System.Globalization;
using System.Reflection;
namespace System.Runtime.Serialization.Formatters.Binary
{
internal sealed class ParseRecord
{
// Enums
internal InternalParseTypeE _parseTypeEnum = InternalParseTypeE.Empty;
internal InternalObjectTypeE _objectTypeEnum = InternalObjectTypeE.Empty;
internal InternalArrayTypeE _arrayTypeEnum = InternalArrayTypeE.Empty;
internal InternalMemberTypeE _memberTypeEnum = InternalMemberTypeE.Empty;
internal InternalMemberValueE _memberValueEnum = InternalMemberValueE.Empty;
internal InternalObjectPositionE _objectPositionEnum = InternalObjectPositionE.Empty;
// Object
internal string _name;
// Value
internal string _value;
internal object _varValue;
// dt attribute
internal string _keyDt;
internal Type _dtType;
internal InternalPrimitiveTypeE _dtTypeCode;
// Object ID
internal long _objectId;
// Reference ID
internal long _idRef;
// Array
// Array Element Type
internal string _arrayElementTypeString;
internal Type _arrayElementType;
internal bool _isArrayVariant = false;
internal InternalPrimitiveTypeE _arrayElementTypeCode;
// Parsed array information
internal int _rank;
internal int[] _lengthA;
internal int[] _lowerBoundA;
// Array map for placing array elements in array
internal int[] _indexMap;
internal int _memberIndex;
internal int _linearlength;
internal int[] _rectangularMap;
internal bool _isLowerBound;
// MemberInfo accumulated during parsing of members
internal ReadObjectInfo _objectInfo;
// ValueType Fixup needed
internal bool _isValueTypeFixup = false;
// Created object
internal object _newObj;
internal object[] _objectA; //optimization, will contain object[]
internal PrimitiveArray _primitiveArray; // for Primitive Soap arrays, optimization
internal bool _isRegistered; // Used when registering nested classes
internal object[] _memberData; // member data is collected here before populating
internal SerializationInfo _si;
internal int _consecutiveNullArrayEntryCount;
internal ParseRecord() { }
// Initialize ParseRecord. Called when reusing.
internal void Init()
{
// Enums
_parseTypeEnum = InternalParseTypeE.Empty;
_objectTypeEnum = InternalObjectTypeE.Empty;
_arrayTypeEnum = InternalArrayTypeE.Empty;
_memberTypeEnum = InternalMemberTypeE.Empty;
_memberValueEnum = InternalMemberValueE.Empty;
_objectPositionEnum = InternalObjectPositionE.Empty;
// Object
_name = null;
// Value
_value = null;
// dt attribute
_keyDt = null;
_dtType = null;
_dtTypeCode = InternalPrimitiveTypeE.Invalid;
// Object ID
_objectId = 0;
// Reference ID
_idRef = 0;
// Array
// Array Element Type
_arrayElementTypeString = null;
_arrayElementType = null;
_isArrayVariant = false;
_arrayElementTypeCode = InternalPrimitiveTypeE.Invalid;
// Parsed array information
_rank = 0;
_lengthA = null;
_lowerBoundA = null;
// Array map for placing array elements in array
_indexMap = null;
_memberIndex = 0;
_linearlength = 0;
_rectangularMap = null;
_isLowerBound = false;
// ValueType Fixup needed
_isValueTypeFixup = false;
_newObj = null;
_objectA = null;
_primitiveArray = null;
_objectInfo = null;
_isRegistered = false;
_memberData = null;
_si = null;
_consecutiveNullArrayEntryCount = 0;
}
}
// Implements a stack used for parsing
internal sealed class SerStack
{
internal object[] _objects = new object[5];
internal string _stackId;
internal int _top = -1;
internal SerStack(string stackId)
{
_stackId = stackId;
}
// Push the object onto the stack
internal void Push(object obj)
{
if (_top == (_objects.Length - 1))
{
IncreaseCapacity();
}
_objects[++_top] = obj;
}
// Pop the object from the stack
internal object Pop()
{
if (_top < 0)
{
return null;
}
object obj = _objects[_top];
_objects[_top--] = null;
return obj;
}
internal void IncreaseCapacity()
{
int size = _objects.Length * 2;
object[] newItems = new object[size];
Array.Copy(_objects, 0, newItems, 0, _objects.Length);
_objects = newItems;
}
// Gets the object on the top of the stack
internal object Peek() => _top < 0 ? null : _objects[_top];
// Gets the second entry in the stack.
internal object PeekPeek() => _top < 1 ? null : _objects[_top - 1];
// The number of entries in the stack
internal bool IsEmpty() => _top <= 0;
}
// Implements a Growable array
internal sealed class SizedArray : ICloneable
{
internal object[] _objects = null;
internal object[] _negObjects = null;
internal SizedArray()
{
_objects = new object[16];
_negObjects = new object[4];
}
internal SizedArray(int length)
{
_objects = new object[length];
_negObjects = new object[length];
}
private SizedArray(SizedArray sizedArray)
{
_objects = new object[sizedArray._objects.Length];
sizedArray._objects.CopyTo(_objects, 0);
_negObjects = new object[sizedArray._negObjects.Length];
sizedArray._negObjects.CopyTo(_negObjects, 0);
}
public object Clone() => new SizedArray(this);
internal object this[int index]
{
get
{
if (index < 0)
{
return -index > _negObjects.Length - 1 ? null : _negObjects[-index];
}
else
{
return index > _objects.Length - 1 ? null : _objects[index];
}
}
set
{
if (index < 0)
{
if (-index > _negObjects.Length - 1)
{
IncreaseCapacity(index);
}
_negObjects[-index] = value;
}
else
{
if (index > _objects.Length - 1)
{
IncreaseCapacity(index);
}
_objects[index] = value;
}
}
}
internal void IncreaseCapacity(int index)
{
try
{
if (index < 0)
{
int size = Math.Max(_negObjects.Length * 2, (-index) + 1);
object[] newItems = new object[size];
Array.Copy(_negObjects, 0, newItems, 0, _negObjects.Length);
_negObjects = newItems;
}
else
{
int size = Math.Max(_objects.Length * 2, index + 1);
object[] newItems = new object[size];
Array.Copy(_objects, 0, newItems, 0, _objects.Length);
_objects = newItems;
}
}
catch (Exception)
{
throw new SerializationException(SR.Serialization_CorruptedStream);
}
}
}
internal sealed class IntSizedArray : ICloneable
{
internal int[] _objects = new int[16];
internal int[] _negObjects = new int[4];
public IntSizedArray() { }
private IntSizedArray(IntSizedArray sizedArray)
{
_objects = new int[sizedArray._objects.Length];
sizedArray._objects.CopyTo(_objects, 0);
_negObjects = new int[sizedArray._negObjects.Length];
sizedArray._negObjects.CopyTo(_negObjects, 0);
}
public object Clone() => new IntSizedArray(this);
internal int this[int index]
{
get
{
if (index < 0)
{
return -index > _negObjects.Length - 1 ? 0 : _negObjects[-index];
}
else
{
return index > _objects.Length - 1 ? 0 : _objects[index];
}
}
set
{
if (index < 0)
{
if (-index > _negObjects.Length - 1)
{
IncreaseCapacity(index);
}
_negObjects[-index] = value;
}
else
{
if (index > _objects.Length - 1)
{
IncreaseCapacity(index);
}
_objects[index] = value;
}
}
}
internal void IncreaseCapacity(int index)
{
try
{
if (index < 0)
{
int size = Math.Max(_negObjects.Length * 2, (-index) + 1);
int[] newItems = new int[size];
Array.Copy(_negObjects, 0, newItems, 0, _negObjects.Length);
_negObjects = newItems;
}
else
{
int size = Math.Max(_objects.Length * 2, index + 1);
int[] newItems = new int[size];
Array.Copy(_objects, 0, newItems, 0, _objects.Length);
_objects = newItems;
}
}
catch (Exception)
{
throw new SerializationException(SR.Serialization_CorruptedStream);
}
}
}
internal sealed class NameCache
{
private static readonly ConcurrentDictionary<string, object> s_ht = new ConcurrentDictionary<string, object>();
private string _name = null;
internal object GetCachedValue(string name)
{
_name = name;
object value;
return s_ht.TryGetValue(name, out value) ? value : null;
}
internal void SetCachedValue(object value) => s_ht[_name] = value;
}
// Used to fixup value types. Only currently used for valuetypes which are array items.
internal sealed class ValueFixup
{
internal ValueFixupEnum _valueFixupEnum = ValueFixupEnum.Empty;
internal Array _arrayObj;
internal int[] _indexMap;
internal object _header = null;
internal object _memberObject;
internal ReadObjectInfo _objectInfo;
internal string _memberName;
internal ValueFixup(Array arrayObj, int[] indexMap)
{
_valueFixupEnum = ValueFixupEnum.Array;
_arrayObj = arrayObj;
_indexMap = indexMap;
}
internal ValueFixup(object memberObject, string memberName, ReadObjectInfo objectInfo)
{
_valueFixupEnum = ValueFixupEnum.Member;
_memberObject = memberObject;
_memberName = memberName;
_objectInfo = objectInfo;
}
internal void Fixup(ParseRecord record, ParseRecord parent)
{
object obj = record._newObj;
switch (_valueFixupEnum)
{
case ValueFixupEnum.Array:
_arrayObj.SetValue(obj, _indexMap);
break;
case ValueFixupEnum.Header:
throw new PlatformNotSupportedException();
case ValueFixupEnum.Member:
if (_objectInfo._isSi)
{
_objectInfo._objectManager.RecordDelayedFixup(parent._objectId, _memberName, record._objectId);
}
else
{
MemberInfo memberInfo = _objectInfo.GetMemberInfo(_memberName);
if (memberInfo != null)
{
_objectInfo._objectManager.RecordFixup(parent._objectId, memberInfo, record._objectId);
}
}
break;
}
}
}
// Class used to transmit Enums from the XML and Binary Formatter class to the ObjectWriter and ObjectReader class
internal sealed class InternalFE
{
internal FormatterTypeStyle _typeFormat;
internal FormatterAssemblyStyle _assemblyFormat;
internal TypeFilterLevel _securityLevel;
internal InternalSerializerTypeE _serializerTypeEnum;
}
internal sealed class NameInfo
{
internal string _fullName; // Name from SerObjectInfo.GetType
internal long _objectId;
internal long _assemId;
internal InternalPrimitiveTypeE _primitiveTypeEnum = InternalPrimitiveTypeE.Invalid;
internal Type _type;
internal bool _isSealed;
internal bool _isArray;
internal bool _isArrayItem;
internal bool _transmitTypeOnObject;
internal bool _transmitTypeOnMember;
internal bool _isParentTypeOnObject;
internal InternalArrayTypeE _arrayEnum;
private bool _sealedStatusChecked = false;
internal NameInfo() { }
internal void Init()
{
_fullName = null;
_objectId = 0;
_assemId = 0;
_primitiveTypeEnum = InternalPrimitiveTypeE.Invalid;
_type = null;
_isSealed = false;
_transmitTypeOnObject = false;
_transmitTypeOnMember = false;
_isParentTypeOnObject = false;
_isArray = false;
_isArrayItem = false;
_arrayEnum = InternalArrayTypeE.Empty;
_sealedStatusChecked = false;
}
public bool IsSealed
{
get
{
if (!_sealedStatusChecked)
{
_isSealed = _type.IsSealed;
_sealedStatusChecked = true;
}
return _isSealed;
}
}
public string NIname
{
get { return _fullName ?? (_fullName = _type.FullName); }
set { _fullName = value; }
}
}
internal sealed class PrimitiveArray
{
private InternalPrimitiveTypeE _code;
private bool[] _booleanA = null;
private char[] _charA = null;
private double[] _doubleA = null;
private short[] _int16A = null;
private int[] _int32A = null;
private long[] _int64A = null;
private sbyte[] _sbyteA = null;
private float[] _singleA = null;
private ushort[] _uint16A = null;
private uint[] _uint32A = null;
private ulong[] _uint64A = null;
internal PrimitiveArray(InternalPrimitiveTypeE code, Array array)
{
_code = code;
switch (code)
{
case InternalPrimitiveTypeE.Boolean: _booleanA = (bool[])array; break;
case InternalPrimitiveTypeE.Char: _charA = (char[])array; break;
case InternalPrimitiveTypeE.Double: _doubleA = (double[])array; break;
case InternalPrimitiveTypeE.Int16: _int16A = (short[])array; break;
case InternalPrimitiveTypeE.Int32: _int32A = (int[])array; break;
case InternalPrimitiveTypeE.Int64: _int64A = (long[])array; break;
case InternalPrimitiveTypeE.SByte: _sbyteA = (sbyte[])array; break;
case InternalPrimitiveTypeE.Single: _singleA = (float[])array; break;
case InternalPrimitiveTypeE.UInt16: _uint16A = (ushort[])array; break;
case InternalPrimitiveTypeE.UInt32: _uint32A = (uint[])array; break;
case InternalPrimitiveTypeE.UInt64: _uint64A = (ulong[])array; break;
}
}
internal void SetValue(string value, int index)
{
switch (_code)
{
case InternalPrimitiveTypeE.Boolean:
_booleanA[index] = bool.Parse(value);
break;
case InternalPrimitiveTypeE.Char:
if ((value[0] == '_') && (value.Equals("_0x00_")))
{
_charA[index] = char.MinValue;
}
else
{
_charA[index] = char.Parse(value);
}
break;
case InternalPrimitiveTypeE.Double:
_doubleA[index] = double.Parse(value, CultureInfo.InvariantCulture);
break;
case InternalPrimitiveTypeE.Int16:
_int16A[index] = short.Parse(value, CultureInfo.InvariantCulture);
break;
case InternalPrimitiveTypeE.Int32:
_int32A[index] = int.Parse(value, CultureInfo.InvariantCulture);
break;
case InternalPrimitiveTypeE.Int64:
_int64A[index] = long.Parse(value, CultureInfo.InvariantCulture);
break;
case InternalPrimitiveTypeE.SByte:
_sbyteA[index] = sbyte.Parse(value, CultureInfo.InvariantCulture);
break;
case InternalPrimitiveTypeE.Single:
_singleA[index] = float.Parse(value, CultureInfo.InvariantCulture);
break;
case InternalPrimitiveTypeE.UInt16:
_uint16A[index] = ushort.Parse(value, CultureInfo.InvariantCulture);
break;
case InternalPrimitiveTypeE.UInt32:
_uint32A[index] = uint.Parse(value, CultureInfo.InvariantCulture);
break;
case InternalPrimitiveTypeE.UInt64:
_uint64A[index] = ulong.Parse(value, CultureInfo.InvariantCulture);
break;
}
}
}
}
| |
// -- FILE ------------------------------------------------------------------
// name : TimePeriodChain.cs
// project : Itenso Time Period
// created : Jani Giannoudis - 2011.02.18
// language : C# 4.0
// environment: .NET 2.0
// copyright : (c) 2011-2012 by Itenso GmbH, Switzerland
// --------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
namespace Itenso.TimePeriod
{
// ------------------------------------------------------------------------
public class TimePeriodChain : ITimePeriodChain
{
// ----------------------------------------------------------------------
public TimePeriodChain()
{
} // TimePeriodChain
// ----------------------------------------------------------------------
public TimePeriodChain( IEnumerable<ITimePeriod> timePeriods )
{
if ( timePeriods == null )
{
throw new ArgumentNullException( "timePeriods" );
}
AddAll( timePeriods );
} // TimePeriodChain
// ----------------------------------------------------------------------
public bool IsReadOnly
{
get { return false; }
} // IsReadOnly
// ----------------------------------------------------------------------
public ITimePeriod First
{
get { return periods.Count > 0 ? periods[ 0 ] : null; }
} // First
// ----------------------------------------------------------------------
public ITimePeriod Last
{
get { return periods.Count > 0 ? periods[ periods.Count - 1 ] : null; }
} // Last
// ----------------------------------------------------------------------
public int Count
{
get { return periods.Count; }
} // Count
// ----------------------------------------------------------------------
public ITimePeriod this[ int index ]
{
get { return periods[ index ]; }
set
{
RemoveAt( index );
Insert( index, value );
}
} // this[]
// ----------------------------------------------------------------------
public bool IsAnytime
{
get { return !HasStart && !HasEnd; }
} // IsAnytime
// ----------------------------------------------------------------------
public bool IsMoment
{
get { return Count != 0 && First.Start.Equals( Last.End ); }
} // IsMoment
// ----------------------------------------------------------------------
public bool HasStart
{
get { return Start != TimeSpec.MinPeriodDate; }
} // HasStart
// ----------------------------------------------------------------------
public DateTime Start
{
get { return Count > 0 ? First.Start : TimeSpec.MinPeriodDate; }
set
{
if ( Count == 0 )
{
return;
}
Move( value - Start );
}
} // Start
// ----------------------------------------------------------------------
public bool HasEnd
{
get { return End != TimeSpec.MaxPeriodDate; }
} // HasEnd
// ----------------------------------------------------------------------
public DateTime End
{
get { return Count > 0 ? Last.End : TimeSpec.MaxPeriodDate; }
set
{
if ( Count == 0 )
{
return;
}
Move( value - End );
}
} // End
// ----------------------------------------------------------------------
public TimeSpan Duration
{
get { return End - Start; }
} // Duration
// ----------------------------------------------------------------------
public string DurationDescription
{
get { return TimeFormatter.Instance.GetDuration( Duration, DurationFormatType.Detailed ); }
} // DurationDescription
// ----------------------------------------------------------------------
public virtual TimeSpan GetDuration( IDurationProvider provider )
{
if ( provider == null )
{
throw new ArgumentNullException( "provider" );
}
return provider.GetDuration( Start, End );
} // GetDuration
// ----------------------------------------------------------------------
public virtual void Setup( DateTime newStart, DateTime newEnd )
{
throw new InvalidOperationException();
} // Setup
// ----------------------------------------------------------------------
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
} // IEnumerable.GetEnumerator
// ----------------------------------------------------------------------
public IEnumerator<ITimePeriod> GetEnumerator()
{
return periods.GetEnumerator();
} // GetEnumerator
// ----------------------------------------------------------------------
public virtual void Move( TimeSpan delta )
{
if ( delta == TimeSpan.Zero )
{
return;
}
foreach ( ITimePeriod timePeriod in periods )
{
DateTime start = timePeriod.Start + delta;
timePeriod.Setup( start, start.Add( timePeriod.Duration ) );
}
} // Move
// ----------------------------------------------------------------------
public virtual void Add( ITimePeriod item )
{
if ( item == null )
{
throw new ArgumentNullException( "item" );
}
CheckReadOnlyItem( item );
ITimePeriod last = Last;
if ( last != null )
{
CheckSpaceAfter( last.End, item.Duration );
item.Setup( last.End, last.End.Add( item.Duration ) );
}
periods.Add( item );
} // Add
// ----------------------------------------------------------------------
public bool ContainsPeriod( ITimePeriod test )
{
if ( test == null )
{
throw new ArgumentNullException( "test" );
}
foreach ( ITimePeriod period in periods )
{
if ( period.IsSamePeriod( test ) )
{
return true;
}
}
return false;
} // ContainsPeriod
// ----------------------------------------------------------------------
public void AddAll( IEnumerable<ITimePeriod> timePeriods )
{
if ( timePeriods == null )
{
throw new ArgumentNullException( "timePeriods" );
}
foreach ( ITimePeriod period in timePeriods )
{
Add( period );
}
} // AddAll
// ----------------------------------------------------------------------
public virtual void Insert( int index, ITimePeriod period )
{
if ( index < 0 || index > Count )
{
throw new ArgumentOutOfRangeException( "index" );
}
if ( period == null )
{
throw new ArgumentNullException( "period" );
}
CheckReadOnlyItem( period );
TimeSpan itemDuration = period.Duration;
ITimePeriod previous = null;
ITimePeriod next = null;
if ( Count > 0 )
{
if ( index > 0 )
{
previous = this[ index - 1 ];
CheckSpaceAfter( End, itemDuration );
}
if ( index < Count - 1 )
{
next = this[ index ];
CheckSpaceBefore( Start, itemDuration );
}
}
periods.Insert( index, period );
// adjust time periods after the inserted item
if ( previous != null )
{
period.Setup( previous.End, previous.End + period.Duration );
for ( int i = index + 1; i < Count; i++ )
{
DateTime previousStart = this[ i ].Start.Add( itemDuration );
this[ i ].Setup( previousStart, previousStart.Add( this[ i ].Duration ) );
}
}
// adjust time periods before the inserted item
if ( next == null )
{
return;
}
DateTime nextStart = next.Start.Subtract( itemDuration );
period.Setup( nextStart, nextStart.Add( period.Duration ) );
for ( int i = 0; i < index - 1; i++ )
{
nextStart = this[ i ].Start.Subtract( itemDuration );
this[ i ].Setup( nextStart, nextStart.Add( this[ i ].Duration ) );
}
} // Insert
// ----------------------------------------------------------------------
public virtual bool Contains( ITimePeriod period )
{
if ( period == null )
{
throw new ArgumentNullException( "period" );
}
return periods.Contains( period );
} // Contains
// ----------------------------------------------------------------------
public virtual int IndexOf( ITimePeriod period )
{
if ( period == null )
{
throw new ArgumentNullException( "period" );
}
return periods.IndexOf( period );
} // IndexOf
// ----------------------------------------------------------------------
public virtual void CopyTo( ITimePeriod[] array, int arrayIndex )
{
if ( array == null )
{
throw new ArgumentNullException( "array" );
}
periods.CopyTo( array, arrayIndex );
} // CopyTo
// ----------------------------------------------------------------------
public virtual void Clear()
{
periods.Clear();
} // Clear
// ----------------------------------------------------------------------
public virtual bool Remove( ITimePeriod period )
{
if ( period == null )
{
throw new ArgumentNullException( "period" );
}
TimeSpan itemDuration = period.Duration;
int index = IndexOf( period );
ITimePeriod next = null;
if ( itemDuration > TimeSpan.Zero && Count > 1 && index > 0 && index < Count - 1 ) // between
{
next = this[ index ];
}
bool removed = periods.Remove( period );
if ( removed && next != null ) // fill the gap
{
for ( int i = index; i < Count; i++ )
{
DateTime start = this[ i ].Start.Subtract( itemDuration );
this[ i ].Setup( start, start.Add( this[ i ].Duration ) );
}
}
return removed;
} // Remove
// ----------------------------------------------------------------------
public virtual void RemoveAt( int index )
{
Remove( this[ index ] );
} // RemoveAt
// ----------------------------------------------------------------------
public virtual bool IsSamePeriod( ITimePeriod test )
{
if ( test == null )
{
throw new ArgumentNullException( "test" );
}
return Start == test.Start && End == test.End;
} // IsSamePeriod
// ----------------------------------------------------------------------
public virtual bool HasInside( DateTime test )
{
return TimePeriodCalc.HasInside( this, test );
} // HasInside
// ----------------------------------------------------------------------
public virtual bool HasInside( ITimePeriod test )
{
if ( test == null )
{
throw new ArgumentNullException( "test" );
}
return TimePeriodCalc.HasInside( this, test );
} // HasInside
// ----------------------------------------------------------------------
public virtual bool IntersectsWith( ITimePeriod test )
{
if ( test == null )
{
throw new ArgumentNullException( "test" );
}
return TimePeriodCalc.IntersectsWith( this, test );
} // IntersectsWith
// ----------------------------------------------------------------------
public virtual bool OverlapsWith( ITimePeriod test )
{
if ( test == null )
{
throw new ArgumentNullException( "test" );
}
return TimePeriodCalc.OverlapsWith( this, test );
} // OverlapsWith
// ----------------------------------------------------------------------
public virtual PeriodRelation GetRelation( ITimePeriod test )
{
if ( test == null )
{
throw new ArgumentNullException( "test" );
}
return TimePeriodCalc.GetRelation( this, test );
} // GetRelation
// ----------------------------------------------------------------------
public virtual int CompareTo( ITimePeriod other, ITimePeriodComparer comparer )
{
if ( other == null )
{
throw new ArgumentNullException( "other" );
}
if ( comparer == null )
{
throw new ArgumentNullException( "comparer" );
}
return comparer.Compare( this, other );
} // CompareTo
// ----------------------------------------------------------------------
public string GetDescription( ITimeFormatter formatter = null )
{
return Format( formatter ?? TimeFormatter.Instance );
} // GetDescription
// ----------------------------------------------------------------------
protected virtual string Format( ITimeFormatter formatter )
{
return formatter.GetCollectionPeriod( Count, Start, End, Duration );
} // Format
// ----------------------------------------------------------------------
public override string ToString()
{
return GetDescription();
} // ToString
// ----------------------------------------------------------------------
public sealed override bool Equals( object obj )
{
if ( obj == this )
{
return true;
}
if ( obj == null || GetType() != obj.GetType() )
{
return false;
}
return IsEqual( obj );
} // Equals
// ----------------------------------------------------------------------
protected virtual bool IsEqual( object obj )
{
return HasSameData( obj as TimePeriodChain );
} // IsEqual
// ----------------------------------------------------------------------
private bool HasSameData( IList<ITimePeriod> comp )
{
if ( Count != comp.Count )
{
return false;
}
for ( int i = 0; i < Count; i++ )
{
if ( !this[ i ].Equals( comp[ i ] ) )
{
return false;
}
}
return true;
} // HasSameData
// ----------------------------------------------------------------------
public sealed override int GetHashCode()
{
return HashTool.AddHashCode( GetType().GetHashCode(), ComputeHashCode() );
} // GetHashCode
// ----------------------------------------------------------------------
protected virtual int ComputeHashCode()
{
return HashTool.ComputeHashCode( periods );
} // ComputeHashCode
// ----------------------------------------------------------------------
protected void CheckSpaceBefore( DateTime moment, TimeSpan duration )
{
bool hasSpace = moment != TimeSpec.MinPeriodDate;
if ( hasSpace )
{
TimeSpan remaining = moment - TimeSpec.MinPeriodDate;
hasSpace = duration <= remaining;
}
if ( !hasSpace )
{
throw new InvalidOperationException( "duration " + duration + " out of range " );
}
} // CheckSpaceBefore
// ----------------------------------------------------------------------
protected void CheckSpaceAfter( DateTime moment, TimeSpan duration )
{
bool hasSpace = moment != TimeSpec.MaxPeriodDate;
if ( hasSpace )
{
TimeSpan remaining = TimeSpec.MaxPeriodDate - moment;
hasSpace = duration <= remaining;
}
if ( !hasSpace )
{
throw new InvalidOperationException( "duration " + duration + " out of range" );
}
} // CheckSpaceAfter
// ----------------------------------------------------------------------
protected void CheckReadOnlyItem( ITimePeriod timePeriod )
{
if ( timePeriod.IsReadOnly )
{
throw new NotSupportedException( "TimePeriod is read-only" );
}
} // CheckReadOnlyItem
// ----------------------------------------------------------------------
// members
private readonly List<ITimePeriod> periods = new List<ITimePeriod>();
} // class TimePeriodChain
} // namespace Itenso.TimePeriod
// -- EOF -------------------------------------------------------------------
| |
#region Header
/**
* JsonData.cs
* Generic type to hold JSON data (objects, arrays, and so on). This is
* the default type returned by JsonMapper.ToObject().
*
* The authors disclaim copyright to this source code. For more details, see
* the COPYING file included with this distribution.
**/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
namespace LitJsonStomt
{
public class JsonData : IJsonWrapper, IEquatable<JsonData>
{
#region Fields
private IList<JsonData> inst_array;
private bool inst_boolean;
private double inst_double;
private int inst_int;
private long inst_long;
private IDictionary<string, JsonData> inst_object;
private string inst_string;
private string json;
private JsonType type;
// Used to implement the IOrderedDictionary interface
private IList<KeyValuePair<string, JsonData>> object_list;
#endregion
#region Properties
public int Count {
get { return EnsureCollection ().Count; }
}
public bool IsArray {
get { return type == JsonType.Array; }
}
public bool IsBoolean {
get { return type == JsonType.Boolean; }
}
public bool IsDouble {
get { return type == JsonType.Double; }
}
public bool IsInt {
get { return type == JsonType.Int; }
}
public bool IsLong {
get { return type == JsonType.Long; }
}
public bool IsObject {
get { return type == JsonType.Object; }
}
public bool IsString {
get { return type == JsonType.String; }
}
public ICollection<string> Keys {
get { EnsureDictionary (); return inst_object.Keys; }
}
#endregion
#region ICollection Properties
int ICollection.Count {
get {
return Count;
}
}
bool ICollection.IsSynchronized {
get {
return EnsureCollection ().IsSynchronized;
}
}
object ICollection.SyncRoot {
get {
return EnsureCollection ().SyncRoot;
}
}
#endregion
#region IDictionary Properties
bool IDictionary.IsFixedSize {
get {
return EnsureDictionary ().IsFixedSize;
}
}
bool IDictionary.IsReadOnly {
get {
return EnsureDictionary ().IsReadOnly;
}
}
ICollection IDictionary.Keys {
get {
EnsureDictionary ();
IList<string> keys = new List<string> ();
foreach (KeyValuePair<string, JsonData> entry in
object_list) {
keys.Add (entry.Key);
}
return (ICollection) keys;
}
}
ICollection IDictionary.Values {
get {
EnsureDictionary ();
IList<JsonData> values = new List<JsonData> ();
foreach (KeyValuePair<string, JsonData> entry in
object_list) {
values.Add (entry.Value);
}
return (ICollection) values;
}
}
#endregion
#region IJsonWrapper Properties
bool IJsonWrapper.IsArray {
get { return IsArray; }
}
bool IJsonWrapper.IsBoolean {
get { return IsBoolean; }
}
bool IJsonWrapper.IsDouble {
get { return IsDouble; }
}
bool IJsonWrapper.IsInt {
get { return IsInt; }
}
bool IJsonWrapper.IsLong {
get { return IsLong; }
}
bool IJsonWrapper.IsObject {
get { return IsObject; }
}
bool IJsonWrapper.IsString {
get { return IsString; }
}
#endregion
#region IList Properties
bool IList.IsFixedSize {
get {
return EnsureList ().IsFixedSize;
}
}
bool IList.IsReadOnly {
get {
return EnsureList ().IsReadOnly;
}
}
#endregion
#region IDictionary Indexer
object IDictionary.this[object key] {
get {
return EnsureDictionary ()[key];
}
set {
if (! (key is String))
throw new ArgumentException (
"The key has to be a string");
JsonData data = ToJsonData (value);
this[(string) key] = data;
}
}
#endregion
#region IOrderedDictionary Indexer
object IOrderedDictionary.this[int idx] {
get {
EnsureDictionary ();
return object_list[idx].Value;
}
set {
EnsureDictionary ();
JsonData data = ToJsonData (value);
KeyValuePair<string, JsonData> old_entry = object_list[idx];
inst_object[old_entry.Key] = data;
KeyValuePair<string, JsonData> entry =
new KeyValuePair<string, JsonData> (old_entry.Key, data);
object_list[idx] = entry;
}
}
#endregion
#region IList Indexer
object IList.this[int index] {
get {
return EnsureList ()[index];
}
set {
EnsureList ();
JsonData data = ToJsonData (value);
this[index] = data;
}
}
#endregion
#region Public Indexers
public JsonData this[string prop_name] {
get {
EnsureDictionary ();
return inst_object[prop_name];
}
set {
EnsureDictionary ();
KeyValuePair<string, JsonData> entry =
new KeyValuePair<string, JsonData> (prop_name, value);
if (inst_object.ContainsKey (prop_name)) {
for (int i = 0; i < object_list.Count; i++) {
if (object_list[i].Key == prop_name) {
object_list[i] = entry;
break;
}
}
} else
object_list.Add (entry);
inst_object[prop_name] = value;
json = null;
}
}
public JsonData this[int index] {
get {
EnsureCollection ();
if (type == JsonType.Array)
return inst_array[index];
return object_list[index].Value;
}
set {
EnsureCollection ();
if (type == JsonType.Array)
inst_array[index] = value;
else {
KeyValuePair<string, JsonData> entry = object_list[index];
KeyValuePair<string, JsonData> new_entry =
new KeyValuePair<string, JsonData> (entry.Key, value);
object_list[index] = new_entry;
inst_object[entry.Key] = value;
}
json = null;
}
}
#endregion
#region Constructors
public JsonData ()
{
}
public JsonData (bool boolean)
{
type = JsonType.Boolean;
inst_boolean = boolean;
}
public JsonData (double number)
{
type = JsonType.Double;
inst_double = number;
}
public JsonData (int number)
{
type = JsonType.Int;
inst_int = number;
}
public JsonData (long number)
{
type = JsonType.Long;
inst_long = number;
}
public JsonData (object obj)
{
if (obj is Boolean) {
type = JsonType.Boolean;
inst_boolean = (bool) obj;
return;
}
if (obj is Double) {
type = JsonType.Double;
inst_double = (double) obj;
return;
}
if (obj is Int32) {
type = JsonType.Int;
inst_int = (int) obj;
return;
}
if (obj is Int64) {
type = JsonType.Long;
inst_long = (long) obj;
return;
}
if (obj is String) {
type = JsonType.String;
inst_string = (string) obj;
return;
}
throw new ArgumentException (
"Unable to wrap the given object with JsonData");
}
public JsonData (string str)
{
type = JsonType.String;
inst_string = str;
}
#endregion
#region Implicit Conversions
public static implicit operator JsonData (Boolean data)
{
return new JsonData (data);
}
public static implicit operator JsonData (Double data)
{
return new JsonData (data);
}
public static implicit operator JsonData (Int32 data)
{
return new JsonData (data);
}
public static implicit operator JsonData (Int64 data)
{
return new JsonData (data);
}
public static implicit operator JsonData (String data)
{
return new JsonData (data);
}
#endregion
#region Explicit Conversions
public static explicit operator Boolean (JsonData data)
{
if (data.type != JsonType.Boolean)
throw new InvalidCastException (
"Instance of JsonData doesn't hold a double");
return data.inst_boolean;
}
public static explicit operator Double (JsonData data)
{
if (data.type != JsonType.Double)
throw new InvalidCastException (
"Instance of JsonData doesn't hold a double");
return data.inst_double;
}
public static explicit operator Int32 (JsonData data)
{
if (data.type != JsonType.Int)
throw new InvalidCastException (
"Instance of JsonData doesn't hold an int");
return data.inst_int;
}
public static explicit operator Int64 (JsonData data)
{
if (data.type != JsonType.Long)
throw new InvalidCastException (
"Instance of JsonData doesn't hold an int");
return data.inst_long;
}
public static explicit operator String (JsonData data)
{
if (data.type != JsonType.String)
throw new InvalidCastException (
"Instance of JsonData doesn't hold a string");
return data.inst_string;
}
#endregion
#region ICollection Methods
void ICollection.CopyTo (Array array, int index)
{
EnsureCollection ().CopyTo (array, index);
}
#endregion
#region IDictionary Methods
void IDictionary.Add (object key, object value)
{
JsonData data = ToJsonData (value);
EnsureDictionary ().Add (key, data);
KeyValuePair<string, JsonData> entry =
new KeyValuePair<string, JsonData> ((string) key, data);
object_list.Add (entry);
json = null;
}
void IDictionary.Clear ()
{
EnsureDictionary ().Clear ();
object_list.Clear ();
json = null;
}
bool IDictionary.Contains (object key)
{
return EnsureDictionary ().Contains (key);
}
IDictionaryEnumerator IDictionary.GetEnumerator ()
{
return ((IOrderedDictionary) this).GetEnumerator ();
}
void IDictionary.Remove (object key)
{
EnsureDictionary ().Remove (key);
for (int i = 0; i < object_list.Count; i++) {
if (object_list[i].Key == (string) key) {
object_list.RemoveAt (i);
break;
}
}
json = null;
}
#endregion
#region IEnumerable Methods
IEnumerator IEnumerable.GetEnumerator ()
{
return EnsureCollection ().GetEnumerator ();
}
#endregion
#region IJsonWrapper Methods
bool IJsonWrapper.GetBoolean ()
{
if (type != JsonType.Boolean)
throw new InvalidOperationException (
"JsonData instance doesn't hold a boolean");
return inst_boolean;
}
double IJsonWrapper.GetDouble ()
{
if (type != JsonType.Double)
throw new InvalidOperationException (
"JsonData instance doesn't hold a double");
return inst_double;
}
int IJsonWrapper.GetInt ()
{
if (type != JsonType.Int)
throw new InvalidOperationException (
"JsonData instance doesn't hold an int");
return inst_int;
}
long IJsonWrapper.GetLong ()
{
if (type != JsonType.Long)
throw new InvalidOperationException (
"JsonData instance doesn't hold a long");
return inst_long;
}
string IJsonWrapper.GetString ()
{
if (type != JsonType.String)
throw new InvalidOperationException (
"JsonData instance doesn't hold a string");
return inst_string;
}
void IJsonWrapper.SetBoolean (bool val)
{
type = JsonType.Boolean;
inst_boolean = val;
json = null;
}
void IJsonWrapper.SetDouble (double val)
{
type = JsonType.Double;
inst_double = val;
json = null;
}
void IJsonWrapper.SetInt (int val)
{
type = JsonType.Int;
inst_int = val;
json = null;
}
void IJsonWrapper.SetLong (long val)
{
type = JsonType.Long;
inst_long = val;
json = null;
}
void IJsonWrapper.SetString (string val)
{
type = JsonType.String;
inst_string = val;
json = null;
}
string IJsonWrapper.ToJson ()
{
return ToJson ();
}
void IJsonWrapper.ToJson (JsonWriter writer)
{
ToJson (writer);
}
#endregion
#region IList Methods
int IList.Add (object value)
{
return Add (value);
}
void IList.Clear ()
{
EnsureList ().Clear ();
json = null;
}
bool IList.Contains (object value)
{
return EnsureList ().Contains (value);
}
int IList.IndexOf (object value)
{
return EnsureList ().IndexOf (value);
}
void IList.Insert (int index, object value)
{
EnsureList ().Insert (index, value);
json = null;
}
void IList.Remove (object value)
{
EnsureList ().Remove (value);
json = null;
}
void IList.RemoveAt (int index)
{
EnsureList ().RemoveAt (index);
json = null;
}
#endregion
#region IOrderedDictionary Methods
IDictionaryEnumerator IOrderedDictionary.GetEnumerator ()
{
EnsureDictionary ();
return new OrderedDictionaryEnumerator (
object_list.GetEnumerator ());
}
void IOrderedDictionary.Insert (int idx, object key, object value)
{
string property = (string) key;
JsonData data = ToJsonData (value);
this[property] = data;
KeyValuePair<string, JsonData> entry =
new KeyValuePair<string, JsonData> (property, data);
object_list.Insert (idx, entry);
}
void IOrderedDictionary.RemoveAt (int idx)
{
EnsureDictionary ();
inst_object.Remove (object_list[idx].Key);
object_list.RemoveAt (idx);
}
#endregion
#region Private Methods
private ICollection EnsureCollection ()
{
if (type == JsonType.Array)
return (ICollection) inst_array;
if (type == JsonType.Object)
return (ICollection) inst_object;
throw new InvalidOperationException (
"The JsonData instance has to be initialized first");
}
private IDictionary EnsureDictionary ()
{
if (type == JsonType.Object)
return (IDictionary) inst_object;
if (type != JsonType.None)
throw new InvalidOperationException (
"Instance of JsonData is not a dictionary");
type = JsonType.Object;
inst_object = new Dictionary<string, JsonData> ();
object_list = new List<KeyValuePair<string, JsonData>> ();
return (IDictionary) inst_object;
}
private IList EnsureList ()
{
if (type == JsonType.Array)
return (IList) inst_array;
if (type != JsonType.None)
throw new InvalidOperationException (
"Instance of JsonData is not a list");
type = JsonType.Array;
inst_array = new List<JsonData> ();
return (IList) inst_array;
}
private JsonData ToJsonData (object obj)
{
if (obj == null)
return null;
if (obj is JsonData)
return (JsonData) obj;
return new JsonData (obj);
}
private static void WriteJson (IJsonWrapper obj, JsonWriter writer)
{
if (obj == null) {
writer.Write (null);
return;
}
if (obj.IsString) {
writer.Write (obj.GetString ());
return;
}
if (obj.IsBoolean) {
writer.Write (obj.GetBoolean ());
return;
}
if (obj.IsDouble) {
writer.Write (obj.GetDouble ());
return;
}
if (obj.IsInt) {
writer.Write (obj.GetInt ());
return;
}
if (obj.IsLong) {
writer.Write (obj.GetLong ());
return;
}
if (obj.IsArray) {
writer.WriteArrayStart ();
foreach (object elem in (IList) obj)
WriteJson ((JsonData) elem, writer);
writer.WriteArrayEnd ();
return;
}
if (obj.IsObject) {
writer.WriteObjectStart ();
foreach (DictionaryEntry entry in ((IDictionary) obj)) {
writer.WritePropertyName ((string) entry.Key);
WriteJson ((JsonData) entry.Value, writer);
}
writer.WriteObjectEnd ();
return;
}
}
#endregion
public int Add (object value)
{
JsonData data = ToJsonData (value);
json = null;
return EnsureList ().Add (data);
}
public void Clear ()
{
if (IsObject) {
((IDictionary) this).Clear ();
return;
}
if (IsArray) {
((IList) this).Clear ();
return;
}
}
public bool Equals (JsonData x)
{
if (x == null)
return false;
if (x.type != this.type)
return false;
switch (this.type) {
case JsonType.None:
return true;
case JsonType.Object:
return this.inst_object.Equals (x.inst_object);
case JsonType.Array:
return this.inst_array.Equals (x.inst_array);
case JsonType.String:
return this.inst_string.Equals (x.inst_string);
case JsonType.Int:
return this.inst_int.Equals (x.inst_int);
case JsonType.Long:
return this.inst_long.Equals (x.inst_long);
case JsonType.Double:
return this.inst_double.Equals (x.inst_double);
case JsonType.Boolean:
return this.inst_boolean.Equals (x.inst_boolean);
}
return false;
}
public JsonType GetJsonType ()
{
return type;
}
public void SetJsonType (JsonType type)
{
if (this.type == type)
return;
switch (type) {
case JsonType.None:
break;
case JsonType.Object:
inst_object = new Dictionary<string, JsonData> ();
object_list = new List<KeyValuePair<string, JsonData>> ();
break;
case JsonType.Array:
inst_array = new List<JsonData> ();
break;
case JsonType.String:
inst_string = default (String);
break;
case JsonType.Int:
inst_int = default (Int32);
break;
case JsonType.Long:
inst_long = default (Int64);
break;
case JsonType.Double:
inst_double = default (Double);
break;
case JsonType.Boolean:
inst_boolean = default (Boolean);
break;
}
this.type = type;
}
public string ToJson ()
{
if (json != null)
return json;
StringWriter sw = new StringWriter ();
JsonWriter writer = new JsonWriter (sw);
writer.Validate = false;
WriteJson (this, writer);
json = sw.ToString ();
return json;
}
public void ToJson (JsonWriter writer)
{
bool old_validate = writer.Validate;
writer.Validate = false;
WriteJson (this, writer);
writer.Validate = old_validate;
}
public override string ToString ()
{
switch (type) {
case JsonType.Array:
return "JsonData array";
case JsonType.Boolean:
return inst_boolean.ToString ();
case JsonType.Double:
return inst_double.ToString ();
case JsonType.Int:
return inst_int.ToString ();
case JsonType.Long:
return inst_long.ToString ();
case JsonType.Object:
return "JsonData object";
case JsonType.String:
return inst_string;
}
return "Uninitialized JsonData";
}
}
internal class OrderedDictionaryEnumerator : IDictionaryEnumerator
{
IEnumerator<KeyValuePair<string, JsonData>> list_enumerator;
public object Current {
get { return Entry; }
}
public DictionaryEntry Entry {
get {
KeyValuePair<string, JsonData> curr = list_enumerator.Current;
return new DictionaryEntry (curr.Key, curr.Value);
}
}
public object Key {
get { return list_enumerator.Current.Key; }
}
public object Value {
get { return list_enumerator.Current.Value; }
}
public OrderedDictionaryEnumerator (
IEnumerator<KeyValuePair<string, JsonData>> enumerator)
{
list_enumerator = enumerator;
}
public bool MoveNext ()
{
return list_enumerator.MoveNext ();
}
public void Reset ()
{
list_enumerator.Reset ();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DataLake.Analytics
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Creates an Azure Data Lake Analytics account management client.
/// </summary>
public partial class DataLakeAnalyticsAccountManagementClient : ServiceClient<DataLakeAnalyticsAccountManagementClient>, IDataLakeAnalyticsAccountManagementClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Get subscription credentials which uniquely identify Microsoft Azure
/// subscription. The subscription ID forms part of the URI for every service
/// call.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// Client Api Version.
/// </summary>
public string ApiVersion { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IAccountOperations.
/// </summary>
public virtual IAccountOperations Account { get; private set; }
/// <summary>
/// Initializes a new instance of the DataLakeAnalyticsAccountManagementClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected DataLakeAnalyticsAccountManagementClient(params DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the DataLakeAnalyticsAccountManagementClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected DataLakeAnalyticsAccountManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the DataLakeAnalyticsAccountManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected DataLakeAnalyticsAccountManagementClient(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the DataLakeAnalyticsAccountManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected DataLakeAnalyticsAccountManagementClient(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the DataLakeAnalyticsAccountManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal DataLakeAnalyticsAccountManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the DataLakeAnalyticsAccountManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal DataLakeAnalyticsAccountManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the DataLakeAnalyticsAccountManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal DataLakeAnalyticsAccountManagementClient(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the DataLakeAnalyticsAccountManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal DataLakeAnalyticsAccountManagementClient(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.Account = new AccountOperations(this);
this.BaseUri = new Uri("https://management.azure.com");
this.ApiVersion = "2015-10-01-preview";
this.AcceptLanguage = "en-US";
this.LongRunningOperationRetryTimeout = 30;
this.GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Net.Security;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Security.Cryptography.X509Certificates;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using Mono.Addins;
/*****************************************************
*
* ScriptsHttpRequests
*
* Implements the llHttpRequest and http_response
* callback.
*
* Some stuff was already in LSLLongCmdHandler, and then
* there was this file with a stub class in it. So,
* I am moving some of the objects and functions out of
* LSLLongCmdHandler, such as the HttpRequestClass, the
* start and stop methods, and setting up pending and
* completed queues. These are processed in the
* LSLLongCmdHandler polling loop. Similiar to the
* XMLRPCModule, since that seems to work.
*
* //TODO
*
* This probably needs some throttling mechanism but
* it's wide open right now. This applies to both
* number of requests and data volume.
*
* Linden puts all kinds of header fields in the requests.
* Not doing any of that:
* User-Agent
* X-SecondLife-Shard
* X-SecondLife-Object-Name
* X-SecondLife-Object-Key
* X-SecondLife-Region
* X-SecondLife-Local-Position
* X-SecondLife-Local-Velocity
* X-SecondLife-Local-Rotation
* X-SecondLife-Owner-Name
* X-SecondLife-Owner-Key
*
* HTTPS support
*
* Configurable timeout?
* Configurable max response size?
* Configurable
*
* **************************************************/
namespace OpenSim.Region.CoreModules.Scripting.HttpRequest
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "HttpRequestModule")]
public class HttpRequestModule : ISharedRegionModule, IHttpRequestModule
{
private object HttpListLock = new object();
private int httpTimeout = 30000;
private string m_name = "HttpScriptRequests";
private string m_proxyurl = "";
private string m_proxyexcepts = "";
// <request id, HttpRequestClass>
private Dictionary<UUID, HttpRequestClass> m_pendingRequests;
private Scene m_scene;
// private Queue<HttpRequestClass> rpcQueue = new Queue<HttpRequestClass>();
public HttpRequestModule()
{
ServicePointManager.ServerCertificateValidationCallback +=ValidateServerCertificate;
}
public static bool ValidateServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
// If this is a web request we need to check the headers first
// We may want to ignore SSL
if (sender is HttpWebRequest)
{
HttpWebRequest Request = (HttpWebRequest)sender;
ServicePoint sp = Request.ServicePoint;
// We don't case about encryption, get out of here
if (Request.Headers.Get("NoVerifyCert") != null)
{
return true;
}
// If there was an upstream cert verification error, bail
if ((((int)sslPolicyErrors) & ~4) != 0)
return false;
// Check for policy and execute it if defined
if (ServicePointManager.CertificatePolicy != null)
{
return ServicePointManager.CertificatePolicy.CheckValidationResult (sp, certificate, Request, 0);
}
return true;
}
// If it's not HTTP, trust .NET to check it
if ((((int)sslPolicyErrors) & ~4) != 0)
return false;
return true;
}
#region IHttpRequestModule Members
public UUID MakeHttpRequest(string url, string parameters, string body)
{
return UUID.Zero;
}
public UUID StartHttpRequest(uint localID, UUID itemID, string url, List<string> parameters, Dictionary<string, string> headers, string body)
{
UUID reqID = UUID.Random();
HttpRequestClass htc = new HttpRequestClass();
// Partial implementation: support for parameter flags needed
// see http://wiki.secondlife.com/wiki/LlHTTPRequest
//
// Parameters are expected in {key, value, ... , key, value}
if (parameters != null)
{
string[] parms = parameters.ToArray();
for (int i = 0; i < parms.Length; i += 2)
{
switch (Int32.Parse(parms[i]))
{
case (int)HttpRequestConstants.HTTP_METHOD:
htc.HttpMethod = parms[i + 1];
break;
case (int)HttpRequestConstants.HTTP_MIMETYPE:
htc.HttpMIMEType = parms[i + 1];
break;
case (int)HttpRequestConstants.HTTP_BODY_MAXLENGTH:
// TODO implement me
break;
case (int)HttpRequestConstants.HTTP_VERIFY_CERT:
htc.HttpVerifyCert = (int.Parse(parms[i + 1]) != 0);
break;
case (int)HttpRequestConstants.HTTP_VERBOSE_THROTTLE:
// TODO implement me
break;
case (int)HttpRequestConstants.HTTP_CUSTOM_HEADER:
//Parameters are in pairs and custom header takes
//arguments in pairs so adjust for header marker.
++i;
//Maximum of 8 headers are allowed based on the
//Second Life documentation for llHTTPRequest.
for (int count = 1; count <= 8; ++count)
{
//Not enough parameters remaining for a header?
if (parms.Length - i < 2)
break;
//Have we reached the end of the list of headers?
//End is marked by a string with a single digit.
//We already know we have at least one parameter
//so it is safe to do this check at top of loop.
if (Char.IsDigit(parms[i][0]))
break;
if (htc.HttpCustomHeaders == null)
htc.HttpCustomHeaders = new List<string>();
htc.HttpCustomHeaders.Add(parms[i]);
htc.HttpCustomHeaders.Add(parms[i+1]);
i += 2;
}
break;
case (int)HttpRequestConstants.HTTP_PRAGMA_NO_CACHE:
htc.HttpPragmaNoCache = (int.Parse(parms[i + 1]) != 0);
break;
}
}
}
htc.LocalID = localID;
htc.ItemID = itemID;
htc.Url = url;
htc.ReqID = reqID;
htc.HttpTimeout = httpTimeout;
htc.OutboundBody = body;
htc.ResponseHeaders = headers;
htc.proxyurl = m_proxyurl;
htc.proxyexcepts = m_proxyexcepts;
lock (HttpListLock)
{
m_pendingRequests.Add(reqID, htc);
}
htc.Process();
return reqID;
}
public void StopHttpRequestsForScript(UUID id)
{
if (m_pendingRequests != null)
{
List<UUID> keysToRemove = null;
lock (HttpListLock)
{
foreach (HttpRequestClass req in m_pendingRequests.Values)
{
if (req.ItemID == id)
{
req.Stop();
if (keysToRemove == null)
keysToRemove = new List<UUID>();
keysToRemove.Add(req.ReqID);
}
}
if (keysToRemove != null)
keysToRemove.ForEach(keyToRemove => m_pendingRequests.Remove(keyToRemove));
}
}
}
/*
* TODO
* Not sure how important ordering is is here - the next first
* one completed in the list is returned, based soley on its list
* position, not the order in which the request was started or
* finished. I thought about setting up a queue for this, but
* it will need some refactoring and this works 'enough' right now
*/
public IServiceRequest GetNextCompletedRequest()
{
lock (HttpListLock)
{
foreach (HttpRequestClass req in m_pendingRequests.Values)
{
if (req.Finished)
return req;
}
}
return null;
}
public void RemoveCompletedRequest(UUID id)
{
lock (HttpListLock)
{
HttpRequestClass tmpReq;
if (m_pendingRequests.TryGetValue(id, out tmpReq))
{
tmpReq.Stop();
tmpReq = null;
m_pendingRequests.Remove(id);
}
}
}
#endregion
#region ISharedRegionModule Members
public void Initialise(IConfigSource config)
{
m_proxyurl = config.Configs["Startup"].GetString("HttpProxy");
m_proxyexcepts = config.Configs["Startup"].GetString("HttpProxyExceptions");
m_pendingRequests = new Dictionary<UUID, HttpRequestClass>();
}
public void AddRegion(Scene scene)
{
m_scene = scene;
m_scene.RegisterModuleInterface<IHttpRequestModule>(this);
}
public void RemoveRegion(Scene scene)
{
scene.UnregisterModuleInterface<IHttpRequestModule>(this);
if (scene == m_scene)
m_scene = null;
}
public void PostInitialise()
{
}
public void RegionLoaded(Scene scene)
{
}
public void Close()
{
}
public string Name
{
get { return m_name; }
}
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
}
public class HttpRequestClass: IServiceRequest
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// Constants for parameters
// public const int HTTP_BODY_MAXLENGTH = 2;
// public const int HTTP_METHOD = 0;
// public const int HTTP_MIMETYPE = 1;
// public const int HTTP_VERIFY_CERT = 3;
// public const int HTTP_VERBOSE_THROTTLE = 4;
// public const int HTTP_CUSTOM_HEADER = 5;
// public const int HTTP_PRAGMA_NO_CACHE = 6;
private bool _finished;
public bool Finished
{
get { return _finished; }
}
// public int HttpBodyMaxLen = 2048; // not implemented
// Parameter members and default values
public string HttpMethod = "GET";
public string HttpMIMEType = "text/plain;charset=utf-8";
public int HttpTimeout;
public bool HttpVerifyCert = true;
//public bool HttpVerboseThrottle = true; // not implemented
public List<string> HttpCustomHeaders = null;
public bool HttpPragmaNoCache = true;
// Request info
private UUID _itemID;
public UUID ItemID
{
get { return _itemID; }
set { _itemID = value; }
}
private uint _localID;
public uint LocalID
{
get { return _localID; }
set { _localID = value; }
}
public DateTime Next;
public string proxyurl;
public string proxyexcepts;
public string OutboundBody;
private UUID _reqID;
public UUID ReqID
{
get { return _reqID; }
set { _reqID = value; }
}
public WebRequest Request;
public string ResponseBody;
public List<string> ResponseMetadata;
public Dictionary<string, string> ResponseHeaders;
public int Status;
public string Url;
public void Process()
{
SendRequest();
}
public void SendRequest()
{
try
{
Request = WebRequest.Create(Url);
Request.Method = HttpMethod;
Request.ContentType = HttpMIMEType;
if (!HttpVerifyCert)
{
// We could hijack Connection Group Name to identify
// a desired security exception. But at the moment we'll use a dummy header instead.
// Request.ConnectionGroupName = "NoVerify";
Request.Headers.Add("NoVerifyCert", "true");
}
// else
// {
// Request.ConnectionGroupName="Verify";
// }
if (!HttpPragmaNoCache)
{
Request.Headers.Add("Pragma", "no-cache");
}
if (HttpCustomHeaders != null)
{
for (int i = 0; i < HttpCustomHeaders.Count; i += 2)
Request.Headers.Add(HttpCustomHeaders[i],
HttpCustomHeaders[i+1]);
}
if (!string.IsNullOrEmpty(proxyurl))
{
if (!string.IsNullOrEmpty(proxyexcepts))
{
string[] elist = proxyexcepts.Split(';');
Request.Proxy = new WebProxy(proxyurl, true, elist);
}
else
{
Request.Proxy = new WebProxy(proxyurl, true);
}
}
if (ResponseHeaders != null)
{
foreach (KeyValuePair<string, string> entry in ResponseHeaders)
if (entry.Key.ToLower().Equals("user-agent") && Request is HttpWebRequest)
((HttpWebRequest)Request).UserAgent = entry.Value;
else
Request.Headers[entry.Key] = entry.Value;
}
// Encode outbound data
if (!string.IsNullOrEmpty(OutboundBody))
{
byte[] data = Util.UTF8.GetBytes(OutboundBody);
Request.ContentLength = data.Length;
using (Stream bstream = Request.GetRequestStream())
bstream.Write(data, 0, data.Length);
}
try
{
IAsyncResult result = (IAsyncResult)Request.BeginGetResponse(ResponseCallback, null);
ThreadPool.RegisterWaitForSingleObject(
result.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), null, HttpTimeout, true);
}
catch (WebException e)
{
if (e.Status != WebExceptionStatus.ProtocolError)
{
throw;
}
HttpWebResponse response = (HttpWebResponse)e.Response;
Status = (int)response.StatusCode;
ResponseBody = response.StatusDescription;
_finished = true;
}
}
catch (Exception e)
{
// m_log.Debug(
// string.Format("[SCRIPTS HTTP REQUESTS]: Exception on request to {0} for {1} ", Url, ItemID), e);
Status = (int)OSHttpStatusCode.ClientErrorJoker;
ResponseBody = e.Message;
_finished = true;
}
}
private void ResponseCallback(IAsyncResult ar)
{
HttpWebResponse response = null;
try
{
try
{
response = (HttpWebResponse)Request.EndGetResponse(ar);
}
catch (WebException e)
{
if (e.Status != WebExceptionStatus.ProtocolError)
{
throw;
}
response = (HttpWebResponse)e.Response;
}
Status = (int)response.StatusCode;
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
ResponseBody = reader.ReadToEnd();
}
}
catch (Exception e)
{
Status = (int)OSHttpStatusCode.ClientErrorJoker;
ResponseBody = e.Message;
// m_log.Debug(
// string.Format("[SCRIPTS HTTP REQUESTS]: Exception on response to {0} for {1} ", Url, ItemID), e);
}
finally
{
if (response != null)
response.Close();
_finished = true;
}
}
private void TimeoutCallback(object state, bool timedOut)
{
if (timedOut)
Request.Abort();
}
public void Stop()
{
// m_log.DebugFormat("[SCRIPTS HTTP REQUESTS]: Stopping request to {0} for {1} ", Url, ItemID);
if (Request != null)
Request.Abort();
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the PnPrestacion class.
/// </summary>
[Serializable]
public partial class PnPrestacionCollection : ActiveList<PnPrestacion, PnPrestacionCollection>
{
public PnPrestacionCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>PnPrestacionCollection</returns>
public PnPrestacionCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
PnPrestacion o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the PN_prestacion table.
/// </summary>
[Serializable]
public partial class PnPrestacion : ActiveRecord<PnPrestacion>, IActiveRecord
{
#region .ctors and Default Settings
public PnPrestacion()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public PnPrestacion(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public PnPrestacion(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public PnPrestacion(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("PN_prestacion", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdPrestacion = new TableSchema.TableColumn(schema);
colvarIdPrestacion.ColumnName = "id_prestacion";
colvarIdPrestacion.DataType = DbType.Int32;
colvarIdPrestacion.MaxLength = 0;
colvarIdPrestacion.AutoIncrement = true;
colvarIdPrestacion.IsNullable = false;
colvarIdPrestacion.IsPrimaryKey = true;
colvarIdPrestacion.IsForeignKey = false;
colvarIdPrestacion.IsReadOnly = false;
colvarIdPrestacion.DefaultSetting = @"";
colvarIdPrestacion.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdPrestacion);
TableSchema.TableColumn colvarIdComprobante = new TableSchema.TableColumn(schema);
colvarIdComprobante.ColumnName = "id_comprobante";
colvarIdComprobante.DataType = DbType.Int32;
colvarIdComprobante.MaxLength = 0;
colvarIdComprobante.AutoIncrement = false;
colvarIdComprobante.IsNullable = false;
colvarIdComprobante.IsPrimaryKey = false;
colvarIdComprobante.IsForeignKey = true;
colvarIdComprobante.IsReadOnly = false;
colvarIdComprobante.DefaultSetting = @"";
colvarIdComprobante.ForeignKeyTableName = "PN_comprobante";
schema.Columns.Add(colvarIdComprobante);
TableSchema.TableColumn colvarIdNomenclador = new TableSchema.TableColumn(schema);
colvarIdNomenclador.ColumnName = "id_nomenclador";
colvarIdNomenclador.DataType = DbType.Int32;
colvarIdNomenclador.MaxLength = 0;
colvarIdNomenclador.AutoIncrement = false;
colvarIdNomenclador.IsNullable = false;
colvarIdNomenclador.IsPrimaryKey = false;
colvarIdNomenclador.IsForeignKey = true;
colvarIdNomenclador.IsReadOnly = false;
colvarIdNomenclador.DefaultSetting = @"";
colvarIdNomenclador.ForeignKeyTableName = "PN_nomenclador";
schema.Columns.Add(colvarIdNomenclador);
TableSchema.TableColumn colvarCantidad = new TableSchema.TableColumn(schema);
colvarCantidad.ColumnName = "cantidad";
colvarCantidad.DataType = DbType.Int32;
colvarCantidad.MaxLength = 0;
colvarCantidad.AutoIncrement = false;
colvarCantidad.IsNullable = true;
colvarCantidad.IsPrimaryKey = false;
colvarCantidad.IsForeignKey = false;
colvarCantidad.IsReadOnly = false;
colvarCantidad.DefaultSetting = @"";
colvarCantidad.ForeignKeyTableName = "";
schema.Columns.Add(colvarCantidad);
TableSchema.TableColumn colvarPrecioPrestacion = new TableSchema.TableColumn(schema);
colvarPrecioPrestacion.ColumnName = "precio_prestacion";
colvarPrecioPrestacion.DataType = DbType.Decimal;
colvarPrecioPrestacion.MaxLength = 0;
colvarPrecioPrestacion.AutoIncrement = false;
colvarPrecioPrestacion.IsNullable = true;
colvarPrecioPrestacion.IsPrimaryKey = false;
colvarPrecioPrestacion.IsForeignKey = false;
colvarPrecioPrestacion.IsReadOnly = false;
colvarPrecioPrestacion.DefaultSetting = @"";
colvarPrecioPrestacion.ForeignKeyTableName = "";
schema.Columns.Add(colvarPrecioPrestacion);
TableSchema.TableColumn colvarIdAnexo = new TableSchema.TableColumn(schema);
colvarIdAnexo.ColumnName = "id_anexo";
colvarIdAnexo.DataType = DbType.Int32;
colvarIdAnexo.MaxLength = 0;
colvarIdAnexo.AutoIncrement = false;
colvarIdAnexo.IsNullable = true;
colvarIdAnexo.IsPrimaryKey = false;
colvarIdAnexo.IsForeignKey = false;
colvarIdAnexo.IsReadOnly = false;
colvarIdAnexo.DefaultSetting = @"";
colvarIdAnexo.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdAnexo);
TableSchema.TableColumn colvarPeso = new TableSchema.TableColumn(schema);
colvarPeso.ColumnName = "peso";
colvarPeso.DataType = DbType.Decimal;
colvarPeso.MaxLength = 0;
colvarPeso.AutoIncrement = false;
colvarPeso.IsNullable = true;
colvarPeso.IsPrimaryKey = false;
colvarPeso.IsForeignKey = false;
colvarPeso.IsReadOnly = false;
colvarPeso.DefaultSetting = @"";
colvarPeso.ForeignKeyTableName = "";
schema.Columns.Add(colvarPeso);
TableSchema.TableColumn colvarTensionArterial = new TableSchema.TableColumn(schema);
colvarTensionArterial.ColumnName = "tension_arterial";
colvarTensionArterial.DataType = DbType.AnsiString;
colvarTensionArterial.MaxLength = -1;
colvarTensionArterial.AutoIncrement = false;
colvarTensionArterial.IsNullable = true;
colvarTensionArterial.IsPrimaryKey = false;
colvarTensionArterial.IsForeignKey = false;
colvarTensionArterial.IsReadOnly = false;
colvarTensionArterial.DefaultSetting = @"";
colvarTensionArterial.ForeignKeyTableName = "";
schema.Columns.Add(colvarTensionArterial);
TableSchema.TableColumn colvarDiagnostico = new TableSchema.TableColumn(schema);
colvarDiagnostico.ColumnName = "diagnostico";
colvarDiagnostico.DataType = DbType.AnsiString;
colvarDiagnostico.MaxLength = -1;
colvarDiagnostico.AutoIncrement = false;
colvarDiagnostico.IsNullable = true;
colvarDiagnostico.IsPrimaryKey = false;
colvarDiagnostico.IsForeignKey = false;
colvarDiagnostico.IsReadOnly = false;
colvarDiagnostico.DefaultSetting = @"";
colvarDiagnostico.ForeignKeyTableName = "";
schema.Columns.Add(colvarDiagnostico);
TableSchema.TableColumn colvarEdad = new TableSchema.TableColumn(schema);
colvarEdad.ColumnName = "edad";
colvarEdad.DataType = DbType.AnsiString;
colvarEdad.MaxLength = 2;
colvarEdad.AutoIncrement = false;
colvarEdad.IsNullable = true;
colvarEdad.IsPrimaryKey = false;
colvarEdad.IsForeignKey = false;
colvarEdad.IsReadOnly = false;
colvarEdad.DefaultSetting = @"";
colvarEdad.ForeignKeyTableName = "";
schema.Columns.Add(colvarEdad);
TableSchema.TableColumn colvarSexo = new TableSchema.TableColumn(schema);
colvarSexo.ColumnName = "sexo";
colvarSexo.DataType = DbType.AnsiString;
colvarSexo.MaxLength = 2;
colvarSexo.AutoIncrement = false;
colvarSexo.IsNullable = true;
colvarSexo.IsPrimaryKey = false;
colvarSexo.IsForeignKey = false;
colvarSexo.IsReadOnly = false;
colvarSexo.DefaultSetting = @"";
colvarSexo.ForeignKeyTableName = "";
schema.Columns.Add(colvarSexo);
TableSchema.TableColumn colvarCodigoComp = new TableSchema.TableColumn(schema);
colvarCodigoComp.ColumnName = "codigo_comp";
colvarCodigoComp.DataType = DbType.AnsiString;
colvarCodigoComp.MaxLength = -1;
colvarCodigoComp.AutoIncrement = false;
colvarCodigoComp.IsNullable = true;
colvarCodigoComp.IsPrimaryKey = false;
colvarCodigoComp.IsForeignKey = false;
colvarCodigoComp.IsReadOnly = false;
colvarCodigoComp.DefaultSetting = @"";
colvarCodigoComp.ForeignKeyTableName = "";
schema.Columns.Add(colvarCodigoComp);
TableSchema.TableColumn colvarFechaNacimiento = new TableSchema.TableColumn(schema);
colvarFechaNacimiento.ColumnName = "fecha_nacimiento";
colvarFechaNacimiento.DataType = DbType.DateTime;
colvarFechaNacimiento.MaxLength = 0;
colvarFechaNacimiento.AutoIncrement = false;
colvarFechaNacimiento.IsNullable = true;
colvarFechaNacimiento.IsPrimaryKey = false;
colvarFechaNacimiento.IsForeignKey = false;
colvarFechaNacimiento.IsReadOnly = false;
colvarFechaNacimiento.DefaultSetting = @"";
colvarFechaNacimiento.ForeignKeyTableName = "";
schema.Columns.Add(colvarFechaNacimiento);
TableSchema.TableColumn colvarFechaPrestacion = new TableSchema.TableColumn(schema);
colvarFechaPrestacion.ColumnName = "fecha_prestacion";
colvarFechaPrestacion.DataType = DbType.DateTime;
colvarFechaPrestacion.MaxLength = 0;
colvarFechaPrestacion.AutoIncrement = false;
colvarFechaPrestacion.IsNullable = true;
colvarFechaPrestacion.IsPrimaryKey = false;
colvarFechaPrestacion.IsForeignKey = false;
colvarFechaPrestacion.IsReadOnly = false;
colvarFechaPrestacion.DefaultSetting = @"";
colvarFechaPrestacion.ForeignKeyTableName = "";
schema.Columns.Add(colvarFechaPrestacion);
TableSchema.TableColumn colvarAnio = new TableSchema.TableColumn(schema);
colvarAnio.ColumnName = "anio";
colvarAnio.DataType = DbType.Int32;
colvarAnio.MaxLength = 0;
colvarAnio.AutoIncrement = false;
colvarAnio.IsNullable = true;
colvarAnio.IsPrimaryKey = false;
colvarAnio.IsForeignKey = false;
colvarAnio.IsReadOnly = false;
colvarAnio.DefaultSetting = @"";
colvarAnio.ForeignKeyTableName = "";
schema.Columns.Add(colvarAnio);
TableSchema.TableColumn colvarMes = new TableSchema.TableColumn(schema);
colvarMes.ColumnName = "mes";
colvarMes.DataType = DbType.Int32;
colvarMes.MaxLength = 0;
colvarMes.AutoIncrement = false;
colvarMes.IsNullable = true;
colvarMes.IsPrimaryKey = false;
colvarMes.IsForeignKey = false;
colvarMes.IsReadOnly = false;
colvarMes.DefaultSetting = @"";
colvarMes.ForeignKeyTableName = "";
schema.Columns.Add(colvarMes);
TableSchema.TableColumn colvarDia = new TableSchema.TableColumn(schema);
colvarDia.ColumnName = "dia";
colvarDia.DataType = DbType.Int32;
colvarDia.MaxLength = 0;
colvarDia.AutoIncrement = false;
colvarDia.IsNullable = true;
colvarDia.IsPrimaryKey = false;
colvarDia.IsForeignKey = false;
colvarDia.IsReadOnly = false;
colvarDia.DefaultSetting = @"";
colvarDia.ForeignKeyTableName = "";
schema.Columns.Add(colvarDia);
TableSchema.TableColumn colvarTalla = new TableSchema.TableColumn(schema);
colvarTalla.ColumnName = "talla";
colvarTalla.DataType = DbType.Int32;
colvarTalla.MaxLength = 0;
colvarTalla.AutoIncrement = false;
colvarTalla.IsNullable = true;
colvarTalla.IsPrimaryKey = false;
colvarTalla.IsForeignKey = false;
colvarTalla.IsReadOnly = false;
colvarTalla.DefaultSetting = @"";
colvarTalla.ForeignKeyTableName = "";
schema.Columns.Add(colvarTalla);
TableSchema.TableColumn colvarPerimetroCefalico = new TableSchema.TableColumn(schema);
colvarPerimetroCefalico.ColumnName = "perimetro_cefalico";
colvarPerimetroCefalico.DataType = DbType.String;
colvarPerimetroCefalico.MaxLength = -1;
colvarPerimetroCefalico.AutoIncrement = false;
colvarPerimetroCefalico.IsNullable = true;
colvarPerimetroCefalico.IsPrimaryKey = false;
colvarPerimetroCefalico.IsForeignKey = false;
colvarPerimetroCefalico.IsReadOnly = false;
colvarPerimetroCefalico.DefaultSetting = @"";
colvarPerimetroCefalico.ForeignKeyTableName = "";
schema.Columns.Add(colvarPerimetroCefalico);
TableSchema.TableColumn colvarSemanasGestacion = new TableSchema.TableColumn(schema);
colvarSemanasGestacion.ColumnName = "semanas_gestacion";
colvarSemanasGestacion.DataType = DbType.Int32;
colvarSemanasGestacion.MaxLength = 0;
colvarSemanasGestacion.AutoIncrement = false;
colvarSemanasGestacion.IsNullable = true;
colvarSemanasGestacion.IsPrimaryKey = false;
colvarSemanasGestacion.IsForeignKey = false;
colvarSemanasGestacion.IsReadOnly = false;
colvarSemanasGestacion.DefaultSetting = @"";
colvarSemanasGestacion.ForeignKeyTableName = "";
schema.Columns.Add(colvarSemanasGestacion);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("PN_prestacion",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdPrestacion")]
[Bindable(true)]
public int IdPrestacion
{
get { return GetColumnValue<int>(Columns.IdPrestacion); }
set { SetColumnValue(Columns.IdPrestacion, value); }
}
[XmlAttribute("IdComprobante")]
[Bindable(true)]
public int IdComprobante
{
get { return GetColumnValue<int>(Columns.IdComprobante); }
set { SetColumnValue(Columns.IdComprobante, value); }
}
[XmlAttribute("IdNomenclador")]
[Bindable(true)]
public int IdNomenclador
{
get { return GetColumnValue<int>(Columns.IdNomenclador); }
set { SetColumnValue(Columns.IdNomenclador, value); }
}
[XmlAttribute("Cantidad")]
[Bindable(true)]
public int? Cantidad
{
get { return GetColumnValue<int?>(Columns.Cantidad); }
set { SetColumnValue(Columns.Cantidad, value); }
}
[XmlAttribute("PrecioPrestacion")]
[Bindable(true)]
public decimal? PrecioPrestacion
{
get { return GetColumnValue<decimal?>(Columns.PrecioPrestacion); }
set { SetColumnValue(Columns.PrecioPrestacion, value); }
}
[XmlAttribute("IdAnexo")]
[Bindable(true)]
public int? IdAnexo
{
get { return GetColumnValue<int?>(Columns.IdAnexo); }
set { SetColumnValue(Columns.IdAnexo, value); }
}
[XmlAttribute("Peso")]
[Bindable(true)]
public decimal? Peso
{
get { return GetColumnValue<decimal?>(Columns.Peso); }
set { SetColumnValue(Columns.Peso, value); }
}
[XmlAttribute("TensionArterial")]
[Bindable(true)]
public string TensionArterial
{
get { return GetColumnValue<string>(Columns.TensionArterial); }
set { SetColumnValue(Columns.TensionArterial, value); }
}
[XmlAttribute("Diagnostico")]
[Bindable(true)]
public string Diagnostico
{
get { return GetColumnValue<string>(Columns.Diagnostico); }
set { SetColumnValue(Columns.Diagnostico, value); }
}
[XmlAttribute("Edad")]
[Bindable(true)]
public string Edad
{
get { return GetColumnValue<string>(Columns.Edad); }
set { SetColumnValue(Columns.Edad, value); }
}
[XmlAttribute("Sexo")]
[Bindable(true)]
public string Sexo
{
get { return GetColumnValue<string>(Columns.Sexo); }
set { SetColumnValue(Columns.Sexo, value); }
}
[XmlAttribute("CodigoComp")]
[Bindable(true)]
public string CodigoComp
{
get { return GetColumnValue<string>(Columns.CodigoComp); }
set { SetColumnValue(Columns.CodigoComp, value); }
}
[XmlAttribute("FechaNacimiento")]
[Bindable(true)]
public DateTime? FechaNacimiento
{
get { return GetColumnValue<DateTime?>(Columns.FechaNacimiento); }
set { SetColumnValue(Columns.FechaNacimiento, value); }
}
[XmlAttribute("FechaPrestacion")]
[Bindable(true)]
public DateTime? FechaPrestacion
{
get { return GetColumnValue<DateTime?>(Columns.FechaPrestacion); }
set { SetColumnValue(Columns.FechaPrestacion, value); }
}
[XmlAttribute("Anio")]
[Bindable(true)]
public int? Anio
{
get { return GetColumnValue<int?>(Columns.Anio); }
set { SetColumnValue(Columns.Anio, value); }
}
[XmlAttribute("Mes")]
[Bindable(true)]
public int? Mes
{
get { return GetColumnValue<int?>(Columns.Mes); }
set { SetColumnValue(Columns.Mes, value); }
}
[XmlAttribute("Dia")]
[Bindable(true)]
public int? Dia
{
get { return GetColumnValue<int?>(Columns.Dia); }
set { SetColumnValue(Columns.Dia, value); }
}
[XmlAttribute("Talla")]
[Bindable(true)]
public int? Talla
{
get { return GetColumnValue<int?>(Columns.Talla); }
set { SetColumnValue(Columns.Talla, value); }
}
[XmlAttribute("PerimetroCefalico")]
[Bindable(true)]
public string PerimetroCefalico
{
get { return GetColumnValue<string>(Columns.PerimetroCefalico); }
set { SetColumnValue(Columns.PerimetroCefalico, value); }
}
[XmlAttribute("SemanasGestacion")]
[Bindable(true)]
public int? SemanasGestacion
{
get { return GetColumnValue<int?>(Columns.SemanasGestacion); }
set { SetColumnValue(Columns.SemanasGestacion, value); }
}
#endregion
#region PrimaryKey Methods
protected override void SetPrimaryKey(object oValue)
{
base.SetPrimaryKey(oValue);
SetPKValues();
}
private DalSic.PnRelPrestacionXDatoReportableCollection colPnRelPrestacionXDatoReportableRecords;
public DalSic.PnRelPrestacionXDatoReportableCollection PnRelPrestacionXDatoReportableRecords
{
get
{
if(colPnRelPrestacionXDatoReportableRecords == null)
{
colPnRelPrestacionXDatoReportableRecords = new DalSic.PnRelPrestacionXDatoReportableCollection().Where(PnRelPrestacionXDatoReportable.Columns.IdPrestacion, IdPrestacion).Load();
colPnRelPrestacionXDatoReportableRecords.ListChanged += new ListChangedEventHandler(colPnRelPrestacionXDatoReportableRecords_ListChanged);
}
return colPnRelPrestacionXDatoReportableRecords;
}
set
{
colPnRelPrestacionXDatoReportableRecords = value;
colPnRelPrestacionXDatoReportableRecords.ListChanged += new ListChangedEventHandler(colPnRelPrestacionXDatoReportableRecords_ListChanged);
}
}
void colPnRelPrestacionXDatoReportableRecords_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded)
{
// Set foreign key value
colPnRelPrestacionXDatoReportableRecords[e.NewIndex].IdPrestacion = IdPrestacion;
}
}
#endregion
#region ForeignKey Properties
/// <summary>
/// Returns a PnNomenclador ActiveRecord object related to this PnPrestacion
///
/// </summary>
public DalSic.PnNomenclador PnNomenclador
{
get { return DalSic.PnNomenclador.FetchByID(this.IdNomenclador); }
set { SetColumnValue("id_nomenclador", value.IdNomenclador); }
}
/// <summary>
/// Returns a PnComprobante ActiveRecord object related to this PnPrestacion
///
/// </summary>
public DalSic.PnComprobante PnComprobante
{
get { return DalSic.PnComprobante.FetchByID(this.IdComprobante); }
set { SetColumnValue("id_comprobante", value.IdComprobante); }
}
#endregion
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(int varIdComprobante,int varIdNomenclador,int? varCantidad,decimal? varPrecioPrestacion,int? varIdAnexo,decimal? varPeso,string varTensionArterial,string varDiagnostico,string varEdad,string varSexo,string varCodigoComp,DateTime? varFechaNacimiento,DateTime? varFechaPrestacion,int? varAnio,int? varMes,int? varDia,int? varTalla,string varPerimetroCefalico,int? varSemanasGestacion)
{
PnPrestacion item = new PnPrestacion();
item.IdComprobante = varIdComprobante;
item.IdNomenclador = varIdNomenclador;
item.Cantidad = varCantidad;
item.PrecioPrestacion = varPrecioPrestacion;
item.IdAnexo = varIdAnexo;
item.Peso = varPeso;
item.TensionArterial = varTensionArterial;
item.Diagnostico = varDiagnostico;
item.Edad = varEdad;
item.Sexo = varSexo;
item.CodigoComp = varCodigoComp;
item.FechaNacimiento = varFechaNacimiento;
item.FechaPrestacion = varFechaPrestacion;
item.Anio = varAnio;
item.Mes = varMes;
item.Dia = varDia;
item.Talla = varTalla;
item.PerimetroCefalico = varPerimetroCefalico;
item.SemanasGestacion = varSemanasGestacion;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdPrestacion,int varIdComprobante,int varIdNomenclador,int? varCantidad,decimal? varPrecioPrestacion,int? varIdAnexo,decimal? varPeso,string varTensionArterial,string varDiagnostico,string varEdad,string varSexo,string varCodigoComp,DateTime? varFechaNacimiento,DateTime? varFechaPrestacion,int? varAnio,int? varMes,int? varDia,int? varTalla,string varPerimetroCefalico,int? varSemanasGestacion)
{
PnPrestacion item = new PnPrestacion();
item.IdPrestacion = varIdPrestacion;
item.IdComprobante = varIdComprobante;
item.IdNomenclador = varIdNomenclador;
item.Cantidad = varCantidad;
item.PrecioPrestacion = varPrecioPrestacion;
item.IdAnexo = varIdAnexo;
item.Peso = varPeso;
item.TensionArterial = varTensionArterial;
item.Diagnostico = varDiagnostico;
item.Edad = varEdad;
item.Sexo = varSexo;
item.CodigoComp = varCodigoComp;
item.FechaNacimiento = varFechaNacimiento;
item.FechaPrestacion = varFechaPrestacion;
item.Anio = varAnio;
item.Mes = varMes;
item.Dia = varDia;
item.Talla = varTalla;
item.PerimetroCefalico = varPerimetroCefalico;
item.SemanasGestacion = varSemanasGestacion;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdPrestacionColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn IdComprobanteColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn IdNomencladorColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn CantidadColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn PrecioPrestacionColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn IdAnexoColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn PesoColumn
{
get { return Schema.Columns[6]; }
}
public static TableSchema.TableColumn TensionArterialColumn
{
get { return Schema.Columns[7]; }
}
public static TableSchema.TableColumn DiagnosticoColumn
{
get { return Schema.Columns[8]; }
}
public static TableSchema.TableColumn EdadColumn
{
get { return Schema.Columns[9]; }
}
public static TableSchema.TableColumn SexoColumn
{
get { return Schema.Columns[10]; }
}
public static TableSchema.TableColumn CodigoCompColumn
{
get { return Schema.Columns[11]; }
}
public static TableSchema.TableColumn FechaNacimientoColumn
{
get { return Schema.Columns[12]; }
}
public static TableSchema.TableColumn FechaPrestacionColumn
{
get { return Schema.Columns[13]; }
}
public static TableSchema.TableColumn AnioColumn
{
get { return Schema.Columns[14]; }
}
public static TableSchema.TableColumn MesColumn
{
get { return Schema.Columns[15]; }
}
public static TableSchema.TableColumn DiaColumn
{
get { return Schema.Columns[16]; }
}
public static TableSchema.TableColumn TallaColumn
{
get { return Schema.Columns[17]; }
}
public static TableSchema.TableColumn PerimetroCefalicoColumn
{
get { return Schema.Columns[18]; }
}
public static TableSchema.TableColumn SemanasGestacionColumn
{
get { return Schema.Columns[19]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdPrestacion = @"id_prestacion";
public static string IdComprobante = @"id_comprobante";
public static string IdNomenclador = @"id_nomenclador";
public static string Cantidad = @"cantidad";
public static string PrecioPrestacion = @"precio_prestacion";
public static string IdAnexo = @"id_anexo";
public static string Peso = @"peso";
public static string TensionArterial = @"tension_arterial";
public static string Diagnostico = @"diagnostico";
public static string Edad = @"edad";
public static string Sexo = @"sexo";
public static string CodigoComp = @"codigo_comp";
public static string FechaNacimiento = @"fecha_nacimiento";
public static string FechaPrestacion = @"fecha_prestacion";
public static string Anio = @"anio";
public static string Mes = @"mes";
public static string Dia = @"dia";
public static string Talla = @"talla";
public static string PerimetroCefalico = @"perimetro_cefalico";
public static string SemanasGestacion = @"semanas_gestacion";
}
#endregion
#region Update PK Collections
public void SetPKValues()
{
if (colPnRelPrestacionXDatoReportableRecords != null)
{
foreach (DalSic.PnRelPrestacionXDatoReportable item in colPnRelPrestacionXDatoReportableRecords)
{
if (item.IdPrestacion != IdPrestacion)
{
item.IdPrestacion = IdPrestacion;
}
}
}
}
#endregion
#region Deep Save
public void DeepSave()
{
Save();
if (colPnRelPrestacionXDatoReportableRecords != null)
{
colPnRelPrestacionXDatoReportableRecords.SaveAll();
}
}
#endregion
}
}
| |
using System;
using System.Linq;
using System.Web.UI;
using Telerik.Sitefinity.Web.UI;
using Telerik.Sitefinity.Web.UI.ControlDesign;
using System.Collections.Generic;
using System.Web.UI.WebControls;
namespace Fenetre.Sitefinity.TwitterFeed
{
/// <summary>
/// Represents a designer for the <typeparamref name="Mejudice.Website.Web.TwitterFeed"/> widget
/// </summary>
public class TwitterFeedDesigner : ControlDesignerBase
{
#region Properties
/// <summary>
/// Gets the layout template path
/// </summary>
public override string LayoutTemplatePath
{
get
{
return String.Empty;
}
}
/// <summary>
/// Gets the layout template name
/// </summary>
protected override string LayoutTemplateName
{
get
{
return TwitterFeedDesigner.layoutTemplateName;
}
}
protected override HtmlTextWriterTag TagKey
{
get
{
return HtmlTextWriterTag.Div;
}
}
#endregion
#region Control references
/// <summary>
/// Gets the control that is bound to the HeaderTitle property
/// </summary>
protected virtual Control HeaderTitle
{
get
{
return this.Container.GetControl<Control>("HeaderTitle", true);
}
}
/// <summary>
/// Gets the control that is bound to the SearchType property
/// </summary>
protected virtual DropDownList SearchType
{
get
{
return this.Container.GetControl<DropDownList>("SearchType", true);
}
}
/// <summary>
/// Gets the control that is bound to the SearchString property
/// </summary>
protected virtual Control SearchString
{
get
{
return this.Container.GetControl<Control>("SearchString", true);
}
}
protected virtual Control SearchStringMultiLine
{
get
{
return this.Container.GetControl<Control>("SearchStringMultiLine", true);
}
}
/// <summary>
/// Gets the control that is bound to the MessageLimit property
/// </summary>
protected virtual Control MessageLimit
{
get
{
return this.Container.GetControl<Control>("MessageLimit", true);
}
}
/// <summary>
/// Gets the control that is bound to the ReadMoreText property
/// </summary>
protected virtual Control ReadMoreText
{
get
{
return this.Container.GetControl<Control>("ReadMoreText", true);
}
}
/// <summary>
/// Gets the control that is bound to the ShowReadMore property
/// </summary>
protected virtual Control ShowReadMore
{
get
{
return this.Container.GetControl<Control>("ShowReadMore", true);
}
}
/// <summary>
/// Token used to access Twitter
/// </summary>
protected virtual Control TwitterUserAccessToken
{
get
{
return this.Container.GetControl<Control>("TwitterUserAccessToken", true);
}
}
/// <summary>
/// Secret token used to access Twitter
/// </summary>
protected virtual Control TwitterUserAccessTokenSecret
{
get
{
return this.Container.GetControl<Control>("TwitterUserAccessTokenSecret", true);
}
}
/// <summary>
/// Consumer key used to access Twitter
/// </summary>
protected virtual Control TwitterConsumerKey
{
get
{
return this.Container.GetControl<Control>("TwitterConsumerKey", true);
}
}
/// <summary>
/// Consumer secret used to access Twitter
/// </summary>
protected virtual Control TwitterConsumerSecret
{
get
{
return this.Container.GetControl<Control>("TwitterConsumerSecret", true);
}
}
#endregion
#region Methods
/// <summary>
/// Initializes the Twitter feed.
/// </summary>
/// <param name="container"></param>
protected override void InitializeControls(Telerik.Sitefinity.Web.UI.GenericContainer container)
{
SearchType.Items.Clear();
SearchType.Items.Add(new ListItem("Accounts", "Accounts"));
SearchType.Items.Add(new ListItem("HashTags", "HashTags"));
SearchType.Items.Add(new ListItem("Custom", "Custom"));
}
#endregion
#region IScriptControl implementation
/// <summary>
/// Gets a collection of script descriptors that represent ECMAScript (JavaScript) client components.
/// </summary>
public override System.Collections.Generic.IEnumerable<System.Web.UI.ScriptDescriptor> GetScriptDescriptors()
{
var scriptDescriptors = new List<ScriptDescriptor>(base.GetScriptDescriptors());
var descriptor = (ScriptControlDescriptor)scriptDescriptors.Last();
descriptor.AddElementProperty("headerTitle", this.HeaderTitle.ClientID);
descriptor.AddElementProperty("searchString", this.SearchString.ClientID);
descriptor.AddElementProperty("messageLimit", this.MessageLimit.ClientID);
descriptor.AddElementProperty("showReadMore", this.ShowReadMore.ClientID);
descriptor.AddElementProperty("searchType", this.SearchType.ClientID);
descriptor.AddElementProperty("searchStringMultiLine", this.SearchStringMultiLine.ClientID);
descriptor.AddElementProperty("twitterConsumerKey", this.TwitterConsumerKey.ClientID);
descriptor.AddElementProperty("twitterConsumerSecret", this.TwitterConsumerSecret.ClientID);
descriptor.AddElementProperty("twitterUserAccessToken", this.TwitterUserAccessToken.ClientID);
descriptor.AddElementProperty("twitterUserAccessTokenSecret", this.TwitterUserAccessTokenSecret.ClientID);
descriptor.AddElementProperty("readMoreText", this.ReadMoreText.ClientID);
return scriptDescriptors;
}
/// <summary>
/// Gets a collection of ScriptReference objects that define script resources that the control requires.
/// </summary>
public override System.Collections.Generic.IEnumerable<System.Web.UI.ScriptReference> GetScriptReferences()
{
var scripts = new List<ScriptReference>(base.GetScriptReferences());
scripts.Add(new ScriptReference(TwitterFeedDesigner.scriptReference, "Fenetre.Sitefinity.TwitterFeed"));
return scripts;
}
#endregion
#region Private members & constants
public static readonly string layoutTemplateName = "Fenetre.Sitefinity.TwitterFeed.Widgets.TwitterFeedDesigner.ascx";
public const string scriptReference = "Fenetre.Sitefinity.TwitterFeed.Widgets.TwitterFeedDesigner.js";
#endregion
}
}
| |
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
/* ****************************************************************************
* RuntimeObjectEditor
*
* Copyright (c) 2005 Corneliu I. Tusnea
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the author be held liable for any damages arising from
* the use of this software.
* Permission to use, copy, modify, distribute and sell this software for any
* purpose is hereby granted without fee, provided that the above copyright
* notice appear in all copies and that both that copyright notice and this
* permission notice appear in supporting documentation.
*
* Corneliu I. Tusnea ([email protected])
* www.acorns.com.au
* ****************************************************************************/
namespace Function_Debugger.Forms
{
/// <summary>
/// windowFinder - Control to help find other windows/controls.
/// </summary>
[DefaultEvent("ActiveWindowChanged")]
public class WindowFinder : UserControl
{
public event EventHandler ActiveWindowChanged;
public event EventHandler ActiveWindowSelected;
#region PInvoke
#region Consts
private const uint RDW_INVALIDATE = 0x0001;
private const uint RDW_INTERNALPAINT = 0x0002;
private const uint RDW_ERASE = 0x0004;
private const uint RDW_VALIDATE = 0x0008;
private const uint RDW_NOINTERNALPAINT = 0x0010;
private const uint RDW_NOERASE = 0x0020;
private const uint RDW_NOCHILDREN = 0x0040;
private const uint RDW_ALLCHILDREN = 0x0080;
private const uint RDW_UPDATENOW = 0x0100;
private const uint RDW_ERASENOW = 0x0200;
private const uint RDW_FRAME = 0x0400;
private const uint RDW_NOFRAME = 0x0800;
#endregion
[DllImport("user32.dll")]
private static extern IntPtr WindowFromPoint(POINT point);
[DllImport("user32.dll")]
private static extern IntPtr ChildWindowFromPoint(IntPtr hWndParent, POINT point);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern int GetWindowText(IntPtr hWnd, [Out] StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll")]
private static extern int GetClassName(IntPtr hWnd, [Out] StringBuilder lpClassName, int nMaxCount);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr GetParent(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern bool InvalidateRect(IntPtr hWnd, IntPtr lpRect, bool bErase);
[DllImport("user32.dll")]
public static extern bool UpdateWindow(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern bool RedrawWindow(IntPtr hWnd, IntPtr lpRect, IntPtr hrgnUpdate, uint flags);
[DllImport("user32.dll")]
private static extern bool ScreenToClient(IntPtr hWnd, ref POINT lpPoint);
[DllImport("gdi32.dll")]
private static extern IntPtr CreatePen(int fnPenStyle, int nWidth, uint crColor);
[DllImport("user32.dll")]
public static extern bool GetWindowRect(IntPtr hWnd, out Rect lpRect);
[DllImport("user32.dll")]
public static extern IntPtr GetWindowDC(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDc);
#region RECT
[Serializable, StructLayout(LayoutKind.Sequential)]
public struct Rect
{
public int Left;
public int Top;
public int Right;
public int Bottom;
public Rect(int left, int top, int right, int bottom)
{
Left = left;
Top = top;
Right = right;
Bottom = bottom;
}
public int Height
{
get { return Bottom - Top; }
}
public int Width
{
get { return Right - Left; }
}
public Size Size
{
get { return new Size(Width, Height); }
}
public Point Location
{
get { return new Point(Left, Top); }
}
// Handy method for converting to a System.Drawing.Rectangle
public Rectangle ToRectangle()
{
return Rectangle.FromLTRB(Left, Top, Right, Bottom);
}
public static Rect FromRectangle(Rectangle rectangle)
{
return new Rect(rectangle.Left, rectangle.Top, rectangle.Right, rectangle.Bottom);
}
}
#endregion
#region POINT
[StructLayout(LayoutKind.Sequential)]
private struct POINT
{
private readonly int x;
private readonly int y;
private POINT(int x, int y)
{
this.x = x;
this.y = y;
}
public POINT ToPoint()
{
return new POINT(x, y);
}
public static POINT FromPoint(Point pt)
{
return new POINT(pt.X, pt.Y);
}
public override bool Equals(object obj)
{
// I wish we could use the "as" operator
// and check the type compatibility only
// once here, just like with reference
// types. Maybe in the v2.0 :)
if (!(obj is POINT))
{
return false;
}
POINT point = (POINT) obj;
if (point.x == x)
{
return (point.y == y);
}
return false;
}
public override int GetHashCode()
{
// this is the Microsoft implementation for the
// System.Drawing.Point's GetHashCode() method.
return (x ^ y);
}
public override string ToString()
{
return string.Format("{{X={0}, Y={1}}}", x, y);
}
}
#endregion
#endregion
#region WindowProperties
public class WindowProperties : IDisposable
{
private static readonly Pen DrawPen = new Pen(Brushes.Red, 2);
private IntPtr detectedWindow = IntPtr.Zero;
public IntPtr DetectedWindow
{
get { return detectedWindow; }
}
public Control ActiveWindow
{
get
{
if (detectedWindow != IntPtr.Zero)
{
return FromHandle(detectedWindow);
}
return null;
}
}
public string Name
{
get
{
if (ActiveWindow != null)
return ActiveWindow.Name;
return null;
}
}
public string Text
{
get
{
if (!IsValid)
return null;
if (IsManaged)
return ActiveWindow.Text;
StringBuilder builder = new StringBuilder();
GetWindowText(detectedWindow, builder, 255);
return builder.ToString();
}
}
public string ClassName
{
get
{
if (!IsValid)
return null;
StringBuilder builder = new StringBuilder();
GetClassName(detectedWindow, builder, 255);
return builder.ToString();
}
}
public bool IsManagedByClassName
{
get
{
string className = ClassName;
if (className != null && className.StartsWith("WindowsForms10"))
{
return true;
}
return false;
}
}
public bool IsValid
{
get { return detectedWindow != IntPtr.Zero; }
}
public bool IsManaged
{
get { return ActiveWindow != null; }
}
internal void SetWindowHandle(IntPtr handle)
{
Refresh();
detectedWindow = handle;
Refresh();
Highlight();
}
public void Refresh()
{
if (!IsValid)
return;
IntPtr toUpdate = detectedWindow;
IntPtr parentWindow = GetParent(toUpdate);
if (parentWindow != IntPtr.Zero)
{
toUpdate = parentWindow; // using parent
}
InvalidateRect(toUpdate, IntPtr.Zero, true);
UpdateWindow(toUpdate);
RedrawWindow(toUpdate, IntPtr.Zero, IntPtr.Zero,
RDW_FRAME | RDW_INVALIDATE | RDW_UPDATENOW | RDW_ERASENOW | RDW_ALLCHILDREN);
}
public void Highlight()
{
Rect windowRect;
GetWindowRect(detectedWindow, out windowRect);
GetParent(detectedWindow);
IntPtr windowDc = GetWindowDC(detectedWindow);
if (windowDc != IntPtr.Zero)
{
Graphics graph = Graphics.FromHdc(windowDc, detectedWindow);
graph.DrawRectangle(DrawPen, 1, 1, windowRect.Width - 2, windowRect.Height - 2);
graph.Dispose();
ReleaseDC(detectedWindow, windowDc);
}
}
#region IDisposable Members
public void Dispose()
{
Refresh();
}
#endregion
}
#endregion
private bool searching;
private readonly WindowProperties window;
public WindowFinder()
{
InitializeComponent();
window = new WindowProperties();
MouseDown += WindowFinder_MouseDown;
}
protected override void Dispose(bool disposing)
{
window.Dispose();
base.Dispose(disposing);
}
#region Designer Generated
#endregion
#region DetectedWindowProperties
public WindowProperties Window
{
get { return window; }
}
#endregion
#region Start/Stop Search
public void StartSearch()
{
searching = true;
Cursor.Current = Cursors.Cross;
Capture = true;
MouseMove += WindowFinder_MouseMove;
MouseUp += WindowFinder_MouseUp;
}
public void EndSearch()
{
MouseMove -= WindowFinder_MouseMove;
Capture = false;
searching = false;
Cursor.Current = Cursors.Default;
if (ActiveWindowSelected != null)
{
ActiveWindowSelected(this, EventArgs.Empty);
}
}
#endregion
private void WindowFinder_MouseDown(object sender, MouseEventArgs e)
{
if (!searching)
StartSearch();
}
private void WindowFinder_MouseMove(object sender, MouseEventArgs e)
{
if (!searching)
EndSearch();
// Grab the window from the screen location of the mouse.
POINT windowPoint = POINT.FromPoint(PointToScreen(new Point(e.X, e.Y)));
IntPtr found = WindowFromPoint(windowPoint);
// we have a valid window handle
if (found != IntPtr.Zero)
{
// give it another try, it might be a child window (disabled, hidden .. something else)
// offset the point to be a client point of the active window
if (ScreenToClient(found, ref windowPoint))
{
// check if there is some hidden/disabled child window at this point
IntPtr childWindow = ChildWindowFromPoint(found, windowPoint);
if (childWindow != IntPtr.Zero)
{
// great, we have the inner child
found = childWindow;
}
}
}
// Is this the same window as the last detected one?
if (found != window.DetectedWindow)
{
window.SetWindowHandle(found);
Trace.WriteLine("FoundWindow:" + window.Name + ":" + window.Text + " Managed:" + window.IsManaged);
InvokeActiveWindowChanged();
}
}
private void InvokeActiveWindowChanged()
{
if (ActiveWindowChanged != null)
ActiveWindowChanged(this, EventArgs.Empty);
}
private void WindowFinder_MouseUp(object sender, MouseEventArgs e)
{
EndSearch();
}
public object SelectedObject
{
get { return window.ActiveWindow; }
}
public IntPtr SelectedHandle
{
get { return window.DetectedWindow; }
set
{
window.SetWindowHandle(value);
InvokeActiveWindowChanged();
}
}
public bool IsManagedByClassName
{
get { return window.IsManagedByClassName; }
}
private void InitializeComponent()
{
this.SuspendLayout();
//
// WindowFinder
//
this.BackgroundImage = global::Function_Debugger.Properties.Resources.scope;
this.Name = "WindowFinder";
this.Size = new System.Drawing.Size(32, 32);
this.ResumeLayout(false);
}
public void RefreshWindow()
{
window.Refresh();
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="ObstacleAvoidanceForm.cs" company="Microsoft Corporation">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace Microsoft.Robotics.Services.ObstacleAvoidanceDrive
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Ccr.Core;
using Microsoft.Robotics.Services.ObstacleAvoidanceDrive;
using joystick = Microsoft.Robotics.Services.GameController.Proxy;
using webcam = Microsoft.Robotics.Services.WebCam.Proxy;
/// <summary>
/// The main ObstacleAvoidance Form
/// </summary>
public partial class ObstacleAvoidanceForm : Form
{
/// <summary>
/// The port for sending events
/// </summary>
private ObstacleAvoidanceFormEvents eventsPort;
/// <summary>
/// Initializes a new instance of the DashboardForm class
/// </summary>
/// <param name="theEventsPort">The Events Port for passing events back to the service</param>
/// <param name="state">The service state</param>
public ObstacleAvoidanceForm(ObstacleAvoidanceFormEvents theEventsPort, ObstacleAvoidanceDriveState state)
{
this.eventsPort = theEventsPort;
this.InitializeComponent();
this.UpdatePIDControllersValue(state);
}
/// <summary>
/// Handle Form Load
/// </summary>
/// <param name="sender">The parameter is not used.</param>
/// <param name="e">The parameter is not used.</param>
private void ObstacleAvoidanceForm_Load(object sender, EventArgs e)
{
this.eventsPort.Post(new OnLoad(this));
}
/// <summary>
/// Handle Form Closed
/// </summary>
/// <param name="sender">The parameter is not used.</param>
/// <param name="e">The parameter is not used.</param>
private void ObstacleAvoidanceForm_FormClosed(object sender, FormClosedEventArgs e)
{
this.eventsPort.Post(new OnClosed(this));
}
/// <summary>
/// Update PID controller parameter values on the form.
/// This is a one-off call during constructor where we need to
/// set the initial state of the PID controllers
/// </summary>
/// <param name="state">state</param>
public void UpdatePIDControllersValue(ObstacleAvoidanceDriveState state)
{
// Set all the PID values on the form, copying them from state:
this.textBoxAngularKp.Text = state.Controller.Kp.ToString();
this.textBoxAngularKi.Text = state.Controller.Ki.ToString();
this.textBoxAngularKd.Text = state.Controller.Kd.ToString();
this.textBoxAngularMax.Text = state.Controller.MaxPidValue.ToString();
this.textBoxAngularMin.Text = state.Controller.MinPidValue.ToString();
this.textBoxAngularIntegralMax.Text = state.Controller.MaxIntegralError.ToString();
}
/// <summary>
/// Set new PID controller values
/// </summary>
public void PostPIDControllersValue(bool doSaveState)
{
try
{
this.eventsPort.Post(new OnPIDChanges(this,
double.Parse(this.textBoxAngularKp.Text), double.Parse(this.textBoxAngularKi.Text), double.Parse(this.textBoxAngularKd.Text),
double.Parse(this.textBoxAngularMax.Text), double.Parse(this.textBoxAngularMin.Text), double.Parse(this.textBoxAngularIntegralMax.Text),
doSaveState
));
PIDControllerGroupBox.BackColor = Color.LightBlue;
}
catch
{
PIDControllerGroupBox.BackColor = Color.Red;
}
}
/// <summary>
/// A bitmap to hold the depth profile image
/// </summary>
private Bitmap depthProfileImage;
/// <summary>
/// Gets or sets the Depth Profile Image
/// </summary>
/// <remarks>Provides external access for updating the depth profile image</remarks>
public Bitmap DepthProfileImage
{
get
{
return this.depthProfileImage;
}
set
{
this.depthProfileImage = value;
Image old = this.depthProfileCtrl.Image;
this.depthProfileCtrl.Image = value;
// Dispose of the old bitmap to save memory
// (It will be garbage collected eventually, but this is faster)
if (old != null)
{
old.Dispose();
}
}
}
private void buttonUpdatePidControllers_Click(object sender, EventArgs e)
{
this.PostPIDControllersValue(false); // no SaveState
}
private void buttonSaveState_Click(object sender, EventArgs e)
{
this.PostPIDControllersValue(true); // with SaveState
}
}
/// <summary>
/// Operations Port for ObstacleAvoidance Events
/// </summary>
public class ObstacleAvoidanceFormEvents :
PortSet<OnLoad,
OnClosed,
OnQueryFrame,
OnPIDChanges>
{
}
/// <summary>
/// Class used for events sent by the ObstacleAvoidance Form back to the service
/// </summary>
public class ObstacleAvoidanceFormEvent
{
/// <summary>
/// Obstacle Avoidance Form
/// </summary>
private ObstacleAvoidanceForm obstacleAvoidanceForm;
/// <summary>
/// Gets or sets the associated Form
/// </summary>
public ObstacleAvoidanceForm ObstacleAvoidanceForm
{
get { return this.obstacleAvoidanceForm; }
set { this.obstacleAvoidanceForm = value; }
}
/// <summary>
/// Initializes an instance of the ObstacleAvoidanceFormEvent class
/// </summary>
/// <param name="obstacleAvoidanceForm">The associated Form</param>
public ObstacleAvoidanceFormEvent(ObstacleAvoidanceForm obstacleAvoidanceForm)
{
this.obstacleAvoidanceForm = obstacleAvoidanceForm;
}
}
/// <summary>
/// Form Loaded message
/// </summary>
public class OnLoad : ObstacleAvoidanceFormEvent
{
/// <summary>
/// Initializes an instance of the OnLoad class
/// </summary>
/// <param name="form">The associated Form</param>
public OnLoad(ObstacleAvoidanceForm form)
: base(form)
{
}
}
/// <summary>
/// Form Closed message
/// </summary>
public class OnClosed : ObstacleAvoidanceFormEvent
{
/// <summary>
/// Initializes an instance of the OnClosed class
/// </summary>
/// <param name="form">The associated Form</param>
public OnClosed(ObstacleAvoidanceForm form)
: base(form)
{
}
}
/// <summary>
/// Query Frame message
/// </summary>
public class OnQueryFrame : ObstacleAvoidanceFormEvent
{
/// <summary>
/// Initializes an instance of the OnQueryFrame class
/// </summary>
/// <param name="form">The associated form</param>
public OnQueryFrame(ObstacleAvoidanceForm form)
: base(form)
{
}
}
/// <summary>
/// PID parameter values changes
/// </summary>
public class OnPIDChanges : ObstacleAvoidanceFormEvent
{
/// <summary>
/// Gets or sets the Proportional constant
/// </summary>
public double Kp { get; set; }
/// <summary>
/// Gets or sets the Proportional constant
/// </summary>
public double Ki { get; set; }
/// <summary>
/// Gets or sets the Derivative constant
/// </summary>
public double Kd { get; set; }
/// <summary>
/// Gets or sets the Max PID Value
/// </summary>
public double MaxPidValue { get; set; }
/// <summary>
/// Gets or sets the Min PID Value
/// </summary>
public double MinPidValue { get; set; }
/// <summary>
/// Gets or sets the Max Integral Error
/// </summary>
public double MaxIntegralError { get; set; }
/// <summary>
/// Gets or sets the DoSaveState flag
/// </summary>
public bool DoSaveState { get; set; }
/// <summary>
/// Initializes an instance of the OnPIDChanges class
/// </summary>
/// <param name="form"></param>
/// <param name="kp"></param>
/// <param name="ki"></param>
/// <param name="kd"></param>
/// <param name="vMax"></param>
/// <param name="vMin"></param>
/// <param name="vIntMax"></param>
/// <param name="doSaveState"></param>
public OnPIDChanges(ObstacleAvoidanceForm form, double kp, double ki, double kd, double vMax, double vMin, double vIntMax, bool doSaveState)
: base(form)
{
this.Kp = kp;
this.Ki = ki;
this.Kd = kd;
this.MaxPidValue = vMax;
this.MinPidValue = vMin;
this.MaxIntegralError = vIntMax;
this.DoSaveState = doSaveState;
}
}
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
#if !NET35 && !PORTABLE
using System;
using System.Abstract;
using System.Collections.Generic;
using System.Linq;
using SystemCaching = System.Runtime.Caching;
namespace Contoso.Abstract
{
/// <summary>
/// ISystemServiceCache
/// </summary>
/// <seealso cref="System.Abstract.IServiceCache" />
public interface ISystemServiceCache : IServiceCache
{
/// <summary>
/// Gets the cache.
/// </summary>
SystemCaching.ObjectCache Cache { get; }
/// <summary>
/// Gets the specified tag.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="regionName">Name of the region.</param>
/// <param name="names">The names.</param>
/// <returns></returns>
object Get(object tag, string regionName, IEnumerable<string> names);
}
/// <summary>
/// SystemServiceCache
/// </summary>
public class SystemServiceCache : ISystemServiceCache, ServiceCacheManager.IRegisterWithLocator
{
/// <summary>
/// Initializes a new instance of the <see cref="SystemServiceCache" /> class.
/// </summary>
public SystemServiceCache()
: this(SystemCaching.MemoryCache.Default) { }
/// <summary>
/// Initializes a new instance of the <see cref="SystemServiceCache" /> class.
/// </summary>
/// <param name="name">The name.</param>
public SystemServiceCache(string name)
: this(new SystemCaching.MemoryCache(name)) { }
/// <summary>
/// Initializes a new instance of the <see cref="SystemServiceCache" /> class.
/// </summary>
/// <param name="cache">The cache.</param>
public SystemServiceCache(SystemCaching.ObjectCache cache)
{
Cache = cache;
Settings = new ServiceCacheSettings(new DefaultFileTouchableCacheItem(this, new DefaultTouchableCacheItem(this, null)));
}
Action<IServiceLocator, string> ServiceCacheManager.IRegisterWithLocator.RegisterWithLocator =>
(locator, name) => ServiceCacheManager.RegisterInstance<ISystemServiceCache>(this, name, locator);
/// <summary>
/// Gets the service object of the specified type.
/// </summary>
/// <param name="serviceType">An object that specifies the type of service object to get.</param>
/// <returns>
/// A service object of type <paramref name="serviceType"/>.-or- null if there is no service object of type <paramref name="serviceType"/>.
/// </returns>
public object GetService(Type serviceType) { throw new NotImplementedException(); }
/// <summary>
/// Gets or sets the <see cref="System.Object"/> with the specified name.
/// </summary>
public object this[string name]
{
get => Get(null, name);
set => Set(null, name, CacheItemPolicy.Default, value, ServiceCacheByDispatcher.Empty);
}
/// <summary>
/// Adds the specified tag.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="name">The name.</param>
/// <param name="itemPolicy">The item policy.</param>
/// <param name="value">The value.</param>
/// <param name="dispatch">The dispatch.</param>
/// <returns>System.Object.</returns>
/// <exception cref="System.ArgumentNullException">itemPolicy</exception>
public object Add(object tag, string name, CacheItemPolicy itemPolicy, object value, ServiceCacheByDispatcher dispatch)
{
if (itemPolicy == null)
throw new ArgumentNullException(nameof(itemPolicy));
itemPolicy.UpdateCallback?.Invoke(name, value);
Settings.TryGetRegion(ref name, out var regionName);
//
value = Cache.Add(name, value, GetCacheDependency(tag, itemPolicy, dispatch), regionName);
var registration = dispatch.Registration;
if (registration != null && registration.UseHeaders)
{
var headerPolicy = new SystemCaching.CacheItemPolicy();
headerPolicy.ChangeMonitors.Add(Cache.CreateCacheEntryChangeMonitor(new[] { name }, regionName));
var header = dispatch.Header;
header.Item = name;
Cache.Add(name + "#", header, headerPolicy, regionName);
}
return value;
}
/// <summary>
/// Gets the item from cache associated with the key provided.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="name">The name.</param>
/// <returns>The cached item.</returns>
public object Get(object tag, string name)
{
Settings.TryGetRegion(ref name, out var regionName);
return Cache.Get(name, regionName);
}
/// <summary>
/// Gets the specified tag.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="name">The name.</param>
/// <param name="registration">The registration.</param>
/// <param name="header">The header.</param>
/// <returns>System.Object.</returns>
/// <exception cref="System.ArgumentNullException">registration</exception>
public object Get(object tag, string name, IServiceCacheRegistration registration, out CacheItemHeader header)
{
if (registration == null)
throw new ArgumentNullException(nameof(registration));
Settings.TryGetRegion(ref name, out var regionName);
header = registration.UseHeaders ? (CacheItemHeader)Cache.Get(name + "#", regionName) : null;
return Cache.Get(name, regionName);
}
/// <summary>
/// Gets the specified tag.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="names">The names.</param>
/// <returns>System.Object.</returns>
public object Get(object tag, IEnumerable<string> names) =>
Cache.GetValues(null, names.ToArray());
/// <summary>
/// Gets the specified tag.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="regionName">Name of the region.</param>
/// <param name="names">The names.</param>
/// <returns>System.Object.</returns>
public object Get(object tag, string regionName, IEnumerable<string> names) =>
Cache.GetValues(regionName, names.ToArray());
/// <summary>
/// Gets the specified registration.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="registration">The registration.</param>
/// <returns>IEnumerable<CacheItemHeader>.</returns>
/// <exception cref="System.ArgumentNullException">registration</exception>
/// <exception cref="System.NotImplementedException"></exception>
public IEnumerable<CacheItemHeader> Get(object tag, IServiceCacheRegistration registration)
{
if (registration == null)
throw new ArgumentNullException(nameof(registration));
throw new NotImplementedException();
}
/// <summary>
/// Tries the get.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="name">The name.</param>
/// <param name="value">The value.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
public bool TryGet(object tag, string name, out object value)
{
Settings.TryGetRegion(ref name, out var regionName);
var cacheItem = Cache.GetCacheItem(name, regionName);
if (cacheItem != null)
{
value = cacheItem.Value;
return true;
}
value = null;
return false;
}
/// <summary>
/// Adds an object into cache based on the parameters provided.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="name">The name.</param>
/// <param name="itemPolicy">The itemPolicy object.</param>
/// <param name="value">The value to store in cache.</param>
/// <param name="dispatch">The dispatch.</param>
/// <returns>System.Object.</returns>
/// <exception cref="System.ArgumentNullException">itemPolicy</exception>
public object Set(object tag, string name, CacheItemPolicy itemPolicy, object value, ServiceCacheByDispatcher dispatch)
{
if (itemPolicy == null)
throw new ArgumentNullException("itemPolicy");
itemPolicy.UpdateCallback?.Invoke(name, value);
Settings.TryGetRegion(ref name, out var regionName);
//
Cache.Set(name, value, GetCacheDependency(tag, itemPolicy, dispatch), regionName);
var registration = dispatch.Registration;
if (registration != null && registration.UseHeaders)
{
var headerPolicy = new SystemCaching.CacheItemPolicy();
headerPolicy.ChangeMonitors.Add(Cache.CreateCacheEntryChangeMonitor(new[] { name }, regionName));
var header = dispatch.Header;
header.Item = name;
Cache.Set(name + "#", header, headerPolicy, regionName);
}
return value;
}
/// <summary>
/// Removes from cache the item associated with the key provided.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="name">The name.</param>
/// <param name="registration">The registration.</param>
/// <returns>The item removed from the Cache. If the value in the key parameter is not found, returns null.</returns>
public object Remove(object tag, string name, IServiceCacheRegistration registration)
{
Settings.TryGetRegion(ref name, out var regionName);
if (registration != null && registration.UseHeaders)
Cache.Remove(name + "#", regionName);
return Cache.Remove(name, regionName);
}
/// <summary>
/// Settings
/// </summary>
/// <value>The settings.</value>
public ServiceCacheSettings Settings { get; private set; }
#region TouchableCacheItem
/// <summary>
/// DefaultTouchableCacheItem
/// </summary>
/// <seealso cref="System.Abstract.ITouchableCacheItem" />
public class DefaultTouchableCacheItem : ITouchableCacheItem
{
SystemServiceCache _parent;
ITouchableCacheItem _base;
/// <summary>
/// Initializes a new instance of the <see cref="DefaultTouchableCacheItem" /> class.
/// </summary>
/// <param name="parent">The parent.</param>
/// <param name="base">The @base.</param>
public DefaultTouchableCacheItem(SystemServiceCache parent, ITouchableCacheItem @base) { _parent = parent; _base = @base; }
/// <summary>
/// Touches the specified tag.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="names">The names.</param>
public void Touch(object tag, string[] names)
{
if (names == null || names.Length == 0)
return;
var settings = _parent.Settings;
var cache = _parent.Cache;
foreach (var name in names)
{
var touchName = name;
settings.TryGetRegion(ref touchName, out var regionName);
cache.Set(touchName, string.Empty, ServiceCache.InfiniteAbsoluteExpiration, regionName);
}
if (_base != null)
_base.Touch(tag, names);
}
/// <summary>
/// Makes the dependency.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="names">The names.</param>
/// <returns>System.Object.</returns>
public object MakeDependency(object tag, string[] names)
{
if (names == null || names.Length == 0)
return null;
var changeMonitors = new[] { _parent.Cache.CreateCacheEntryChangeMonitor(names) };
return _base == null ? changeMonitors : changeMonitors.Union(_base.MakeDependency(tag, names) as IEnumerable<SystemCaching.ChangeMonitor>);
}
}
/// <summary>
/// DefaultFileTouchableCacheItem
/// </summary>
public class DefaultFileTouchableCacheItem : AbstractFileTouchableCacheItem
{
/// <summary>
/// Initializes a new instance of the <see cref="DefaultFileTouchableCacheItem"/> class.
/// </summary>
/// <param name="parent">The parent.</param>
/// <param name="base">The @base.</param>
public DefaultFileTouchableCacheItem(SystemServiceCache parent, ITouchableCacheItem @base)
: base(parent, @base) { }
/// <summary>
/// Makes the dependency internal.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="names">The names.</param>
/// <param name="baseDependency">The base dependency.</param>
/// <returns></returns>
protected override object MakeDependencyInternal(object tag, string[] names, object baseDependency) =>
new SystemCaching.HostFileChangeMonitor(names.Select(x => GetFilePathForName(x)).ToArray());
}
#endregion
#region Domain-specific
/// <summary>
/// Gets the cache.
/// </summary>
/// <value>The cache.</value>
public SystemCaching.ObjectCache Cache { get; private set; }
#endregion
SystemCaching.CacheItemPolicy GetCacheDependency(object tag, CacheItemPolicy itemPolicy, ServiceCacheByDispatcher dispatch)
{
// item priority
SystemCaching.CacheItemPriority itemPriority;
switch (itemPolicy.Priority)
{
case CacheItemPriority.NotRemovable: itemPriority = SystemCaching.CacheItemPriority.NotRemovable; break;
default: itemPriority = SystemCaching.CacheItemPriority.Default; break;
}
var removedCallback = itemPolicy.RemovedCallback != null ? new SystemCaching.CacheEntryRemovedCallback(x => { itemPolicy.RemovedCallback(x.CacheItem.Key, x.CacheItem.Value); }) : null;
var updateCallback = itemPolicy.UpdateCallback != null ? new SystemCaching.CacheEntryUpdateCallback(x => { itemPolicy.UpdateCallback(x.UpdatedCacheItem.Key, x.UpdatedCacheItem.Value); }) : null;
var newItemPolicy = new SystemCaching.CacheItemPolicy
{
AbsoluteExpiration = itemPolicy.AbsoluteExpiration,
Priority = itemPriority,
RemovedCallback = removedCallback,
SlidingExpiration = itemPolicy.SlidingExpiration,
UpdateCallback = updateCallback,
};
var changeMonitors = GetCacheDependency(tag, itemPolicy.Dependency, dispatch);
if (changeMonitors != null)
{
var list = newItemPolicy.ChangeMonitors;
foreach (var changeMonitor in changeMonitors)
list.Add(changeMonitor);
}
return newItemPolicy;
}
IEnumerable<SystemCaching.ChangeMonitor> GetCacheDependency(object tag, CacheItemDependency dependency, ServiceCacheByDispatcher dispatch)
{
object value;
if (dependency == null || (value = dependency(this, dispatch.Registration, tag, dispatch.Values)) == null)
return null;
//
var names = value as string[];
var touchable = Settings.Touchable;
return (touchable != null && names != null ? touchable.MakeDependency(tag, names) : value) as IEnumerable<SystemCaching.ChangeMonitor>;
}
}
}
#endif
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
namespace DiscUtils.Ntfs
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
/// <summary>
/// Class that checks NTFS file system integrity.
/// </summary>
/// <remarks>Poor relation of chkdsk/fsck.</remarks>
public sealed class NtfsFileSystemChecker : DiscFileSystemChecker
{
private Stream _target;
private NtfsContext _context;
private TextWriter _report;
private ReportLevels _reportLevels;
private ReportLevels _levelsDetected;
private ReportLevels _levelsConsideredFail = ReportLevels.Errors;
/// <summary>
/// Initializes a new instance of the NtfsFileSystemChecker class.
/// </summary>
/// <param name="diskData">The file system to check</param>
public NtfsFileSystemChecker(Stream diskData)
{
SnapshotStream protectiveStream = new SnapshotStream(diskData, Ownership.None);
protectiveStream.Snapshot();
protectiveStream.Freeze();
_target = protectiveStream;
}
/// <summary>
/// Checks the integrity of an NTFS file system held in a stream.
/// </summary>
/// <param name="reportOutput">A report on issues found</param>
/// <param name="levels">The amount of detail to report</param>
/// <returns><c>true</c> if the file system appears valid, else <c>false</c></returns>
public override bool Check(TextWriter reportOutput, ReportLevels levels)
{
_context = new NtfsContext();
_context.RawStream = _target;
_context.Options = new NtfsOptions();
_report = reportOutput;
_reportLevels = levels;
_levelsDetected = ReportLevels.None;
try
{
DoCheck();
}
catch (AbortException ae)
{
ReportError("File system check aborted: " + ae.ToString());
return false;
}
catch (Exception e)
{
ReportError("File system check aborted with exception: " + e.ToString());
return false;
}
return (_levelsDetected & _levelsConsideredFail) == 0;
}
/// <summary>
/// Gets an object that can convert between clusters and files.
/// </summary>
/// <returns>The cluster map</returns>
public ClusterMap BuildClusterMap()
{
_context = new NtfsContext();
_context.RawStream = _target;
_context.Options = new NtfsOptions();
_context.RawStream.Position = 0;
byte[] bytes = Utilities.ReadFully(_context.RawStream, 512);
_context.BiosParameterBlock = BiosParameterBlock.FromBytes(bytes, 0);
_context.Mft = new MasterFileTable(_context);
File mftFile = new File(_context, _context.Mft.GetBootstrapRecord());
_context.Mft.Initialize(mftFile);
return _context.Mft.GetClusterMap();
}
private static void Abort()
{
throw new AbortException();
}
private void DoCheck()
{
_context.RawStream.Position = 0;
byte[] bytes = Utilities.ReadFully(_context.RawStream, 512);
_context.BiosParameterBlock = BiosParameterBlock.FromBytes(bytes, 0);
//-----------------------------------------------------------------------
// MASTER FILE TABLE
//
// Bootstrap the Master File Table
_context.Mft = new MasterFileTable(_context);
File mftFile = new File(_context, _context.Mft.GetBootstrapRecord());
// Verify basic MFT records before initializing the Master File Table
PreVerifyMft(mftFile);
_context.Mft.Initialize(mftFile);
// Now the MFT is up and running, do more detailed analysis of it's contents - double-accounted clusters, etc
VerifyMft();
_context.Mft.Dump(_report, "INFO: ");
//-----------------------------------------------------------------------
// INDEXES
//
// Need UpperCase in order to verify some indexes (i.e. directories).
File ucFile = new File(_context, _context.Mft.GetRecord(MasterFileTable.UpCaseIndex, false));
_context.UpperCase = new UpperCase(ucFile);
SelfCheckIndexes();
//-----------------------------------------------------------------------
// DIRECTORIES
//
VerifyDirectories();
//-----------------------------------------------------------------------
// WELL KNOWN FILES
//
VerifyWellKnownFilesExist();
//-----------------------------------------------------------------------
// OBJECT IDS
//
VerifyObjectIds();
//-----------------------------------------------------------------------
// FINISHED
//
// Temporary...
using (NtfsFileSystem fs = new NtfsFileSystem(_context.RawStream))
{
if ((_reportLevels & ReportLevels.Information) != 0)
{
ReportDump(fs);
}
}
}
private void VerifyWellKnownFilesExist()
{
Directory rootDir = new Directory(_context, _context.Mft.GetRecord(MasterFileTable.RootDirIndex, false));
DirectoryEntry extendDirEntry = rootDir.GetEntryByName("$Extend");
if (extendDirEntry == null)
{
ReportError("$Extend does not exist in root directory");
Abort();
}
Directory extendDir = new Directory(_context, _context.Mft.GetRecord(extendDirEntry.Reference));
DirectoryEntry objIdDirEntry = extendDir.GetEntryByName("$ObjId");
if (objIdDirEntry == null)
{
ReportError("$ObjId does not exist in $Extend directory");
Abort();
}
// Stash ObjectIds
_context.ObjectIds = new ObjectIds(new File(_context, _context.Mft.GetRecord(objIdDirEntry.Reference)));
DirectoryEntry sysVolInfDirEntry = rootDir.GetEntryByName("System Volume Information");
if (sysVolInfDirEntry == null)
{
ReportError("'System Volume Information' does not exist in root directory");
Abort();
}
////Directory sysVolInfDir = new Directory(_context, _context.Mft.GetRecord(sysVolInfDirEntry.Reference));
}
private void VerifyObjectIds()
{
foreach (FileRecord fr in _context.Mft.Records)
{
if (fr.BaseFile.Value != 0)
{
File f = new File(_context, fr);
foreach (var stream in f.AllStreams)
{
if (stream.AttributeType == AttributeType.ObjectId)
{
ObjectId objId = stream.GetContent<ObjectId>();
ObjectIdRecord objIdRec;
if (!_context.ObjectIds.TryGetValue(objId.Id, out objIdRec))
{
ReportError("ObjectId {0} for file {1} is not indexed", objId.Id, f.BestName);
}
else if (objIdRec.MftReference != f.MftReference)
{
ReportError("ObjectId {0} for file {1} points to {2}", objId.Id, f.BestName, objIdRec.MftReference);
}
}
}
}
}
foreach (var objIdRec in _context.ObjectIds.All)
{
if (_context.Mft.GetRecord(objIdRec.Value.MftReference) == null)
{
ReportError("ObjectId {0} refers to non-existant file {1}", objIdRec.Key, objIdRec.Value.MftReference);
}
}
}
private void VerifyDirectories()
{
foreach (FileRecord fr in _context.Mft.Records)
{
if (fr.BaseFile.Value != 0)
{
continue;
}
File f = new File(_context, fr);
foreach (var stream in f.AllStreams)
{
if (stream.AttributeType == AttributeType.IndexRoot && stream.Name == "$I30")
{
IndexView<FileNameRecord, FileRecordReference> dir = new IndexView<FileNameRecord, FileRecordReference>(f.GetIndex("$I30"));
foreach (var entry in dir.Entries)
{
FileRecord refFile = _context.Mft.GetRecord(entry.Value);
// Make sure each referenced file actually exists...
if (refFile == null)
{
ReportError("Directory {0} references non-existent file {1}", f, entry.Key);
}
File referencedFile = new File(_context, refFile);
StandardInformation si = referencedFile.StandardInformation;
if (si.CreationTime != entry.Key.CreationTime || si.MftChangedTime != entry.Key.MftChangedTime
|| si.ModificationTime != entry.Key.ModificationTime)
{
ReportInfo("Directory entry {0} in {1} is out of date", entry.Key, f);
}
}
}
}
}
}
private void SelfCheckIndexes()
{
foreach (FileRecord fr in _context.Mft.Records)
{
File f = new File(_context, fr);
foreach (var stream in f.AllStreams)
{
if (stream.AttributeType == AttributeType.IndexRoot)
{
SelfCheckIndex(f, stream.Name);
}
}
}
}
private void SelfCheckIndex(File file, string name)
{
ReportInfo("About to self-check index {0} in file {1} (MFT:{2})", name, file.BestName, file.IndexInMft);
IndexRoot root = file.GetStream(AttributeType.IndexRoot, name).GetContent<IndexRoot>();
byte[] rootBuffer;
using (Stream s = file.OpenStream(AttributeType.IndexRoot, name, FileAccess.Read))
{
rootBuffer = Utilities.ReadFully(s, (int)s.Length);
}
Bitmap indexBitmap = null;
if (file.GetStream(AttributeType.Bitmap, name) != null)
{
indexBitmap = new Bitmap(file.OpenStream(AttributeType.Bitmap, name, FileAccess.Read), long.MaxValue);
}
if (!SelfCheckIndexNode(rootBuffer, IndexRoot.HeaderOffset, indexBitmap, root, file.BestName, name))
{
ReportError("Index {0} in file {1} (MFT:{2}) has corrupt IndexRoot attribute", name, file.BestName, file.IndexInMft);
}
else
{
ReportInfo("Self-check of index {0} in file {1} (MFT:{2}) complete", name, file.BestName, file.IndexInMft);
}
}
private bool SelfCheckIndexNode(byte[] buffer, int offset, Bitmap bitmap, IndexRoot root, string fileName, string indexName)
{
bool ok = true;
IndexHeader header = new IndexHeader(buffer, offset);
IndexEntry lastEntry = null;
IComparer<byte[]> collator = root.GetCollator(_context.UpperCase);
int pos = (int)header.OffsetToFirstEntry;
while (pos < header.TotalSizeOfEntries)
{
IndexEntry entry = new IndexEntry(indexName == "$I30");
entry.Read(buffer, offset + pos);
pos += entry.Size;
if ((entry.Flags & IndexEntryFlags.Node) != 0)
{
long bitmapIdx = entry.ChildrenVirtualCluster / Utilities.Ceil(root.IndexAllocationSize, _context.BiosParameterBlock.SectorsPerCluster * _context.BiosParameterBlock.BytesPerSector);
if (!bitmap.IsPresent(bitmapIdx))
{
ReportError("Index entry {0} is non-leaf, but child vcn {1} is not in bitmap at index {2}", Index.EntryAsString(entry, fileName, indexName), entry.ChildrenVirtualCluster, bitmapIdx);
}
}
if ((entry.Flags & IndexEntryFlags.End) != 0)
{
if (pos != header.TotalSizeOfEntries)
{
ReportError("Found END index entry {0}, but not at end of node", Index.EntryAsString(entry, fileName, indexName));
ok = false;
}
}
if (lastEntry != null && collator.Compare(lastEntry.KeyBuffer, entry.KeyBuffer) >= 0)
{
ReportError("Found entries out of order {0} was before {1}", Index.EntryAsString(lastEntry, fileName, indexName), Index.EntryAsString(entry, fileName, indexName));
ok = false;
}
lastEntry = entry;
}
return ok;
}
private void PreVerifyMft(File file)
{
int recordLength = _context.BiosParameterBlock.MftRecordSize;
int bytesPerSector = _context.BiosParameterBlock.BytesPerSector;
// Check out the MFT's clusters
foreach (var range in file.GetAttribute(AttributeType.Data, null).GetClusters())
{
if (!VerifyClusterRange(range))
{
ReportError("Corrupt cluster range in MFT data attribute {0}", range.ToString());
Abort();
}
}
foreach (var range in file.GetAttribute(AttributeType.Bitmap, null).GetClusters())
{
if (!VerifyClusterRange(range))
{
ReportError("Corrupt cluster range in MFT bitmap attribute {0}", range.ToString());
Abort();
}
}
using (Stream mftStream = file.OpenStream(AttributeType.Data, null, FileAccess.Read))
using (Stream bitmapStream = file.OpenStream(AttributeType.Bitmap, null, FileAccess.Read))
{
Bitmap bitmap = new Bitmap(bitmapStream, long.MaxValue);
long index = 0;
while (mftStream.Position < mftStream.Length)
{
byte[] recordData = Utilities.ReadFully(mftStream, recordLength);
string magic = Utilities.BytesToString(recordData, 0, 4);
if (magic != "FILE")
{
if (bitmap.IsPresent(index))
{
ReportError("Invalid MFT record magic at index {0} - was ({2},{3},{4},{5}) \"{1}\"", index, magic.Trim('\0'), (int)magic[0], (int)magic[1], (int)magic[2], (int)magic[3]);
}
}
else
{
if (!VerifyMftRecord(recordData, bitmap.IsPresent(index), bytesPerSector))
{
ReportError("Invalid MFT record at index {0}", index);
StringBuilder bldr = new StringBuilder();
for (int i = 0; i < recordData.Length; ++i)
{
bldr.Append(string.Format(CultureInfo.InvariantCulture, " {0:X2}", recordData[i]));
}
ReportInfo("MFT record binary data for index {0}:{1}", index, bldr.ToString());
}
}
index++;
}
}
}
private void VerifyMft()
{
// Cluster allocation check - check for double allocations
Dictionary<long, string> clusterMap = new Dictionary<long, string>();
foreach (FileRecord fr in _context.Mft.Records)
{
if ((fr.Flags & FileRecordFlags.InUse) != 0)
{
File f = new File(_context, fr);
foreach (NtfsAttribute attr in f.AllAttributes)
{
string attrKey = fr.MasterFileTableIndex + ":" + attr.Id;
foreach (var range in attr.GetClusters())
{
if (!VerifyClusterRange(range))
{
ReportError("Attribute {0} contains bad cluster range {1}", attrKey, range);
}
for (long cluster = range.Offset; cluster < range.Offset + range.Count; ++cluster)
{
string existingKey;
if (clusterMap.TryGetValue(cluster, out existingKey))
{
ReportError("Two attributes referencing cluster {0} (0x{0:X16}) - {1} and {2} (as MftIndex:AttrId)", cluster, existingKey, attrKey);
}
}
}
}
}
}
}
private bool VerifyMftRecord(byte[] recordData, bool presentInBitmap, int bytesPerSector)
{
bool ok = true;
//
// Verify the attributes seem OK...
//
byte[] tempBuffer = new byte[recordData.Length];
Array.Copy(recordData, tempBuffer, tempBuffer.Length);
GenericFixupRecord genericRecord = new GenericFixupRecord(bytesPerSector);
genericRecord.FromBytes(tempBuffer, 0);
int pos = Utilities.ToUInt16LittleEndian(genericRecord.Content, 0x14);
while (Utilities.ToUInt32LittleEndian(genericRecord.Content, pos) != 0xFFFFFFFF)
{
int attrLen;
try
{
AttributeRecord ar = AttributeRecord.FromBytes(genericRecord.Content, pos, out attrLen);
if (attrLen != ar.Size)
{
ReportError("Attribute size is different to calculated size. AttrId={0}", ar.AttributeId);
ok = false;
}
if (ar.IsNonResident)
{
NonResidentAttributeRecord nrr = (NonResidentAttributeRecord)ar;
if (nrr.DataRuns.Count > 0)
{
long totalVcn = 0;
foreach (var run in nrr.DataRuns)
{
totalVcn += run.RunLength;
}
if (totalVcn != nrr.LastVcn - nrr.StartVcn + 1)
{
ReportError("Declared VCNs doesn't match data runs. AttrId={0}", ar.AttributeId);
ok = false;
}
}
}
}
catch
{
ReportError("Failure parsing attribute at pos={0}", pos);
return false;
}
pos += attrLen;
}
//
// Now consider record as a whole
//
FileRecord record = new FileRecord(bytesPerSector);
record.FromBytes(recordData, 0);
bool inUse = (record.Flags & FileRecordFlags.InUse) != 0;
if (inUse != presentInBitmap)
{
ReportError("MFT bitmap and record in-use flag don't agree. Mft={0}, Record={1}", presentInBitmap ? "InUse" : "Free", inUse ? "InUse" : "Free");
ok = false;
}
if (record.Size != record.RealSize)
{
ReportError("MFT record real size is different to calculated size. Stored in MFT={0}, Calculated={1}", record.RealSize, record.Size);
ok = false;
}
if (Utilities.ToUInt32LittleEndian(recordData, (int)record.RealSize - 8) != uint.MaxValue)
{
ReportError("MFT record is not correctly terminated with 0xFFFFFFFF");
ok = false;
}
return ok;
}
private bool VerifyClusterRange(Range<long, long> range)
{
bool ok = true;
if (range.Offset < 0)
{
ReportError("Invalid cluster range {0} - negative start", range);
ok = false;
}
if (range.Count <= 0)
{
ReportError("Invalid cluster range {0} - negative/zero count", range);
ok = false;
}
if ((range.Offset + range.Count) * _context.BiosParameterBlock.BytesPerCluster > _context.RawStream.Length)
{
ReportError("Invalid cluster range {0} - beyond end of disk", range);
ok = false;
}
return ok;
}
private void ReportDump(IDiagnosticTraceable toDump)
{
_levelsDetected |= ReportLevels.Information;
if ((_reportLevels & ReportLevels.Information) != 0)
{
toDump.Dump(_report, "INFO: ");
}
}
private void ReportInfo(string str, params object[] args)
{
_levelsDetected |= ReportLevels.Information;
if ((_reportLevels & ReportLevels.Information) != 0)
{
_report.WriteLine("INFO: " + str, args);
}
}
private void ReportError(string str, params object[] args)
{
_levelsDetected |= ReportLevels.Errors;
if ((_reportLevels & ReportLevels.Errors) != 0)
{
_report.WriteLine("ERROR: " + str, args);
}
}
[Serializable]
private sealed class AbortException : InvalidFileSystemException
{
public AbortException()
: base()
{
}
private AbortException(SerializationInfo info, StreamingContext ctxt)
: base(info, ctxt)
{
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.strcts.strct001.strct001
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.strcts.strct001.strct001;
// <Title>Structs</Title>
// <Description>
// is by design because of "d.s.Field = 4;" equals as "dynamic d2 = d.s; d2.Field = 4;" and
// "object d2 = d.s; d2.Field = 4;", the modification occurs on the boxed object, so the origin value wasn't changed.
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
#pragma warning disable 0649
public struct S
{
public int Field;
}
public class C
{
public S s;
public S prop
{
get;
set;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
int rez = 0;
dynamic d = new S();
d.Field = 3;
if (d.Field != 3)
rez += 1;
//Struct as a field
d = new C();
d.s = default(S);
d.s.Field = 4;
//
if (d.s.Field != 0)
rez += 1;
//Struct as a property
d.prop = default(S);
d.prop.Field = 5;
//
if (d.prop.Field != 0)
rez += 1;
return rez == 0 ? 0 : 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.strcts.strct002.strct002
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.strcts.strct002.strct002;
// <Title>Structs</Title>
// <Description>
// is by design because of "d.s.Field = 4;" equals as "dynamic d2 = d.s; d2.Field = 4;" and
// "object d2 = d.s; d2.Field = 4;", the modification occurs on the boxed object, so the origin value wasn't changed.
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
#pragma warning disable 0649
public struct S
{
public int Field;
}
public class C<T>
{
public T s;
public T prop
{
get;
set;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
int rez = 0;
//Struct as a field
dynamic d = new C<S>();
d.s = default(S);
d.s.Field = 4;
//
if (d.s.Field != 0)
rez += 1;
//Struct as a property
d.prop = default(S);
d.prop.Field = 5;
//
if (d.prop.Field != 0)
rez += 1;
return rez == 0 ? 0 : 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.strcts.strct003.strct003
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.strcts.strct003.strct003;
// <Title>Structs</Title>
// <Description>
// is by design because of "d.s.Field = 4;" equals as "dynamic d2 = d.s; d2.Field = 4;" and
// "object d2 = d.s; d2.Field = 4;", the modification occurs on the boxed object, so the origin value wasn't changed.
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
#pragma warning disable 0649
public struct S
{
public int Field;
public struct S2
{
public float Foo;
}
public S2 Field2;
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
int rez = 0;
dynamic d = new S();
d.Field2 = default(S.S2);
d.Field2.Foo = 4;
//
if (d.Field2.Foo != 0)
rez++;
return rez == 0 ? 0 : 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.strcts.strct004.strct004
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.strcts.strct004.strct004;
// <Title>Structs</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public struct S
{
public int x;
public void Set(int val)
{
this.x = val;
}
}
public class Test
{
[Fact(Skip = "870811")]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
S dy = new S();
dynamic val = 1;
dy.Set(val);
if (dy.x != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.strcts.strct005.strct005
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.strcts.strct005.strct005;
public class DynamicTest
{
public struct MyStruct
{
public int M(int p)
{
return p;
}
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic x = 0;
return new MyStruct().M(x);
}
}
// </Code>
}
| |
// 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.ComponentModel;
using System.Diagnostics;
using System.Drawing.Imaging;
using System.Drawing.Internal;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using Gdip = System.Drawing.SafeNativeMethods.Gdip;
namespace System.Drawing
{
public abstract partial class Image
{
#if FINALIZATION_WATCH
private string allocationSite = Graphics.GetAllocationStack();
#endif
public static Image FromFile(string filename, bool useEmbeddedColorManagement)
{
if (!File.Exists(filename))
{
// Throw a more specific exception for invalid paths that are null or empty,
// contain invalid characters or are too long.
filename = Path.GetFullPath(filename);
throw new FileNotFoundException(filename);
}
// GDI+ will read this file multiple times. Get the fully qualified path
// so if our app changes default directory we won't get an error
filename = Path.GetFullPath(filename);
IntPtr image = IntPtr.Zero;
if (useEmbeddedColorManagement)
{
Gdip.CheckStatus(Gdip.GdipLoadImageFromFileICM(filename, out image));
}
else
{
Gdip.CheckStatus(Gdip.GdipLoadImageFromFile(filename, out image));
}
ValidateImage(image);
Image img = CreateImageObject(image);
EnsureSave(img, filename, null);
return img;
}
public static Image FromStream(Stream stream, bool useEmbeddedColorManagement, bool validateImageData)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
IntPtr image = IntPtr.Zero;
if (useEmbeddedColorManagement)
{
Gdip.CheckStatus(Gdip.GdipLoadImageFromStreamICM(new GPStream(stream), out image));
}
else
{
Gdip.CheckStatus(Gdip.GdipLoadImageFromStream(new GPStream(stream), out image));
}
if (validateImageData)
ValidateImage(image);
Image img = CreateImageObject(image);
EnsureSave(img, null, stream);
return img;
}
// Used for serialization
private IntPtr InitializeFromStream(Stream stream)
{
IntPtr image = IntPtr.Zero;
Gdip.CheckStatus(Gdip.GdipLoadImageFromStream(new GPStream(stream), out image));
ValidateImage(image);
nativeImage = image;
int type = -1;
Gdip.CheckStatus(Gdip.GdipGetImageType(new HandleRef(this, nativeImage), out type));
EnsureSave(this, null, stream);
return image;
}
internal Image(IntPtr nativeImage) => SetNativeImage(nativeImage);
/// <summary>
/// Creates an exact copy of this <see cref='Image'/>.
/// </summary>
public object Clone()
{
IntPtr cloneImage = IntPtr.Zero;
Gdip.CheckStatus(Gdip.GdipCloneImage(new HandleRef(this, nativeImage), out cloneImage));
ValidateImage(cloneImage);
return CreateImageObject(cloneImage);
}
protected virtual void Dispose(bool disposing)
{
#if FINALIZATION_WATCH
if (!disposing && nativeImage != IntPtr.Zero)
Debug.WriteLine("**********************\nDisposed through finalization:\n" + allocationSite);
#endif
if (nativeImage == IntPtr.Zero)
return;
try
{
#if DEBUG
int status =
#endif
Gdip.GdipDisposeImage(new HandleRef(this, nativeImage));
#if DEBUG
Debug.Assert(status == Gdip.Ok, "GDI+ returned an error status: " + status.ToString(CultureInfo.InvariantCulture));
#endif
}
catch (Exception ex)
{
if (ClientUtils.IsSecurityOrCriticalException(ex))
{
throw;
}
Debug.Fail("Exception thrown during Dispose: " + ex.ToString());
}
finally
{
nativeImage = IntPtr.Zero;
}
}
internal static Image CreateImageObject(IntPtr nativeImage)
{
Image image;
Gdip.CheckStatus(Gdip.GdipGetImageType(new HandleRef(null, nativeImage), out int type));
switch ((ImageType)type)
{
case ImageType.Bitmap:
image = new Bitmap(nativeImage);
break;
case ImageType.Metafile:
image = Metafile.FromGDIplus(nativeImage);
break;
default:
throw new ArgumentException(SR.Format(SR.InvalidImage));
}
return image;
}
/// <summary>
/// Returns information about the codecs used for this <see cref='Image'/>.
/// </summary>
public EncoderParameters GetEncoderParameterList(Guid encoder)
{
EncoderParameters p;
Gdip.CheckStatus(Gdip.GdipGetEncoderParameterListSize(
new HandleRef(this, nativeImage),
ref encoder,
out int size));
if (size <= 0)
return null;
IntPtr buffer = Marshal.AllocHGlobal(size);
try
{
Gdip.CheckStatus(Gdip.GdipGetEncoderParameterList(
new HandleRef(this, nativeImage),
ref encoder,
size,
buffer));
p = EncoderParameters.ConvertFromMemory(buffer);
}
finally
{
Marshal.FreeHGlobal(buffer);
}
return p;
}
/// <summary>
/// Saves this <see cref='Image'/> to the specified file in the specified format.
/// </summary>
public void Save(string filename, ImageFormat format)
{
if (format == null)
throw new ArgumentNullException(nameof(format));
ImageCodecInfo codec = format.FindEncoder();
if (codec == null)
codec = ImageFormat.Png.FindEncoder();
Save(filename, codec, null);
}
/// <summary>
/// Saves this <see cref='Image'/> to the specified file in the specified format and with the specified encoder parameters.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void Save(string filename, ImageCodecInfo encoder, EncoderParameters encoderParams)
{
if (filename == null)
throw new ArgumentNullException(nameof(filename));
if (encoder == null)
throw new ArgumentNullException(nameof(encoder));
IntPtr encoderParamsMemory = IntPtr.Zero;
if (encoderParams != null)
{
_rawData = null;
encoderParamsMemory = encoderParams.ConvertToMemory();
}
try
{
Guid g = encoder.Clsid;
bool saved = false;
if (_rawData != null)
{
ImageCodecInfo rawEncoder = RawFormat.FindEncoder();
if (rawEncoder != null && rawEncoder.Clsid == g)
{
using (FileStream fs = File.OpenWrite(filename))
{
fs.Write(_rawData, 0, _rawData.Length);
saved = true;
}
}
}
if (!saved)
{
Gdip.CheckStatus(Gdip.GdipSaveImageToFile(
new HandleRef(this, nativeImage),
filename,
ref g,
new HandleRef(encoderParams, encoderParamsMemory)));
}
}
finally
{
if (encoderParamsMemory != IntPtr.Zero)
{
Marshal.FreeHGlobal(encoderParamsMemory);
}
}
}
private void Save(MemoryStream stream)
{
// Jpeg loses data, so we don't want to use it to serialize...
ImageFormat dest = RawFormat;
if (dest.Guid == ImageFormat.Jpeg.Guid)
dest = ImageFormat.Png;
// If we don't find an Encoder (for things like Icon), we just switch back to PNG...
ImageCodecInfo codec = dest.FindEncoder() ?? ImageFormat.Png.FindEncoder();
Save(stream, codec, null);
}
/// <summary>
/// Saves this <see cref='Image'/> to the specified stream in the specified format.
/// </summary>
public void Save(Stream stream, ImageFormat format)
{
if (format == null)
throw new ArgumentNullException(nameof(format));
ImageCodecInfo codec = format.FindEncoder();
Save(stream, codec, null);
}
/// <summary>
/// Saves this <see cref='Image'/> to the specified stream in the specified format.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void Save(Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
if (encoder == null)
throw new ArgumentNullException(nameof(encoder));
IntPtr encoderParamsMemory = IntPtr.Zero;
if (encoderParams != null)
{
_rawData = null;
encoderParamsMemory = encoderParams.ConvertToMemory();
}
try
{
Guid g = encoder.Clsid;
bool saved = false;
if (_rawData != null)
{
ImageCodecInfo rawEncoder = RawFormat.FindEncoder();
if (rawEncoder != null && rawEncoder.Clsid == g)
{
stream.Write(_rawData, 0, _rawData.Length);
saved = true;
}
}
if (!saved)
{
Gdip.CheckStatus(Gdip.GdipSaveImageToStream(
new HandleRef(this, nativeImage),
new GPStream(stream),
ref g,
new HandleRef(encoderParams, encoderParamsMemory)));
}
}
finally
{
if (encoderParamsMemory != IntPtr.Zero)
{
Marshal.FreeHGlobal(encoderParamsMemory);
}
}
}
/// <summary>
/// Adds an <see cref='EncoderParameters'/> to this <see cref='Image'/>.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void SaveAdd(EncoderParameters encoderParams)
{
IntPtr encoder = IntPtr.Zero;
if (encoderParams != null)
encoder = encoderParams.ConvertToMemory();
_rawData = null;
try
{
Gdip.CheckStatus(Gdip.GdipSaveAdd(new HandleRef(this, nativeImage), new HandleRef(encoderParams, encoder)));
}
finally
{
if (encoder != IntPtr.Zero)
{
Marshal.FreeHGlobal(encoder);
}
}
}
/// <summary>
/// Adds an <see cref='EncoderParameters'/> to the specified <see cref='Image'/>.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void SaveAdd(Image image, EncoderParameters encoderParams)
{
IntPtr encoder = IntPtr.Zero;
if (image == null)
throw new ArgumentNullException(nameof(image));
if (encoderParams != null)
encoder = encoderParams.ConvertToMemory();
_rawData = null;
try
{
Gdip.CheckStatus(Gdip.GdipSaveAddImage(
new HandleRef(this, nativeImage),
new HandleRef(image, image.nativeImage),
new HandleRef(encoderParams, encoder)));
}
finally
{
if (encoder != IntPtr.Zero)
{
Marshal.FreeHGlobal(encoder);
}
}
}
/// <summary>
/// Gets a bounding rectangle in the specified units for this <see cref='Image'/>.
/// </summary>
public RectangleF GetBounds(ref GraphicsUnit pageUnit)
{
Gdip.CheckStatus(Gdip.GdipGetImageBounds(new HandleRef(this, nativeImage), out RectangleF bounds, out pageUnit));
return bounds;
}
/// <summary>
/// Gets or sets the color palette used for this <see cref='Image'/>.
/// </summary>
[Browsable(false)]
public ColorPalette Palette
{
get
{
Gdip.CheckStatus(Gdip.GdipGetImagePaletteSize(new HandleRef(this, nativeImage), out int size));
// "size" is total byte size:
// sizeof(ColorPalette) + (pal->Count-1)*sizeof(ARGB)
ColorPalette palette = new ColorPalette(size);
// Memory layout is:
// UINT Flags
// UINT Count
// ARGB Entries[size]
IntPtr memory = Marshal.AllocHGlobal(size);
try
{
Gdip.CheckStatus(Gdip.GdipGetImagePalette(new HandleRef(this, nativeImage), memory, size));
palette.ConvertFromMemory(memory);
}
finally
{
Marshal.FreeHGlobal(memory);
}
return palette;
}
set
{
IntPtr memory = value.ConvertToMemory();
try
{
Gdip.CheckStatus(Gdip.GdipSetImagePalette(new HandleRef(this, nativeImage), memory));
}
finally
{
if (memory != IntPtr.Zero)
{
Marshal.FreeHGlobal(memory);
}
}
}
}
// Thumbnail support
/// <summary>
/// Returns the thumbnail for this <see cref='Image'/>.
/// </summary>
public Image GetThumbnailImage(int thumbWidth, int thumbHeight, GetThumbnailImageAbort callback, IntPtr callbackData)
{
IntPtr thumbImage = IntPtr.Zero;
Gdip.CheckStatus(Gdip.GdipGetImageThumbnail(
new HandleRef(this, nativeImage),
thumbWidth,
thumbHeight,
out thumbImage,
callback,
callbackData));
return CreateImageObject(thumbImage);
}
/// <summary>
/// Gets an array of the property IDs stored in this <see cref='Image'/>.
/// </summary>
[Browsable(false)]
public int[] PropertyIdList
{
get
{
Gdip.CheckStatus(Gdip.GdipGetPropertyCount(new HandleRef(this, nativeImage), out int count));
int[] propid = new int[count];
//if we have a 0 count, just return our empty array
if (count == 0)
return propid;
Gdip.CheckStatus(Gdip.GdipGetPropertyIdList(new HandleRef(this, nativeImage), count, propid));
return propid;
}
}
/// <summary>
/// Gets the specified property item from this <see cref='Image'/>.
/// </summary>
public PropertyItem GetPropertyItem(int propid)
{
Gdip.CheckStatus(Gdip.GdipGetPropertyItemSize(new HandleRef(this, nativeImage), propid, out int size));
if (size == 0)
return null;
IntPtr propdata = Marshal.AllocHGlobal(size);
if (propdata == IntPtr.Zero)
throw Gdip.StatusException(Gdip.OutOfMemory);
try
{
Gdip.CheckStatus(Gdip.GdipGetPropertyItem(new HandleRef(this, nativeImage), propid, size, propdata));
return PropertyItemInternal.ConvertFromMemory(propdata, 1)[0];
}
finally
{
Marshal.FreeHGlobal(propdata);
}
}
/// <summary>
/// Sets the specified property item to the specified value.
/// </summary>
public void SetPropertyItem(PropertyItem propitem)
{
PropertyItemInternal propItemInternal = PropertyItemInternal.ConvertFromPropertyItem(propitem);
using (propItemInternal)
{
Gdip.CheckStatus(Gdip.GdipSetPropertyItem(new HandleRef(this, nativeImage), propItemInternal));
}
}
/// <summary>
/// Gets an array of <see cref='PropertyItem'/> objects that describe this <see cref='Image'/>.
/// </summary>
[Browsable(false)]
public PropertyItem[] PropertyItems
{
get
{
Gdip.CheckStatus(Gdip.GdipGetPropertyCount(new HandleRef(this, nativeImage), out int count));
Gdip.CheckStatus(Gdip.GdipGetPropertySize(new HandleRef(this, nativeImage), out int size, ref count));
if (size == 0 || count == 0)
return Array.Empty<PropertyItem>();
IntPtr propdata = Marshal.AllocHGlobal(size);
try
{
Gdip.CheckStatus(Gdip.GdipGetAllPropertyItems(new HandleRef(this, nativeImage), size, count, propdata));
return PropertyItemInternal.ConvertFromMemory(propdata, count);
}
finally
{
Marshal.FreeHGlobal(propdata);
}
}
}
/// <summary>
/// Returns the size of the specified pixel format.
/// </summary>
public static int GetPixelFormatSize(PixelFormat pixfmt)
{
return (unchecked((int)pixfmt) >> 8) & 0xFF;
}
/// <summary>
/// Returns a value indicating whether the pixel format contains alpha information.
/// </summary>
public static bool IsAlphaPixelFormat(PixelFormat pixfmt)
{
return (pixfmt & PixelFormat.Alpha) != 0;
}
internal static void ValidateImage(IntPtr image)
{
try
{
Gdip.CheckStatus(Gdip.GdipImageForceValidation(new HandleRef(null, image)));
}
catch
{
Gdip.GdipDisposeImage(new HandleRef(null, image));
throw;
}
}
}
}
| |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
using log4net.Layout;
using log4net.Core;
using log4net.DateFormatter;
using log4net.Layout.Pattern;
using log4net.Util;
namespace log4net.Util
{
/// <summary>
/// Most of the work of the <see cref="PatternLayout"/> class
/// is delegated to the PatternParser class.
/// </summary>
/// <remarks>
/// <para>
/// The <c>PatternParser</c> processes a pattern string and
/// returns a chain of <see cref="PatternConverter"/> objects.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public sealed class PatternParser
{
#region Public Instance Constructors
/// <summary>
/// Constructor
/// </summary>
/// <param name="pattern">The pattern to parse.</param>
/// <remarks>
/// <para>
/// Initializes a new instance of the <see cref="PatternParser" /> class
/// with the specified pattern string.
/// </para>
/// </remarks>
public PatternParser(string pattern)
{
m_pattern = pattern;
}
#endregion Public Instance Constructors
#region Public Instance Methods
/// <summary>
/// Parses the pattern into a chain of pattern converters.
/// </summary>
/// <returns>The head of a chain of pattern converters.</returns>
/// <remarks>
/// <para>
/// Parses the pattern into a chain of pattern converters.
/// </para>
/// </remarks>
public PatternConverter Parse()
{
string[] converterNamesCache = BuildCache();
ParseInternal(m_pattern, converterNamesCache);
return m_head;
}
#endregion Public Instance Methods
#region Public Instance Properties
/// <summary>
/// Get the converter registry used by this parser
/// </summary>
/// <value>
/// The converter registry used by this parser
/// </value>
/// <remarks>
/// <para>
/// Get the converter registry used by this parser
/// </para>
/// </remarks>
public Hashtable PatternConverters
{
get { return m_patternConverters; }
}
#endregion Public Instance Properties
#region Private Instance Methods
/// <summary>
/// Build the unified cache of converters from the static and instance maps
/// </summary>
/// <returns>the list of all the converter names</returns>
/// <remarks>
/// <para>
/// Build the unified cache of converters from the static and instance maps
/// </para>
/// </remarks>
private string[] BuildCache()
{
string[] converterNamesCache = new string[m_patternConverters.Keys.Count];
m_patternConverters.Keys.CopyTo(converterNamesCache, 0);
// sort array so that longer strings come first
Array.Sort(converterNamesCache, 0, converterNamesCache.Length, StringLengthComparer.Instance);
return converterNamesCache;
}
#region StringLengthComparer
/// <summary>
/// Sort strings by length
/// </summary>
/// <remarks>
/// <para>
/// <see cref="IComparer" /> that orders strings by string length.
/// The longest strings are placed first
/// </para>
/// </remarks>
private sealed class StringLengthComparer : IComparer
{
public static readonly StringLengthComparer Instance = new StringLengthComparer();
private StringLengthComparer()
{
}
#region Implementation of IComparer
public int Compare(object x, object y)
{
string s1 = x as string;
string s2 = y as string;
if (s1 == null && s2 == null)
{
return 0;
}
if (s1 == null)
{
return 1;
}
if (s2 == null)
{
return -1;
}
return s2.Length.CompareTo(s1.Length);
}
#endregion
}
#endregion // StringLengthComparer
/// <summary>
/// Internal method to parse the specified pattern to find specified matches
/// </summary>
/// <param name="pattern">the pattern to parse</param>
/// <param name="matches">the converter names to match in the pattern</param>
/// <remarks>
/// <para>
/// The matches param must be sorted such that longer strings come before shorter ones.
/// </para>
/// </remarks>
private void ParseInternal(string pattern, string[] matches)
{
int offset = 0;
while(offset < pattern.Length)
{
int i = pattern.IndexOf('%', offset);
if (i < 0 || i == pattern.Length - 1)
{
ProcessLiteral(pattern.Substring(offset));
offset = pattern.Length;
}
else
{
if (pattern[i+1] == '%')
{
// Escaped
ProcessLiteral(pattern.Substring(offset, i - offset + 1));
offset = i + 2;
}
else
{
ProcessLiteral(pattern.Substring(offset, i - offset));
offset = i + 1;
FormattingInfo formattingInfo = new FormattingInfo();
// Process formatting options
// Look for the align flag
if (offset < pattern.Length)
{
if (pattern[offset] == '-')
{
// Seen align flag
formattingInfo.LeftAlign = true;
offset++;
}
}
// Look for the minimum length
while (offset < pattern.Length && char.IsDigit(pattern[offset]))
{
// Seen digit
if (formattingInfo.Min < 0)
{
formattingInfo.Min = 0;
}
formattingInfo.Min = (formattingInfo.Min * 10) + int.Parse(pattern[offset].ToString(CultureInfo.InvariantCulture), System.Globalization.NumberFormatInfo.InvariantInfo);
offset++;
}
// Look for the separator between min and max
if (offset < pattern.Length)
{
if (pattern[offset] == '.')
{
// Seen separator
offset++;
}
}
// Look for the maximum length
while (offset < pattern.Length && char.IsDigit(pattern[offset]))
{
// Seen digit
if (formattingInfo.Max == int.MaxValue)
{
formattingInfo.Max = 0;
}
formattingInfo.Max = (formattingInfo.Max * 10) + int.Parse(pattern[offset].ToString(CultureInfo.InvariantCulture), System.Globalization.NumberFormatInfo.InvariantInfo);
offset++;
}
int remainingStringLength = pattern.Length - offset;
// Look for pattern
for(int m=0; m<matches.Length; m++)
{
if (matches[m].Length <= remainingStringLength)
{
if (String.Compare(pattern, offset, matches[m], 0, matches[m].Length, false, System.Globalization.CultureInfo.InvariantCulture) == 0)
{
// Found match
offset = offset + matches[m].Length;
string option = null;
// Look for option
if (offset < pattern.Length)
{
if (pattern[offset] == '{')
{
// Seen option start
offset++;
int optEnd = pattern.IndexOf('}', offset);
if (optEnd < 0)
{
// error
}
else
{
option = pattern.Substring(offset, optEnd - offset);
offset = optEnd + 1;
}
}
}
ProcessConverter(matches[m], option, formattingInfo);
break;
}
}
}
}
}
}
}
/// <summary>
/// Process a parsed literal
/// </summary>
/// <param name="text">the literal text</param>
private void ProcessLiteral(string text)
{
if (text.Length > 0)
{
// Convert into a pattern
ProcessConverter("literal", text, new FormattingInfo());
}
}
/// <summary>
/// Process a parsed converter pattern
/// </summary>
/// <param name="converterName">the name of the converter</param>
/// <param name="option">the optional option for the converter</param>
/// <param name="formattingInfo">the formatting info for the converter</param>
private void ProcessConverter(string converterName, string option, FormattingInfo formattingInfo)
{
LogLog.Debug(declaringType, "Converter ["+converterName+"] Option ["+option+"] Format [min="+formattingInfo.Min+",max="+formattingInfo.Max+",leftAlign="+formattingInfo.LeftAlign+"]");
// Lookup the converter type
ConverterInfo converterInfo = (ConverterInfo)m_patternConverters[converterName];
if (converterInfo == null)
{
LogLog.Error(declaringType, "Unknown converter name ["+converterName+"] in conversion pattern.");
}
else
{
// Create the pattern converter
PatternConverter pc = null;
try
{
pc = (PatternConverter)Activator.CreateInstance(converterInfo.Type);
}
catch(Exception createInstanceEx)
{
LogLog.Error(declaringType, "Failed to create instance of Type [" + converterInfo.Type.FullName + "] using default constructor. Exception: " + createInstanceEx.ToString());
}
// formattingInfo variable is an instance variable, occasionally reset
// and used over and over again
pc.FormattingInfo = formattingInfo;
pc.Option = option;
pc.Properties = converterInfo.Properties;
IOptionHandler optionHandler = pc as IOptionHandler;
if (optionHandler != null)
{
optionHandler.ActivateOptions();
}
AddConverter(pc);
}
}
/// <summary>
/// Resets the internal state of the parser and adds the specified pattern converter
/// to the chain.
/// </summary>
/// <param name="pc">The pattern converter to add.</param>
private void AddConverter(PatternConverter pc)
{
// Add the pattern converter to the list.
if (m_head == null)
{
m_head = m_tail = pc;
}
else
{
// Set the next converter on the tail
// Update the tail reference
// note that a converter may combine the 'next' into itself
// and therefore the tail would not change!
m_tail = m_tail.SetNext(pc);
}
}
#endregion Protected Instance Methods
#region Private Constants
private const char ESCAPE_CHAR = '%';
#endregion Private Constants
#region Private Instance Fields
/// <summary>
/// The first pattern converter in the chain
/// </summary>
private PatternConverter m_head;
/// <summary>
/// the last pattern converter in the chain
/// </summary>
private PatternConverter m_tail;
/// <summary>
/// The pattern
/// </summary>
private string m_pattern;
/// <summary>
/// Internal map of converter identifiers to converter types
/// </summary>
/// <remarks>
/// <para>
/// This map overrides the static s_globalRulesRegistry map.
/// </para>
/// </remarks>
private Hashtable m_patternConverters = new Hashtable();
#endregion Private Instance Fields
#region Private Static Fields
/// <summary>
/// The fully qualified type of the PatternParser class.
/// </summary>
/// <remarks>
/// Used by the internal logger to record the Type of the
/// log message.
/// </remarks>
private readonly static Type declaringType = typeof(PatternParser);
#endregion Private Static Fields
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Sockets
{
// The System.Net.Sockets.TcpClient class provide TCP services at a higher level
// of abstraction than the System.Net.Sockets.Socket class. System.Net.Sockets.TcpClient
// is used to create a Client connection to a remote host.
public class TcpClient : IDisposable
{
private Socket _clientSocket;
private bool _active;
private NetworkStream _dataStream;
// IPv6: Maintain address family for the client.
private AddressFamily _family = AddressFamily.InterNetwork;
// Initializes a new instance of the System.Net.Sockets.TcpClient class.
public TcpClient()
: this(AddressFamily.InterNetwork)
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "TcpClient", null);
}
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "TcpClient", null);
}
}
// Initializes a new instance of the System.Net.Sockets.TcpClient class.
public TcpClient(AddressFamily family)
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "TcpClient", family);
}
// Validate parameter
if (family != AddressFamily.InterNetwork && family != AddressFamily.InterNetworkV6)
{
throw new ArgumentException(SR.Format(SR.net_protocol_invalid_family, "TCP"), "family");
}
_family = family;
initialize();
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "TcpClient", null);
}
}
// Used by TcpListener.Accept().
internal TcpClient(Socket acceptedSocket)
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "TcpClient", acceptedSocket);
}
Client = acceptedSocket;
_active = true;
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "TcpClient", null);
}
}
// Used by the class to provide the underlying network socket.
public Socket Client
{
get
{
return _clientSocket;
}
set
{
_clientSocket = value;
}
}
// Used by the class to indicate that a connection has been made.
protected bool Active
{
get
{
return _active;
}
set
{
_active = value;
}
}
public int Available { get { return _clientSocket.Available; } }
public bool Connected { get { return _clientSocket.Connected; } }
public bool ExclusiveAddressUse
{
get
{
return _clientSocket.ExclusiveAddressUse;
}
set
{
_clientSocket.ExclusiveAddressUse = value;
}
}
internal IAsyncResult BeginConnect(string host, int port, AsyncCallback requestCallback, object state)
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "BeginConnect", host);
}
IAsyncResult result = Client.BeginConnect(host, port, requestCallback, state);
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "BeginConnect", null);
}
return result;
}
internal IAsyncResult BeginConnect(IPAddress address, int port, AsyncCallback requestCallback, object state)
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "BeginConnect", address);
}
IAsyncResult result = Client.BeginConnect(address, port, requestCallback, state);
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "BeginConnect", null);
}
return result;
}
internal IAsyncResult BeginConnect(IPAddress[] addresses, int port, AsyncCallback requestCallback, object state)
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "BeginConnect", addresses);
}
IAsyncResult result = Client.BeginConnect(addresses, port, requestCallback, state);
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "BeginConnect", null);
}
return result;
}
internal void EndConnect(IAsyncResult asyncResult)
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "EndConnect", asyncResult);
}
Client.EndConnect(asyncResult);
_active = true;
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "EndConnect", null);
}
}
public Task ConnectAsync(IPAddress address, int port)
{
return Task.Factory.FromAsync(
(targetAddess, targetPort, callback, state) => ((TcpClient)state).BeginConnect(targetAddess, targetPort, callback, state),
asyncResult => ((TcpClient)asyncResult.AsyncState).EndConnect(asyncResult),
address,
port,
state: this);
}
public Task ConnectAsync(string host, int port)
{
return Task.Factory.FromAsync(
(targetHost, targetPort, callback, state) => ((TcpClient)state).BeginConnect(targetHost, targetPort, callback, state),
asyncResult => ((TcpClient)asyncResult.AsyncState).EndConnect(asyncResult),
host,
port,
state: this);
}
public Task ConnectAsync(IPAddress[] addresses, int port)
{
return Task.Factory.FromAsync(
(targetAddresses, targetPort, callback, state) => ((TcpClient)state).BeginConnect(targetAddresses, targetPort, callback, state),
asyncResult => ((TcpClient)asyncResult.AsyncState).EndConnect(asyncResult),
addresses,
port,
state: this);
}
// Returns the stream used to read and write data to the remote host.
public NetworkStream GetStream()
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "GetStream", "");
}
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (!Client.Connected)
{
throw new InvalidOperationException(SR.net_notconnected);
}
if (_dataStream == null)
{
_dataStream = new NetworkStream(Client, true);
}
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "GetStream", _dataStream);
}
return _dataStream;
}
private bool _cleanedUp = false;
// Disposes the Tcp connection.
protected virtual void Dispose(bool disposing)
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "Dispose", "");
}
if (_cleanedUp)
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "Dispose", "");
}
return;
}
if (disposing)
{
IDisposable dataStream = _dataStream;
if (dataStream != null)
{
dataStream.Dispose();
}
else
{
// If the NetworkStream wasn't created, the Socket might
// still be there and needs to be closed. In the case in which
// we are bound to a local IPEndPoint this will remove the
// binding and free up the IPEndPoint for later uses.
Socket chkClientSocket = Client;
if (chkClientSocket != null)
{
try
{
chkClientSocket.InternalShutdown(SocketShutdown.Both);
}
finally
{
chkClientSocket.Dispose();
Client = null;
}
}
}
GC.SuppressFinalize(this);
}
_cleanedUp = true;
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "Dispose", "");
}
}
public void Dispose()
{
Dispose(true);
}
~TcpClient()
{
#if DEBUG
GlobalLog.SetThreadSource(ThreadKinds.Finalization);
using (GlobalLog.SetThreadKind(ThreadKinds.System | ThreadKinds.Async))
{
#endif
Dispose(false);
#if DEBUG
}
#endif
}
// Gets or sets the size of the receive buffer in bytes.
public int ReceiveBufferSize
{
get
{
return numericOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer);
}
set
{
Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, value);
}
}
// Gets or sets the size of the send buffer in bytes.
public int SendBufferSize
{
get
{
return numericOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer);
}
set
{
Client.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.SendBuffer, value);
}
}
// Gets or sets the receive time out value of the connection in milliseconds.
public int ReceiveTimeout
{
get
{
return numericOption(SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout);
}
set
{
Client.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout, value);
}
}
// Gets or sets the send time out value of the connection in milliseconds.
public int SendTimeout
{
get
{
return numericOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout);
}
set
{
Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, value);
}
}
// Gets or sets the value of the connection's linger option.
public LingerOption LingerState
{
get
{
return (LingerOption)Client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger);
}
set
{
Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, value);
}
}
// Enables or disables delay when send or receive buffers are full.
public bool NoDelay
{
get
{
return numericOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay) != 0 ? true : false;
}
set
{
Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, value ? 1 : 0);
}
}
private void initialize()
{
// IPv6: Use the address family from the constructor (or Connect method).
Client = new Socket(_family, SocketType.Stream, ProtocolType.Tcp);
_active = false;
}
private int numericOption(SocketOptionLevel optionLevel, SocketOptionName optionName)
{
return (int)Client.GetSocketOption(optionLevel, optionName);
}
}
}
| |
// ****************************************************************
// Copyright 2002-2003, Charlie Poole
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org
// ****************************************************************
namespace NUnit.UiKit.Tests
{
using System;
using System.Reflection;
using System.Windows.Forms;
using NUnit.Framework;
using NUnit.Core;
using NUnit.Util;
using NUnit.Tests.Assemblies;
/// <summary>
/// Summary description for TestSuiteFixture.
/// </summary>
///
public class TestSuiteTreeViewFixture
{
protected string testsDll = MockAssembly.AssemblyPath;
protected Test suite;
protected TestSuiteTreeView treeView;
[SetUp]
public void SetUp()
{
TestSuiteBuilder builder = new TestSuiteBuilder();
suite = builder.Build( new TestPackage( testsDll ) );
treeView = new TestSuiteTreeView();
treeView.Load(new TestNode(suite));
}
}
[TestFixture]
public class TestSuiteTreeViewTests : TestSuiteTreeViewFixture
{
private bool AllExpanded( TreeNode node)
{
if ( node.Nodes.Count == 0 )
return true;
if ( !node.IsExpanded )
return false;
return AllExpanded( node.Nodes );
}
private bool AllExpanded( TreeNodeCollection nodes )
{
foreach( TestSuiteTreeNode node in nodes )
if ( !AllExpanded( node ) )
return false;
return true;
}
[Test]
public void BuildTreeView()
{
Assert.IsNotNull( treeView.Nodes[0] );
Assert.AreEqual( MockAssembly.Nodes, treeView.GetNodeCount( true ) );
Assert.AreEqual( testsDll, treeView.Nodes[0].Text );
Assert.AreEqual( "NUnit", treeView.Nodes[0].Nodes[0].Text );
Assert.AreEqual( "Tests", treeView.Nodes[0].Nodes[0].Nodes[0].Text );
}
[Test]
public void BuildFromResult()
{
TestResult result = suite.Run(new NullListener(), TestFilter.Empty);
treeView.Load( result );
Assert.AreEqual( MockAssembly.Nodes - MockAssembly.Explicit - MockAssembly.ExplicitFixtures,
treeView.GetNodeCount( true ) );
TestSuiteTreeNode node = treeView.Nodes[0] as TestSuiteTreeNode;
Assert.AreEqual( testsDll, node.Text );
Assert.IsNotNull( node.Result, "No Result on top-level Node" );
node = node.Nodes[0].Nodes[0] as TestSuiteTreeNode;
Assert.AreEqual( "Tests", node.Text );
Assert.IsNotNull( node.Result, "No Result on TestSuite" );
foreach( TestSuiteTreeNode child in node.Nodes )
{
if ( child.Text == "Assemblies" )
{
node = child.Nodes[0] as TestSuiteTreeNode;
Assert.AreEqual( "MockTestFixture", node.Text );
Assert.IsNotNull( node.Result, "No Result on TestFixture" );
Assert.AreEqual( true, node.Result.Executed, "MockTestFixture: Executed" );
TestSuiteTreeNode test1 = node.Nodes[2] as TestSuiteTreeNode;
Assert.AreEqual( "MockTest1", test1.Text );
Assert.IsNotNull( test1.Result, "No Result on TestCase" );
Assert.AreEqual( true, test1.Result.Executed, "MockTest1: Executed" );
Assert.AreEqual( false, test1.Result.IsFailure, "MockTest1: IsFailure");
Assert.AreEqual( TestSuiteTreeNode.SuccessIndex, test1.ImageIndex );
TestSuiteTreeNode test4 = node.Nodes[5] as TestSuiteTreeNode;
Assert.AreEqual( false, test4.Result.Executed, "MockTest4: Executed" );
Assert.AreEqual( TestSuiteTreeNode.IgnoredIndex, test4.ImageIndex );
return;
}
}
Assert.Fail( "Cannot locate NUnit.Tests.Assemblies node" );
}
/// <summary>
/// Return the MockTestFixture node from a tree built
/// from the mock-assembly dll.
/// </summary>
private TestSuiteTreeNode FixtureNode( TestSuiteTreeView treeView )
{
return (TestSuiteTreeNode)treeView.Nodes[0].Nodes[0].Nodes[0].Nodes[0].Nodes[0];
}
/// <summary>
/// The tree view CollapseAll method doesn't seem to work in
/// this test environment. This replaces it.
/// </summary>
private void CollapseAll( TreeNode node )
{
node.Collapse();
CollapseAll( node.Nodes );
}
private void CollapseAll( TreeNodeCollection nodes )
{
foreach( TreeNode node in nodes )
CollapseAll( node );
}
[Test]
public void ClearTree()
{
//treeView.Load( new TestNode( suite ) );
treeView.Clear();
Assert.AreEqual( 0, treeView.Nodes.Count );
}
[Test]
public void SetTestResult()
{
TestSuite fixture = (TestSuite)findTest( "MockTestFixture", suite );
TestResult result = new TestResult( new TestInfo( fixture ) );
treeView.SetTestResult( result );
TestSuiteTreeNode fixtureNode = FixtureNode( treeView );
Assert.IsNotNull(fixtureNode.Result, "Result not set" );
Assert.AreEqual( fixture.TestName.Name, fixtureNode.Result.Name );
Assert.AreEqual( fixtureNode.Test.TestName.FullName, fixtureNode.Result.Test.TestName.FullName );
}
private Test findTest(string name, Test test)
{
Test result = null;
if (test.TestName.Name == name)
result = test;
else if (test.Tests != null)
{
foreach(Test t in test.Tests)
{
result = findTest(name, t);
if (result != null)
break;
}
}
return result;
}
[Test]
public void ProcessChecks()
{
Assert.AreEqual(0, treeView.CheckedTests.Length);
Assert.IsFalse(Checked(treeView.Nodes));
treeView.Nodes[0].Checked = true;
treeView.Nodes[0].Nodes[0].Checked = true;
Assert.AreEqual(2, treeView.CheckedTests.Length);
Assert.AreEqual(1, treeView.SelectedTests.Length);
Assert.IsTrue(Checked(treeView.Nodes));
treeView.ClearCheckedNodes();
Assert.AreEqual(0, treeView.CheckedTests.Length);
Assert.IsFalse(Checked(treeView.Nodes));
}
// TODO: Unused Tests
// [Test]
// public void CheckCategory()
// {
// treeView.Load(suite);
//
// Assert.AreEqual(0, treeView.CheckedTests.Length);
//
// CheckCategoryVisitor visitor = new CheckCategoryVisitor("MockCategory");
// treeView.Accept(visitor);
//
// Assert.AreEqual(2, treeView.CheckedTests.Length);
// }
//
// [Test]
// public void UnCheckCategory()
// {
// treeView.Load(suite);
//
// Assert.AreEqual(0, treeView.CheckedTests.Length);
//
// CheckCategoryVisitor visitor = new CheckCategoryVisitor("MockCategory");
// treeView.Accept(visitor);
//
// Assert.AreEqual(2, treeView.CheckedTests.Length);
//
// UnCheckCategoryVisitor unvisitor = new UnCheckCategoryVisitor("MockCategory");
// treeView.Accept(unvisitor);
//
// Assert.AreEqual(0, treeView.CheckedTests.Length);
// }
private bool Checked(TreeNodeCollection nodes)
{
bool result = false;
foreach (TreeNode node in nodes)
{
result |= node.Checked;
if (node.Nodes != null)
result |= Checked(node.Nodes);
}
return result;
}
}
[TestFixture]
public class TestSuiteTreeViewReloadTests : TestSuiteTreeViewFixture
{
private TestSuite nunitNamespaceSuite;
private TestSuite testsNamespaceSuite;
private TestSuite assembliesNamespaceSuite;
private TestSuite mockTestFixture;
private int originalTestCount;
[SetUp]
public void Initialize()
{
nunitNamespaceSuite = suite.Tests[0] as TestSuite;
testsNamespaceSuite = nunitNamespaceSuite.Tests[0] as TestSuite;
assembliesNamespaceSuite = testsNamespaceSuite.Tests[0] as TestSuite;
mockTestFixture = assembliesNamespaceSuite.Tests[0] as TestSuite;
originalTestCount = suite.TestCount;
}
[Test]
public void VerifyCheckTreeWorks()
{
CheckTreeAgainstSuite(suite, "initially");
}
[Test]
public void CanReloadWithoutChange()
{
treeView.Reload(new TestNode(suite));
CheckTreeAgainstSuite(suite, "unchanged");
}
[Test]
public void CanReloadAfterDeletingOneTestCase()
{
mockTestFixture.Tests.RemoveAt(0);
Assert.AreEqual(originalTestCount - 1, suite.TestCount);
ReassignTestIDsAndReload(suite);
CheckTreeAgainstSuite(suite, "after removing test case");
}
[Test]
public void CanReloadAfterDeletingThreeTestCases()
{
mockTestFixture.Tests.RemoveAt(4);
mockTestFixture.Tests.RemoveAt(2);
mockTestFixture.Tests.RemoveAt(0);
Assert.AreEqual(originalTestCount - 3, suite.TestCount);
ReassignTestIDsAndReload(suite);
CheckTreeAgainstSuite(suite, "after removing test case");
}
[Test]
public void CanReloadAfterDeletingBranch()
{
int removeCount = ((Test)testsNamespaceSuite.Tests[0]).TestCount;
testsNamespaceSuite.Tests.RemoveAt(0);
Assert.AreEqual(originalTestCount-removeCount, suite.TestCount);
ReassignTestIDsAndReload(suite);
CheckTreeAgainstSuite(suite, "after removing branch");
}
[Test]
public void CanReloadAfterInsertingTestCase()
{
mockTestFixture.Tests.Add(new NUnitTestMethod((MethodInfo)MethodInfo.GetCurrentMethod()));
Assert.AreEqual(originalTestCount + 1, suite.TestCount);
ReassignTestIDsAndReload(suite);
CheckTreeAgainstSuite(suite, "after inserting test case");
}
[Test]
public void CanReloadAfterInsertingTestFixture()
{
Test fixture = new TestSuite(this.GetType());
testsNamespaceSuite.Tests.Add(fixture);
Assert.AreEqual(originalTestCount + fixture.TestCount, suite.TestCount);
ReassignTestIDsAndReload(suite);
CheckTreeAgainstSuite(suite, "after inserting test case");
}
[Test]
public void ReloadTreeWithWrongTest()
{
TestSuite suite2 = new TestSuite("WrongSuite");
treeView.Reload(new TestNode(suite2));
}
[Test]
public void CanReloadAfterChangingOrder()
{
// Just swap the first and second test
object first = mockTestFixture.Tests[0];
mockTestFixture.Tests.RemoveAt(0);
mockTestFixture.Tests.Insert(1, first);
Assert.AreEqual(originalTestCount, suite.TestCount);
ReassignTestIDsAndReload(suite);
CheckTreeAgainstSuite(suite, "after reordering");
}
[Test]
public void CanReloadAfterMultipleChanges()
{
// Add a fixture
Test fixture = new TestSuite(this.GetType());
testsNamespaceSuite.Tests.Add(fixture);
// Remove two tests
mockTestFixture.Tests.RemoveAt(4);
mockTestFixture.Tests.RemoveAt(2);
// Interchange two tests
object first = mockTestFixture.Tests[0];
mockTestFixture.Tests.RemoveAt(0);
mockTestFixture.Tests.Insert(2, first);
// Add an new test case
mockTestFixture.Tests.Add(new NUnitTestMethod((MethodInfo)MethodInfo.GetCurrentMethod()));
int expectedCount = fixture.TestCount - 1;
Assert.AreEqual(originalTestCount + expectedCount, suite.TestCount);
ReassignTestIDsAndReload(suite);
CheckTreeAgainstSuite(suite, "after multiple changes");
}
[Test]
public void CanReloadAfterTurningOffAutoNamespaces()
{
TestSuiteBuilder builder = new TestSuiteBuilder();
TestPackage package = new TestPackage(testsDll);
package.Settings["AutoNamespaceSuites"] = false;
TestSuite suite2 = builder.Build(package);
Assert.AreEqual(originalTestCount, suite2.TestCount);
Assert.AreEqual(MockAssembly.Classes, suite2.Tests.Count);
ReassignTestIDsAndReload(suite2);
CheckTreeAgainstSuite(suite2, "after turning automatic namespaces OFF");
// TODO: This currently doesn't work
//ReassignTestIDsAndReload(suite);
//CheckTreeAgainstSuite(suite, "after turning automatic namespaces ON");
}
private void CheckTreeAgainstSuite(Test suite, string msg)
{
CheckThatTreeMatchesTests(treeView, suite, "Tree out of order " + msg);
CheckTreeMap(treeView, suite, "Map incorrect " + msg);
}
private void CheckThatTreeMatchesTests(TestSuiteTreeView treeView, Test suite, string msg)
{
CheckThatNodeMatchesTest((TestSuiteTreeNode)treeView.Nodes[0], suite, msg);
}
private void CheckThatNodeMatchesTest(TestSuiteTreeNode node, Test test, string msg)
{
Assert.AreEqual(test.TestName, node.Test.TestName, "{0}: Names do not match for {1}", msg, test.TestName.FullName);
if (test.IsSuite)
{
//if ( test.TestName.FullName == "NUnit.Tests.Assemblies.MockTestFixture" )
// foreach( TestSuiteTreeNode n in node.Nodes )
// Console.WriteLine( n.Test.TestName );
Assert.AreEqual(test.Tests.Count, node.Nodes.Count, "{0}: Incorrect count for {1}", msg, test.TestName.FullName);
for (int index = 0; index < test.Tests.Count; index++)
{
CheckThatNodeMatchesTest((TestSuiteTreeNode)node.Nodes[index], (Test)test.Tests[index], msg);
}
}
}
private void CheckTreeMap(TestSuiteTreeView treeView, Test test, string msg)
{
TestSuiteTreeNode node = treeView[test.TestName.UniqueName];
Assert.IsNotNull(node, "{0}: {1} not in map", msg, test.TestName.UniqueName);
Assert.AreEqual(test.TestName, treeView[test.TestName.UniqueName].Test.TestName, msg);
if (test.IsSuite)
foreach (Test child in test.Tests)
CheckTreeMap(treeView, child, msg);
}
// Reload re-assigns the test IDs, so we simulate it
private void ReassignTestIDs(Test test)
{
test.TestName.TestID = new TestID();
if (test.IsSuite)
foreach (Test child in test.Tests)
ReassignTestIDs(child);
}
private void ReassignTestIDsAndReload(Test test)
{
ReassignTestIDs(test);
treeView.Reload(new TestNode(test));
}
}
}
| |
#region License
// Distributed under the MIT License
// ============================================================
// Copyright (c) 2019 Hotcakes Commerce, 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.
#endregion
using System;
using System.Globalization;
using System.Web.UI.WebControls;
using Hotcakes.Commerce.Shipping;
using Hotcakes.Commerce.Utilities;
using Hotcakes.Modules.Core.Admin.AppCode;
using Hotcakes.Shipping;
using Hotcakes.Shipping.Services;
namespace Hotcakes.Modules.Core.Modules.Shipping.Rate_Table_Per_Item
{
partial class Edit : HccShippingPart
{
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
LocalizeView();
AddHighlightColors(lstHighlights);
LoadZones();
LoadData();
LoadLevels();
}
protected void btnCancel_Click(object sender, EventArgs e)
{
NotifyFinishedEditing("Canceled");
}
protected void btnSave_Click(object sender, EventArgs e)
{
SaveData();
NotifyFinishedEditing(NameField.Text.Trim());
}
private void LoadZones()
{
lstZones.DataSource = HccApp.OrderServices.ShippingZones.FindForStore(HccApp.CurrentStore.Id);
lstZones.DataTextField = "Name";
lstZones.DataValueField = "id";
lstZones.DataBind();
}
private void LoadData()
{
NameField.Text = ShippingMethod.Name;
if (NameField.Text == string.Empty)
{
NameField.Text = Localization.GetString("RateTablePerItem");
}
AdjustmentDropDownList.SelectedValue = ((int) ShippingMethod.AdjustmentType).ToString();
if (ShippingMethod.AdjustmentType == ShippingMethodAdjustmentType.Amount)
{
AdjustmentTextBox.Text = string.Format("{0:c}", ShippingMethod.Adjustment);
}
else
{
AdjustmentTextBox.Text = string.Format("{0:f}", ShippingMethod.Adjustment);
}
// ZONES
if (lstZones.Items.FindByValue(ShippingMethod.ZoneId.ToString()) != null)
{
lstZones.ClearSelection();
lstZones.Items.FindByValue(ShippingMethod.ZoneId.ToString()).Selected = true;
}
// Select Hightlights
var highlight = ShippingMethod.Settings.GetSettingOrEmpty("highlight");
if (lstHighlights.Items.FindByText(highlight) != null)
{
lstHighlights.ClearSelection();
lstHighlights.Items.FindByText(highlight).Selected = true;
}
}
private void LoadLevels()
{
var settings = new RateTableSettings();
settings.Merge(ShippingMethod.Settings);
var levels = settings.GetLevels();
gvRates.DataSource = levels;
gvRates.DataBind();
}
private void SaveData()
{
ShippingMethod.Name = NameField.Text.Trim();
ShippingMethod.AdjustmentType =
(ShippingMethodAdjustmentType) int.Parse(AdjustmentDropDownList.SelectedValue);
ShippingMethod.Adjustment = decimal.Parse(AdjustmentTextBox.Text, NumberStyles.Currency);
if (ShippingMethod.AdjustmentType == ShippingMethodAdjustmentType.Amount)
{
ShippingMethod.Adjustment = Money.RoundCurrency(ShippingMethod.Adjustment);
}
ShippingMethod.ZoneId = long.Parse(lstZones.SelectedItem.Value);
ShippingMethod.Settings["highlight"] = lstHighlights.SelectedValue;
}
protected void btnNew_Click(object sender, EventArgs e)
{
var r = new RateTableLevel
{
Level = decimal.Parse(NewLevelField.Text),
Rate = decimal.Parse(NewAmountField.Text)
};
var settings = new RateTableSettings();
settings.Merge(ShippingMethod.Settings);
settings.AddLevel(r);
ShippingMethod.Settings = settings;
HccApp.OrderServices.ShippingMethods.Update(ShippingMethod);
LoadLevels();
}
private void RemoveLevel(string level, string rate)
{
var settings = new RateTableSettings();
settings.Merge(ShippingMethod.Settings);
var r = new RateTableLevel
{
Level = decimal.Parse(level),
Rate = Money.RoundCurrency(decimal.Parse(rate, NumberStyles.Currency))
};
settings.RemoveLevel(r);
ShippingMethod.Settings = settings;
HccApp.OrderServices.ShippingMethods.Update(ShippingMethod);
LoadLevels();
}
protected void gvRates_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
var lblLevel = (Label) gvRates.Rows[e.RowIndex].FindControl("lblLevel");
var lblRate = (Label) gvRates.Rows[e.RowIndex].FindControl("lblAmount");
if (lblLevel != null)
{
if (lblRate != null)
{
RemoveLevel(lblLevel.Text, lblRate.Text);
}
}
}
protected void cvAdjustmentTextBox_ServerValidate(object source, ServerValidateEventArgs args)
{
var val = 0m;
if (decimal.TryParse(AdjustmentTextBox.Text, NumberStyles.Currency, CultureInfo.CurrentCulture, out val))
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
private void LocalizeView()
{
rfvAdjustmentTextBox.ErrorMessage = Localization.GetString("rfvAdjustmentTextBox.ErrorMessage");
cvAdjustmentTextBox.ErrorMessage = Localization.GetString("cvAdjustmentTextBox.ErrorMessage");
if (AdjustmentDropDownList.Items.Count == 0)
{
AdjustmentDropDownList.Items.Add(new ListItem(Localization.GetString("Amount"), "1"));
AdjustmentDropDownList.Items.Add(new ListItem(Localization.GetString("Percentage"), "2"));
AdjustmentDropDownList.Items[0].Selected = true;
}
rfvNewLevelField.ErrorMessage = Localization.GetString("rfvNewLevelField.ErrorMessage");
cvNewLevelField.ErrorMessage = Localization.GetString("cvNewLevelField.ErrorMessage");
rfvNewAmountField.ErrorMessage = Localization.GetString("rfvNewAmountField.ErrorMessage");
cvNewAmountField.ErrorMessage = Localization.GetString("cvNewAmountField.ErrorMessage");
}
protected void gvRates_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].Text = Localization.GetString("TotalItemCountAtLeast");
e.Row.Cells[1].Text = Localization.GetString("ChargeAmountPerItem");
}
rfvNewLevelField.ErrorMessage = Localization.GetString("rfvNewLevelField.ErrorMessage");
cvNewLevelField.ErrorMessage = Localization.GetString("cvNewLevelField.ErrorMessage");
rfvNewAmountField.ErrorMessage = Localization.GetString("rfvNewAmountField.ErrorMessage");
cvNewAmountField.ErrorMessage = Localization.GetString("cvNewAmountField.ErrorMessage");
}
protected void btnDelete_OnPreRender(object sender, EventArgs e)
{
var link = (LinkButton) sender;
link.Text = Localization.GetString("Delete");
}
}
}
| |
using System;
namespace ClosedXML.Excel
{
using System.Linq;
internal class XLTableRange : XLRange, IXLTableRange
{
private readonly XLTable _table;
private readonly XLRange _range;
public XLTableRange(XLRange range, XLTable table):base(range.RangeParameters)
{
_table = table;
_range = range;
}
IXLTableRow IXLTableRange.FirstRow(Func<IXLTableRow, Boolean> predicate)
{
return FirstRow(predicate);
}
public XLTableRow FirstRow(Func<IXLTableRow, Boolean> predicate = null)
{
if (predicate == null)
return new XLTableRow(this, (_range.FirstRow()));
Int32 rowCount = _range.RowCount();
for (Int32 ro = 1; ro <= rowCount; ro++)
{
var row = new XLTableRow(this, (_range.Row(ro)));
if (predicate(row)) return row;
row.Dispose();
}
return null;
}
IXLTableRow IXLTableRange.FirstRowUsed(Func<IXLTableRow, Boolean> predicate)
{
return FirstRowUsed(false, predicate);
}
public XLTableRow FirstRowUsed(Func<IXLTableRow, Boolean> predicate = null)
{
return FirstRowUsed(false, predicate);
}
IXLTableRow IXLTableRange.FirstRowUsed(Boolean includeFormats, Func<IXLTableRow, Boolean> predicate)
{
return FirstRowUsed(includeFormats, predicate);
}
public XLTableRow FirstRowUsed(Boolean includeFormats, Func<IXLTableRow, Boolean> predicate = null)
{
if (predicate == null)
return new XLTableRow(this, (_range.FirstRowUsed(includeFormats)));
Int32 rowCount = _range.RowCount();
for (Int32 ro = 1; ro <= rowCount; ro++)
{
var row = new XLTableRow(this, (_range.Row(ro)));
if (!row.IsEmpty(includeFormats) && predicate(row))
return row;
row.Dispose();
}
return null;
}
IXLTableRow IXLTableRange.LastRow(Func<IXLTableRow, Boolean> predicate)
{
return LastRow(predicate);
}
public XLTableRow LastRow(Func<IXLTableRow, Boolean> predicate = null)
{
if (predicate == null)
return new XLTableRow(this, (_range.LastRow()));
Int32 rowCount = _range.RowCount();
for (Int32 ro = rowCount; ro >= 1; ro--)
{
var row = new XLTableRow(this, (_range.Row(ro)));
if (predicate(row)) return row;
row.Dispose();
}
return null;
}
IXLTableRow IXLTableRange.LastRowUsed(Func<IXLTableRow, Boolean> predicate)
{
return LastRowUsed(false, predicate);
}
public XLTableRow LastRowUsed(Func<IXLTableRow, Boolean> predicate = null)
{
return LastRowUsed(false, predicate);
}
IXLTableRow IXLTableRange.LastRowUsed(Boolean includeFormats, Func<IXLTableRow, Boolean> predicate)
{
return LastRowUsed(includeFormats, predicate);
}
public XLTableRow LastRowUsed(Boolean includeFormats, Func<IXLTableRow, Boolean> predicate = null)
{
if (predicate == null)
return new XLTableRow(this, (_range.LastRowUsed(includeFormats)));
Int32 rowCount = _range.RowCount();
for (Int32 ro = rowCount; ro >= 1; ro--)
{
var row = new XLTableRow(this, (_range.Row(ro)));
if (!row.IsEmpty(includeFormats) && predicate(row))
return row;
row.Dispose();
}
return null;
}
IXLTableRow IXLTableRange.Row(int row)
{
return Row(row);
}
public new XLTableRow Row(int row)
{
if (row <= 0 || row > XLHelper.MaxRowNumber)
{
throw new IndexOutOfRangeException(String.Format("Row number must be between 1 and {0}",
XLHelper.MaxRowNumber));
}
return new XLTableRow(this, base.Row(row));
}
public IXLTableRows Rows(Func<IXLTableRow, Boolean> predicate = null)
{
var retVal = new XLTableRows(Worksheet.Style);
Int32 rowCount = _range.RowCount();
for (int r = 1; r <= rowCount; r++)
{
var row = Row(r);
if (predicate == null || predicate(row))
retVal.Add(row);
else
row.Dispose();
}
return retVal;
}
public new IXLTableRows Rows(int firstRow, int lastRow)
{
var retVal = new XLTableRows(Worksheet.Style);
for (int ro = firstRow; ro <= lastRow; ro++)
retVal.Add(Row(ro));
return retVal;
}
public new IXLTableRows Rows(string rows)
{
var retVal = new XLTableRows(Worksheet.Style);
var rowPairs = rows.Split(',');
foreach (string tPair in rowPairs.Select(pair => pair.Trim()))
{
String firstRow;
String lastRow;
if (tPair.Contains(':') || tPair.Contains('-'))
{
var rowRange = XLHelper.SplitRange(tPair);
firstRow = rowRange[0];
lastRow = rowRange[1];
}
else
{
firstRow = tPair;
lastRow = tPair;
}
foreach (IXLTableRow row in Rows(Int32.Parse(firstRow), Int32.Parse(lastRow)))
retVal.Add(row);
}
return retVal;
}
IXLTableRows IXLTableRange.RowsUsed(Boolean includeFormats, Func<IXLTableRow, Boolean> predicate)
{
return RowsUsed(includeFormats, predicate);
}
public IXLTableRows RowsUsed(Boolean includeFormats, Func<IXLTableRow, Boolean> predicate = null)
{
var rows = new XLTableRows(Worksheet.Style);
Int32 rowCount = RowCount();
for (Int32 ro = 1; ro <= rowCount; ro++)
{
var row = Row(ro);
if (!row.IsEmpty(includeFormats) && (predicate == null || predicate(row)))
rows.Add(row);
else
row.Dispose();
}
return rows;
}
IXLTableRows IXLTableRange.RowsUsed(Func<IXLTableRow, Boolean> predicate)
{
return RowsUsed(predicate);
}
public IXLTableRows RowsUsed(Func<IXLTableRow, Boolean> predicate = null)
{
return RowsUsed(false, predicate);
}
IXLTable IXLTableRange.Table { get { return _table; } }
public XLTable Table { get { return _table; } }
public new IXLTableRows InsertRowsAbove(int numberOfRows)
{
return XLHelper.InsertRowsWithoutEvents(base.InsertRowsAbove, this, numberOfRows, !Table.ShowTotalsRow );
}
public new IXLTableRows InsertRowsBelow(int numberOfRows)
{
return XLHelper.InsertRowsWithoutEvents(base.InsertRowsBelow, this, numberOfRows, !Table.ShowTotalsRow);
}
public new IXLRangeColumn Column(String column)
{
if (XLHelper.IsValidColumn(column))
{
Int32 coNum = XLHelper.GetColumnNumberFromLetter(column);
return coNum > ColumnCount() ? Column(_table.GetFieldIndex(column) + 1) : Column(coNum);
}
return Column(_table.GetFieldIndex(column) + 1);
}
}
}
| |
namespace FakeItEasy.Configuration
{
using System;
using System.Linq;
using System.Linq.Expressions;
using FakeItEasy.Core;
using FakeItEasy.Expressions;
internal partial class PropertySetterConfiguration<TValue>
: IPropertySetterAnyValueConfiguration<TValue>
{
private readonly ParsedCallExpression parsedSetterExpression;
private readonly Func<ParsedCallExpression, IVoidArgumentValidationConfiguration> voidArgumentValidationConfigurationFactory;
public PropertySetterConfiguration(
ParsedCallExpression parsedCallExpression,
Func<ParsedCallExpression, IVoidArgumentValidationConfiguration> voidArgumentValidationConfigurationFactory)
{
this.parsedSetterExpression = parsedCallExpression;
this.voidArgumentValidationConfigurationFactory = voidArgumentValidationConfigurationFactory;
}
public IPropertySetterConfiguration To(TValue value) =>
this.To(() => value);
public IPropertySetterConfiguration To(Expression<Func<TValue>> valueConstraint)
{
Guard.AgainstNull(valueConstraint);
var newSetterExpression = this.CreateSetterExpressionWithNewValue(valueConstraint);
var voidArgumentValidationConfiguration = this.CreateArgumentValidationConfiguration(newSetterExpression);
return AsPropertySetterConfiguration(voidArgumentValidationConfiguration);
}
public IAfterCallConfiguredConfiguration<IPropertySetterConfiguration> Throws(Func<IFakeObjectCall, Exception> exceptionFactory) =>
AsPropertySetterConfiguration(this.CreateArgumentValidationConfiguration(this.parsedSetterExpression))
.Throws(exceptionFactory);
public IAfterCallConfiguredConfiguration<IPropertySetterConfiguration> Throws<T>() where T : Exception, new() =>
this.Throws<IPropertySetterConfiguration, T>();
public IPropertySetterAfterCallbackConfiguredConfiguration Invokes(Action<IFakeObjectCall> action)
{
var voidConfiguration = this.CreateArgumentValidationConfiguration(this.parsedSetterExpression)
.Invokes(action);
return AsPropertySetterAfterCallbackConfiguredConfiguration(voidConfiguration);
}
public IAfterCallConfiguredConfiguration<IPropertySetterConfiguration> CallsBaseMethod() =>
AsPropertySetterConfiguration(this.CreateArgumentValidationConfiguration(this.parsedSetterExpression))
.CallsBaseMethod();
public IAfterCallConfiguredConfiguration<IPropertySetterConfiguration> CallsWrappedMethod() =>
AsPropertySetterConfiguration(this.CreateArgumentValidationConfiguration(this.parsedSetterExpression))
.CallsWrappedMethod();
public UnorderedCallAssertion MustHaveHappened(int numberOfTimes, Times timesOption)
{
Guard.AgainstNull(timesOption);
return this.CreateArgumentValidationConfiguration(this.parsedSetterExpression).MustHaveHappened(numberOfTimes, timesOption);
}
public UnorderedCallAssertion MustHaveHappenedANumberOfTimesMatching(Expression<Func<int, bool>> predicate)
{
Guard.AgainstNull(predicate);
return this.CreateArgumentValidationConfiguration(this.parsedSetterExpression).MustHaveHappenedANumberOfTimesMatching(predicate);
}
public IAfterCallConfiguredConfiguration<IPropertySetterConfiguration> DoesNothing() =>
AsPropertySetterConfiguration(this.CreateArgumentValidationConfiguration(this.parsedSetterExpression))
.DoesNothing();
public IPropertySetterConfiguration WhenArgumentsMatch(Func<ArgumentCollection, bool> argumentsPredicate)
{
var voidConfiguration = this.CreateArgumentValidationConfiguration(this.parsedSetterExpression)
.WhenArgumentsMatch(argumentsPredicate);
return AsPropertySetterConfiguration(voidConfiguration);
}
private static IPropertySetterConfiguration AsPropertySetterConfiguration(
IVoidConfiguration voidArgumentValidationConfiguration) =>
new PropertySetterAdapter(voidArgumentValidationConfiguration);
private static IPropertySetterAfterCallbackConfiguredConfiguration AsPropertySetterAfterCallbackConfiguredConfiguration(
IVoidAfterCallbackConfiguredConfiguration voidArgumentValidationConfiguration) =>
new PropertySetterAfterCallbackConfiguredAdapter(voidArgumentValidationConfiguration);
private ParsedCallExpression CreateSetterExpressionWithNewValue(Expression<Func<TValue>> valueExpression)
{
var originalParameterInfos = this.parsedSetterExpression.CalledMethod.GetParameters();
var parsedValueExpression = new ParsedArgumentExpression(
valueExpression.Body,
originalParameterInfos.Last());
var arguments = new ParsedArgumentExpression[originalParameterInfos.Length];
Array.Copy(this.parsedSetterExpression.ArgumentsExpressions, arguments, originalParameterInfos.Length - 1);
arguments[originalParameterInfos.Length - 1] = parsedValueExpression;
return new ParsedCallExpression(
this.parsedSetterExpression.CalledMethod,
this.parsedSetterExpression.CallTarget,
arguments);
}
private IVoidArgumentValidationConfiguration CreateArgumentValidationConfiguration(
ParsedCallExpression parsedSetter) =>
this.voidArgumentValidationConfigurationFactory(parsedSetter);
private partial class PropertySetterAdapter : IPropertySetterConfiguration
{
private IVoidConfiguration voidConfiguration;
public PropertySetterAdapter(IVoidConfiguration voidArgumentValidationConfiguration)
{
this.voidConfiguration = voidArgumentValidationConfiguration;
}
public IAfterCallConfiguredConfiguration<IPropertySetterConfiguration> Throws(Func<IFakeObjectCall, Exception> exceptionFactory) =>
new PropertySetterAfterCallConfiguredAdapter(this.voidConfiguration.Throws(exceptionFactory));
public IAfterCallConfiguredConfiguration<IPropertySetterConfiguration> Throws<T>() where T : Exception, new() =>
this.Throws<IPropertySetterConfiguration, T>();
public IAfterCallConfiguredConfiguration<IPropertySetterConfiguration> CallsBaseMethod() =>
new PropertySetterAfterCallConfiguredAdapter(this.voidConfiguration.CallsBaseMethod());
public IAfterCallConfiguredConfiguration<IPropertySetterConfiguration> CallsWrappedMethod() =>
new PropertySetterAfterCallConfiguredAdapter(this.voidConfiguration.CallsWrappedMethod());
public UnorderedCallAssertion MustHaveHappened(int numberOfTimes, Times timesOption)
{
Guard.AgainstNull(timesOption);
return this.voidConfiguration.MustHaveHappened(numberOfTimes, timesOption);
}
public UnorderedCallAssertion MustHaveHappenedANumberOfTimesMatching(Expression<Func<int, bool>> predicate)
{
Guard.AgainstNull(predicate);
return this.voidConfiguration.MustHaveHappenedANumberOfTimesMatching(predicate);
}
public IAfterCallConfiguredConfiguration<IPropertySetterConfiguration> DoesNothing() =>
new PropertySetterAfterCallConfiguredAdapter(this.voidConfiguration.DoesNothing());
public IPropertySetterAfterCallbackConfiguredConfiguration Invokes(Action<IFakeObjectCall> action) =>
AsPropertySetterAfterCallbackConfiguredConfiguration(this.voidConfiguration.Invokes(action));
}
private partial class PropertySetterAfterCallbackConfiguredAdapter : IPropertySetterAfterCallbackConfiguredConfiguration
{
private IVoidAfterCallbackConfiguredConfiguration voidConfiguration;
public PropertySetterAfterCallbackConfiguredAdapter(IVoidAfterCallbackConfiguredConfiguration voidArgumentValidationConfiguration)
{
this.voidConfiguration = voidArgumentValidationConfiguration;
}
public IAfterCallConfiguredConfiguration<IPropertySetterConfiguration> Throws(Func<IFakeObjectCall, Exception> exceptionFactory) =>
new PropertySetterAfterCallConfiguredAdapter(this.voidConfiguration.Throws(exceptionFactory));
public IAfterCallConfiguredConfiguration<IPropertySetterConfiguration> Throws<T>() where T : Exception, new() =>
this.Throws<IPropertySetterConfiguration, T>();
public IAfterCallConfiguredConfiguration<IPropertySetterConfiguration> CallsBaseMethod() =>
new PropertySetterAfterCallConfiguredAdapter(this.voidConfiguration.CallsBaseMethod());
public IAfterCallConfiguredConfiguration<IPropertySetterConfiguration> CallsWrappedMethod() =>
new PropertySetterAfterCallConfiguredAdapter(this.voidConfiguration.CallsWrappedMethod());
public IAfterCallConfiguredConfiguration<IPropertySetterConfiguration> DoesNothing() =>
new PropertySetterAfterCallConfiguredAdapter(this.voidConfiguration.DoesNothing());
public IPropertySetterAfterCallbackConfiguredConfiguration Invokes(Action<IFakeObjectCall> action)
{
this.voidConfiguration = this.voidConfiguration.Invokes(action);
return this;
}
public IThenConfiguration<IPropertySetterConfiguration> NumberOfTimes(int numberOfTimes) =>
new PropertySetterThenAdapter(this.voidConfiguration.NumberOfTimes(numberOfTimes));
}
private class PropertySetterAfterCallConfiguredAdapter : IAfterCallConfiguredConfiguration<IPropertySetterConfiguration>
{
private readonly IAfterCallConfiguredConfiguration<IVoidConfiguration> voidAfterCallConfiguration;
public PropertySetterAfterCallConfiguredAdapter(IAfterCallConfiguredConfiguration<IVoidConfiguration> voidAfterCallConfiguration)
{
this.voidAfterCallConfiguration = voidAfterCallConfiguration;
}
public IThenConfiguration<IPropertySetterConfiguration> NumberOfTimes(int numberOfTimes) =>
new PropertySetterThenAdapter(this.voidAfterCallConfiguration.NumberOfTimes(numberOfTimes));
}
private class PropertySetterThenAdapter : IThenConfiguration<IPropertySetterConfiguration>
{
private readonly IThenConfiguration<IVoidConfiguration> voidThenConfiguration;
public PropertySetterThenAdapter(IThenConfiguration<IVoidConfiguration> voidThenConfiguration)
{
this.voidThenConfiguration = voidThenConfiguration;
}
public IPropertySetterConfiguration Then => AsPropertySetterConfiguration(this.voidThenConfiguration.Then);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Communications.Clients;
using OpenSim.Region.Framework.Scenes.Serialization;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Services.Interfaces;
//using HyperGrid.Framework;
//using OpenSim.Region.Communications.Hypergrid;
namespace OpenSim.Region.Framework.Scenes.Hypergrid
{
public class HGAssetMapper
{
#region Fields
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// This maps between inventory server urls and inventory server clients
// private Dictionary<string, InventoryClient> m_inventoryServers = new Dictionary<string, InventoryClient>();
private Scene m_scene;
private IHyperAssetService m_hyper;
IHyperAssetService HyperlinkAssets
{
get
{
if (m_hyper == null)
m_hyper = m_scene.RequestModuleInterface<IHyperAssetService>();
return m_hyper;
}
}
#endregion
#region Constructor
public HGAssetMapper(Scene scene)
{
m_scene = scene;
}
#endregion
#region Internal functions
private string UserAssetURL(UUID userID)
{
CachedUserInfo uinfo = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(userID);
if (uinfo != null)
return (uinfo.UserProfile.UserAssetURI == "") ? null : uinfo.UserProfile.UserAssetURI;
return null;
}
// private string UserInventoryURL(UUID userID)
// {
// CachedUserInfo uinfo = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(userID);
// if (uinfo != null)
// return (uinfo.UserProfile.UserInventoryURI == "") ? null : uinfo.UserProfile.UserInventoryURI;
// return null;
// }
public AssetBase FetchAsset(string url, UUID assetID)
{
AssetBase asset = m_scene.AssetService.Get(url + "/" + assetID.ToString());
if (asset != null)
{
m_log.DebugFormat("[HGScene]: Copied asset {0} from {1} to local asset server. ", asset.ID, url);
return asset;
}
return null;
}
public bool PostAsset(string url, AssetBase asset)
{
if (asset != null)
{
// See long comment in AssetCache.AddAsset
if (!asset.Temporary || asset.Local)
{
// We need to copy the asset into a new asset, because
// we need to set its ID to be URL+UUID, so that the
// HGAssetService dispatches it to the remote grid.
// It's not pretty, but the best that can be done while
// not having a global naming infrastructure
AssetBase asset1 = new AssetBase();
Copy(asset, asset1);
try
{
asset1.ID = url + "/" + asset.ID;
}
catch
{
m_log.Warn("[HGScene]: Oops.");
}
m_scene.AssetService.Store(asset1);
m_log.DebugFormat("[HGScene]: Posted copy of asset {0} from local asset server to {1}", asset1.ID, url);
}
return true;
}
else
m_log.Warn("[HGScene]: Tried to post asset to remote server, but asset not in local cache.");
return false;
}
private void Copy(AssetBase from, AssetBase to)
{
to.Data = from.Data;
to.Description = from.Description;
to.FullID = from.FullID;
to.ID = from.ID;
to.Local = from.Local;
to.Name = from.Name;
to.Temporary = from.Temporary;
to.Type = from.Type;
}
// TODO: unused
// private void Dump(Dictionary<UUID, bool> lst)
// {
// m_log.Debug("XXX -------- UUID DUMP ------- XXX");
// foreach (KeyValuePair<UUID, bool> kvp in lst)
// m_log.Debug(" >> " + kvp.Key + " (texture? " + kvp.Value + ")");
// m_log.Debug("XXX -------- UUID DUMP ------- XXX");
// }
#endregion
#region Public interface
public void Get(UUID assetID, UUID ownerID)
{
// Get the item from the remote asset server onto the local AssetCache
// and place an entry in m_assetMap
string userAssetURL = HyperlinkAssets.GetUserAssetServer(ownerID);
if ((userAssetURL != string.Empty) && (userAssetURL != HyperlinkAssets.GetSimAssetServer()))
{
m_log.Debug("[HGScene]: Fetching object " + assetID + " from asset server " + userAssetURL);
AssetBase asset = FetchAsset(userAssetURL, assetID);
if (asset != null)
{
// OK, now fetch the inside.
Dictionary<UUID, int> ids = new Dictionary<UUID, int>();
HGUuidGatherer uuidGatherer = new HGUuidGatherer(this, m_scene.AssetService, userAssetURL);
uuidGatherer.GatherAssetUuids(asset.FullID, (AssetType)asset.Type, ids);
foreach (UUID uuid in ids.Keys)
FetchAsset(userAssetURL, uuid);
m_log.DebugFormat("[HGScene]: Successfully fetched asset {0} from asset server {1}", asset.ID, userAssetURL);
}
else
m_log.Warn("[HGScene]: Could not fetch asset from remote asset server " + userAssetURL);
}
else
m_log.Debug("[HGScene]: user's asset server is the local region's asset server");
}
//public InventoryItemBase Get(InventoryItemBase item, UUID rootFolder, CachedUserInfo userInfo)
//{
// InventoryClient invCli = null;
// string inventoryURL = UserInventoryURL(item.Owner);
// if (!m_inventoryServers.TryGetValue(inventoryURL, out invCli))
// {
// m_log.Debug("[HGScene]: Starting new InventorytClient for " + inventoryURL);
// invCli = new InventoryClient(inventoryURL);
// m_inventoryServers.Add(inventoryURL, invCli);
// }
// item = invCli.GetInventoryItem(item);
// if (item != null)
// {
// // Change the folder, stick it in root folder, all items flattened out here in this region cache
// item.Folder = rootFolder;
// //userInfo.AddItem(item); don't use this, it calls back to the inventory server
// lock (userInfo.RootFolder.Items)
// {
// userInfo.RootFolder.Items[item.ID] = item;
// }
// }
// return item;
//}
public void Post(UUID assetID, UUID ownerID)
{
// Post the item from the local AssetCache onto the remote asset server
// and place an entry in m_assetMap
string userAssetURL = HyperlinkAssets.GetUserAssetServer(ownerID);
if ((userAssetURL != string.Empty) && (userAssetURL != HyperlinkAssets.GetSimAssetServer()))
{
m_log.Debug("[HGScene]: Posting object " + assetID + " to asset server " + userAssetURL);
AssetBase asset = m_scene.AssetService.Get(assetID.ToString());
if (asset != null)
{
Dictionary<UUID, int> ids = new Dictionary<UUID, int>();
HGUuidGatherer uuidGatherer = new HGUuidGatherer(this, m_scene.AssetService, string.Empty);
uuidGatherer.GatherAssetUuids(asset.FullID, (AssetType)asset.Type, ids);
foreach (UUID uuid in ids.Keys)
{
asset = m_scene.AssetService.Get(uuid.ToString());
if (asset == null)
m_log.DebugFormat("[HGScene]: Could not find asset {0}", uuid);
else
PostAsset(userAssetURL, asset);
}
// maybe all pieces got there...
m_log.DebugFormat("[HGScene]: Successfully posted item {0} to asset server {1}", assetID, userAssetURL);
}
else
m_log.DebugFormat("[HGScene]: Something wrong with asset {0}, it could not be found", assetID);
}
else
m_log.Debug("[HGScene]: user's asset server is local region's asset server");
}
#endregion
}
}
| |
// Track BuildR
// Available on the Unity3D Asset Store
// Copyright (c) 2013 Jasper Stocker http://support.jasperstocker.com
// For support contact [email protected]
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
using System;
using System.Text;
using System.Xml;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
using System.Collections.Generic;
/// <summary>
/// Track BuildR Track holds all the point and curve data
/// It is responsible for holding other track based data
/// It also generates all the curve data in Recalculate Data which is used in Generator class
/// It has some functions to allow other scripts to access basic track information
/// </summary>
public class TrackBuildRTrack : MonoBehaviour
{
[SerializeField]
private List<TrackBuildRPoint> _points = new List<TrackBuildRPoint>();
[SerializeField]
private bool _looped = true;
public Transform baseTransform;
private const float CLIP_THREASHOLD = 0.5f;
[SerializeField]
private bool _disconnectBoundary = false;
[SerializeField]
private bool _renderBoundaryWallReverse = false;
public bool includeCollider = true;
public bool includeColliderRoof = true;
public float trackColliderWallHeight = 5.0f;
public bool trackBumpers = true;
public float bumperAngleThresold = 0.5f;
public float bumperWidth = 0.5f;
public float bumperHeight = 0.03f;
//Stunt piece values
public int loopPoints = 6;
public float loopRadius = 15.0f;
public float jumpHeight = 10.0f;
public float maxJumpLength = 50.0f;
public float twistAngle = 0.0f;
public int twistPoints = 6;
public float twistRadius = 20.0f;
public bool drawMode = false;
//Diagram variables
public GameObject diagramGO;
public Mesh diagramMesh;
public string diagramFilepath = "";
public Material diagramMaterial = null;
public float scale = 1.0f;
public Vector3 scalePointA = Vector3.zero;
public Vector3 scalePointB = Vector3.right;
public bool showDiagram = false;
public int assignedPoints = 0;
[SerializeField]
private bool _showWireframe = true;
[SerializeField]
private float _trackLength;
[SerializeField]
private float _meshResolution = 1.5f;//the world unit distance for mesh face sizes for nextNormIndex completed mesh
public float editMeshResolution = 3.0f;//the world unit distance for mesh face sizes - used when editing the track to reduce redraw time
[SerializeField]
private List<TrackBuildRTexture> _textures = new List<TrackBuildRTexture>();
//Terrain
public float terrainMergeWidth = 10;
public AnimationCurve mergeCurve = new AnimationCurve(new Keyframe(0,0,0,0), new Keyframe(1,1,0,0));
public Terrain mergeTerrain = null;
public float terrainAccuracy = 0.25f;
public float terrainMergeMargin = 1.75f;
public float conformAccuracy = 10.0f;
[SerializeField]
private bool _tangentsGenerated = false;
[SerializeField]
private bool _lightmapGenerated = false;
[SerializeField]
private bool _optimised = false;
[SerializeField]
private bool _render = true;
public int lastPolycount = 0;
public void InitTextures()
{
TrackBuildRTexture newTrackTexture = gameObject.AddComponent<TrackBuildRTexture>();
newTrackTexture.customName = "Track Texture";
_textures.Add(newTrackTexture);
TrackBuildRTexture newOffroadTexture = gameObject.AddComponent<TrackBuildRTexture>();
newOffroadTexture.customName = "Offroad Texture";
_textures.Add(newOffroadTexture);
TrackBuildRTexture newWallTexture = gameObject.AddComponent<TrackBuildRTexture>();
newWallTexture.customName = "Wall Texture";
_textures.Add(newWallTexture);
TrackBuildRTexture newBumperTexture = gameObject.AddComponent<TrackBuildRTexture>();
newBumperTexture.customName = "Bumper Texture";
_textures.Add(newBumperTexture);
}
public void CheckDiagram()
{
if (diagramMesh == null)
{
diagramMesh = new Mesh();
diagramMesh.vertices = new[] { new Vector3(-1, 0, -1), new Vector3(1, 0, -1), new Vector3(-1, 0, 1), new Vector3(1, 0, 1) };
diagramMesh.uv = new[] { new Vector2(0, 0), new Vector2(1, 0), new Vector2(0, 1), new Vector2(1, 1) };
diagramMesh.triangles = new[] { 1, 0, 2, 1, 2, 3 };
}
if (diagramGO == null)
{
diagramGO = new GameObject("Diagram");
diagramGO.transform.parent = transform;
diagramGO.transform.localPosition = Vector3.zero;
diagramGO.AddComponent<MeshFilter>().mesh = diagramMesh;
diagramMaterial = new Material(Shader.Find("Unlit/Texture"));
diagramGO.AddComponent<MeshRenderer>().material = diagramMaterial;
diagramGO.AddComponent<MeshCollider>().sharedMesh = diagramMesh;
}
}
void OnEnable()
{
hideFlags = HideFlags.HideInInspector;
}
public TrackBuildRPoint this[int index]
{
get
{
if (_looped && index > _points.Count - 1)//loop value around
index = index % _points.Count;
if (index < 0)
Debug.LogError("Index can't be minus");
if (index >= _points.Count)
Debug.LogError("Index out of range");
return _points[index];
}
}
public TrackBuildRPoint[] points
{
get
{
return _points.ToArray();
}
}
public TrackBuildRTexture Texture(int index)
{
if (_textures.Count == 0)
Debug.LogError("There are no textures to access");
if (index < 0)
Debug.LogError("Index can't be minus");
if (index >= _textures.Count)
Debug.LogError("Index out of range");
return _textures[index];
}
public void AddTexture()
{
#if UNITY_EDITOR
TrackBuildRTexture newTexture = Undo.AddComponent<TrackBuildRTexture>(gameObject);
#else
TrackBuildRTexture newTexture = gameObject.AddComponent<TrackBuildRTexture>();
#endif
newTexture.customName = "new texture " + (_textures.Count + 1);
_textures.Add(newTexture);
}
public void RemoveTexture(TrackBuildRTexture texture)
{
int textureIndex = _textures.IndexOf(texture);
#if UNITY_EDITOR
Undo.IncrementCurrentGroup();
Undo.RecordObject(this, "Remove Texture");
_textures.Remove(texture);
Undo.DestroyObjectImmediate(texture);
Undo.CollapseUndoOperations(Undo.GetCurrentGroup());
#else
_textures.Remove(texture);
#endif
//ensure that curves are not referenceing textures that no longer exist
for(int i = 0; i < numberOfCurves; i++)
{
TrackBuildRPoint curve = _points[i];
if (curve.trackTextureStyleIndex > textureIndex)
curve.trackTextureStyleIndex--;
if (curve.offroadTextureStyleIndex > textureIndex)
curve.offroadTextureStyleIndex--;
if (curve.bumperTextureStyleIndex > textureIndex)
curve.bumperTextureStyleIndex--;
if (curve.boundaryTextureStyleIndex > textureIndex)
curve.boundaryTextureStyleIndex--;
if (curve.bottomTextureStyleIndex > textureIndex)
curve.bottomTextureStyleIndex--;
}
}
public int numberOfTextures
{
get {return _textures.Count;}
}
public TrackBuildRTexture[] GetTexturesArray()
{
return _textures.ToArray();
}
public int numberOfPoints
{
get
{
if(_points.Count==0)
return 0;
return (_looped) ? _points.Count + 1 : _points.Count;
}
}
public int realNumberOfPoints { get { return _points.Count; } }
public bool tangentsGenerated { get { return _tangentsGenerated; } }
public bool lightmapGenerated { get { return _lightmapGenerated; } }
public bool optimised { get { return _optimised; } }
public int numberOfCurves
{
get
{
if (_points.Count < 2)
return 0;
return numberOfPoints - 1;
}
}
public bool loop
{
get { return _looped; }
set
{
if(_looped!=value)
{
_looped = value;
SetTrackDirty();
GUI.changed = true;
}
}
}
public float trackLength { get { return _trackLength; } }
public float meshResolution
{
get
{
return _meshResolution;
}
set
{
_meshResolution = value;
}
}
public bool disconnectBoundary {get {return _disconnectBoundary;}
set
{
_disconnectBoundary = value;
if(value)
{
foreach(TrackBuildRPoint point in _points)
{
if (point.leftForwardControlPoint == Vector3.zero)
point.leftForwardControlPoint = point.forwardControlPoint;
if (point.rightForwardControlPoint == Vector3.zero)
point.rightForwardControlPoint = point.forwardControlPoint;
}
}
}
}
public bool showWireframe
{
get
{
return _showWireframe;
}
set
{
#if UNITY_EDITOR
if(_showWireframe!=value)
{
foreach(TrackBuildRPoint curve in _points)
{
if (curve.holder == null)
continue;
foreach (MeshRenderer holderR in curve.holder.GetComponentsInChildren<MeshRenderer>())
EditorUtility.SetSelectedWireframeHidden(holderR, !value);
}
_showWireframe = value;
}
#endif
}
}
public bool isDirty
{
get
{
foreach (TrackBuildRPoint point in _points)
if (point.isDirty) return true;
return false;
}
}
public bool renderBoundaryWallReverse
{
get {return _renderBoundaryWallReverse;}
set
{
if (_renderBoundaryWallReverse != value)
{
ReRenderTrack();
_renderBoundaryWallReverse = value;
}
}
}
public bool render
{
get {return _render;}
set
{
if(value != _render)
{
_render = value;
gameObject.GetComponent<TrackBuildR>().ForceFullRecalculation();
}
}
}
public TrackBuildRPoint AddPoint(Vector3 position)
{
#if UNITY_EDITOR
TrackBuildRPoint point = Undo.AddComponent<TrackBuildRPoint>(gameObject);//ScriptableObject.CreateInstance<TrackBuildRPoint>();
#else
TrackBuildRPoint point = gameObject.AddComponent<TrackBuildRPoint>();//ScriptableObject.CreateInstance<TrackBuildRPoint>();
#endif
point.baseTransform = baseTransform;
point.position = position;
point.isDirty = true;
_points.Add(point);
RecalculateCurves();
return point;
}
public void AddPoint(TrackBuildRPoint point)
{
point.baseTransform = baseTransform;
_points.Add(point);
RecalculateCurves();
}
public void InsertPoint(TrackBuildRPoint point, int index)
{
point.baseTransform = baseTransform;
_points.Insert(index, point);
RecalculateCurves();
}
public TrackBuildRPoint InsertPoint(int index)
{
#if UNITY_EDITOR
Undo.IncrementCurrentGroup();
TrackBuildRPoint point = Undo.AddComponent<TrackBuildRPoint>(gameObject);//ScriptableObject.CreateInstance<TrackBuildRPoint>();
#else
TrackBuildRPoint point = gameObject.AddComponent<TrackBuildRPoint>();//ScriptableObject.CreateInstance<TrackBuildRPoint>();
#endif
point.baseTransform = baseTransform;
#if UNITY_EDITOR
Undo.RecordObject(this, "Remove Point");
#endif
_points.Insert(index, point);
#if UNITY_EDITOR
Undo.CollapseUndoOperations(Undo.GetCurrentGroup());
#endif
RecalculateCurves();
return point;
}
public void RemovePoint(TrackBuildRPoint point)
{
if(_points.Count < 3)
{
Debug.Log("We can't see any point in allowing you to delete any more points so we're not going to do it.");
return;
}
#if UNITY_EDITOR
Undo.IncrementCurrentGroup();
_points.Remove(point);
Undo.DestroyObjectImmediate(point.holder);
Undo.DestroyObjectImmediate(point);
Undo.CollapseUndoOperations(Undo.GetCurrentGroup());
#else
_points.Remove(point);
#endif
RecalculateCurves();
}
//Sample nextNormIndex position on the entire curve based on time (0-1)
public Vector3 GetTrackPosition(float t)
{
if(realNumberOfPoints<2)
{
Debug.LogError("Not enough points to define a curve");
return Vector3.zero;
}
float curveT = 1.0f / numberOfCurves;
int point = Mathf.FloorToInt(t / curveT);
float ct = Mathf.Clamp01((t - point * curveT) * numberOfCurves);
TrackBuildRPoint pointA = GetPoint(point);
TrackBuildRPoint pointB = GetPoint(point + 1);
return SplineMaths.CalculateBezierPoint(ct, pointA.position, pointA.forwardControlPoint, pointB.backwardControlPoint, pointB.position);
}
public float GetTrackWidth(float t)
{
float curveT = 1.0f / numberOfCurves;
int point = Mathf.FloorToInt(t / curveT);
float ct = Mathf.Clamp01((t - point * curveT) * numberOfCurves);
float hermite = SplineMaths.CalculateHermite(ct);
TrackBuildRPoint pointA = GetPoint(point);
TrackBuildRPoint pointB = GetPoint(point + 1);
return Mathf.Lerp(pointA.width, pointB.width, hermite);
}
// public float GetTrackCant(float t)
// {
// float curveT = 1.0f / numberOfCurves;
// int point = Mathf.FloorToInt(t / curveT);
// float ct = Mathf.Clamp01((t - point * curveT) * numberOfCurves);
// float hermite = SplineMaths.CalculateHermite(ct);
// TrackBuildRPoint pointA = GetPoint(point);
// TrackBuildRPoint pointB = GetPoint(point + 1);
// return Mathf.LerpAngle(pointA.cant, pointB.cant, hermite);
// }
public Quaternion GetTrackUp(float t)
{
float curveT = 1.0f / numberOfCurves;
int point = Mathf.FloorToInt(t / curveT);
float ct = Mathf.Clamp01((t - point * curveT) * numberOfCurves);
float hermite = SplineMaths.CalculateHermite(ct);
TrackBuildRPoint pointA = GetPoint(point);
TrackBuildRPoint pointB = GetPoint(point + 1);
return Quaternion.Slerp(pointA.trackUpQ, pointB.trackUpQ, hermite);
}
public float GetTrackCrownAngle(float t)
{
float curveT = 1.0f / numberOfCurves;
int point = Mathf.FloorToInt(t / curveT);
float ct = Mathf.Clamp01((t - point * curveT) * numberOfCurves);
float hermite = SplineMaths.CalculateHermite(ct);
TrackBuildRPoint pointA = GetPoint(point);
TrackBuildRPoint pointB = GetPoint(point + 1);
return Mathf.LerpAngle(pointA.crownAngle, pointB.crownAngle, hermite);
}
public Vector3 GetTrackCross(float t)
{
float curveT = 1.0f / numberOfCurves;
int point = Mathf.FloorToInt(t / curveT);
float ct = Mathf.Clamp01((t - point * curveT) * numberOfCurves);
float hermite = SplineMaths.CalculateHermite(ct);
TrackBuildRPoint pointA = GetPoint(point);
TrackBuildRPoint pointB = GetPoint(point + 1);
return Vector3.Slerp(pointA.trackCross, pointB.trackCross, hermite);
}
public float GetTrackPercentage(TrackBuildRPoint point)
{
int index = _points.IndexOf(point);
return index / (float)numberOfPoints;
}
public float GetTrackPercentage(int pointIndex)
{
return pointIndex / (float)numberOfPoints;
}
public int GetNearestPointIndex(float trackPercentage)
{
return Mathf.RoundToInt(numberOfCurves * trackPercentage);
}
public int GetLastPointIndex(float trackPercentage)
{
return Mathf.FloorToInt(numberOfCurves * trackPercentage);
}
public int GetNextPointIndex(float trackPercentage)
{
return Mathf.CeilToInt(numberOfCurves * trackPercentage);
}
//Sample nextNormIndex position on the entire curve based on time (0-1)
public Vector3 GetLeftBoundaryPosition(float t)
{
float curveT = 1.0f / numberOfCurves;
int point = Mathf.FloorToInt(t / curveT);
float ct = Mathf.Clamp01((t - point * curveT) * numberOfCurves);
TrackBuildRPoint pointA = GetPoint(point);
TrackBuildRPoint pointB = GetPoint(point + 1);
return SplineMaths.CalculateBezierPoint(ct, pointA.leftTrackBoundary, pointA.leftForwardControlPoint, pointB.leftBackwardControlPoint, pointB.leftTrackBoundary);
}
//Sample nextNormIndex position on the entire curve based on time (0-1)
public Vector3 GetRightBoundaryPosition(float t)
{
float curveT = 1.0f / numberOfCurves;
int point = Mathf.FloorToInt(t / curveT);
float ct = Mathf.Clamp01((t - point * curveT) * numberOfCurves);
TrackBuildRPoint pointA = GetPoint(point);
TrackBuildRPoint pointB = GetPoint(point + 1);
return SplineMaths.CalculateBezierPoint(ct, pointA.rightTrackBoundary, pointA.rightForwardControlPoint, pointB.rightBackwardControlPoint, pointB.rightTrackBoundary);
}
public Vector3 GetTrackDirection(float t)
{
float curveT = 1.0f / numberOfCurves;
int point = Mathf.FloorToInt(t / curveT);
float ct = Mathf.Clamp01((t - point * curveT) * numberOfCurves);
float hermite = SplineMaths.CalculateHermite(ct);
TrackBuildRPoint pointA = GetPoint(point);
TrackBuildRPoint pointB = GetPoint(point + 1);
Quaternion trackDirectionA = Quaternion.LookRotation(pointA.trackDirection);
Quaternion trackDirectionB = Quaternion.LookRotation(pointB.trackDirection);
Quaternion trackDirectionQ = Quaternion.Slerp(trackDirectionA, trackDirectionB, hermite);
return trackDirectionQ * Vector3.forward;
}
public void RecalculateCurves()
{
if (_points.Count < 2)//there is no track with only one point :o)
return;
if (isDirty)
{
_tangentsGenerated = false;
_lightmapGenerated = false;
_optimised = false;
}
//calculate approx bezier arc length per curve
for (int i = 0; i < realNumberOfPoints; i++)
{
TrackBuildRPoint pointA = GetPoint(i);
TrackBuildRPoint pointB = GetPoint(i+1);
float thisArcLength = 0;
thisArcLength += Vector3.Distance(pointA.position, pointA.forwardControlPoint);
thisArcLength += Vector3.Distance(pointA.forwardControlPoint, pointB.backwardControlPoint);
thisArcLength += Vector3.Distance(pointB.backwardControlPoint, pointB.position);
_points[i].arcLength = thisArcLength;
if(thisArcLength == 0)
{
DestroyImmediate(pointA);
i--;
}
}
for (int i = 0; i < realNumberOfPoints; i++)
{
TrackBuildRPoint pointA = GetPoint(i);
TrackBuildRPoint pointB = GetPoint(i + 1);
TrackBuildRPoint pointC = GetPoint(i - 1);
pointA.nextPoint = pointB;
pointA.lastPoint = pointC;
pointA.pointName = "point " + i;
}
foreach (TrackBuildRPoint curve in _points)
{
if (!curve.curveIsDirty)//only recalculate modified points
continue;
if (curve.arcLength > 0)
{
TrackBuildRPoint pointA = curve;
TrackBuildRPoint pointB = curve.nextPoint;
//Build accurate arc length data into curve
curve.center = Vector3.zero;
int arcLengthResolution = Mathf.Max(Mathf.RoundToInt(curve.arcLength * 10), 1);
float alTime = 1.0f / arcLengthResolution;
float calculatedTotalArcLength = 0;
curve.storedArcLengthsFull = new float[arcLengthResolution];
curve.storedArcLengthsFull[0] = 0.0f;
Vector3 pA = curve.position;
for (int i = 0; i < arcLengthResolution - 1; i++)
{
curve.center += pA;
float altB = alTime * (i + 1) + alTime;
Vector3 pB = SplineMaths.CalculateBezierPoint(altB, curve.position, curve.forwardControlPoint, pointB.backwardControlPoint, pointB.position);
float arcLength = Vector3.Distance(pA, pB);
calculatedTotalArcLength += arcLength;
curve.storedArcLengthsFull[i + 1] = calculatedTotalArcLength;
pA = pB;//switch over values so we only calculate the bezier once
}
curve.arcLength = calculatedTotalArcLength;
curve.center /= arcLengthResolution;
int storedPointSize = Mathf.RoundToInt(calculatedTotalArcLength / meshResolution);
curve.storedPointSize = storedPointSize;
curve.normalisedT = new float[storedPointSize];
curve.targetSize = new float[storedPointSize];
curve.midPointPerc = new float[storedPointSize];
curve.prevNormIndex = new int[storedPointSize];
curve.nextNormIndex = new int[storedPointSize];
curve.clipArrayLeft = new bool[storedPointSize];
curve.clipArrayRight = new bool[storedPointSize];
//calculate normalised spline data
int normalisedIndex = 0;
curve.normalisedT[0] = 0;
for (int p = 1; p < storedPointSize; p++)
{
float t = p / (float)(storedPointSize - 1);
float targetLength = t * calculatedTotalArcLength;
curve.targetSize[p] = targetLength;
int it = 1000;
while (targetLength > curve.storedArcLengthsFull[normalisedIndex])
{
normalisedIndex++;
it--;
if (it < 0)
{
curve.normalisedT[p] = 0;
break;
}
}
normalisedIndex = Mathf.Min(normalisedIndex, arcLengthResolution);//ensure we've not exceeded the length
int prevNormIndex = Mathf.Max((normalisedIndex - 1), 0);
int nextNormIndex = normalisedIndex;
float lengthBefore = curve.storedArcLengthsFull[prevNormIndex];
float lengthAfter = curve.storedArcLengthsFull[nextNormIndex];
float midPointPercentage = (targetLength - lengthBefore) / (lengthAfter - lengthBefore);
curve.midPointPerc[p] = midPointPercentage;
curve.prevNormIndex[p] = prevNormIndex;
curve.nextNormIndex[p] = nextNormIndex;
float normalisedT = (normalisedIndex + midPointPercentage) / arcLengthResolution;//lerp between the values to get the exact normal T
curve.normalisedT[p] = normalisedT;
}
curve.sampledPoints = new Vector3[storedPointSize];
curve.sampledLeftBoundaryPoints = new Vector3[storedPointSize];
curve.sampledRightBoundaryPoints = new Vector3[storedPointSize];
curve.sampledWidths = new float[storedPointSize];
curve.sampledCrowns = new float[storedPointSize];
curve.sampledTrackDirections = new Vector3[storedPointSize];
curve.sampledTrackUps = new Vector3[storedPointSize];
curve.sampledTrackCrosses = new Vector3[storedPointSize];
curve.sampledAngles = new float[storedPointSize];
for (int p = 0; p < storedPointSize; p++)
{
float tN = curve.normalisedT[p];
float tH = SplineMaths.CalculateHermite(tN);
curve.sampledPoints[p] = SplineMaths.CalculateBezierPoint(tN, pointA.position, pointA.forwardControlPoint, pointB.backwardControlPoint, pointB.position);
curve.sampledLeftBoundaryPoints[p] = SplineMaths.CalculateBezierPoint(tN, pointA.leftTrackBoundary, pointA.leftForwardControlPoint, pointB.leftBackwardControlPoint, pointB.leftTrackBoundary);
curve.sampledRightBoundaryPoints[p] = SplineMaths.CalculateBezierPoint(tN, pointA.rightTrackBoundary, pointA.rightForwardControlPoint, pointB.rightBackwardControlPoint, pointB.rightTrackBoundary);
curve.sampledWidths[p] = Mathf.LerpAngle(pointA.width, pointB.width, tH);
curve.sampledCrowns[p] = Mathf.LerpAngle(pointA.crownAngle, pointB.crownAngle, tH);
curve.sampledTrackUps[p] = Quaternion.Slerp(pointA.trackUpQ, pointB.trackUpQ, tH) * Vector3.forward;
curve.clipArrayLeft[p] = true;
curve.clipArrayRight[p] = true;
}
}
}
for (int i = 0; i < numberOfCurves; i++)
{
TrackBuildRPoint curve = _points[i];
if (!curve.curveIsDirty)//only recalculate modified points
continue;
if (curve.arcLength > 0)
{
int lastCurveIndex = (i > 0) ? i - 1 : (_looped) ? numberOfCurves - 1 : 0;
int nextCurveIndex = (i < numberOfCurves - 1) ? i + 1 : (_looped) ? 0 : numberOfCurves - 1;
TrackBuildRPoint lastcurve = _points[lastCurveIndex];
TrackBuildRPoint nextcurve = _points[nextCurveIndex];
int storedPointSize = curve.storedPointSize;
for (int p = 0; p < storedPointSize; p++)
{
int pA = p - 1;
int pB = p;
int pC = p + 1;
if(pA < 0) pA = 0;
if(pC >= storedPointSize) pC = storedPointSize - 1;
Vector3 sampledPointA = curve.sampledPoints[pA];
Vector3 sampledPointB = curve.sampledPoints[pB];
Vector3 sampledPointC = curve.sampledPoints[pC];
if(p == 0 && lastcurve != null && lastcurve.sampledPoints.Length > 1)
sampledPointA = lastcurve.sampledPoints[lastcurve.storedPointSize - 2];//retrieve the penultimate point from the last curve
if(p == storedPointSize - 1 && nextcurve != null && nextcurve.sampledPoints.Length > 1)
sampledPointC = nextcurve.sampledPoints[1];//retrieve the second point from the next curve
Vector3 sampledTrackDirectionA = (sampledPointB - sampledPointA);
Vector3 sampledTrackDirectionB = (sampledPointC - sampledPointB);
Vector3 sampledTrackDirection = (sampledTrackDirectionA + sampledTrackDirectionB).normalized;
curve.sampledTrackDirections[pB] = sampledTrackDirection;
curve.sampledTrackCrosses[pB] = Vector3.Cross(curve.sampledTrackUps[pB], sampledTrackDirection);
curve.sampledAngles[pB] = Vector3.Angle(sampledTrackDirectionA, sampledTrackDirectionB) * -Mathf.Sign(Vector3.Dot((sampledTrackDirectionB - sampledTrackDirectionA), curve.sampledTrackCrosses[pB]));
curve.clipArrayLeft[pB] = true;
curve.clipArrayRight[pB] = true;
}
}
}
bool dirtyTextures = false;
foreach (TrackBuildRTexture texture in _textures)
{
if (texture.isDirty)
dirtyTextures = true;//if nextNormIndex point was dirty, ensure it's rerendered
texture.isDirty = false;
}
foreach(TrackBuildRPoint point in _points)
if (point.curveIsDirty || dirtyTextures)
point.shouldReRender = true;//if nextNormIndex point was dirty, ensure it's rerendered
//clean points
foreach (TrackBuildRPoint point in _points)
point.isDirty = false;//reset all points - data is no longer considered dirty
//recalculate track length
_trackLength = 0;
foreach(TrackBuildRPoint curve in _points)
_trackLength += curve.arcLength;
}
public float GetNearestPoint(Vector3 fromPostition)
{
int testPoints = 10;
float testResolution = 1.0f / testPoints;
float nearestPercentage = 0;
float nextNearestPercentage = 0;
float nearestPercentageSqrDistance = Mathf.Infinity;
float nextNearestPercentageSqrDistance = Mathf.Infinity;
for (float i = 0; i < 1; i += testResolution)
{
Vector3 point = GetTrackPosition(i);
Vector3 difference = point - fromPostition;
float newSqrDistance = Vector3.SqrMagnitude(difference);
if (nearestPercentageSqrDistance > newSqrDistance)
{
nearestPercentage = i;
nearestPercentageSqrDistance = newSqrDistance;
}
}
nextNearestPercentage = nearestPercentage;
nextNearestPercentageSqrDistance = nearestPercentageSqrDistance;
int numberOfRefinments = Mathf.RoundToInt(Mathf.Pow(_trackLength * 10, 1.0f / 5.0f));
Debug.Log(numberOfRefinments);
for (int r = 0; r < numberOfRefinments; r++)
{
float refinedResolution = testResolution / testPoints;
float startSearch = nearestPercentage - testResolution / 2;
float endSearch = nearestPercentage + testResolution / 2;
for (float i = startSearch; i < endSearch; i += refinedResolution)
{
Vector3 point = GetTrackPosition(i);
Vector3 difference = point - fromPostition;
float newSqrDistance = Vector3.SqrMagnitude(difference);
if (nearestPercentageSqrDistance > newSqrDistance)
{
nextNearestPercentage = nearestPercentage;
nextNearestPercentageSqrDistance = nearestPercentageSqrDistance;
nearestPercentage = i;
nearestPercentageSqrDistance = newSqrDistance;
}
else
{
if (nextNearestPercentageSqrDistance > newSqrDistance)
{
nextNearestPercentage = i;
nextNearestPercentageSqrDistance = newSqrDistance;
}
}
}
testResolution = refinedResolution;
}
float lerpvalue = nearestPercentageSqrDistance / (nearestPercentageSqrDistance + nextNearestPercentageSqrDistance);
return Mathf.Clamp01(Mathf.Lerp(nearestPercentage, nextNearestPercentage, lerpvalue));
}
public void Clear()
{
int numCurves = numberOfCurves;
for (int i = 0; i < numCurves; i++)
{
if (_points[i].holder != null)
{
DestroyImmediate(_points[i].holder);
}
}
_points.Clear();
_textures.Clear();
}
public TrackBuildRPoint GetPoint(int index)
{
if (_points.Count == 0)
return null;
if (!_looped)
{
return _points[Mathf.Clamp(index, 0, numberOfCurves)];
}
if (index >= numberOfCurves)
index = index - numberOfCurves;
if (index < 0)
index = index + numberOfCurves;
return _points[index];
}
private float SignedAngle(Vector3 from, Vector3 to, Vector3 up)
{
Vector3 direction = (to - from).normalized;
Vector3 cross = Vector3.Cross(up, direction);
float dot = Vector3.Dot(from, cross);
return Vector3.Angle(from, to) * Mathf.Sign(dot);
}
/// <summary>
/// Set all point data as rendered
/// </summary>
public void TrackRendered()
{
foreach (TrackBuildRPoint point in _points)
{
point.shouldReRender = false;
}
// int numberOfPitlanPoints = pitlane.numberOfPoints;
// for (int i = 0; i < numberOfPitlanPoints; i++)
// {
// pitlane[i].shouldReRender = false;
// }
}
/// <summary>
/// Mark the entire track as dirty so it will be recalculated/rebuilt
/// </summary>
public void SetTrackDirty()
{
foreach (TrackBuildRPoint point in _points)
{
point.isDirty = true;
}
// for (int i = 0; i < pitlane.numberOfPoints; i++)
// {
// pitlane[i].isDirty = true;
// }
// SetPitDirty();
}
/// <summary>
/// Set all point data to rerender
/// </summary>
public void ReRenderTrack()
{
foreach (TrackBuildRPoint point in _points)
{
point.shouldReRender = true;
}
// for (int i = 0; i < pitlane.numberOfPoints; i++)
// {
// pitlane[i].shouldReRender = true;
// }
// ReRenderPit();
}
// /// <summary>
// /// Mark the pit lane as dirty so it will be recalculated/rebuilt
// /// </summary>
// public void SetPitDirty()
// {
// for (int i = 0; i < pitlane.numberOfPoints; i++)
// {
// pitlane[i].isDirty = true;
// }
// }
//
// /// <summary>
// /// Set pit lane point data to rerender
// /// </summary>
// public void ReRenderPit()
// {
// for (int i = 0; i < pitlane.numberOfPoints; i++)
// {
// pitlane[i].shouldReRender = true;
// }
// }
public void SolveTangents()
{
for (int i = 0; i < numberOfCurves; i++)
{
TrackBuildRPoint curve = _points[i];
curve.dynamicTrackMesh.SolveTangents();
curve.dynamicOffroadMesh.SolveTangents();
curve.dynamicBumperMesh.SolveTangents();
curve.dynamicBoundaryMesh.SolveTangents();
curve.dynamicBottomMesh.SolveTangents();
}
_tangentsGenerated = true;
}
public void GenerateSecondaryUVSet()
{
#if UNITY_EDITOR
for (int i = 0; i < numberOfCurves; i++)
{
TrackBuildRPoint curve = _points[i];
for (int m = 0; m < curve.dynamicTrackMesh.meshCount; m++)
Unwrapping.GenerateSecondaryUVSet(curve.dynamicTrackMesh[m].mesh);
for (int m = 0; m < curve.dynamicOffroadMesh.meshCount; m++)
Unwrapping.GenerateSecondaryUVSet(curve.dynamicOffroadMesh[m].mesh);
for (int m = 0; m < curve.dynamicBumperMesh.meshCount; m++)
Unwrapping.GenerateSecondaryUVSet(curve.dynamicBumperMesh[m].mesh);
for (int m = 0; m < curve.dynamicBoundaryMesh.meshCount; m++)
Unwrapping.GenerateSecondaryUVSet(curve.dynamicBoundaryMesh[m].mesh);
for (int m = 0; m < curve.dynamicBottomMesh.meshCount; m++)
Unwrapping.GenerateSecondaryUVSet(curve.dynamicBottomMesh[m].mesh);
}
_lightmapGenerated = true;
#endif
}
public void OptimseMeshes()
{
#if UNITY_EDITOR
for (int i = 0; i < numberOfCurves; i++)
{
TrackBuildRPoint curve = _points[i];
for (int m = 0; m < curve.dynamicTrackMesh.meshCount; m++)
MeshUtility.Optimize(curve.dynamicTrackMesh[m].mesh);
for (int m = 0; m < curve.dynamicOffroadMesh.meshCount; m++)
MeshUtility.Optimize(curve.dynamicOffroadMesh[m].mesh);
for (int m = 0; m < curve.dynamicBumperMesh.meshCount; m++)
MeshUtility.Optimize(curve.dynamicBumperMesh[m].mesh);
for (int m = 0; m < curve.dynamicBoundaryMesh.meshCount; m++)
MeshUtility.Optimize(curve.dynamicBoundaryMesh[m].mesh);
for (int m = 0; m < curve.dynamicBottomMesh.meshCount; m++)
MeshUtility.Optimize(curve.dynamicBottomMesh[m].mesh);
}
_optimised = true;
#endif
}
#if UNITY_EDITOR
public virtual string ToXML()
{
//todo track variables...
StringBuilder sb = new StringBuilder();
sb.AppendLine("<track>");
sb.AppendLine("<textures>");
foreach (TrackBuildRTexture texture in _textures)
sb.Append(texture.ToXML());
sb.AppendLine("</textures>");
sb.AppendLine("<trackpoints>");
foreach (TrackBuildRPoint point in _points)
sb.Append(point.ToXML());
sb.AppendLine("</trackpoints>");
sb.AppendLine("<meshResolution>" + _meshResolution.ToString("F3") + "</meshResolution>");
sb.AppendLine("<includeCollider>" + includeCollider + "</includeCollider>");
sb.AppendLine("<includeColliderRoof>" + includeColliderRoof + "</includeColliderRoof>");
sb.AppendLine("<trackColliderWallHeight>" + trackColliderWallHeight.ToString("F3") + "</trackColliderWallHeight>");
sb.AppendLine("<trackBumpers>" + trackBumpers + "</trackBumpers>");
sb.AppendLine("<bumperHeight>" + bumperHeight.ToString("F3") + "</bumperHeight>");
sb.AppendLine("<bumperWidth>" + bumperWidth.ToString("F3") + "</bumperWidth>");
sb.AppendLine("<bumperAngleThresold>" + bumperAngleThresold.ToString("F3") + "</bumperAngleThresold>");
sb.AppendLine("<disconnectBoundary>" + _disconnectBoundary + "</disconnectBoundary>");
sb.AppendLine("<renderBoundaryWallReverse>" + _renderBoundaryWallReverse + "</renderBoundaryWallReverse>");
sb.AppendLine("</track>");
return sb.ToString();
}
public virtual void FromXML(XmlNode node)
{
XmlNodeList textureNodes = node.SelectNodes("textures/texture");
foreach(XmlNode textureNode in textureNodes)
{
TrackBuildRTexture newTexture = gameObject.AddComponent<TrackBuildRTexture>();
newTexture.FromXML(textureNode);
_textures.Add(newTexture);
}
XmlNodeList trackPointNodes = node.SelectNodes("trackpoints/trackpoint");
foreach(XmlNode trackPointNode in trackPointNodes)
{
TrackBuildRPoint point = gameObject.AddComponent<TrackBuildRPoint>();
point.FromXML(trackPointNode);
point.baseTransform = baseTransform;
point.isDirty = true;
_points.Add(point);
}
if (node["meshResolution"] != null)
_meshResolution = float.Parse(node["meshResolution"].FirstChild.Value);
if (node["includeCollider"] != null)
includeCollider = bool.Parse(node["includeCollider"].FirstChild.Value);
if (node["includeColliderRoof"] != null)
includeColliderRoof = bool.Parse(node["includeColliderRoof"].FirstChild.Value);
if (node["trackColliderWallHeight"] != null)
trackColliderWallHeight = float.Parse(node["trackColliderWallHeight"].FirstChild.Value);
if (node["trackBumpers"] != null)
trackBumpers = bool.Parse(node["trackBumpers"].FirstChild.Value);
if (node["bumperHeight"] != null)
bumperHeight = float.Parse(node["bumperHeight"].FirstChild.Value);
if (node["bumperWidth"] != null)
bumperWidth = float.Parse(node["bumperWidth"].FirstChild.Value);
if (node["bumperAngleThresold"] != null)
bumperAngleThresold = float.Parse(node["bumperAngleThresold"].FirstChild.Value);
if (node["disconnectBoundary"] != null)
_disconnectBoundary = bool.Parse(node["disconnectBoundary"].FirstChild.Value);
if (node["renderBoundaryWallReverse"] != null)
_renderBoundaryWallReverse = bool.Parse(node["renderBoundaryWallReverse"].FirstChild.Value);
RecalculateCurves();
}
#endif
#if UNITY_EDITOR
public void FromKML(string coordinates)
{
Clear();
string[] coorArray = coordinates.Split(new []{" "}, StringSplitOptions.RemoveEmptyEntries);
List<Vector3> kmlpoints = new List<Vector3>();
Vector3 xyCenter = new Vector3();
Vector3 lastCoord = Vector3.zero;
int numberOfCoords = coorArray.Length;
for (int i = 0; i < numberOfCoords; i++)
{
string coord = coorArray[i];
if (coord == "")
continue;
string[] coordEntry = coord.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
if (coordEntry.Length < 3)
continue;
float KMLPointX = float.Parse(coordEntry[0]);
float KMLPointY = float.Parse(coordEntry[2]);
float KMLPointZ = float.Parse(coordEntry[1]);
Vector3 newKMLPoint = new Vector3(KMLPointX, KMLPointY, KMLPointZ);
if (Vector3.Distance(newKMLPoint, lastCoord) < 1.0f && lastCoord != Vector3.zero)
continue;//skip duplicate point
kmlpoints.Add(newKMLPoint);
xyCenter.x += newKMLPoint.x;
xyCenter.z += newKMLPoint.z;
lastCoord = newKMLPoint;
}
int numberOfPoints = kmlpoints.Count;
xyCenter.x *= 1.0f / numberOfPoints;
xyCenter.z *= 1.0f / numberOfPoints;
if (Vector3.Distance(kmlpoints[numberOfPoints - 1], kmlpoints[0]) < 1.0f)
kmlpoints.RemoveAt(numberOfPoints - 1);
numberOfPoints = kmlpoints.Count;
List<Vector3> eulerpoints = new List<Vector3>();
float dataTrackLength = 0;
Vector3 lastPoint = Vector3.zero;
for (int i = 0; i < numberOfPoints; i++)
{
Vector3 KMLPoint = kmlpoints[i];
Vector3 newEulerPoint = GPSMaths.Simple(xyCenter, KMLPoint);
newEulerPoint.y = KMLPoint.y;
eulerpoints.Add(newEulerPoint);
if(i > 0)
dataTrackLength += Vector3.Distance(lastPoint, newEulerPoint);
lastPoint = newEulerPoint;
}
if (dataTrackLength > 20000)
if (!EditorUtility.DisplayDialog("Really Long Track!", "The Data is creating a track length around " + (dataTrackLength / 1000).ToString("F1") + "km long", "Continue", "Cancel"))
return;
if (dataTrackLength < 1)
if (EditorUtility.DisplayDialog("No Track!", "The Data not producing a viable track", "Ok"))
return;
for(int i = 0; i < numberOfPoints; i++)
{
TrackBuildRPoint point = gameObject.AddComponent<TrackBuildRPoint>();
point.baseTransform = baseTransform;
point.position = eulerpoints[i];
point.isDirty = true;
_points.Add(point);
}
for (int i = 0; i < numberOfPoints; i++)
{
TrackBuildRPoint point = _points[i];
Vector3 thisPosition = point.worldPosition;
Vector3 lastPosition = GetPoint(i - 1).worldPosition;
Vector3 nextPosition = GetPoint(i + 1).worldPosition;
Vector3 backwardTrack = thisPosition - lastPosition;
Vector3 forwardTrack = nextPosition - thisPosition;
Vector3 controlDirection = (backwardTrack + forwardTrack).normalized;
float forwardMag = forwardTrack.magnitude;
float backwardMag = backwardTrack.magnitude;
if (forwardMag == 0)
forwardMag = backwardMag;
if (backwardMag == 0)
backwardMag = forwardMag;
float controlMagnitude = Mathf.Min(forwardMag, backwardMag) * 0.1666f;
point.forwardControlPoint = (controlDirection * controlMagnitude) + thisPosition;
}
InitTextures();
RecalculateCurves();
}
#endif
}
| |
using System;
using System.Net;
using System.Net.Mail;
using System.Security.Principal;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;
using AnglicanGeek.MarkdownMailer;
using Elmah;
using Microsoft.WindowsAzure.ServiceRuntime;
using Ninject;
using Ninject.Web.Common;
using Ninject.Modules;
using NuGetGallery.Configuration;
using NuGetGallery.Infrastructure;
using System.Diagnostics;
using NuGetGallery.Auditing;
using NuGetGallery.Infrastructure.Lucene;
namespace NuGetGallery
{
public class ContainerBindings : NinjectModule
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:CyclomaticComplexity", Justification = "This code is more maintainable in the same function.")]
public override void Load()
{
var configuration = new ConfigurationService();
Bind<ConfigurationService>()
.ToMethod(context => configuration);
Bind<IAppConfiguration>()
.ToMethod(context => configuration.Current);
Bind<PoliteCaptcha.IConfigurationSource>()
.ToMethod(context => configuration);
Bind<Lucene.Net.Store.Directory>()
.ToMethod(_ => LuceneCommon.GetDirectory(configuration.Current.LuceneIndexLocation))
.InSingletonScope();
ConfigureSearch(configuration);
if (!String.IsNullOrEmpty(configuration.Current.AzureStorageConnectionString))
{
Bind<ErrorLog>()
.ToMethod(_ => new TableErrorLog(configuration.Current.AzureStorageConnectionString))
.InSingletonScope();
}
else
{
Bind<ErrorLog>()
.ToMethod(_ => new SqlErrorLog(configuration.Current.SqlConnectionString))
.InSingletonScope();
}
Bind<ICacheService>()
.To<HttpContextCacheService>()
.InRequestScope();
Bind<IContentService>()
.To<ContentService>()
.InSingletonScope();
Bind<IEntitiesContext>()
.ToMethod(context => new EntitiesContext(configuration.Current.SqlConnectionString, readOnly: configuration.Current.ReadOnlyMode))
.InRequestScope();
Bind<IEntityRepository<User>>()
.To<EntityRepository<User>>()
.InRequestScope();
Bind<IEntityRepository<CuratedFeed>>()
.To<EntityRepository<CuratedFeed>>()
.InRequestScope();
Bind<IEntityRepository<CuratedPackage>>()
.To<EntityRepository<CuratedPackage>>()
.InRequestScope();
Bind<IEntityRepository<PackageRegistration>>()
.To<EntityRepository<PackageRegistration>>()
.InRequestScope();
Bind<IEntityRepository<Package>>()
.To<EntityRepository<Package>>()
.InRequestScope();
Bind<IEntityRepository<PackageDependency>>()
.To<EntityRepository<PackageDependency>>()
.InRequestScope();
Bind<IEntityRepository<PackageStatistics>>()
.To<EntityRepository<PackageStatistics>>()
.InRequestScope();
Bind<IEntityRepository<Credential>>()
.To<EntityRepository<Credential>>()
.InRequestScope();
Bind<ICuratedFeedService>()
.To<CuratedFeedService>()
.InRequestScope();
Bind<IUserService>()
.To<UserService>()
.InRequestScope();
Bind<IPackageService>()
.To<PackageService>()
.InRequestScope();
Bind<EditPackageService>().ToSelf();
Bind<IFormsAuthenticationService>()
.To<FormsAuthenticationService>()
.InSingletonScope();
Bind<IControllerFactory>()
.To<NuGetControllerFactory>()
.InRequestScope();
Bind<INuGetExeDownloaderService>()
.To<NuGetExeDownloaderService>()
.InRequestScope();
Bind<IStatusService>()
.To<StatusService>()
.InRequestScope();
var mailSenderThunk = new Lazy<IMailSender>(
() =>
{
var settings = Kernel.Get<ConfigurationService>();
if (settings.Current.SmtpUri != null && settings.Current.SmtpUri.IsAbsoluteUri)
{
var smtpUri = new SmtpUri(settings.Current.SmtpUri);
var mailSenderConfiguration = new MailSenderConfiguration
{
DeliveryMethod = SmtpDeliveryMethod.Network,
Host = smtpUri.Host,
Port = smtpUri.Port,
EnableSsl = smtpUri.Secure
};
if (!String.IsNullOrWhiteSpace(smtpUri.UserName))
{
mailSenderConfiguration.UseDefaultCredentials = false;
mailSenderConfiguration.Credentials = new NetworkCredential(
smtpUri.UserName,
smtpUri.Password);
}
return new MailSender(mailSenderConfiguration);
}
else
{
var mailSenderConfiguration = new MailSenderConfiguration
{
DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory,
PickupDirectoryLocation = HostingEnvironment.MapPath("~/App_Data/Mail")
};
return new MailSender(mailSenderConfiguration);
}
});
Bind<IMailSender>()
.ToMethod(context => mailSenderThunk.Value);
Bind<IMessageService>()
.To<MessageService>();
Bind<IPrincipal>().ToMethod(context => HttpContext.Current.User);
switch (configuration.Current.StorageType)
{
case StorageType.FileSystem:
case StorageType.NotSpecified:
ConfigureForLocalFileSystem();
break;
case StorageType.AzureStorage:
ConfigureForAzureStorage(configuration);
break;
}
Bind<IFileSystemService>()
.To<FileSystemService>()
.InSingletonScope();
Bind<IPackageFileService>()
.To<PackageFileService>();
Bind<IEntityRepository<PackageOwnerRequest>>()
.To<EntityRepository<PackageOwnerRequest>>()
.InRequestScope();
Bind<IUploadFileService>()
.To<UploadFileService>();
// todo: bind all package curators by convention
Bind<IAutomaticPackageCurator>()
.To<WebMatrixPackageCurator>();
Bind<IAutomaticPackageCurator>()
.To<Windows8PackageCurator>();
// todo: bind all commands by convention
Bind<IAutomaticallyCuratePackageCommand>()
.To<AutomaticallyCuratePackageCommand>()
.InRequestScope();
Bind<IPackageIdsQuery>()
.To<PackageIdsQuery>()
.InRequestScope();
Bind<IPackageVersionsQuery>()
.To<PackageVersionsQuery>()
.InRequestScope();
}
private void ConfigureSearch(ConfigurationService configuration)
{
if (configuration.Current.SearchServiceUri == null)
{
Bind<ISearchService>()
.To<LuceneSearchService>()
.InRequestScope();
Bind<IIndexingService>()
.To<LuceneIndexingService>()
.InRequestScope();
}
else
{
Bind<ISearchService>()
.To<ExternalSearchService>()
.InRequestScope();
Bind<IIndexingService>()
.To<ExternalSearchService>()
.InRequestScope();
}
}
private void ConfigureForLocalFileSystem()
{
Bind<IFileStorageService>()
.To<FileSystemFileStorageService>()
.InSingletonScope();
// Ninject is doing some weird things with constructor selection without these.
// Anyone requesting an IReportService or IStatisticsService should be prepared
// to receive null anyway.
Bind<IReportService>().ToConstant(NullReportService.Instance);
Bind<IStatisticsService>().ToConstant(NullStatisticsService.Instance);
Bind<AuditingService>().ToConstant(AuditingService.None);
// If we're not using azure storage, then aggregate stats comes from SQL
Bind<IAggregateStatsService>()
.To<SqlAggregateStatsService>()
.InRequestScope();
}
private void ConfigureForAzureStorage(ConfigurationService configuration)
{
Bind<ICloudBlobClient>()
.ToMethod(_ => new CloudBlobClientWrapper(configuration.Current.AzureStorageConnectionString))
.InSingletonScope();
Bind<IFileStorageService>()
.To<CloudBlobFileStorageService>()
.InSingletonScope();
// when running on Windows Azure, we use a back-end job to calculate stats totals and store in the blobs
Bind<IAggregateStatsService>()
.ToMethod(_ => new JsonAggregateStatsService(configuration.Current.AzureStorageConnectionString))
.InSingletonScope();
// when running on Windows Azure, pull the statistics from the warehouse via storage
Bind<IReportService>()
.ToMethod(_ => new CloudReportService(configuration.Current.AzureStorageConnectionString))
.InSingletonScope();
Bind<IStatisticsService>()
.To<JsonStatisticsService>()
.InSingletonScope();
string instanceId;
try
{
instanceId = RoleEnvironment.CurrentRoleInstance.Id;
}
catch (Exception)
{
instanceId = Environment.MachineName;
}
var localIP = AuditActor.GetLocalIP().Result;
Bind<AuditingService>()
.ToMethod(_ => new CloudAuditingService(
instanceId, localIP, configuration.Current.AzureStorageConnectionString, CloudAuditingService.AspNetActorThunk))
.InSingletonScope();
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
namespace WebApplication2
{
/// <summary>
/// Summary description for frmEmergencyProcedures.
/// </summary>
public partial class frmOrgVis : System.Web.UI.Page
{
private static string strURL =
System.Configuration.ConfigurationSettings.AppSettings["local_url"];
private static string strDB =
System.Configuration.ConfigurationSettings.AppSettings["local_db"];
protected System.Web.UI.WebControls.Label Label2;
public SqlConnection epsDbConn=new SqlConnection(strDB);
protected void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
Load_Procedures();
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.DataGrid1.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_ItemCommand);
}
#endregion
private void Load_Procedures()
{
lblContents1.Text="Listed below are the Visibility Levels for various entities.";
lblContents2.Text="Each process has certain basic characteristics, including the level of detail"
+ " at which it is budgeted and progress monitored, service standards, and so on. Click on the"
+ " button titled 'Update' to maintain these characteristics for that process.";
lblContents3.Text="A given process is delivered in a series of steps."
+ " Click on the button titled 'Timetables' to identify and provide details about"
+ " steps for each process."
;
if (!IsPostBack)
{
loadData();
}
}
private void loadData ()
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="wms_RetrieveProfileSEProcs";
cmd.Connection=this.epsDbConn;
cmd.Parameters.Add ("@ProfileSEventsId",SqlDbType.Int);
cmd.Parameters["@ProfileSEventsId"].Value=Session["ProfileSEventsId"].ToString();
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter(cmd);
da.Fill(ds,"ProfileSEProcs");
Session["ds"] = ds;
DataGrid1.DataSource=ds;
DataGrid1.DataBind();
refreshGrid();
}
protected void btnExit_Click(object sender, System.EventArgs e)
{
Exit();
}
private void Exit()
{
updateGrid();
Response.Redirect (strURL + Session["CPSEProcs"].ToString() + ".aspx?");
}
private void refreshGrid()
{
foreach (DataGridItem i in DataGrid1.Items)
{
TextBox tb = (TextBox) (i.Cells[2].FindControl("txtSeq"));
Button btSt = (Button) (i.Cells[4].FindControl("btnStaff"));
Button btSe = (Button) (i.Cells[4].FindControl("btnServices"));
Button btRe = (Button) (i.Cells[4].FindControl("btnOther"));
//Button btTimetables = (Button) (i.Cells[4].FindControl("btnTimetables"));
if (i.Cells[1].Text == " ")
{
tb.Text="99";
}
else tb.Text=i.Cells[1].Text;
/*if (i.Cells[6].Text == "1")
{
}
else
{
btTimetables.Enabled = false;
btTimetables.BackColor=Color.Transparent;
btTimetables.Text="";
}*/
}
}
private void updateGrid()
{
foreach (DataGridItem i in DataGrid1.Items)
{
TextBox tb = (TextBox) (i.Cells[2].FindControl("txtSeq"));
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="wms_UpdateProfileSEProcsSeqNo";
cmd.Connection=this.epsDbConn;
cmd.Parameters.Add("@Id", SqlDbType.Int);
cmd.Parameters ["@Id"].Value=i.Cells[0].Text;
cmd.Parameters.Add("@Seq", SqlDbType.Int);
cmd.Parameters ["@Seq"].Value=Int32.Parse(tb.Text);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
}
}
private void DataGrid1_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
updateGrid();
if (e.CommandName == "Update")
{
Session["CUPSEP"]="frmProfileSEProcs";
Session["btnAction"]="Update";
Session["ProcessName"]=e.Item.Cells[3].Text;
Session["Id"]=e.Item.Cells[0].Text;
Response.Redirect (strURL + "frmUpdProfileSEProcs.aspx?");
}
else if (e.CommandName == "Staff")
{
Session["CPSEPStaff"]="frmProfileSEProcs";
Session["ProcessName"]=e.Item.Cells[3].Text;
Session["PSEPID"]=e.Item.Cells[0].Text;
Response.Redirect (strURL + "frmPSEPStaff.aspx?");
}
else if (e.CommandName == "Clients")
{
Session["CPSEPC"]="frmProfileSEProcs";
Session["ProcessName"]=e.Item.Cells[3].Text;
Session["PSEPID"]=e.Item.Cells[0].Text;
Response.Redirect (strURL + "frmPSEPClient.aspx?");
}
else if (e.CommandName == "Services")
{
Session["CPSEPSer"]="frmProfileSEProcs";
Session["ProcessName"]=e.Item.Cells[3].Text;
Session["PSEPID"]=e.Item.Cells[0].Text;
Response.Redirect (strURL + "frmPSEPSer.aspx?");
}
else if (e.CommandName == "Other")
{
Session["CPSEPRes"]="frmProfileSEProcs";
Session["ProcessName"]=e.Item.Cells[3].Text;
Session["PSEPID"]=e.Item.Cells[0].Text;
Response.Redirect (strURL + "frmPSEPRes.aspx?");
}
else if (e.CommandName == "Steps")
{
Session["ProfileSEProcsId"]=e.Item.Cells[0].Text;
Session["ProfileSEProcsName"]=e.Item.Cells[3].Text;
Session["CPSEPSteps"]="frmProfileSEProcs";
Response.Redirect (strURL + "frmPSEPSteps.aspx?");
}
else if (e.CommandName == "Remove")
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="wms_DeleteProfileSEProcs";
cmd.Connection=this.epsDbConn;
cmd.Parameters.Add ("@Id",SqlDbType.Int);
cmd.Parameters["@Id"].Value=e.Item.Cells[0].Text;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
loadData();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using NetGore.IO;
namespace NetGore.World
{
/// <summary>
/// Represents the ID of a Map.
/// </summary>
[Serializable]
[TypeConverter(typeof(MapIDTypeConverter))]
public struct MapID : IComparable<MapID>, IConvertible, IFormattable, IComparable<int>, IEquatable<int>
{
/// <summary>
/// Represents the largest possible value of MapID. This field is constant.
/// </summary>
public const int MaxValue = ushort.MaxValue;
/// <summary>
/// Represents the smallest possible value of MapID. This field is constant.
/// </summary>
public const int MinValue = ushort.MinValue;
/// <summary>
/// The underlying value. This contains the actual value of the struct instance.
/// </summary>
readonly ushort _value;
/// <summary>
/// Initializes a new instance of the <see cref="MapID"/> struct.
/// </summary>
/// <param name="value">Value to assign to the new <see cref="MapID"/>.</param>
/// <exception cref="ArgumentOutOfRangeException"><c>value</c> is out of range.</exception>
public MapID(int value)
{
if (value < MinValue || value > MaxValue)
throw new ArgumentOutOfRangeException("value");
_value = (ushort)value;
}
/// <summary>
/// Indicates whether this instance and a specified object are equal.
/// </summary>
/// <param name="other">Another object to compare to.</param>
/// <returns>
/// True if <paramref name="other"/> and this instance are the same type and represent the same value; otherwise, false.
/// </returns>
public bool Equals(MapID other)
{
return other._value == _value;
}
/// <summary>
/// Indicates whether this instance and a specified object are equal.
/// </summary>
/// <param name="obj">Another object to compare to.</param>
/// <returns>
/// True if <paramref name="obj"/> and this instance are the same type and represent the same value; otherwise, false.
/// </returns>
public override bool Equals(object obj)
{
return obj is MapID && this == (MapID)obj;
}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>
/// A 32-bit signed integer that is the hash code for this instance.
/// </returns>
public override int GetHashCode()
{
return _value.GetHashCode();
}
/// <summary>
/// Gets the raw internal value of this MapID.
/// </summary>
/// <returns>The raw internal value.</returns>
public ushort GetRawValue()
{
return _value;
}
/// <summary>
/// Reads an MapID from an IValueReader.
/// </summary>
/// <param name="reader">IValueReader to read from.</param>
/// <param name="name">Unique name of the value to read.</param>
/// <returns>The MapID read from the IValueReader.</returns>
public static MapID Read(IValueReader reader, string name)
{
var value = reader.ReadUShort(name);
return new MapID(value);
}
/// <summary>
/// Reads an MapID from an <see cref="IDataRecord"/>.
/// </summary>
/// <param name="reader"><see cref="IDataRecord"/> to get the value from.</param>
/// <param name="i">The index of the field to find.</param>
/// <returns>The MapID read from the <see cref="IDataRecord"/>.</returns>
public static MapID Read(IDataRecord reader, int i)
{
var value = reader.GetValue(i);
if (value is ushort)
return new MapID((ushort)value);
var convertedValue = Convert.ToUInt16(value);
return new MapID(convertedValue);
}
/// <summary>
/// Reads an MapID from an <see cref="IDataRecord"/>.
/// </summary>
/// <param name="reader"><see cref="IDataRecord"/> to get the value from.</param>
/// <param name="name">The name of the field to find.</param>
/// <returns>The MapID read from the <see cref="IDataRecord"/>.</returns>
public static MapID Read(IDataRecord reader, string name)
{
return Read(reader, reader.GetOrdinal(name));
}
/// <summary>
/// Reads an MapID from an IValueReader.
/// </summary>
/// <param name="bitStream">BitStream to read from.</param>
/// <returns>The MapID read from the BitStream.</returns>
public static MapID Read(BitStream bitStream)
{
var value = bitStream.ReadUShort();
return new MapID(value);
}
/// <summary>
/// Converts the numeric value of this instance to its equivalent string representation.
/// </summary>
/// <returns>The string representation of the value of this instance, consisting of a sequence
/// of digits ranging from 0 to 9, without leading zeroes.</returns>
public override string ToString()
{
return _value.ToString();
}
/// <summary>
/// Writes the MapID to an IValueWriter.
/// </summary>
/// <param name="writer">IValueWriter to write to.</param>
/// <param name="name">Unique name of the MapID that will be used to distinguish it
/// from other values when reading.</param>
public void Write(IValueWriter writer, string name)
{
writer.Write(name, _value);
}
/// <summary>
/// Writes the MapID to an IValueWriter.
/// </summary>
/// <param name="bitStream">BitStream to write to.</param>
public void Write(BitStream bitStream)
{
bitStream.Write(_value);
}
#region IComparable<int> Members
/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has the following meanings:
/// Value
/// Meaning
/// Less than zero
/// This object is less than the <paramref name="other"/> parameter.
/// Zero
/// This object is equal to <paramref name="other"/>.
/// Greater than zero
/// This object is greater than <paramref name="other"/>.
/// </returns>
public int CompareTo(int other)
{
return _value.CompareTo(other);
}
#endregion
#region IComparable<MapID> Members
/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the objects being compared.
/// The return value has the following meanings:
/// Value
/// Meaning
/// Less than zero
/// This object is less than the <paramref name="other"/> parameter.
/// Zero
/// This object is equal to <paramref name="other"/>.
/// Greater than zero
/// This object is greater than <paramref name="other"/>.
/// </returns>
public int CompareTo(MapID other)
{
return _value.CompareTo(other._value);
}
#endregion
#region IConvertible Members
/// <summary>
/// Returns the <see cref="T:System.TypeCode"/> for this instance.
/// </summary>
/// <returns>
/// The enumerated constant that is the <see cref="T:System.TypeCode"/> of the class or value type that implements this interface.
/// </returns>
public TypeCode GetTypeCode()
{
return _value.GetTypeCode();
}
/// <summary>
/// Converts the value of this instance to an equivalent Boolean value using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation
/// that supplies culture-specific formatting information.</param>
/// <returns>
/// A Boolean value equivalent to the value of this instance.
/// </returns>
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return ((IConvertible)_value).ToBoolean(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 8-bit unsigned integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 8-bit unsigned integer equivalent to the value of this instance.
/// </returns>
byte IConvertible.ToByte(IFormatProvider provider)
{
return ((IConvertible)_value).ToByte(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent Unicode character using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// A Unicode character equivalent to the value of this instance.
/// </returns>
char IConvertible.ToChar(IFormatProvider provider)
{
return ((IConvertible)_value).ToChar(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent <see cref="T:System.DateTime"/> using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// A <see cref="T:System.DateTime"/> instance equivalent to the value of this instance.
/// </returns>
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
return ((IConvertible)_value).ToDateTime(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent <see cref="T:System.Decimal"/> number using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information. </param>
/// <returns>
/// A <see cref="T:System.Decimal"/> number equivalent to the value of this instance.
/// </returns>
decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return ((IConvertible)_value).ToDecimal(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent double-precision floating-point number using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// A double-precision floating-point number equivalent to the value of this instance.
/// </returns>
double IConvertible.ToDouble(IFormatProvider provider)
{
return ((IConvertible)_value).ToDouble(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 16-bit signed integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 16-bit signed integer equivalent to the value of this instance.
/// </returns>
short IConvertible.ToInt16(IFormatProvider provider)
{
return ((IConvertible)_value).ToInt16(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 32-bit signed integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 32-bit signed integer equivalent to the value of this instance.
/// </returns>
int IConvertible.ToInt32(IFormatProvider provider)
{
return ((IConvertible)_value).ToInt32(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 64-bit signed integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 64-bit signed integer equivalent to the value of this instance.
/// </returns>
long IConvertible.ToInt64(IFormatProvider provider)
{
return ((IConvertible)_value).ToInt64(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 8-bit signed integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 8-bit signed integer equivalent to the value of this instance.
/// </returns>
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return ((IConvertible)_value).ToSByte(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent single-precision floating-point number using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information. </param>
/// <returns>
/// A single-precision floating-point number equivalent to the value of this instance.
/// </returns>
float IConvertible.ToSingle(IFormatProvider provider)
{
return ((IConvertible)_value).ToSingle(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent <see cref="T:System.String"/> using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// A <see cref="T:System.String"/> instance equivalent to the value of this instance.
/// </returns>
public string ToString(IFormatProvider provider)
{
return ((IConvertible)_value).ToString(provider);
}
/// <summary>
/// Converts the value of this instance to an <see cref="T:System.Object"/> of the specified <see cref="T:System.Type"/> that has an equivalent value, using the specified culture-specific formatting information.
/// </summary>
/// <param name="conversionType">The <see cref="T:System.Type"/> to which the value of this instance is converted.</param>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An <see cref="T:System.Object"/> instance of type <paramref name="conversionType"/> whose value is equivalent to the value of this instance.
/// </returns>
object IConvertible.ToType(Type conversionType, IFormatProvider provider)
{
return ((IConvertible)_value).ToType(conversionType, provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 16-bit unsigned integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 16-bit unsigned integer equivalent to the value of this instance.
/// </returns>
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return ((IConvertible)_value).ToUInt16(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 32-bit unsigned integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 32-bit unsigned integer equivalent to the value of this instance.
/// </returns>
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return ((IConvertible)_value).ToUInt32(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 64-bit unsigned integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 64-bit unsigned integer equivalent to the value of this instance.
/// </returns>
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return ((IConvertible)_value).ToUInt64(provider);
}
#endregion
#region IEquatable<int> Members
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
/// </returns>
public bool Equals(int other)
{
return _value.Equals(other);
}
#endregion
#region IFormattable Members
/// <summary>
/// Formats the value of the current instance using the specified format.
/// </summary>
/// <param name="format">The <see cref="T:System.String"/> specifying the format to use.
/// -or-
/// null to use the default format defined for the type of the <see cref="T:System.IFormattable"/> implementation.
/// </param>
/// <param name="formatProvider">The <see cref="T:System.IFormatProvider"/> to use to format the value.
/// -or-
/// null to obtain the numeric format information from the current locale setting of the operating system.
/// </param>
/// <returns>
/// A <see cref="T:System.String"/> containing the value of the current instance in the specified format.
/// </returns>
public string ToString(string format, IFormatProvider formatProvider)
{
return _value.ToString(format, formatProvider);
}
#endregion
/// <summary>
/// Implements operator ++.
/// </summary>
/// <param name="l">The MapID to increment.</param>
/// <returns>The incremented MapID.</returns>
public static MapID operator ++(MapID l)
{
return new MapID(l._value + 1);
}
/// <summary>
/// Implements operator --.
/// </summary>
/// <param name="l">The MapID to decrement.</param>
/// <returns>The decremented MapID.</returns>
public static MapID operator --(MapID l)
{
return new MapID(l._value - 1);
}
/// <summary>
/// Implements operator +.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>Result of the left side plus the right side.</returns>
public static MapID operator +(MapID left, MapID right)
{
return new MapID(left._value + right._value);
}
/// <summary>
/// Implements operator -.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>Result of the left side minus the right side.</returns>
public static MapID operator -(MapID left, MapID right)
{
return new MapID(left._value - right._value);
}
/// <summary>
/// Implements operator ==.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the two arguments are equal.</returns>
public static bool operator ==(MapID left, int right)
{
return left._value == right;
}
/// <summary>
/// Implements operator !=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the two arguments are not equal.</returns>
public static bool operator !=(MapID left, int right)
{
return left._value != right;
}
/// <summary>
/// Implements operator ==.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the two arguments are equal.</returns>
public static bool operator ==(int left, MapID right)
{
return left == right._value;
}
/// <summary>
/// Implements operator !=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the two arguments are not equal.</returns>
public static bool operator !=(int left, MapID right)
{
return left != right._value;
}
/// <summary>
/// Casts a MapID to an Int32.
/// </summary>
/// <param name="MapID">MapID to cast.</param>
/// <returns>The Int32.</returns>
public static explicit operator int(MapID MapID)
{
return MapID._value;
}
/// <summary>
/// Casts an Int32 to a MapID.
/// </summary>
/// <param name="value">Int32 to cast.</param>
/// <returns>The MapID.</returns>
public static explicit operator MapID(int value)
{
return new MapID(value);
}
/// <summary>
/// Implements the operator >.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the left argument is greater than the right.</returns>
public static bool operator >(int left, MapID right)
{
return left > right._value;
}
/// <summary>
/// Implements the operator <.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the right argument is greater than the left.</returns>
public static bool operator <(int left, MapID right)
{
return left < right._value;
}
/// <summary>
/// Implements the operator >.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the left argument is greater than the right.</returns>
public static bool operator >(MapID left, MapID right)
{
return left._value > right._value;
}
/// <summary>
/// Implements the operator <.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the right argument is greater than the left.</returns>
public static bool operator <(MapID left, MapID right)
{
return left._value < right._value;
}
/// <summary>
/// Implements the operator >.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the left argument is greater than the right.</returns>
public static bool operator >(MapID left, int right)
{
return left._value > right;
}
/// <summary>
/// Implements the operator <.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the right argument is greater than the left.</returns>
public static bool operator <(MapID left, int right)
{
return left._value < right;
}
/// <summary>
/// Implements the operator >=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the left argument is greater than or equal to the right.</returns>
public static bool operator >=(int left, MapID right)
{
return left >= right._value;
}
/// <summary>
/// Implements the operator <=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the right argument is greater than or equal to the left.</returns>
public static bool operator <=(int left, MapID right)
{
return left <= right._value;
}
/// <summary>
/// Implements the operator >=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the left argument is greater than or equal to the right.</returns>
public static bool operator >=(MapID left, int right)
{
return left._value >= right;
}
/// <summary>
/// Implements the operator <=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the right argument is greater than or equal to the left.</returns>
public static bool operator <=(MapID left, int right)
{
return left._value <= right;
}
/// <summary>
/// Implements the operator >=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the left argument is greater than or equal to the right.</returns>
public static bool operator >=(MapID left, MapID right)
{
return left._value >= right._value;
}
/// <summary>
/// Implements the operator <=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the right argument is greater than or equal to the left.</returns>
public static bool operator <=(MapID left, MapID right)
{
return left._value <= right._value;
}
/// <summary>
/// Implements operator !=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the two arguments are not equal.</returns>
public static bool operator !=(MapID left, MapID right)
{
return left._value != right._value;
}
/// <summary>
/// Implements operator ==.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the two arguments are equal.</returns>
public static bool operator ==(MapID left, MapID right)
{
return left._value == right._value;
}
}
/// <summary>
/// Adds extensions to some data I/O objects for performing Read and Write operations for the MapID.
/// All of the operations are implemented in the MapID struct. These extensions are provided
/// purely for the convenience of accessing all the I/O operations from the same place.
/// </summary>
public static class MapIDReadWriteExtensions
{
/// <summary>
/// Gets the value in the <paramref name="dict"/> entry at the given <paramref name="key"/> as type MapID.
/// </summary>
/// <typeparam name="T">The key Type.</typeparam>
/// <param name="dict">The IDictionary.</param>
/// <param name="key">The key for the value to get.</param>
/// <returns>The value at the given <paramref name="key"/> parsed as a MapID.</returns>
public static MapID AsMapID<T>(this IDictionary<T, string> dict, T key)
{
return Parser.Invariant.ParseMapID(dict[key]);
}
/// <summary>
/// Tries to get the value in the <paramref name="dict"/> entry at the given <paramref name="key"/> as type MapID.
/// </summary>
/// <typeparam name="T">The key Type.</typeparam>
/// <param name="dict">The IDictionary.</param>
/// <param name="key">The key for the value to get.</param>
/// <param name="defaultValue">The value to use if the value at the <paramref name="key"/> could not be parsed.</param>
/// <returns>The value at the given <paramref name="key"/> parsed as an int, or the
/// <paramref name="defaultValue"/> if the <paramref name="key"/> did not exist in the <paramref name="dict"/>
/// or the value at the given <paramref name="key"/> could not be parsed.</returns>
public static MapID AsMapID<T>(this IDictionary<T, string> dict, T key, MapID defaultValue)
{
string value;
if (!dict.TryGetValue(key, out value))
return defaultValue;
MapID parsed;
if (!Parser.Invariant.TryParse(value, out parsed))
return defaultValue;
return parsed;
}
/// <summary>
/// Reads the MapID from an <see cref="IDataRecord"/>.
/// </summary>
/// <param name="r"><see cref="IDataRecord"/> to read the MapID from.</param>
/// <param name="i">The field index to read.</param>
/// <returns>The MapID read from the <see cref="IDataRecord"/>.</returns>
public static MapID GetMapID(this IDataRecord r, int i)
{
return MapID.Read(r, i);
}
/// <summary>
/// Reads the MapID from an <see cref="IDataRecord"/>.
/// </summary>
/// <param name="r"><see cref="IDataRecord"/> to read the MapID from.</param>
/// <param name="name">The name of the field to read the value from.</param>
/// <returns>The MapID read from the <see cref="IDataRecord"/>.</returns>
public static MapID GetMapID(this IDataRecord r, string name)
{
return MapID.Read(r, name);
}
/// <summary>
/// Parses the MapID from a string.
/// </summary>
/// <param name="parser">The Parser to use.</param>
/// <param name="value">The string to parse.</param>
/// <returns>The MapID parsed from the string.</returns>
public static MapID ParseMapID(this Parser parser, string value)
{
return new MapID(parser.ParseUShort(value));
}
/// <summary>
/// Reads the MapID from a BitStream.
/// </summary>
/// <param name="bitStream">BitStream to read the MapID from.</param>
/// <returns>The MapID read from the BitStream.</returns>
public static MapID ReadMapID(this BitStream bitStream)
{
return MapID.Read(bitStream);
}
/// <summary>
/// Reads the MapID from an IValueReader.
/// </summary>
/// <param name="valueReader">IValueReader to read the MapID from.</param>
/// <param name="name">The unique name of the value to read.</param>
/// <returns>The MapID read from the IValueReader.</returns>
public static MapID ReadMapID(this IValueReader valueReader, string name)
{
return MapID.Read(valueReader, name);
}
/// <summary>
/// Tries to parse the MapID from a string.
/// </summary>
/// <param name="parser">The Parser to use.</param>
/// <param name="value">The string to parse.</param>
/// <param name="outValue">If this method returns true, contains the parsed MapID.</param>
/// <returns>True if the parsing was successfully; otherwise false.</returns>
public static bool TryParse(this Parser parser, string value, out MapID outValue)
{
ushort tmp;
var ret = parser.TryParse(value, out tmp);
outValue = new MapID(tmp);
return ret;
}
/// <summary>
/// Writes a MapID to a BitStream.
/// </summary>
/// <param name="bitStream">BitStream to write to.</param>
/// <param name="value">MapID to write.</param>
public static void Write(this BitStream bitStream, MapID value)
{
value.Write(bitStream);
}
/// <summary>
/// Writes a MapID to a IValueWriter.
/// </summary>
/// <param name="valueWriter">IValueWriter to write to.</param>
/// <param name="name">Unique name of the MapID that will be used to distinguish it
/// from other values when reading.</param>
/// <param name="value">MapID to write.</param>
public static void Write(this IValueWriter valueWriter, string name, MapID value)
{
value.Write(valueWriter, name);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Threading;
namespace Apache.Geode.Client.UnitTests
{
using NUnit.Framework;
using Apache.Geode.DUnitFramework;
using Apache.Geode.Client.Tests;
using Apache.Geode.Client;
using QueryStatics = Apache.Geode.Client.Tests.QueryStatics;
using QueryCategory = Apache.Geode.Client.Tests.QueryCategory;
using QueryStrings = Apache.Geode.Client.Tests.QueryStrings;
[TestFixture]
[Category("group1")]
[Category("unicast_only")]
[Category("generics")]
public class ThinClientQueryTests : ThinClientRegionSteps
{
#region Private members
private UnitProcess m_client1;
private UnitProcess m_client2;
private static string[] QueryRegionNames = { "Portfolios", "Positions", "Portfolios2",
"Portfolios3" };
private static string QERegionName = "Portfolios";
#endregion
protected override ClientBase[] GetClients()
{
m_client1 = new UnitProcess();
m_client2 = new UnitProcess();
return new ClientBase[] { m_client1, m_client2 };
}
[TestFixtureSetUp]
public override void InitTests()
{
base.InitTests();
}
[TearDown]
public override void EndTest()
{
m_client1.Call(Close);
m_client2.Call(Close);
CacheHelper.StopJavaServers();
base.EndTest();
}
[SetUp]
public override void InitTest()
{
m_client1.Call(InitClient);
m_client2.Call(InitClient);
}
#region Functions invoked by the tests
public void InitClient()
{
CacheHelper.Init();
CacheHelper.DCache.TypeRegistry.RegisterTypeGeneric(Portfolio.CreateDeserializable);
CacheHelper.DCache.TypeRegistry.RegisterTypeGeneric(Position.CreateDeserializable);
CacheHelper.DCache.TypeRegistry.RegisterPdxType(PortfolioPdx.CreateDeserializable);
CacheHelper.DCache.TypeRegistry.RegisterPdxType(PositionPdx.CreateDeserializable);
}
public void StepOneQE(string locators, bool isPdx)
{
m_isPdx = isPdx;
try
{
var poolFail = CacheHelper.DCache.GetPoolManager().CreateFactory().Create("_TESTFAILPOOL_", CacheHelper.DCache);
var qsFail = poolFail.GetQueryService();
var qryFail = qsFail.NewQuery<object>("select distinct * from /" + QERegionName);
var resultsFail = qryFail.Execute();
Assert.Fail("Since no endpoints defined, so exception expected");
}
catch (IllegalStateException ex)
{
Util.Log("Got expected exception: {0}", ex);
}
catch (Exception e) {
Util.Log("Caught unexpected exception: {0}", e);
throw e;
}
CacheHelper.CreateTCRegion_Pool<object, object>(QERegionName, true, true,
null, locators, "__TESTPOOL1_", true);
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(QERegionName);
if (!m_isPdx)
{
Portfolio p1 = new Portfolio(1, 100);
Portfolio p2 = new Portfolio(2, 100);
Portfolio p3 = new Portfolio(3, 100);
Portfolio p4 = new Portfolio(4, 100);
region["1"] = p1;
region["2"] = p2;
region["3"] = p3;
region["4"] = p4;
}
else
{
PortfolioPdx p1 = new PortfolioPdx(1, 100);
PortfolioPdx p2 = new PortfolioPdx(2, 100);
PortfolioPdx p3 = new PortfolioPdx(3, 100);
PortfolioPdx p4 = new PortfolioPdx(4, 100);
region["1"] = p1;
region["2"] = p2;
region["3"] = p3;
region["4"] = p4;
}
var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();
Query<object> qry = qs.NewQuery<object>("select distinct * from /" + QERegionName);
ISelectResults<object> results = qry.Execute();
Int32 count = results.Size;
Assert.AreEqual(4, count, "Expected 4 as number of portfolio objects.");
// Bring down the region
region.GetLocalView().DestroyRegion();
}
public void StepTwoQE()
{
var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();
Util.Log("Going to execute the query");
Query<object> qry = qs.NewQuery<object>("select distinct * from /" + QERegionName);
ISelectResults<object> results = qry.Execute();
Int32 count = results.Size;
Assert.AreEqual(4, count, "Expected 4 as number of portfolio objects.");
}
public void StepOne(string locators, bool isPdx)
{
m_isPdx = isPdx;
CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[0], true, true,
null, locators, "__TESTPOOL1_", true);
CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[1], true, true,
null, locators, "__TESTPOOL1_", true);
CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[2], true, true,
null, locators, "__TESTPOOL1_", true);
CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[3], true, true,
null, locators, "__TESTPOOL1_", true);
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(QueryRegionNames[0]);
Apache.Geode.Client.RegionAttributes<object, object> regattrs = region.Attributes;
region.CreateSubRegion(QueryRegionNames[1], regattrs);
}
public void StepTwo(bool isPdx)
{
m_isPdx = isPdx;
IRegion<object, object> region0 = CacheHelper.GetRegion<object, object>(QueryRegionNames[0]);
IRegion<object, object> subRegion0 = (IRegion<object, object>)region0.GetSubRegion(QueryRegionNames[1]);
IRegion<object, object> region1 = CacheHelper.GetRegion<object, object>(QueryRegionNames[1]);
IRegion<object, object> region2 = CacheHelper.GetRegion<object, object>(QueryRegionNames[2]);
IRegion<object, object> region3 = CacheHelper.GetRegion<object, object>(QueryRegionNames[3]);
QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache);
Util.Log("SetSize {0}, NumSets {1}.", qh.PortfolioSetSize,
qh.PortfolioNumSets);
if (!m_isPdx)
{
qh.PopulatePortfolioData(region0, qh.PortfolioSetSize,
qh.PortfolioNumSets);
qh.PopulatePositionData(subRegion0, qh.PortfolioSetSize,
qh.PortfolioNumSets);
qh.PopulatePositionData(region1, qh.PortfolioSetSize,
qh.PortfolioNumSets);
qh.PopulatePortfolioData(region2, qh.PortfolioSetSize,
qh.PortfolioNumSets);
qh.PopulatePortfolioData(region3, qh.PortfolioSetSize,
qh.PortfolioNumSets);
}
else
{
qh.PopulatePortfolioPdxData(region0, qh.PortfolioSetSize,
qh.PortfolioNumSets);
qh.PopulatePositionPdxData(subRegion0, qh.PortfolioSetSize,
qh.PortfolioNumSets);
qh.PopulatePositionPdxData(region1, qh.PortfolioSetSize,
qh.PortfolioNumSets);
qh.PopulatePortfolioPdxData(region2, qh.PortfolioSetSize,
qh.PortfolioNumSets);
qh.PopulatePortfolioPdxData(region3, qh.PortfolioSetSize,
qh.PortfolioNumSets);
}
}
public void StepTwoQT()
{
IRegion<object, object> region0 = CacheHelper.GetRegion<object, object>(QueryRegionNames[0]);
IRegion<object, object> subRegion0 = region0.GetSubRegion(QueryRegionNames[1]);
QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache);
if (!m_isPdx)
{
qh.PopulatePortfolioData(region0, 100, 20, 100);
qh.PopulatePositionData(subRegion0, 100, 20);
}
else
{
qh.PopulatePortfolioPdxData(region0, 100, 20, 100);
qh.PopulatePositionPdxData(subRegion0, 100, 20);
}
}
public void StepThreeRS()
{
bool ErrorOccurred = false;
QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache);
var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();
int qryIdx = 0;
foreach (QueryStrings qrystr in QueryStatics.ResultSetQueries)
{
if (qrystr.Category == QueryCategory.Unsupported)
{
Util.Log("Skipping query index {0} because it is unsupported.", qryIdx);
qryIdx++;
continue;
}
if (m_isPdx == true)
{
if (qryIdx == 2 || qryIdx == 3 || qryIdx == 4)
{
Util.Log("Skipping query index {0} for Pdx because it is function type.", qryIdx);
qryIdx++;
continue;
}
}
Util.Log("Evaluating query index {0}. Query string {1}", qryIdx, qrystr.Query);
Query<object> query = qs.NewQuery<object>(qrystr.Query);
ISelectResults<object> results = query.Execute();
int expectedRowCount = qh.IsExpectedRowsConstantRS(qryIdx) ?
QueryStatics.ResultSetRowCounts[qryIdx] : QueryStatics.ResultSetRowCounts[qryIdx] * qh.PortfolioNumSets;
if (!qh.VerifyRS(results, expectedRowCount))
{
ErrorOccurred = true;
Util.Log("Query verify failed for query index {0}.", qryIdx);
qryIdx++;
continue;
}
ResultSet<object> rs = results as ResultSet<object>;
foreach (object item in rs)
{
if (!m_isPdx)
{
Portfolio port = item as Portfolio;
if (port == null)
{
Position pos = item as Position;
if (pos == null)
{
string cs = item.ToString();
if (cs == null)
{
Util.Log("Query got other/unknown object.");
}
else
{
Util.Log("Query got string : {0}.", cs);
}
}
else
{
Util.Log("Query got Position object with secId {0}, shares {1}.", pos.SecId, pos.SharesOutstanding);
}
}
else
{
Util.Log("Query got Portfolio object with ID {0}, pkid {1}.", port.ID, port.Pkid);
}
}
else
{
PortfolioPdx port = item as PortfolioPdx;
if (port == null)
{
PositionPdx pos = item as PositionPdx;
if (pos == null)
{
string cs = item.ToString();
if (cs == null)
{
Util.Log("Query got other/unknown object.");
}
else
{
Util.Log("Query got string : {0}.", cs);
}
}
else
{
Util.Log("Query got Position object with secId {0}, shares {1}.", pos.secId, pos.getSharesOutstanding);
}
}
else
{
Util.Log("Query got Portfolio object with ID {0}, pkid {1}.", port.ID, port.Pkid);
}
}
}
qryIdx++;
}
Assert.IsFalse(ErrorOccurred, "One or more query validation errors occurred.");
}
public void StepThreePQRS()
{
bool ErrorOccurred = false;
QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache);
var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();
int qryIdx = 0;
foreach (QueryStrings paramqrystr in QueryStatics.ResultSetParamQueries)
{
if (paramqrystr.Category == QueryCategory.Unsupported)
{
Util.Log("Skipping query index {0} because it is unsupported.", qryIdx);
qryIdx++;
continue;
}
Util.Log("Evaluating query index {0}. {1}", qryIdx, paramqrystr.Query);
Query<object> query = qs.NewQuery<object>(paramqrystr.Query);
//Populate the parameter list (paramList) for the query.
object[] paramList = new object[QueryStatics.NoOfQueryParam[qryIdx]];
int numVal = 0;
for (int ind = 0; ind < QueryStatics.NoOfQueryParam[qryIdx]; ind++)
{
//Util.Log("NIL::PQRS:: QueryStatics.QueryParamSet[{0},{1}] = {2}", qryIdx, ind, QueryStatics.QueryParamSet[qryIdx][ind]);
try
{
numVal = Convert.ToInt32(QueryStatics.QueryParamSet[qryIdx][ind]);
paramList[ind] = numVal;
//Util.Log("NIL::PQRS::361 Interger Args:: paramList[0] = {1}", ind, paramList[ind]);
}
catch (FormatException)
{
//Console.WriteLine("Param string is not a sequence of digits.");
paramList[ind] = (System.String)QueryStatics.QueryParamSet[qryIdx][ind];
//Util.Log("NIL::PQRS:: Interger Args:: routingObj[0] = {1}", ind, routingObj[ind].ToString());
}
}
ISelectResults<object> results = query.Execute(paramList);
//Varify the result
int expectedRowCount = qh.IsExpectedRowsConstantPQRS(qryIdx) ?
QueryStatics.ResultSetPQRowCounts[qryIdx] : QueryStatics.ResultSetPQRowCounts[qryIdx] * qh.PortfolioNumSets;
if (!qh.VerifyRS(results, expectedRowCount))
{
ErrorOccurred = true;
Util.Log("Query verify failed for query index {0}.", qryIdx);
qryIdx++;
continue;
}
ResultSet<object> rs = results as ResultSet<object>;
foreach (object item in rs)
{
if (!m_isPdx)
{
Portfolio port = item as Portfolio;
if (port == null)
{
Position pos = item as Position;
if (pos == null)
{
string cs = item as string;
if (cs == null)
{
Util.Log("Query got other/unknown object.");
}
else
{
Util.Log("Query got string : {0}.", cs);
}
}
else
{
Util.Log("Query got Position object with secId {0}, shares {1}.", pos.SecId, pos.SharesOutstanding);
}
}
else
{
Util.Log("Query got Portfolio object with ID {0}, pkid {1}.", port.ID, port.Pkid);
}
}
else
{
PortfolioPdx port = item as PortfolioPdx;
if (port == null)
{
PositionPdx pos = item as PositionPdx;
if (pos == null)
{
string cs = item as string;
if (cs == null)
{
Util.Log("Query got other/unknown object.");
}
else
{
Util.Log("Query got string : {0}.", cs);
}
}
else
{
Util.Log("Query got PositionPdx object with secId {0}, shares {1}.", pos.secId, pos.getSharesOutstanding);
}
}
else
{
Util.Log("Query got PortfolioPdx object with ID {0}, pkid {1}.", port.ID, port.Pkid);
}
}
}
qryIdx++;
}
Assert.IsFalse(ErrorOccurred, "One or more query validation errors occurred.");
}
public void StepFourRS()
{
bool ErrorOccurred = false;
QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache);
var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();
int qryIdx = 0;
foreach (QueryStrings qrystr in QueryStatics.ResultSetQueries)
{
if (qrystr.Category != QueryCategory.Unsupported)
{
qryIdx++;
continue;
}
Util.Log("Evaluating unsupported query index {0}.", qryIdx);
Query<object> query = qs.NewQuery<object>(qrystr.Query);
try
{
ISelectResults<object> results = query.Execute();
Util.Log("Query exception did not occur for index {0}.", qryIdx);
ErrorOccurred = true;
qryIdx++;
}
catch (GeodeException)
{
// ok, exception expected, do nothing.
qryIdx++;
}
catch (Exception)
{
Util.Log("Query unexpected exception occurred for index {0}.", qryIdx);
ErrorOccurred = true;
qryIdx++;
}
}
Assert.IsFalse(ErrorOccurred, "Query expected exceptions did not occur.");
}
public void StepFourPQRS()
{
bool ErrorOccurred = false;
QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache);
var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();
int qryIdx = 0;
foreach (QueryStrings qrystr in QueryStatics.ResultSetParamQueries)
{
if (qrystr.Category != QueryCategory.Unsupported)
{
qryIdx++;
continue;
}
Util.Log("Evaluating unsupported query index {0}.", qryIdx);
Query<object> query = qs.NewQuery<object>(qrystr.Query);
object[] paramList = new object[QueryStatics.NoOfQueryParam[qryIdx]];
Int32 numVal = 0;
for (Int32 ind = 0; ind < QueryStatics.NoOfQueryParam[qryIdx]; ind++)
{
//Util.Log("NIL::PQRS:: QueryStatics.QueryParamSet[{0},{1}] = {2}", qryIdx, ind, QueryStatics.QueryParamSet[qryIdx, ind]);
try
{
numVal = Convert.ToInt32(QueryStatics.QueryParamSet[qryIdx][ind]);
paramList[ind] = numVal;
//Util.Log("NIL::PQRS:: Interger Args:: paramList[0] = {1}", ind, paramList[ind]);
}
catch (FormatException)
{
//Console.WriteLine("Param string is not a sequence of digits.");
paramList[ind] = (System.String)QueryStatics.QueryParamSet[qryIdx][ind];
//Util.Log("NIL::PQRS:: Interger Args:: paramList[0] = {1}", ind, paramList[ind].ToString());
}
}
try
{
ISelectResults<object> results = query.Execute(paramList);
Util.Log("Query exception did not occur for index {0}.", qryIdx);
ErrorOccurred = true;
qryIdx++;
}
catch (GeodeException)
{
// ok, exception expected, do nothing.
qryIdx++;
}
catch (Exception)
{
Util.Log("Query unexpected exception occurred for index {0}.", qryIdx);
ErrorOccurred = true;
qryIdx++;
}
}
Assert.IsFalse(ErrorOccurred, "Query expected exceptions did not occur.");
}
public void StepThreeSS()
{
bool ErrorOccurred = false;
QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache);
var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();
int qryIdx = 0;
foreach (QueryStrings qrystr in QueryStatics.StructSetQueries)
{
if (qrystr.Category == QueryCategory.Unsupported)
{
Util.Log("Skipping query index {0} because it is unsupported.", qryIdx);
qryIdx++;
continue;
}
if (m_isPdx == true)
{
if (qryIdx == 12 || qryIdx == 4 || qryIdx == 7 || qryIdx == 22 || qryIdx == 30 || qryIdx == 34)
{
Util.Log("Skipping query index {0} for pdx because it has function.", qryIdx);
qryIdx++;
continue;
}
}
Util.Log("Evaluating query index {0}. {1}", qryIdx, qrystr.Query);
Query<object> query = qs.NewQuery<object>(qrystr.Query);
ISelectResults<object> results = query.Execute();
int expectedRowCount = qh.IsExpectedRowsConstantSS(qryIdx) ?
QueryStatics.StructSetRowCounts[qryIdx] : QueryStatics.StructSetRowCounts[qryIdx] * qh.PortfolioNumSets;
if (!qh.VerifySS(results, expectedRowCount, QueryStatics.StructSetFieldCounts[qryIdx]))
{
ErrorOccurred = true;
Util.Log("Query verify failed for query index {0}.", qryIdx);
qryIdx++;
continue;
}
StructSet<object> ss = results as StructSet<object>;
if (ss == null)
{
Util.Log("Zero records found for query index {0}, continuing.", qryIdx);
qryIdx++;
continue;
}
uint rows = 0;
Int32 fields = 0;
foreach (Struct si in ss)
{
rows++;
fields = (Int32)si.Length;
}
Util.Log("Query index {0} has {1} rows and {2} fields.", qryIdx, rows, fields);
qryIdx++;
}
Assert.IsFalse(ErrorOccurred, "One or more query validation errors occurred.");
}
public void StepThreePQSS()
{
bool ErrorOccurred = false;
QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache);
var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();
int qryIdx = 0;
foreach (QueryStrings qrystr in QueryStatics.StructSetParamQueries)
{
if (qrystr.Category == QueryCategory.Unsupported)
{
Util.Log("Skipping query index {0} because it is unsupported.", qryIdx);
qryIdx++;
continue;
}
Util.Log("Evaluating query index {0}. {1}", qryIdx, qrystr.Query);
if (m_isPdx == true)
{
if (qryIdx == 16)
{
Util.Log("Skipping query index {0} for pdx because it has function.", qryIdx);
qryIdx++;
continue;
}
}
Query<object> query = qs.NewQuery<object>(qrystr.Query);
//Populate the param list, paramList for parameterized query
object[] paramList = new object[QueryStatics.NoOfQueryParamSS[qryIdx]];
Int32 numVal = 0;
for (Int32 ind = 0; ind < QueryStatics.NoOfQueryParamSS[qryIdx]; ind++)
{
//Util.Log("NIL::PQRS:: QueryStatics.QueryParamSetSS[{0},{1}] = {2}", qryIdx, ind, QueryStatics.QueryParamSetSS[qryIdx, ind]);
try
{
numVal = Convert.ToInt32(QueryStatics.QueryParamSetSS[qryIdx][ind]);
paramList[ind] = numVal;
//Util.Log("NIL::PQRS:: Interger Args:: paramList[0] = {1}", ind, paramList[ind]);
}
catch (FormatException)
{
//Console.WriteLine("Param string is not a sequence of digits.");
paramList[ind] = (System.String)QueryStatics.QueryParamSetSS[qryIdx][ind];
//Util.Log("NIL::PQRS:: Interger Args:: paramList[0] = {1}", ind, paramList[ind].ToString());
}
}
ISelectResults<object> results = query.Execute(paramList);
int expectedRowCount = qh.IsExpectedRowsConstantPQSS(qryIdx) ?
QueryStatics.StructSetPQRowCounts[qryIdx] : QueryStatics.StructSetPQRowCounts[qryIdx] * qh.PortfolioNumSets;
if (!qh.VerifySS(results, expectedRowCount, QueryStatics.StructSetPQFieldCounts[qryIdx]))
{
ErrorOccurred = true;
Util.Log("Query verify failed for query index {0}.", qryIdx);
qryIdx++;
continue;
}
StructSet<object> ss = results as StructSet<object>;
if (ss == null)
{
Util.Log("Zero records found for query index {0}, continuing.", qryIdx);
qryIdx++;
continue;
}
uint rows = 0;
Int32 fields = 0;
foreach (Struct si in ss)
{
rows++;
fields = (Int32)si.Length;
}
Util.Log("Query index {0} has {1} rows and {2} fields.", qryIdx, rows, fields);
qryIdx++;
}
Assert.IsFalse(ErrorOccurred, "One or more query validation errors occurred.");
}
public void StepFourSS()
{
bool ErrorOccurred = false;
QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache);
var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();
int qryIdx = 0;
foreach (QueryStrings qrystr in QueryStatics.StructSetQueries)
{
if (qrystr.Category != QueryCategory.Unsupported)
{
qryIdx++;
continue;
}
Util.Log("Evaluating unsupported query index {0}.", qryIdx);
Query<object> query = qs.NewQuery<object>(qrystr.Query);
try
{
ISelectResults<object> results = query.Execute();
Util.Log("Query exception did not occur for index {0}.", qryIdx);
ErrorOccurred = true;
qryIdx++;
}
catch (GeodeException)
{
// ok, exception expected, do nothing.
qryIdx++;
}
catch (Exception)
{
Util.Log("Query unexpected exception occurred for index {0}.", qryIdx);
ErrorOccurred = true;
qryIdx++;
}
}
Assert.IsFalse(ErrorOccurred, "Query expected exceptions did not occur.");
}
public void StepFourPQSS()
{
bool ErrorOccurred = false;
QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache);
var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();
int qryIdx = 0;
foreach (QueryStrings qrystr in QueryStatics.StructSetParamQueries)
{
if (qrystr.Category != QueryCategory.Unsupported)
{
qryIdx++;
continue;
}
Util.Log("Evaluating unsupported query index {0}.", qryIdx);
Query<object> query = qs.NewQuery<object>(qrystr.Query);
//Populate the param list
object[] paramList = new object[QueryStatics.NoOfQueryParamSS[qryIdx]];
Int32 numVal = 0;
for (Int32 ind = 0; ind < QueryStatics.NoOfQueryParamSS[qryIdx]; ind++)
{
//Util.Log("NIL::PQRS:: QueryStatics.QueryParamSetSS[{0},{1}] = {2}", qryIdx, ind, QueryStatics.QueryParamSetSS[qryIdx, ind]);
try
{
numVal = Convert.ToInt32(QueryStatics.QueryParamSetSS[qryIdx][ind]);
paramList[ind] = numVal;
//Util.Log("NIL::PQRS:: Interger Args:: paramList[0] = {1}", ind, paramList[ind]);
}
catch (FormatException)
{
//Console.WriteLine("Param string is not a sequence of digits.");
paramList[ind] = (System.String)QueryStatics.QueryParamSetSS[qryIdx][ind];
//Util.Log("NIL::PQRS:: Interger Args:: paramList[0] = {1}", ind, paramList[ind].ToString());
}
}
try
{
ISelectResults<object> results = query.Execute(paramList);
Util.Log("Query exception did not occur for index {0}.", qryIdx);
ErrorOccurred = true;
qryIdx++;
}
catch (GeodeException)
{
// ok, exception expected, do nothing.
qryIdx++;
}
catch (Exception)
{
Util.Log("Query unexpected exception occurred for index {0}.", qryIdx);
ErrorOccurred = true;
qryIdx++;
}
}
Assert.IsFalse(ErrorOccurred, "Query expected exceptions did not occur.");
}
public void KillServer()
{
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
}
public delegate void KillServerDelegate();
public void StepOneFailover(bool isPdx)
{
m_isPdx = isPdx;
// This is here so that Client1 registers information of the cacheserver
// that has been already started
CacheHelper.SetupJavaServers(true,
"cacheserver_remoteoqlN.xml",
"cacheserver_remoteoql2N.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[0], true, true, null,
CacheHelper.Locators, "__TESTPOOL1_", true);
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(QueryRegionNames[0]);
if (!m_isPdx)
{
Portfolio p1 = new Portfolio(1, 100);
Portfolio p2 = new Portfolio(2, 200);
Portfolio p3 = new Portfolio(3, 300);
Portfolio p4 = new Portfolio(4, 400);
region["1"] = p1;
region["2"] = p2;
region["3"] = p3;
region["4"] = p4;
}
else
{
PortfolioPdx p1 = new PortfolioPdx(1, 100);
PortfolioPdx p2 = new PortfolioPdx(2, 200);
PortfolioPdx p3 = new PortfolioPdx(3, 300);
PortfolioPdx p4 = new PortfolioPdx(4, 400);
region["1"] = p1;
region["2"] = p2;
region["3"] = p3;
region["4"] = p4;
}
}
public void StepTwoFailover()
{
CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1);
Util.Log("Cacheserver 2 started.");
IAsyncResult killRes = null;
KillServerDelegate ksd = new KillServerDelegate(KillServer);
var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();
for (int i = 0; i < 10000; i++)
{
Query<object> qry = qs.NewQuery<object>("select distinct * from /" + QueryRegionNames[0]);
ISelectResults<object> results = qry.Execute();
if (i == 10)
{
killRes = ksd.BeginInvoke(null, null);
}
Int32 resultSize = results.Size;
if (i % 100 == 0)
{
Util.Log("Iteration upto {0} done, result size is {1}", i, resultSize);
}
Assert.AreEqual(4, resultSize, "Result size is not 4!");
}
killRes.AsyncWaitHandle.WaitOne();
ksd.EndInvoke(killRes);
}
public void StepTwoPQFailover()
{
CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1);
Util.Log("Cacheserver 2 started.");
IAsyncResult killRes = null;
KillServerDelegate ksd = new KillServerDelegate(KillServer);
var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();
for (int i = 0; i < 10000; i++)
{
Query<object> qry = qs.NewQuery<object>("select distinct * from /" + QueryRegionNames[0] + " where ID > $1");
//Populate the param list
object[] paramList = new object[1];
paramList[0] = 1;
ISelectResults<object> results = qry.Execute(paramList);
if (i == 10)
{
killRes = ksd.BeginInvoke(null, null);
}
Int32 resultSize = results.Size;
if (i % 100 == 0)
{
Util.Log("Iteration upto {0} done, result size is {1}", i, resultSize);
}
Assert.AreEqual(3, resultSize, "Result size is not 3!");
}
killRes.AsyncWaitHandle.WaitOne();
ksd.EndInvoke(killRes);
}
public void StepThreeQT()
{
QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache);
var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();
Util.Log("query " + QueryStatics.ResultSetQueries[34].Query);
Query<object> query = qs.NewQuery<object>(QueryStatics.ResultSetQueries[34].Query);
try
{
Util.Log("EXECUTE 1 START for query: ", query.QueryString);
ISelectResults<object> results = query.Execute(TimeSpan.FromSeconds(3));
Util.Log("EXECUTE 1 STOP");
Util.Log("Result size is {0}", results.Size);
Assert.Fail("Didnt get expected timeout exception for first execute");
}
catch (GeodeException excp)
{
Util.Log("First execute expected exception: {0}", excp.Message);
}
}
public void StepFourQT()
{
QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache);
var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();
Query<object> query = qs.NewQuery<object>(QueryStatics.ResultSetQueries[35].Query);
try
{
Util.Log("EXECUTE 2 START for query: ", query.QueryString);
ISelectResults<object> results = query.Execute(TimeSpan.FromSeconds(850));
Util.Log("EXECUTE 2 STOP");
Util.Log("Result size is {0}", results.Size);
}
catch (GeodeException excp)
{
Assert.Fail("Second execute unwanted exception: {0}", excp.Message);
}
}
public void StepFiveQT()
{
QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache);
var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();
Query<object> query = qs.NewQuery<object>(QueryStatics.StructSetQueries[17].Query);
try
{
Util.Log("EXECUTE 3 START for query: ", query.QueryString);
ISelectResults<object> results = query.Execute(TimeSpan.FromSeconds(2));
Util.Log("EXECUTE 3 STOP");
Util.Log("Result size is {0}", results.Size);
Assert.Fail("Didnt get expected timeout exception for third execute");
}
catch (GeodeException excp)
{
Util.Log("Third execute expected exception: {0}", excp.Message);
}
}
public void StepSixQT()
{
QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache);
var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();
Query<object> query = qs.NewQuery<object>(QueryStatics.StructSetQueries[17].Query);
try
{
Util.Log("EXECUTE 4 START for query: ", query.QueryString);
ISelectResults<object> results = query.Execute(TimeSpan.FromSeconds(850));
Util.Log("EXECUTE 4 STOP");
Util.Log("Result size is {0}", results.Size);
}
catch (GeodeException excp)
{
Assert.Fail("Fourth execute unwanted exception: {0}", excp.Message);
}
}
public void StepThreePQT()
{
QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache);
var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();
Query<object> query = qs.NewQuery<object>(QueryStatics.StructSetParamQueries[5].Query);
try
{
Util.Log("EXECUTE 5 START for query: ", query.QueryString);
//Populate the param list, paramList for parameterized query
object[] paramList = new object[QueryStatics.NoOfQueryParamSS[5]];
Int32 numVal = 0;
for (Int32 ind = 0; ind < QueryStatics.NoOfQueryParamSS[5]; ind++)
{
try
{
numVal = Convert.ToInt32(QueryStatics.QueryParamSetSS[5][ind]);
paramList[ind] = numVal;
//Util.Log("NIL::PQRS:: Interger Args:: paramList[0] = {1}", ind, paramList[ind]);
}
catch (FormatException)
{
//Console.WriteLine("Param string is not a sequence of digits.");
paramList[ind] = (System.String)QueryStatics.QueryParamSetSS[5][ind];
//Util.Log("NIL::PQRS:: Interger Args:: paramList[0] = {1}", ind, paramList[ind].ToString());
}
}
ISelectResults<object> results = query.Execute(paramList, TimeSpan.FromSeconds(1));
Util.Log("EXECUTE 5 STOP");
Util.Log("Result size is {0}", results.Size);
Assert.Fail("Didnt get expected timeout exception for Fifth execute");
}
catch (GeodeException excp)
{
Util.Log("Fifth execute expected exception: {0}", excp.Message);
}
}
public void StepFourPQT()
{
QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache);
var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();
Query<object> query = qs.NewQuery<object>(QueryStatics.StructSetParamQueries[5].Query);
try
{
Util.Log("EXECUTE 6 START for query: ", query.QueryString);
//Populate the param list, paramList for parameterized query
object[] paramList = new object[QueryStatics.NoOfQueryParamSS[5]];
Int32 numVal = 0;
for (Int32 ind = 0; ind < QueryStatics.NoOfQueryParamSS[5]; ind++)
{
try
{
numVal = Convert.ToInt32(QueryStatics.QueryParamSetSS[5][ind]);
paramList[ind] = numVal;
//Util.Log("NIL::PQRS:: Interger Args:: paramList[0] = {1}", ind, paramList[ind]);
}
catch (FormatException)
{
//Console.WriteLine("Param string is not a sequence of digits.");
paramList[ind] = (System.String)QueryStatics.QueryParamSetSS[5][ind];
//Util.Log("NIL::PQRS:: Interger Args:: paramList[0] = {1}", ind, paramList[ind].ToString());
}
}
ISelectResults<object> results = query.Execute(paramList, TimeSpan.FromSeconds(850));
Util.Log("EXECUTE 6 STOP");
Util.Log("Result size is {0}", results.Size);
}
catch (GeodeException excp)
{
Assert.Fail("Sixth execute unwanted exception: {0}", excp.Message);
}
}
public void StepThreeRQ()
{
bool ErrorOccurred = false;
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(QueryRegionNames[0]);
int qryIdx = 0;
foreach (QueryStrings qrystr in QueryStatics.RegionQueries)
{
if (qrystr.Category == QueryCategory.Unsupported)
{
Util.Log("Skipping query index {0} because it is unsupported.", qryIdx);
qryIdx++;
continue;
}
Util.Log("Evaluating query index {0}. {1}", qryIdx, qrystr.Query);
if (m_isPdx)
{
if (qryIdx == 18)
{
Util.Log("Skipping query index {0} because it is unsupported for pdx type.", qryIdx);
qryIdx++;
continue;
}
}
ISelectResults<object> results = region.Query<object>(qrystr.Query);
if (results.Size != QueryStatics.RegionQueryRowCounts[qryIdx])
{
ErrorOccurred = true;
Util.Log("FAIL: Query # {0} expected result size is {1}, actual is {2}", qryIdx,
QueryStatics.RegionQueryRowCounts[qryIdx], results.Size);
qryIdx++;
continue;
}
qryIdx++;
}
Assert.IsFalse(ErrorOccurred, "One or more query validation errors occurred.");
try
{
ISelectResults<object> results = region.Query<object>("");
Assert.Fail("Expected IllegalArgumentException exception for empty predicate");
}
catch (IllegalArgumentException ex)
{
Util.Log("got expected IllegalArgumentException exception for empty predicate:");
Util.Log(ex.Message);
}
try
{
ISelectResults<object> results = region.Query<object>(QueryStatics.RegionQueries[0].Query, TimeSpan.FromSeconds(2200000));
Assert.Fail("Expected IllegalArgumentException exception for invalid timeout");
}
catch (IllegalArgumentException ex)
{
Util.Log("got expected IllegalArgumentException exception for invalid timeout:");
Util.Log(ex.Message);
}
try
{
ISelectResults<object> results = region.Query<object>("bad predicate");
Assert.Fail("Expected QueryException exception for wrong predicate");
}
catch (QueryException ex)
{
Util.Log("got expected QueryException exception for wrong predicate:");
Util.Log(ex.Message);
}
}
public void StepFourRQ()
{
bool ErrorOccurred = false;
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(QueryRegionNames[0]);
int qryIdx = 0;
foreach (QueryStrings qrystr in QueryStatics.RegionQueries)
{
if (qrystr.Category == QueryCategory.Unsupported)
{
Util.Log("Skipping query index {0} because it is unsupported.", qryIdx);
qryIdx++;
continue;
}
Util.Log("Evaluating query index {0}.{1}", qryIdx, qrystr.Query);
bool existsValue = region.ExistsValue(qrystr.Query);
bool expectedResult = QueryStatics.RegionQueryRowCounts[qryIdx] > 0 ? true : false;
if (existsValue != expectedResult)
{
ErrorOccurred = true;
Util.Log("FAIL: Query # {0} existsValue expected is {1}, actual is {2}", qryIdx,
expectedResult ? "true" : "false", existsValue ? "true" : "false");
qryIdx++;
continue;
}
qryIdx++;
}
Assert.IsFalse(ErrorOccurred, "One or more query validation errors occurred.");
try
{
bool existsValue = region.ExistsValue("");
Assert.Fail("Expected IllegalArgumentException exception for empty predicate");
}
catch (IllegalArgumentException ex)
{
Util.Log("got expected IllegalArgumentException exception for empty predicate:");
Util.Log(ex.Message);
}
try
{
bool existsValue = region.ExistsValue(QueryStatics.RegionQueries[0].Query, TimeSpan.FromSeconds(2200000));
Assert.Fail("Expected IllegalArgumentException exception for invalid timeout");
}
catch (IllegalArgumentException ex)
{
Util.Log("got expected IllegalArgumentException exception for invalid timeout:");
Util.Log(ex.Message);
}
try
{
bool existsValue = region.ExistsValue("bad predicate");
Assert.Fail("Expected QueryException exception for wrong predicate");
}
catch (QueryException ex)
{
Util.Log("got expected QueryException exception for wrong predicate:");
Util.Log(ex.Message);
}
}
public void StepFiveRQ()
{
bool ErrorOccurred = false;
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(QueryRegionNames[0]);
int qryIdx = 0;
foreach (QueryStrings qrystr in QueryStatics.RegionQueries)
{
if (qrystr.Category == QueryCategory.Unsupported)
{
Util.Log("Skipping query index {0} because it is unsupported.", qryIdx);
qryIdx++;
continue;
}
Util.Log("Evaluating query index {0}.", qryIdx);
try
{
Object result = region.SelectValue(qrystr.Query);
if (!(QueryStatics.RegionQueryRowCounts[qryIdx] == 0 ||
QueryStatics.RegionQueryRowCounts[qryIdx] == 1))
{
ErrorOccurred = true;
Util.Log("FAIL: Query # {0} expected query exception did not occur", qryIdx);
qryIdx++;
continue;
}
}
catch (QueryException)
{
if (QueryStatics.RegionQueryRowCounts[qryIdx] == 0 ||
QueryStatics.RegionQueryRowCounts[qryIdx] == 1)
{
ErrorOccurred = true;
Util.Log("FAIL: Query # {0} unexpected query exception occured", qryIdx);
qryIdx++;
continue;
}
}
catch (Exception)
{
ErrorOccurred = true;
Util.Log("FAIL: Query # {0} unexpected exception occured", qryIdx);
qryIdx++;
continue;
}
qryIdx++;
}
Assert.IsFalse(ErrorOccurred, "One or more query validation errors occurred.");
try
{
Object result = region.SelectValue("");
Assert.Fail("Expected IllegalArgumentException exception for empty predicate");
}
catch (IllegalArgumentException ex)
{
Util.Log("got expected IllegalArgumentException exception for empty predicate:");
Util.Log(ex.Message);
}
try
{
Object result = region.SelectValue(QueryStatics.RegionQueries[0].Query, TimeSpan.FromSeconds(2200000));
Assert.Fail("Expected IllegalArgumentException exception for invalid timeout");
}
catch (IllegalArgumentException ex)
{
Util.Log("got expected IllegalArgumentException exception for invalid timeout:");
Util.Log(ex.Message);
}
try
{
Object result = region.SelectValue("bad predicate");
Assert.Fail("Expected QueryException exception for wrong predicate");
}
catch (QueryException ex)
{
Util.Log("got expected QueryException exception for wrong predicate:");
Util.Log(ex.Message);
}
}
public void StepSixRQ()
{
bool ErrorOccurred = false;
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(QueryRegionNames[0]);
int qryIdx = 0;
foreach (QueryStrings qrystr in QueryStatics.RegionQueries)
{
if ((qrystr.Category != QueryCategory.Unsupported) || (qryIdx == 3))
{
qryIdx++;
continue;
}
Util.Log("Evaluating unsupported query index {0}.", qryIdx);
try
{
ISelectResults<object> results = region.Query<object>(qrystr.Query);
Util.Log("Query # {0} expected exception did not occur", qryIdx);
ErrorOccurred = true;
qryIdx++;
}
catch (QueryException)
{
// ok, exception expected, do nothing.
qryIdx++;
}
catch (Exception)
{
ErrorOccurred = true;
Util.Log("FAIL: Query # {0} unexpected exception occured", qryIdx);
qryIdx++;
}
}
Assert.IsFalse(ErrorOccurred, "Query expected exceptions did not occur.");
}
//private void CreateRegions(object p, object USE_ACK, object endPoint1, bool p_4)
//{
// throw new Exception("The method or operation is not implemented.");
//}
//public void CompareMap(CacheableHashMap map1, CacheableHashMap map2)
//{
// if (map1.Count != map2.Count)
// Assert.Fail("Number of Keys dont match");
// if (map1.Count == 0) return;
// foreach (KeyValuePair<ICacheableKey, IGeodeSerializable> entry in map1)
// {
// IGeodeSerializable value;
// if (!(map2.TryGetValue(entry.Key,out value)))
// {
// Assert.Fail("Key was not found");
// return;
// }
// if(entry.Value.Equals(value))
// {
// Assert.Fail("Value was not found");
// return;
// }
// }
//}
//public void GetAllRegionQuery()
//{
// IRegion<object, object> region0 = CacheHelper.GetVerifyRegion(QueryRegionNames[0]);
// IRegion<object, object> region1 = region0.GetSubRegion(QueryRegionNames[1] );
// IRegion<object, object> region2 = CacheHelper.GetVerifyRegion(QueryRegionNames[1]);
// IRegion<object, object> region3 = CacheHelper.GetVerifyRegion(QueryRegionNames[2]);
// IRegion<object, object> region4 = CacheHelper.GetVerifyRegion(QueryRegionNames[3]);
// string[] SecIds = Portfolio.SecIds;
// int NumSecIds = SecIds.Length;
// List<ICacheableKey> PosKeys = new List<ICacheableKey>();
// List<ICacheableKey> PortKeys = new List<ICacheableKey>();
// CacheableHashMap ExpectedPosMap = new CacheableHashMap();
// CacheableHashMap ExpectedPortMap = new CacheableHashMap();
// QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache);
// int SetSize = qh.PositionSetSize;
// int NumSets = qh.PositionNumSets;
// for (int set = 1; set <= NumSets; set++)
// {
// for (int current = 1; current <= SetSize; current++)
// {
// CacheableKey PosKey = "pos" + set + "-" + current;
// Position pos = new Position(SecIds[current % NumSecIds], current * 100 );
// PosKeys.Add(PosKey);
// ExpectedPosMap.Add(PosKey, pos);
// }
// }
// SetSize = qh.PortfolioSetSize;
// NumSets = qh.PortfolioNumSets;
// for (int set = 1; set <= NumSets; set++)
// {
// for (int current = 1; current <= SetSize; current++)
// {
// CacheableKey PortKey = "port" + set + "-" + current;
// Portfolio Port = new Portfolio(current,1);
// PortKeys.Add(PortKey);
// ExpectedPortMap.Add(PortKey, Port);
// }
// }
// CacheableHashMap ResMap = new CacheableHashMap();
// Dictionary<ICacheableKey, Exception> ExMap = new Dictionary<ICacheableKey, Exception>();
// region0.GetAll(PortKeys.ToArray(), ResMap, ExMap);
// CompareMap(ResMap, ExpectedPortMap);
// if (ExMap.Count != 0)
// {
// Assert.Fail("Expected No Exception");
// }
// ResMap.Clear();
// region1.GetAll(PosKeys.ToArray(), ResMap, ExMap);
// CompareMap(ResMap, ExpectedPosMap);
// if (ExMap.Count != 0)
// {
// Assert.Fail("Expected No Exception");
// }
// ResMap.Clear();
// region2.GetAll(PosKeys.ToArray(), ResMap, ExMap);
// CompareMap(ResMap, ExpectedPosMap);
// if (ExMap.Count != 0)
// {
// Assert.Fail("Expected No Exception");
// }
// ResMap.Clear();
// region3.GetAll(PortKeys.ToArray(), ResMap, ExMap);
// CompareMap(ResMap, ExpectedPortMap);
// if (ExMap.Count != 0)
// {
// Assert.Fail("Expected No Exception");
// }
// ResMap.Clear();
// region4.GetAll(PortKeys.ToArray(), ResMap, ExMap);
// CompareMap(ResMap, ExpectedPortMap);
// if (ExMap.Count != 0)
// {
// Assert.Fail("Expected No Exception");
// }
// ResMap.Clear();
//}
#endregion
void runRemoteQueryRS()
{
CacheHelper.SetupJavaServers(true, "remotequeryN.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client1.Call(StepOne, CacheHelper.Locators, m_isPdx);
Util.Log("StepOne complete.");
m_client1.Call(StepTwo, m_isPdx);
Util.Log("StepTwo complete.");
m_client1.Call(StepThreeRS);
Util.Log("StepThree complete.");
m_client1.Call(StepFourRS);
Util.Log("StepFour complete.");
m_client1.Call(Close);
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
}
void runRemoteParamQueryRS()
{
CacheHelper.SetupJavaServers(true, "remotequeryN.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client1.Call(StepOne, CacheHelper.Locators, m_isPdx);
Util.Log("StepOne complete.");
m_client1.Call(StepTwo, m_isPdx);
Util.Log("StepTwo complete.");
m_client1.Call(StepThreePQRS);
Util.Log("StepThree complete.");
m_client1.Call(StepFourPQRS);
Util.Log("StepFour complete.");
m_client1.Call(Close);
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
}
void runRemoteQuerySS()
{
CacheHelper.SetupJavaServers(true, "remotequeryN.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client2.Call(StepOne, CacheHelper.Locators, m_isPdx);
Util.Log("StepOne complete.");
m_client2.Call(StepTwo, m_isPdx);
Util.Log("StepTwo complete.");
m_client2.Call(StepThreeSS);
Util.Log("StepThree complete.");
m_client2.Call(StepFourSS);
Util.Log("StepFour complete.");
//m_client2.Call(GetAllRegionQuery);
m_client2.Call(Close);
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
}
void runRemoteParamQuerySS()
{
CacheHelper.SetupJavaServers(true, "remotequeryN.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client2.Call(StepOne, CacheHelper.Locators, m_isPdx);
Util.Log("StepOne complete.");
m_client2.Call(StepTwo, m_isPdx);
Util.Log("StepTwo complete.");
m_client2.Call(StepThreePQSS);
Util.Log("StepThree complete.");
m_client2.Call(StepFourPQSS);
Util.Log("StepFour complete.");
//m_client2.Call(GetAllRegionQuery);
m_client2.Call(Close);
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
}
void runRemoteQueryFailover()
{
try
{
m_client1.Call(StepOneFailover, m_isPdx);
Util.Log("StepOneFailover complete.");
m_client1.Call(StepTwoFailover);
Util.Log("StepTwoFailover complete.");
m_client1.Call(Close);
Util.Log("Client closed");
}
finally
{
m_client1.Call(CacheHelper.StopJavaServers);
m_client1.Call(CacheHelper.StopJavaLocator, 1);
}
}
void runRemoteParamQueryFailover()
{
try
{
m_client1.Call(StepOneFailover, m_isPdx);
Util.Log("StepOneFailover complete.");
m_client1.Call(StepTwoPQFailover);
Util.Log("StepTwoPQFailover complete.");
m_client1.Call(Close);
Util.Log("Client closed");
}
finally
{
m_client1.Call(CacheHelper.StopJavaServers);
m_client1.Call(CacheHelper.StopJavaLocator, 1);
}
}
void runQueryExclusiveness()
{
CacheHelper.SetupJavaServers(true, "cacheserver_remoteoqlN.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client1.Call(StepOneQE, CacheHelper.Locators, m_isPdx);
Util.Log("StepOne complete.");
m_client1.Call(StepTwoQE);
Util.Log("StepTwo complete.");
m_client1.Call(Close);
Util.Log("Client closed");
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
}
void runQueryTimeout()
{
CacheHelper.SetupJavaServers(true, "remotequeryN.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client1.Call(StepOne, CacheHelper.Locators, m_isPdx);
Util.Log("StepOne complete.");
m_client1.Call(StepTwoQT);
Util.Log("StepTwo complete.");
m_client1.Call(StepThreeQT);
Util.Log("StepThree complete.");
Thread.Sleep(150000); // sleep 2.5min to allow server query to complete
m_client1.Call(StepFourQT);
Util.Log("StepFour complete.");
m_client1.Call(StepFiveQT);
Util.Log("StepFive complete.");
Thread.Sleep(60000); // sleep 1min to allow server query to complete
m_client1.Call(StepSixQT);
Util.Log("StepSix complete.");
m_client1.Call(Close);
Util.Log("Client closed");
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
}
void runParamQueryTimeout()
{
CacheHelper.SetupJavaServers(true, "remotequeryN.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started. WITH PDX = " + m_isPdx);
m_client1.Call(StepOne, CacheHelper.Locators, m_isPdx);
Util.Log("StepOne complete.");
m_client1.Call(StepTwoQT);
Util.Log("StepTwo complete.");
m_client1.Call(StepThreePQT);
Util.Log("StepThreePQT complete.");
Thread.Sleep(60000); // sleep 1min to allow server query to complete
m_client1.Call(StepFourPQT);
Util.Log("StepFourPQT complete.");
m_client1.Call(Close);
Util.Log("Client closed");
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
}
void runRegionQuery()
{
CacheHelper.SetupJavaServers(true, "remotequeryN.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client2.Call(StepOne, CacheHelper.Locators, m_isPdx);
Util.Log("StepOne complete.");
m_client2.Call(StepTwo, m_isPdx);
Util.Log("StepTwo complete.");
//Extra Step
//m_client1.Call(StepExtra);
m_client2.Call(StepThreeRQ);
Util.Log("StepThree complete.");
m_client2.Call(StepFourRQ);
Util.Log("StepFour complete.");
m_client2.Call(StepFiveRQ);
Util.Log("StepFive complete.");
m_client2.Call(StepSixRQ);
Util.Log("StepSix complete.");
m_client2.Call(Close);
Util.Log("Client closed");
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
}
static bool m_isPdx = false;
[Test]
public void RemoteQueryRSWithPdx()
{
m_isPdx = true;
runRemoteQueryRS();
}
[Test]
public void RemoteQueryRSWithoutPdx()
{
m_isPdx = false;
runRemoteQueryRS();
}
[Test]
public void RemoteParamQueryRSWithPdx()
{
m_isPdx = true;
runRemoteParamQueryRS();
}
[Test]
public void RemoteParamQueryRSWithoutPdx()
{
m_isPdx = false;
runRemoteParamQueryRS();
}
[Test]
public void RemoteQuerySSWithPdx()
{
m_isPdx = true;
runRemoteQuerySS();
}
[Test]
public void RemoteQuerySSWithoutPdx()
{
m_isPdx = false;
runRemoteQuerySS();
}
[Test]
public void RemoteParamQuerySSWithoutPdx()
{
m_isPdx = false;
runRemoteParamQuerySS();
}
[Test]
public void RemoteParamQuerySSWithPdx()
{
m_isPdx = true;
runRemoteParamQuerySS();
}
[Test]
public void RemoteQueryFailoverWithPdx()
{
m_isPdx = true;
runRemoteQueryFailover();
}
[Test]
public void RemoteQueryFailoverWithoutPdx()
{
m_isPdx = false;
runRemoteQueryFailover();
}
[Test]
[Ignore]
public void RemoteParamQueryFailover()
{
for (int i = 0; i < 2; i++)
{
runRemoteParamQueryFailover();
m_isPdx = true;
}
m_isPdx = false;
}
[Test]
public void QueryExclusivenessWithoutPdx()
{
m_isPdx = false;
runQueryExclusiveness();
}
[Test]
public void QueryExclusivenessWithPdx()
{
m_isPdx = true;
runQueryExclusiveness();
}
[Test]
[Ignore]
public void QueryTimeout()
{
for (int i = 0; i < 2; i++)
{
runQueryTimeout();
m_isPdx = true;
}
m_isPdx = false;
}
[Test]
[Ignore]
public void ParamQueryTimeout()
{
for (int i = 0; i < 2; i++)
{
runParamQueryTimeout();
m_isPdx = true;
}
m_isPdx = false;
}
[Test]
public void RegionQueryWithPdx()
{
m_isPdx = true;
runRegionQuery();
}
[Test]
public void RegionQueryWithoutPdx()
{
m_isPdx = false;
runRegionQuery();
}
}
}
| |
#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 Property : TypeMember, INodeWithParameters, IExplicitMember
{
protected ParameterDeclarationCollection _parameters;
protected Method _getter;
protected Method _setter;
protected TypeReference _type;
protected ExplicitMemberInfo _explicitInfo;
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public Property CloneNode()
{
return (Property)Clone();
}
/// <summary>
/// <see cref="Node.CleanClone"/>
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public Property CleanClone()
{
return (Property)base.CleanClone();
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public NodeType NodeType
{
get { return NodeType.Property; }
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public void Accept(IAstVisitor visitor)
{
visitor.OnProperty(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 = ( Property)node;
if (_modifiers != other._modifiers) return NoMatch("Property._modifiers");
if (_name != other._name) return NoMatch("Property._name");
if (!Node.AllMatch(_attributes, other._attributes)) return NoMatch("Property._attributes");
if (!Node.AllMatch(_parameters, other._parameters)) return NoMatch("Property._parameters");
if (!Node.Matches(_getter, other._getter)) return NoMatch("Property._getter");
if (!Node.Matches(_setter, other._setter)) return NoMatch("Property._setter");
if (!Node.Matches(_type, other._type)) return NoMatch("Property._type");
if (!Node.Matches(_explicitInfo, other._explicitInfo)) return NoMatch("Property._explicitInfo");
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 (_attributes != null)
{
Attribute item = existing as Attribute;
if (null != item)
{
Attribute newItem = (Attribute)newNode;
if (_attributes.Replace(item, newItem))
{
return true;
}
}
}
if (_parameters != null)
{
ParameterDeclaration item = existing as ParameterDeclaration;
if (null != item)
{
ParameterDeclaration newItem = (ParameterDeclaration)newNode;
if (_parameters.Replace(item, newItem))
{
return true;
}
}
}
if (_getter == existing)
{
this.Getter = (Method)newNode;
return true;
}
if (_setter == existing)
{
this.Setter = (Method)newNode;
return true;
}
if (_type == existing)
{
this.Type = (TypeReference)newNode;
return true;
}
if (_explicitInfo == existing)
{
this.ExplicitInfo = (ExplicitMemberInfo)newNode;
return true;
}
return false;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public object Clone()
{
Property clone = new Property();
clone._lexicalInfo = _lexicalInfo;
clone._endSourceLocation = _endSourceLocation;
clone._documentation = _documentation;
clone._isSynthetic = _isSynthetic;
clone._entity = _entity;
if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone();
clone._modifiers = _modifiers;
clone._name = _name;
if (null != _attributes)
{
clone._attributes = _attributes.Clone() as AttributeCollection;
clone._attributes.InitializeParent(clone);
}
if (null != _parameters)
{
clone._parameters = _parameters.Clone() as ParameterDeclarationCollection;
clone._parameters.InitializeParent(clone);
}
if (null != _getter)
{
clone._getter = _getter.Clone() as Method;
clone._getter.InitializeParent(clone);
}
if (null != _setter)
{
clone._setter = _setter.Clone() as Method;
clone._setter.InitializeParent(clone);
}
if (null != _type)
{
clone._type = _type.Clone() as TypeReference;
clone._type.InitializeParent(clone);
}
if (null != _explicitInfo)
{
clone._explicitInfo = _explicitInfo.Clone() as ExplicitMemberInfo;
clone._explicitInfo.InitializeParent(clone);
}
return clone;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override internal void ClearTypeSystemBindings()
{
_annotations = null;
_entity = null;
if (null != _attributes)
{
_attributes.ClearTypeSystemBindings();
}
if (null != _parameters)
{
_parameters.ClearTypeSystemBindings();
}
if (null != _getter)
{
_getter.ClearTypeSystemBindings();
}
if (null != _setter)
{
_setter.ClearTypeSystemBindings();
}
if (null != _type)
{
_type.ClearTypeSystemBindings();
}
if (null != _explicitInfo)
{
_explicitInfo.ClearTypeSystemBindings();
}
}
[System.Xml.Serialization.XmlArray]
[System.Xml.Serialization.XmlArrayItem(typeof(ParameterDeclaration))]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public ParameterDeclarationCollection Parameters
{
get { return _parameters ?? (_parameters = new ParameterDeclarationCollection(this)); }
set
{
if (_parameters != value)
{
_parameters = value;
if (null != _parameters)
{
_parameters.InitializeParent(this);
}
}
}
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public Method Getter
{
get { return _getter; }
set
{
if (_getter != value)
{
_getter = value;
if (null != _getter)
{
_getter.InitializeParent(this);
}
}
}
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public Method Setter
{
get { return _setter; }
set
{
if (_setter != value)
{
_setter = value;
if (null != _setter)
{
_setter.InitializeParent(this);
}
}
}
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public TypeReference Type
{
get { return _type; }
set
{
if (_type != value)
{
_type = value;
if (null != _type)
{
_type.InitializeParent(this);
}
}
}
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public ExplicitMemberInfo ExplicitInfo
{
get { return _explicitInfo; }
set
{
if (_explicitInfo != value)
{
_explicitInfo = value;
if (null != _explicitInfo)
{
_explicitInfo.InitializeParent(this);
}
}
}
}
}
}
| |
#region Disclaimer/Info
///////////////////////////////////////////////////////////////////////////////////////////////////
// Subtext WebLog
//
// Subtext is an open source weblog system that is a fork of the .TEXT
// weblog system.
//
// For updated news and information please visit http://subtextproject.com/
// Subtext is hosted at Google Code at http://code.google.com/p/subtext/
// The development mailing list is at [email protected]
//
// This project is licensed under the BSD license. See the License.txt file for more information.
///////////////////////////////////////////////////////////////////////////////////////////////////
#endregion
using System;
using System.Configuration;
using System.Globalization;
using System.Web;
using System.Web.UI.WebControls;
using log4net;
using Subtext.Extensibility;
using Subtext.Framework.Components;
using Subtext.Framework.Data;
using Subtext.Framework.Logging;
using Subtext.Framework.Security;
using Subtext.Framework.Services;
using Subtext.Framework.Text;
using Subtext.Framework.Web;
using Subtext.Web.Controls;
using Subtext.Web.UI.ViewModels;
using Image = System.Web.UI.WebControls.Image;
namespace Subtext.Web.UI.Controls
{
/// <summary>
/// Codebehind for the control that displays comments/trackbacks/pingbacks.
/// </summary>
public class Comments : BaseControl, ICommentControl
{
const string Anchortag = "<a name=\"{0}\"></a>";
const string Linktag = "<a title=\"permalink: {0}\" href=\"{1}\">#</a>";
static readonly ILog Log = new Log();
private CommentViewModel _comment;
protected Repeater CommentList;
private GravatarService _gravatarService;
protected Literal NoCommentMessage;
public bool IsEditEnabled
{
get { return Request.IsAuthenticated && User.IsAdministrator(); }
}
/// <summary>
/// If the currecnt comment was written by the author,
/// writes the specified css class
/// </summary>
/// <returns></returns>
protected string AuthorCssClass
{
get { return Comment.IsBlogAuthor ? " author" : ""; }
}
public CommentViewModel Comment
{
get { return _comment; }
}
private Entry RealEntry
{
get
{
if (_entry == null)
{
_entry = Cacher.GetEntryFromRequest(true, SubtextContext);
if (_entry == null)
{
HttpHelper.SetFileNotFoundResponse();
}
}
return _entry;
}
}
Entry _entry;
public string EditUrl(CommentViewModel feedback)
{
string url = AdminUrl.FeedbackEdit(feedback.Id);
return VirtualPathUtility.ToAbsolute(StringHelper.LeftBefore(url, "?")) + "?" +
url.RightAfter("?");
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
_gravatarService = new GravatarService(ConfigurationManager.AppSettings);
if (Blog.CommentsEnabled)
{
BindFeedback(true);
}
else
{
Visible = false;
}
}
internal void BindFeedback(bool fromCache)
{
Entry entry = RealEntry;
if (entry != null && entry.AllowComments)
{
BindFeedback(entry, fromCache);
}
else
{
Visible = false;
}
}
// Customizes the display row for each comment.
protected void CommentsCreated(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
var feedbackItem = (FeedbackItem)e.Item.DataItem;
_comment = new CommentViewModel(feedbackItem, SubtextContext);
if (feedbackItem != null)
{
var title = (Literal)(e.Item.FindControl("Title"));
if (title != null)
{
// we should probably change skin format to dynamically wire up to
// skin located title and permalinks at some point
title.Text = string.Format(CultureInfo.InvariantCulture, "{2} {0}{1}",
Anchor(feedbackItem.Id),
feedbackItem.Title,
Link(feedbackItem.Title, Url.FeedbackUrl(feedbackItem)));
}
//Shows the name of the commenter with a link if provided.
var namelink = (HyperLink)e.Item.FindControl("NameLink");
if (namelink != null)
{
if (feedbackItem.SourceUrl != null)
{
namelink.NavigateUrl = feedbackItem.SourceUrl.ToString();
ControlHelper.SetTitleIfNone(namelink, feedbackItem.SourceUrl.ToString());
}
if (feedbackItem.FeedbackType == FeedbackType.Comment)
{
namelink.Text = feedbackItem.Author;
ControlHelper.SetTitleIfNone(namelink, feedbackItem.Author);
}
else if (feedbackItem.FeedbackType == FeedbackType.PingTrack)
{
namelink.Text = !String.IsNullOrEmpty(feedbackItem.Author)
? feedbackItem.Author
: "Pingback/TrackBack";
ControlHelper.SetTitleIfNone(namelink, "PingBack/TrackBack");
}
if (feedbackItem.IsBlogAuthor)
{
HtmlHelper.AppendCssClass(namelink, "author");
}
}
var postDate = (Literal)(e.Item.FindControl("PostDate"));
if (postDate != null)
{
var dateCreated = feedbackItem.DateCreated;
postDate.Text = dateCreated.ToShortDateString() + " " +
dateCreated.ToShortTimeString();
}
var post = e.Item.FindControl("PostText") as Literal;
if (post != null)
{
if (!String.IsNullOrEmpty(feedbackItem.Body))
{
post.Text = feedbackItem.Body;
if (feedbackItem.Body.Length == 0 && feedbackItem.FeedbackType == FeedbackType.PingTrack)
{
post.Text = "Pingback / Trackback";
}
}
}
if (_gravatarService.Enabled)
{
var gravatarImage = e.Item.FindControl("GravatarImg") as Image;
if (gravatarImage != null)
{
string ip;
if (feedbackItem.IpAddress != null)
{
ip = feedbackItem.IpAddress.ToString();
}
else
{
ip = string.Format("{0} {1}", DateTime.UtcNow.Millisecond, DateTime.UtcNow.Second);
}
string gravatarUrl = gravatarUrl = _gravatarService.GenerateUrl(feedbackItem.Email);
gravatarImage.Attributes.Remove("PlaceHolderImage");
gravatarImage.ImageUrl = gravatarUrl;
gravatarImage.Visible = true;
}
}
if (Request.IsAuthenticated && User.IsAdministrator())
{
var editCommentTextLink = (HyperLink)(e.Item.FindControl("EditCommentTextLink"));
if (editCommentTextLink != null)
{
editCommentTextLink.NavigateUrl = AdminUrl.FeedbackEdit(feedbackItem.Id);
if (String.IsNullOrEmpty(editCommentTextLink.Text))
{
editCommentTextLink.Text = "Edit Comment " +
feedbackItem.Id.ToString(CultureInfo.InstalledUICulture);
}
ControlHelper.SetTitleIfNone(editCommentTextLink, "Click to edit this entry.");
}
var editCommentImgLink = (HyperLink)(e.Item.FindControl("EditCommentImgLink"));
if (editCommentImgLink != null)
{
editCommentImgLink.NavigateUrl = AdminUrl.FeedbackEdit(feedbackItem.Id);
if (String.IsNullOrEmpty(editCommentImgLink.ImageUrl))
{
editCommentImgLink.ImageUrl = Url.EditIconUrl();
}
ControlHelper.SetTitleIfNone(editCommentImgLink,
"Click to edit comment " +
feedbackItem.Id.ToString(CultureInfo.InstalledUICulture));
}
}
}
}
}
private static string Link(string title, string link)
{
if (link == null)
{
return string.Empty;
}
return string.Format(Linktag, title, link);
}
// GC: xhmtl format wreaking havoc in non-xhtml pages in non-IE, changed to non nullable format
private static string Anchor(int id)
{
return string.Format(Anchortag, id);
}
internal void BindFeedback(Entry entry, bool fromCache)
{
try
{
CommentList.DataSource = fromCache ? Cacher.GetFeedback(entry, SubtextContext) : Repository.GetFeedbackForEntry(entry);
CommentList.DataBind();
if (CommentList.Items.Count == 0)
{
if (entry.CommentingClosed)
{
Controls.Clear();
}
else
{
CommentList.Visible = false;
NoCommentMessage.Text = "No comments posted yet.";
}
}
else
{
CommentList.Visible = true;
NoCommentMessage.Text = string.Empty;
}
}
catch (Exception e)
{
Log.Error(e.Message, e);
Visible = false;
}
}
public void InvalidateFeedbackCache()
{
Cacher.InvalidateFeedback(RealEntry, SubtextContext);
}
[Obsolete("This will get removed in the next version")]
protected void RemoveComment_ItemCommand(object sender, EventArgs e)
{
}
}
}
| |
using System;
//
// System.Net.RequestStream
//
// Author:
// Gonzalo Paniagua Javier ([email protected])
//
// Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.IO;
using System.Net.Sockets;
using System.Runtime.InteropServices;
namespace Mono.Upnp.Http {
class RequestStream : Stream
{
byte [] buffer;
int offset;
int length;
long remaining_body;
bool disposed;
Stream stream;
internal RequestStream (Stream stream, byte [] buffer, int offset, int length)
: this (stream, buffer, offset, length, -1)
{
}
internal RequestStream (Stream stream, byte [] buffer, int offset, int length, long contentlength)
{
this.stream = stream;
this.buffer = buffer;
this.offset = offset;
this.length = length;
this.remaining_body = contentlength;
}
public override bool CanRead {
get { return true; }
}
public override bool CanSeek {
get { return false; }
}
public override bool CanWrite {
get { return false; }
}
public override long Length {
get { throw new NotSupportedException (); }
}
public override long Position {
get { throw new NotSupportedException (); }
set { throw new NotSupportedException (); }
}
public override void Close ()
{
disposed = true;
}
public override void Flush ()
{
}
// Returns 0 if we can keep reading from the base stream,
// > 0 if we read something from the buffer.
// -1 if we had a content length set and we finished reading that many bytes.
int FillFromBuffer (byte [] buffer, int off, int count)
{
if (buffer == null)
throw new ArgumentNullException ("buffer");
if (off < 0)
throw new ArgumentOutOfRangeException ("offset", "< 0");
if (count < 0)
throw new ArgumentOutOfRangeException ("count", "< 0");
int len = buffer.Length;
if (off > len)
throw new ArgumentException ("destination offset is beyond array size");
if (off > len - count)
throw new ArgumentException ("Reading would overrun buffer");
if (this.remaining_body == 0)
return -1;
if (this.length == 0)
return 0;
int size = Math.Min (this.length, count);
if (this.remaining_body > 0)
size = (int) Math.Min (size, this.remaining_body);
if (this.offset > this.buffer.Length - size) {
size = Math.Min (size, this.buffer.Length - this.offset);
}
if (size == 0)
return 0;
Buffer.BlockCopy (this.buffer, this.offset, buffer, off, size);
this.offset += size;
this.length -= size;
if (this.remaining_body > 0)
remaining_body -= size;
return size;
}
public override int Read ([In,Out] byte[] buffer, int offset, int count)
{
if (disposed)
throw new ObjectDisposedException (typeof (RequestStream).ToString ());
// Call FillFromBuffer to check for buffer boundaries even when remaining_body is 0
int nread = FillFromBuffer (buffer, offset, count);
if (nread == -1) { // No more bytes available (Content-Length)
return 0;
} else if (nread > 0) {
return nread;
}
nread = stream.Read (buffer, offset, count);
if (nread > 0 && remaining_body > 0)
remaining_body -= nread;
return nread;
}
public override IAsyncResult BeginRead (byte [] buffer, int offset, int count,
AsyncCallback cback, object state)
{
if (disposed)
throw new ObjectDisposedException (typeof (RequestStream).ToString ());
int nread = FillFromBuffer (buffer, offset, count);
if (nread > 0 || nread == -1) {
HttpStreamAsyncResult ares = new HttpStreamAsyncResult ();
ares.Buffer = buffer;
ares.Offset = offset;
ares.Count = count;
ares.Callback = cback;
ares.State = state;
ares.SynchRead = Math.Max (0, nread);
ares.Complete ();
return ares;
}
// Avoid reading past the end of the request to allow
// for HTTP pipelining
if (remaining_body >= 0 && count > remaining_body)
count = (int) Math.Min (Int32.MaxValue, remaining_body);
return stream.BeginRead (buffer, offset, count, cback, state);
}
public override int EndRead (IAsyncResult ares)
{
if (disposed)
throw new ObjectDisposedException (typeof (RequestStream).ToString ());
if (ares == null)
throw new ArgumentNullException ("async_result");
if (ares is HttpStreamAsyncResult) {
HttpStreamAsyncResult r = (HttpStreamAsyncResult) ares;
if (!ares.IsCompleted)
ares.AsyncWaitHandle.WaitOne ();
return r.SynchRead;
}
// Close on exception?
int nread = stream.EndRead (ares);
if (remaining_body > 0 && nread > 0)
remaining_body -= nread;
return nread;
}
public override long Seek (long offset, SeekOrigin origin)
{
throw new NotSupportedException ();
}
public override void SetLength (long value)
{
throw new NotSupportedException ();
}
public override void Write (byte[] buffer, int offset, int count)
{
throw new NotSupportedException ();
}
public override IAsyncResult BeginWrite (byte [] buffer, int offset, int count,
AsyncCallback cback, object state)
{
throw new NotSupportedException ();
}
public override void EndWrite (IAsyncResult async_result)
{
throw new NotSupportedException ();
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
namespace Microsoft.SPOT.Hardware
{
public enum Button
{
/// </summary>
None = 0,
VK_LBUTTON = 0x01,
VK_RBUTTON = 0x02,
VK_CANCEL = 0x03,
VK_MBUTTON = 0x04, /* NOT contiguous with L & RBUTTON */
VK_BACK = 0x08,
VK_TAB = 0x09,
VK_CLEAR = 0x0C,
VK_RETURN = 0x0D,
VK_SHIFT = 0x10,
VK_CONTROL = 0x11,
VK_MENU = 0x12,
VK_PAUSE = 0x13,
VK_CAPITAL = 0x14,
VK_KANA = 0x15,
VK_HANGEUL = 0x15, /* old name - should be here for compatibility */
VK_HANGUL = 0x15,
VK_JUNJA = 0x17,
VK_FINAL = 0x18,
VK_HANJA = 0x19,
VK_KANJI = 0x19,
VK_ESCAPE = 0x1B,
VK_CONVERT = 0x1c,
VK_NOCONVERT = 0x1d,
VK_SPACE = 0x20,
VK_PRIOR = 0x21,
VK_NEXT = 0x22,
VK_END = 0x23,
VK_HOME = 0x24,
// The LEFT button.
VK_LEFT = 0x25,
// The UP button.
VK_UP = 0x26,
// The RIGHT button.
VK_RIGHT = 0x27,
// The DOWN button.
VK_DOWN = 0x28,
VK_SELECT = 0x29,
VK_PRINT = 0x2A,
VK_EXECUTE = 0x2B,
VK_SNAPSHOT = 0x2C,
VK_INSERT = 0x2D,
VK_DELETE = 0x2E,
VK_HELP = 0x2F,
/* VK_0 thru VK_9 are the same as ASCII '0' thru '9' (0x30 - 0x39) */
VK_0 = 0x30,
VK_1 = 0x31,
VK_2 = 0x32,
VK_3 = 0x33,
VK_4 = 0x34,
VK_5 = 0x35,
VK_6 = 0x36,
VK_7 = 0x37,
VK_8 = 0x38,
VK_9 = 0x39,
/* VK_A thru VK_Z are the same as ASCII 'A' thru 'Z' (0x41 - 0x5A) */
VK_A = 0x41,
VK_B = 0x42,
VK_C = 0x43,
VK_D = 0x44,
VK_E = 0x45,
VK_F = 0x46,
VK_G = 0x47,
VK_H = 0x48,
VK_I = 0x49,
VK_J = 0x4A,
VK_K = 0x4B,
VK_L = 0x4C,
VK_M = 0x4D,
VK_N = 0x4E,
VK_O = 0x4F,
VK_P = 0x50,
VK_Q = 0x51,
VK_R = 0x52,
VK_S = 0x53,
VK_T = 0x54,
VK_U = 0x55,
VK_V = 0x56,
VK_W = 0x57,
VK_X = 0x58,
VK_Y = 0x59,
VK_Z = 0x5A,
VK_LWIN = 0x5B,
VK_RWIN = 0x5C,
VK_APPS = 0x5D,
VK_SLEEP = 0x5F,
VK_NUMPAD0 = 0x60,
VK_NUMPAD1 = 0x61,
VK_NUMPAD2 = 0x62,
VK_NUMPAD3 = 0x63,
VK_NUMPAD4 = 0x64,
VK_NUMPAD5 = 0x65,
VK_NUMPAD6 = 0x66,
VK_NUMPAD7 = 0x67,
VK_NUMPAD8 = 0x68,
VK_NUMPAD9 = 0x69,
VK_MULTIPLY = 0x6A,
VK_ADD = 0x6B,
VK_SEPARATOR = 0x6C,
VK_SUBTRACT = 0x6D,
VK_DECIMAL = 0x6E,
VK_DIVIDE = 0x6F,
VK_F1 = 0x70,
VK_F2 = 0x71,
VK_F3 = 0x72,
VK_F4 = 0x73,
VK_F5 = 0x74,
VK_F6 = 0x75,
VK_F7 = 0x76,
VK_F8 = 0x77,
VK_F9 = 0x78,
VK_F10 = 0x79,
VK_F11 = 0x7A,
VK_F12 = 0x7B,
VK_F13 = 0x7C,
VK_F14 = 0x7D,
VK_F15 = 0x7E,
VK_F16 = 0x7F,
VK_F17 = 0x80,
VK_F18 = 0x81,
VK_F19 = 0x82,
VK_F20 = 0x83,
VK_F21 = 0x84,
VK_F22 = 0x85,
VK_F23 = 0x86,
VK_F24 = 0x87,
VK_NUMLOCK = 0x90,
VK_SCROLL = 0x91,
/*
* VK_L* & VK_R* - left and right Alt, Ctrl and Shift virtual keys.
* Used only as parameters to GetAsyncKeyState() and GetKeyState().
* No other API or message will distinguish left and right keys in this way.
*/
VK_LSHIFT = 0xA0,
VK_RSHIFT = 0xA1,
VK_LCONTROL = 0xA2,
VK_RCONTROL = 0xA3,
VK_LMENU = 0xA4,
VK_RMENU = 0xA5,
VK_EXTEND_BSLASH = 0xE2,
VK_OEM_102 = 0xE2,
VK_PROCESSKEY = 0xE5,
VK_ATTN = 0xF6,
VK_CRSEL = 0xF7,
VK_EXSEL = 0xF8,
VK_EREOF = 0xF9,
VK_PLAY = 0xFA,
VK_ZOOM = 0xFB,
VK_NONAME = 0xFC,
VK_PA1 = 0xFD,
VK_OEM_CLEAR = 0xFE,
VK_SEMICOLON = 0xBA,
VK_EQUAL = 0xBB,
VK_COMMA = 0xBC,
VK_HYPHEN = 0xBD,
VK_PERIOD = 0xBE,
VK_SLASH = 0xBF,
VK_BACKQUOTE = 0xC0,
VK_BROWSER_BACK = 0xA6,
VK_BROWSER_FORWARD = 0xA7,
VK_BROWSER_REFRESH = 0xA8,
VK_BROWSER_STOP = 0xA9,
VK_BROWSER_SEARCH = 0xAA,
VK_BROWSER_FAVORITES = 0xAB,
VK_BROWSER_HOME = 0xAC,
VK_VOLUME_MUTE = 0xAD,
VK_VOLUME_DOWN = 0xAE,
VK_VOLUME_UP = 0xAF,
VK_MEDIA_NEXT_TRACK = 0xB0,
VK_MEDIA_PREV_TRACK = 0xB1,
VK_MEDIA_STOP = 0xB2,
VK_MEDIA_PLAY_PAUSE = 0xB3,
VK_LAUNCH_MAIL = 0xB4,
VK_LAUNCH_MEDIA_SELECT = 0xB5,
VK_LAUNCH_APP1 = 0xB6,
VK_LAUNCH_APP2 = 0xB7,
VK_LBRACKET = 0xDB,
VK_BACKSLASH = 0xDC,
VK_RBRACKET = 0xDD,
VK_APOSTROPHE = 0xDE,
VK_OFF = 0xDF,
VK_DBE_ALPHANUMERIC = 0x0f0,
VK_DBE_KATAKANA = 0x0f1,
VK_DBE_HIRAGANA = 0x0f2,
VK_DBE_SBCSCHAR = 0x0f3,
VK_DBE_DBCSCHAR = 0x0f4,
VK_DBE_ROMAN = 0x0f5,
VK_DBE_NOROMAN = 0x0f6,
VK_DBE_ENTERWORDREGISTERMODE = 0x0f7,
VK_DBE_ENTERIMECONFIGMODE = 0x0f8,
VK_DBE_FLUSHSTRING = 0x0f9,
VK_DBE_CODEINPUT = 0x0fa,
VK_DBE_NOCODEINPUT = 0x0fb,
VK_DBE_DETERMINESTRING = 0x0fc,
VK_DBE_ENTERDLGCONVERSIONMODE = 0x0fd,
/// <summary>
/// Last in the standard MF buttons enumeration
/// </summary>
LastSystemDefinedButton = 0x110,
// Users may define their button definitions with values larger than
// Button.LastSystemDefinedButton
// Values less that Button.LastSystemDefinedButton are reserved for standard buttons.
// Values above Button.LastSystemDefinedButton are for third party extensions.
AppDefined1 = LastSystemDefinedButton + 1,
AppDefined2 = LastSystemDefinedButton + 2,
AppDefined3 = LastSystemDefinedButton + 3,
AppDefined4 = LastSystemDefinedButton + 4,
AppDefined5 = LastSystemDefinedButton + 5,
AppDefined6 = LastSystemDefinedButton + 6,
AppDefined7 = LastSystemDefinedButton + 7,
AppDefined8 = LastSystemDefinedButton + 8,
}
}
| |
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
namespace Prime31
{
public class EtceteraAndroidEventListener : MonoBehaviour
{
#if UNITY_ANDROID
void OnEnable()
{
// Listen to all events for illustration purposes
EtceteraAndroidManager.alertButtonClickedEvent += alertButtonClickedEvent;
EtceteraAndroidManager.alertCancelledEvent += alertCancelledEvent;
EtceteraAndroidManager.promptFinishedWithTextEvent += promptFinishedWithTextEvent;
EtceteraAndroidManager.promptCancelledEvent += promptCancelledEvent;
EtceteraAndroidManager.twoFieldPromptFinishedWithTextEvent += twoFieldPromptFinishedWithTextEvent;
EtceteraAndroidManager.twoFieldPromptCancelledEvent += twoFieldPromptCancelledEvent;
EtceteraAndroidManager.webViewCancelledEvent += webViewCancelledEvent;
EtceteraAndroidManager.inlineWebViewJSCallbackEvent += inlineWebViewJSCallbackEvent;
EtceteraAndroidManager.albumChooserCancelledEvent += albumChooserCancelledEvent;
EtceteraAndroidManager.albumChooserSucceededEvent += albumChooserSucceededEvent;
EtceteraAndroidManager.photoChooserCancelledEvent += photoChooserCancelledEvent;
EtceteraAndroidManager.photoChooserSucceededEvent += photoChooserSucceededEvent;
EtceteraAndroidManager.videoRecordingCancelledEvent += videoRecordingCancelledEvent;
EtceteraAndroidManager.videoRecordingSucceededEvent += videoRecordingSucceededEvent;
EtceteraAndroidManager.ttsInitializedEvent += ttsInitializedEvent;
EtceteraAndroidManager.ttsFailedToInitializeEvent += ttsFailedToInitializeEvent;
EtceteraAndroidManager.askForReviewDontAskAgainEvent += askForReviewDontAskAgainEvent;
EtceteraAndroidManager.askForReviewRemindMeLaterEvent += askForReviewRemindMeLaterEvent;
EtceteraAndroidManager.askForReviewWillOpenMarketEvent += askForReviewWillOpenMarketEvent;
EtceteraAndroidManager.notificationReceivedEvent += notificationReceivedEvent;
EtceteraAndroidManager.contactsLoadedEvent += contactsLoadedEvent;
}
void OnDisable()
{
// Remove all event handlers
EtceteraAndroidManager.alertButtonClickedEvent -= alertButtonClickedEvent;
EtceteraAndroidManager.alertCancelledEvent -= alertCancelledEvent;
EtceteraAndroidManager.promptFinishedWithTextEvent -= promptFinishedWithTextEvent;
EtceteraAndroidManager.promptCancelledEvent -= promptCancelledEvent;
EtceteraAndroidManager.twoFieldPromptFinishedWithTextEvent -= twoFieldPromptFinishedWithTextEvent;
EtceteraAndroidManager.twoFieldPromptCancelledEvent -= twoFieldPromptCancelledEvent;
EtceteraAndroidManager.webViewCancelledEvent -= webViewCancelledEvent;
EtceteraAndroidManager.inlineWebViewJSCallbackEvent -= inlineWebViewJSCallbackEvent;
EtceteraAndroidManager.albumChooserCancelledEvent -= albumChooserCancelledEvent;
EtceteraAndroidManager.albumChooserSucceededEvent -= albumChooserSucceededEvent;
EtceteraAndroidManager.photoChooserCancelledEvent -= photoChooserCancelledEvent;
EtceteraAndroidManager.photoChooserSucceededEvent -= photoChooserSucceededEvent;
EtceteraAndroidManager.videoRecordingCancelledEvent -= videoRecordingCancelledEvent;
EtceteraAndroidManager.videoRecordingSucceededEvent -= videoRecordingSucceededEvent;
EtceteraAndroidManager.ttsInitializedEvent -= ttsInitializedEvent;
EtceteraAndroidManager.ttsFailedToInitializeEvent -= ttsFailedToInitializeEvent;
EtceteraAndroidManager.askForReviewDontAskAgainEvent -= askForReviewDontAskAgainEvent;
EtceteraAndroidManager.askForReviewRemindMeLaterEvent -= askForReviewRemindMeLaterEvent;
EtceteraAndroidManager.askForReviewWillOpenMarketEvent -= askForReviewWillOpenMarketEvent;
EtceteraAndroidManager.notificationReceivedEvent -= notificationReceivedEvent;
EtceteraAndroidManager.contactsLoadedEvent -= contactsLoadedEvent;
}
void alertButtonClickedEvent( string positiveButton )
{
Debug.Log( "alertButtonClickedEvent: " + positiveButton );
}
void alertCancelledEvent()
{
Debug.Log( "alertCancelledEvent" );
}
void promptFinishedWithTextEvent( string param )
{
Debug.Log( "promptFinishedWithTextEvent: " + param );
}
void promptCancelledEvent()
{
Debug.Log( "promptCancelledEvent" );
}
void twoFieldPromptFinishedWithTextEvent( string text1, string text2 )
{
Debug.Log( "twoFieldPromptFinishedWithTextEvent: " + text1 + ", " + text2 );
}
void twoFieldPromptCancelledEvent()
{
Debug.Log( "twoFieldPromptCancelledEvent" );
}
void webViewCancelledEvent()
{
Debug.Log( "webViewCancelledEvent" );
}
void inlineWebViewJSCallbackEvent( string message )
{
Debug.Log( "inlineWebViewJSCallbackEvent: " + message );
}
void albumChooserCancelledEvent()
{
Debug.Log( "albumChooserCancelledEvent" );
}
void albumChooserSucceededEvent( string imagePath )
{
Debug.Log( "albumChooserSucceededEvent: " + imagePath );
Debug.Log( "image size: " + EtceteraAndroid.getImageSizeAtPath( imagePath ) );
}
void photoChooserCancelledEvent()
{
Debug.Log( "photoChooserCancelledEvent" );
}
void photoChooserSucceededEvent( string imagePath )
{
Debug.Log( "photoChooserSucceededEvent: " + imagePath );
Debug.Log( "image size: " + EtceteraAndroid.getImageSizeAtPath( imagePath ) );
}
void videoRecordingCancelledEvent()
{
Debug.Log( "videoRecordingCancelledEvent" );
}
void videoRecordingSucceededEvent( string path )
{
Debug.Log( "videoRecordingSucceededEvent: " + path );
}
void ttsInitializedEvent()
{
Debug.Log( "ttsInitializedEvent" );
}
void ttsFailedToInitializeEvent()
{
Debug.Log( "ttsFailedToInitializeEvent" );
}
void askForReviewDontAskAgainEvent()
{
Debug.Log( "askForReviewDontAskAgainEvent" );
}
void askForReviewRemindMeLaterEvent()
{
Debug.Log( "askForReviewRemindMeLaterEvent" );
}
void askForReviewWillOpenMarketEvent()
{
Debug.Log( "askForReviewWillOpenMarketEvent" );
}
void notificationReceivedEvent( string extraData )
{
Debug.Log( "notificationReceivedEvent: " + extraData );
}
void contactsLoadedEvent( List<EtceteraAndroid.Contact> contacts )
{
Debug.Log( "contactsLoadedEvent" );
Prime31.Utils.logObject( contacts );
}
#endif
}
}
| |
/*
* 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.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Text;
using System.Threading;
using OpenMetaverse;
using Nini.Config;
using OpenSim.Framework.Servers.HttpServer;
using log4net;
namespace OpenSim.Framework.Console
{
public class ConsoleConnection
{
public int last;
public long lastLineSeen;
}
// A console that uses REST interfaces
//
public class RemoteConsole : CommandConsole
{
private IHttpServer m_Server = null;
private IConfigSource m_Config = null;
private List<string> m_Scrollback = new List<string>();
private ManualResetEvent m_DataEvent = new ManualResetEvent(false);
private List<string> m_InputData = new List<string>();
private long m_LineNumber = 0;
private Dictionary<UUID, ConsoleConnection> m_Connections =
new Dictionary<UUID, ConsoleConnection>();
private string m_UserName = String.Empty;
private string m_Password = String.Empty;
public RemoteConsole(string defaultPrompt) : base(defaultPrompt)
{
}
public void ReadConfig(IConfigSource config)
{
m_Config = config;
IConfig netConfig = m_Config.Configs["Network"];
if (netConfig == null)
return;
m_UserName = netConfig.GetString("ConsoleUser", String.Empty);
m_Password = netConfig.GetString("ConsolePass", String.Empty);
}
public void SetServer(IHttpServer server)
{
m_Server = server;
m_Server.AddHTTPHandler("/StartSession/", HandleHttpStartSession);
m_Server.AddHTTPHandler("/CloseSession/", HandleHttpCloseSession);
m_Server.AddHTTPHandler("/SessionCommand/", HandleHttpSessionCommand);
}
public override void Output(string text, string level)
{
lock (m_Scrollback)
{
while (m_Scrollback.Count >= 1000)
m_Scrollback.RemoveAt(0);
m_LineNumber++;
m_Scrollback.Add(String.Format("{0}", m_LineNumber)+":"+level+":"+text);
}
System.Console.WriteLine(text.Trim());
}
public override void Output(string text)
{
Output(text, "normal");
}
public override string ReadLine(string p, bool isCommand, bool e)
{
m_DataEvent.WaitOne();
lock (m_InputData)
{
if (m_InputData.Count == 0)
{
m_DataEvent.Reset();
return "";
}
string cmdinput = m_InputData[0];
m_InputData.RemoveAt(0);
if (m_InputData.Count == 0)
m_DataEvent.Reset();
if (isCommand)
{
string[] cmd = Commands.Resolve(Parser.Parse(cmdinput));
if (cmd.Length != 0)
{
int i;
for (i=0 ; i < cmd.Length ; i++)
{
if (cmd[i].Contains(" "))
cmd[i] = "\"" + cmd[i] + "\"";
}
return String.Empty;
}
}
return cmdinput;
}
}
private void DoExpire()
{
List<UUID> expired = new List<UUID>();
lock (m_Connections)
{
foreach (KeyValuePair<UUID, ConsoleConnection> kvp in m_Connections)
{
if (System.Environment.TickCount - kvp.Value.last > 500000)
expired.Add(kvp.Key);
}
foreach (UUID id in expired)
{
m_Connections.Remove(id);
CloseConnection(id);
}
}
}
private Hashtable HandleHttpStartSession(Hashtable request)
{
DoExpire();
Hashtable post = DecodePostString(request["body"].ToString());
Hashtable reply = new Hashtable();
reply["str_response_string"] = "";
reply["int_response_code"] = 401;
reply["content_type"] = "text/plain";
if (m_UserName == String.Empty)
return reply;
if (post["USER"] == null || post["PASS"] == null)
return reply;
if (m_UserName != post["USER"].ToString() ||
m_Password != post["PASS"].ToString())
{
return reply;
}
ConsoleConnection c = new ConsoleConnection();
c.last = System.Environment.TickCount;
c.lastLineSeen = 0;
UUID sessionID = UUID.Random();
lock (m_Connections)
{
m_Connections[sessionID] = c;
}
string uri = "/ReadResponses/" + sessionID.ToString() + "/";
m_Server.AddPollServiceHTTPHandler(uri, HandleHttpPoll,
new PollServiceEventArgs(null, HasEvents, GetEvents, NoEvents,
sessionID));
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
"");
xmldoc.AppendChild(rootElement);
XmlElement id = xmldoc.CreateElement("", "SessionID", "");
id.AppendChild(xmldoc.CreateTextNode(sessionID.ToString()));
rootElement.AppendChild(id);
XmlElement prompt = xmldoc.CreateElement("", "Prompt", "");
prompt.AppendChild(xmldoc.CreateTextNode(DefaultPrompt));
rootElement.AppendChild(prompt);
rootElement.AppendChild(MainConsole.Instance.Commands.GetXml(xmldoc));
reply["str_response_string"] = xmldoc.InnerXml;
reply["int_response_code"] = 200;
reply["content_type"] = "text/xml";
return reply;
}
private Hashtable HandleHttpPoll(Hashtable request)
{
return new Hashtable();
}
private Hashtable HandleHttpCloseSession(Hashtable request)
{
DoExpire();
Hashtable post = DecodePostString(request["body"].ToString());
Hashtable reply = new Hashtable();
reply["str_response_string"] = "";
reply["int_response_code"] = 404;
reply["content_type"] = "text/plain";
if (post["ID"] == null)
return reply;
UUID id;
if (!UUID.TryParse(post["ID"].ToString(), out id))
return reply;
lock (m_Connections)
{
if (m_Connections.ContainsKey(id))
{
m_Connections.Remove(id);
CloseConnection(id);
}
}
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
"");
xmldoc.AppendChild(rootElement);
XmlElement res = xmldoc.CreateElement("", "Result", "");
res.AppendChild(xmldoc.CreateTextNode("OK"));
rootElement.AppendChild(res);
reply["str_response_string"] = xmldoc.InnerXml;
reply["int_response_code"] = 200;
reply["content_type"] = "text/plain";
return reply;
}
private Hashtable HandleHttpSessionCommand(Hashtable request)
{
DoExpire();
Hashtable post = DecodePostString(request["body"].ToString());
Hashtable reply = new Hashtable();
reply["str_response_string"] = "";
reply["int_response_code"] = 404;
reply["content_type"] = "text/plain";
if (post["ID"] == null)
return reply;
UUID id;
if (!UUID.TryParse(post["ID"].ToString(), out id))
return reply;
if (post["COMMAND"] == null || post["COMMAND"].ToString() == String.Empty)
return reply;
lock (m_InputData)
{
m_DataEvent.Set();
m_InputData.Add(post["COMMAND"].ToString());
}
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
"");
xmldoc.AppendChild(rootElement);
XmlElement res = xmldoc.CreateElement("", "Result", "");
res.AppendChild(xmldoc.CreateTextNode("OK"));
rootElement.AppendChild(res);
reply["str_response_string"] = xmldoc.InnerXml;
reply["int_response_code"] = 200;
reply["content_type"] = "text/plain";
return reply;
}
private Hashtable DecodePostString(string data)
{
Hashtable result = new Hashtable();
string[] terms = data.Split(new char[] {'&'});
foreach (string term in terms)
{
string[] elems = term.Split(new char[] {'='});
if (elems.Length == 0)
continue;
string name = System.Web.HttpUtility.UrlDecode(elems[0]);
string value = String.Empty;
if (elems.Length > 1)
value = System.Web.HttpUtility.UrlDecode(elems[1]);
result[name] = value;
}
return result;
}
public void CloseConnection(UUID id)
{
try
{
string uri = "/ReadResponses/" + id.ToString() + "/";
m_Server.RemovePollServiceHTTPHandler("", uri);
}
catch (Exception)
{
}
}
private bool HasEvents(UUID RequestID, UUID sessionID)
{
ConsoleConnection c = null;
lock (m_Connections)
{
if (!m_Connections.ContainsKey(sessionID))
return false;
c = m_Connections[sessionID];
}
c.last = System.Environment.TickCount;
if (c.lastLineSeen < m_LineNumber)
return true;
return false;
}
private Hashtable GetEvents(UUID RequestID, UUID sessionID, string request)
{
ConsoleConnection c = null;
lock (m_Connections)
{
if (!m_Connections.ContainsKey(sessionID))
return NoEvents(RequestID, UUID.Zero);
c = m_Connections[sessionID];
}
c.last = System.Environment.TickCount;
if (c.lastLineSeen >= m_LineNumber)
return NoEvents(RequestID, UUID.Zero);
Hashtable result = new Hashtable();
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
"");
lock (m_Scrollback)
{
long startLine = m_LineNumber - m_Scrollback.Count;
long sendStart = startLine;
if (sendStart < c.lastLineSeen)
sendStart = c.lastLineSeen;
for (long i = sendStart ; i < m_LineNumber ; i++)
{
XmlElement res = xmldoc.CreateElement("", "Line", "");
long line = i + 1;
res.SetAttribute("Number", line.ToString());
res.AppendChild(xmldoc.CreateTextNode(m_Scrollback[(int)(i - startLine)]));
rootElement.AppendChild(res);
}
}
c.lastLineSeen = m_LineNumber;
xmldoc.AppendChild(rootElement);
result["str_response_string"] = xmldoc.InnerXml;
result["int_response_code"] = 200;
result["content_type"] = "application/xml";
result["keepalive"] = false;
result["reusecontext"] = false;
return result;
}
private Hashtable NoEvents(UUID RequestID, UUID id)
{
Hashtable result = new Hashtable();
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
"");
xmldoc.AppendChild(rootElement);
result["str_response_string"] = xmldoc.InnerXml;
result["int_response_code"] = 200;
result["content_type"] = "text/xml";
result["keepalive"] = false;
result["reusecontext"] = false;
return result;
}
}
}
| |
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
namespace SourceUtils
{
public enum BitCoordType
{
None,
LowPrecision,
Integral
};
public class BitBuffer
{
private static int ZigZagDecode32(uint n)
{
return (int) (n >> 1) ^ -unchecked((int)(n & 1));
}
private static long ZigZagDecode64(ulong n)
{
return (long) (n >> 1) ^ -unchecked((long) (n & 1));
}
private static readonly uint[] _sMaskTable = {
0,
( 1 << 1 ) - 1,
( 1 << 2 ) - 1,
( 1 << 3 ) - 1,
( 1 << 4 ) - 1,
( 1 << 5 ) - 1,
( 1 << 6 ) - 1,
( 1 << 7 ) - 1,
( 1 << 8 ) - 1,
( 1 << 9 ) - 1,
( 1 << 10 ) - 1,
( 1 << 11 ) - 1,
( 1 << 12 ) - 1,
( 1 << 13 ) - 1,
( 1 << 14 ) - 1,
( 1 << 15 ) - 1,
( 1 << 16 ) - 1,
( 1 << 17 ) - 1,
( 1 << 18 ) - 1,
( 1 << 19 ) - 1,
( 1 << 20 ) - 1,
( 1 << 21 ) - 1,
( 1 << 22 ) - 1,
( 1 << 23 ) - 1,
( 1 << 24 ) - 1,
( 1 << 25 ) - 1,
( 1 << 26 ) - 1,
( 1 << 27 ) - 1,
( 1 << 28 ) - 1,
( 1 << 29 ) - 1,
( 1 << 30 ) - 1,
0x7fffffff,
0xffffffff
};
private readonly byte[] _buffer;
private int _readOffset;
private int _bitsAvailable;
private int _totalBits;
private uint _bufferDWord;
private bool _overflow;
public BitBuffer(byte[] buffer, int length = -1)
{
_buffer = buffer;
_readOffset = 0;
_bitsAvailable = 0;
_totalBits = (length == -1 ? buffer.Length : length) << 3;
Seek(0);
}
public bool Seek(int position)
{
var success = true;
if (position < 0 || position > _totalBits)
{
SetOverflowFlag();
success = false;
position = _totalBits;
}
var head = _buffer.Length & 3;
var byteOffset = position >> 3;
if ((_buffer.Length < 4) || (head != 0 && byteOffset < head))
{
_bufferDWord = _buffer[_readOffset++];
if (head > 1) _bufferDWord |= (uint) _buffer[_readOffset++] << 8;
if (head > 2) _bufferDWord |= (uint) _buffer[_readOffset++] << 16;
_bufferDWord >>= (position & 31);
_bitsAvailable = (head << 3) - (position & 31);
}
else
{
var adjPosition = position - (head << 3);
_readOffset = ((adjPosition >> 5) << 2) + head;
_bitsAvailable = 32;
GrabNextDWord();
_bufferDWord >>= adjPosition & 31;
_bitsAvailable = Math.Min(_bitsAvailable, 32 - (adjPosition & 31));
}
return success;
}
private void FetchNext()
{
_bitsAvailable = 32;
GrabNextDWord();
}
private void SetOverflowFlag()
{
_overflow = true;
}
private void GrabNextDWord(bool overflowImmediately = false)
{
if (_readOffset == _buffer.Length)
{
_bitsAvailable = 1;
_bufferDWord = 0;
_readOffset += sizeof(uint);
if (overflowImmediately) SetOverflowFlag();
return;
}
if (_readOffset > _buffer.Length)
{
SetOverflowFlag();
_bufferDWord = 0;
return;
}
Debug.Assert(_readOffset + sizeof(uint) <= _buffer.Length);
_bufferDWord = BitConverter.ToUInt32(_buffer, _readOffset);
_readOffset += sizeof (uint);
}
public uint ReadUBitLong(int bits)
{
if (_bitsAvailable >= bits)
{
var ret = _bufferDWord & _sMaskTable[bits];
_bitsAvailable -= bits;
if (_bitsAvailable > 0) _bufferDWord >>= bits;
else FetchNext();
return ret;
}
else
{
var ret = _bufferDWord;
bits -= _bitsAvailable;
GrabNextDWord(true);
if (_overflow) return 0;
ret |= ((_bufferDWord & _sMaskTable[bits]) << _bitsAvailable);
_bitsAvailable = 32 - bits;
_bufferDWord >>= bits;
return ret;
}
}
public int ReadSBitLong(int bits)
{
var ret = (int) ReadUBitLong(bits);
return (ret << (32 - bits)) >> (32 - bits);
}
public uint ReadUBitVar()
{
var ret = ReadUBitLong(6);
switch (ret & (16 | 32))
{
case 16:
ret = (ret & 15) | (ReadUBitLong(4) << 4);
Debug.Assert(ret >= 16);
break;
case 32:
ret = (ret & 15) | (ReadUBitLong(8) << 4);
Debug.Assert(ret >= 256);
break;
case 48:
ret = (ret & 15) | (ReadUBitLong(32 - 4) << 4);
Debug.Assert(ret >= 4096);
break;
}
return ret;
}
public uint ReadVarInt32()
{
uint result = 0;
int count = 0;
uint b;
do
{
if (count == 5)
{
return result;
}
b = ReadUBitLong(8);
result |= (b & 0x7F) << (7 * count);
++count;
} while ((b & 0x80) != 0);
return result;
}
public int ReadSignedVarInt32()
{
return ZigZagDecode32(ReadVarInt32());
}
public ulong ReadVarInt64()
{
ulong result = 0;
int count = 0;
ulong b;
do
{
if (count == 10)
{
return result;
}
b = ReadUBitLong(8);
result |= (b & 0x7F) << (7 * count);
++count;
} while ((b & 0x80) != 0);
return result;
}
public long ReadSignedVarInt64()
{
return ZigZagDecode64(ReadVarInt64());
}
const int CoordIntegerBits = 14;
private const int CoordIntegerBitsMP = 11;
const int CoordFractionalBits = 5;
const int CoordFractionalBitsLowPrecision = 3;
const int CoordDenominator = 1 << CoordFractionalBits;
const int CoordDenominatorLowPrecision = 1 << CoordFractionalBitsLowPrecision;
const float CoordResolution = 1f/CoordDenominator;
const float CoordResolutionLowPrecision = 1f/CoordDenominatorLowPrecision;
public float ReadBitCoord()
{
var hasInt = ReadOneBit();
var hasFract = ReadOneBit();
if (!hasInt && !hasFract) return 0f;
var sign = ReadOneBit() ? -1 : 1;
var intVal = 0;
var fractVal = 0;
if (hasInt) intVal = (int) ReadUBitLong(CoordIntegerBits) + 1;
if (hasFract) fractVal = (int) ReadUBitLong(CoordFractionalBits);
return sign * (intVal + fractVal* CoordResolution);
}
public float ReadBitCoordMP(BitCoordType coordType)
{
int sign;
var integral = coordType == BitCoordType.Integral;
var lowPrec = coordType == BitCoordType.LowPrecision;
var inBounds = ReadOneBit();
if (integral)
{
if (!ReadOneBit()) return 0f;
sign = ReadOneBit() ? -1 : 1;
return sign * ReadUBitLong(inBounds ? CoordIntegerBitsMP : CoordIntegerBits) + 1f;
}
var hasInt = ReadOneBit();
sign = ReadOneBit() ? -1 : 1;
var intVal = 0;
if (hasInt)
{
intVal = (int) ReadUBitLong(inBounds ? CoordIntegerBitsMP : CoordIntegerBits) + 1;
}
var fractVal = ReadUBitLong(lowPrec ? CoordFractionalBitsLowPrecision : CoordFractionalBits);
return sign*(intVal + fractVal*(lowPrec ? CoordResolutionLowPrecision : CoordResolution));
}
[StructLayout(LayoutKind.Explicit)]
private struct FloatIntUnion
{
[FieldOffset(0)]
public uint Uint32Val;
[FieldOffset(0)]
public float FloatVal;
}
public float ReadBitFloat()
{
var union = default(FloatIntUnion);
union.Uint32Val = ReadUBitLong(32);
return union.FloatVal;
}
public float ReadBitNormal()
{
const int normalFractionalBits = 11;
const int normalDenominator = (1 << normalFractionalBits) - 1;
const float normalResolution = 1f/normalDenominator;
var sign = ReadOneBit() ? -1 : 1;
var fractVal = ReadUBitLong(normalFractionalBits);
return sign*fractVal*normalResolution;
}
public float ReadBitCellCoord(int bits, BitCoordType coordType)
{
var integral = coordType == BitCoordType.Integral;
var lowPrec = coordType == BitCoordType.LowPrecision;
if (integral) return ReadUBitLong(bits);
var intVal = ReadUBitLong(bits);
var fractVal = ReadUBitLong(lowPrec ? CoordFractionalBitsLowPrecision : CoordFractionalBits);
return intVal + (fractVal*(lowPrec ? CoordResolutionLowPrecision : CoordResolution));
}
public void ReadBits(byte[] buffer, int bits)
{
var index = 0;
var bitsLeft = bits;
while (bitsLeft >= 8)
{
buffer[index++] = (byte) ReadUBitLong(8);
bitsLeft -= 8;
}
if (bitsLeft > 0)
{
buffer[index] = (byte) ReadUBitLong(bitsLeft);
}
}
public bool ReadBytes(byte[] buffer, int bytes)
{
ReadBits(buffer, bytes << 3);
return !_overflow;
}
public bool ReadOneBit()
{
var ret = (_bufferDWord & 1) == 1;
if (--_bitsAvailable == 0) FetchNext();
else _bufferDWord >>= 1;
return ret;
}
public char ReadChar()
{
return (char) ReadSBitLong(sizeof (byte) << 3);
}
public byte ReadByte()
{
return (byte) ReadUBitLong(sizeof(byte) << 3);
}
public ushort ReadWord()
{
return (ushort) ReadUBitLong(sizeof(ushort) << 3);
}
[ThreadStatic]
private static StringBuilder _sStringBuilder;
public string ReadString(int maxLength, bool line = false)
{
if (_sStringBuilder == null) _sStringBuilder = new StringBuilder(maxLength);
else _sStringBuilder.Remove(0, _sStringBuilder.Length);
var tooSmall = false;
var index = 0;
while (true)
{
char val = ReadChar();
if (val == 0 || line && val == '\n') break;
if (index < maxLength - 1)
{
_sStringBuilder.Append(val);
}
else
{
tooSmall = true;
}
}
return !_overflow && !tooSmall ? _sStringBuilder.ToString() : null;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Portions derived from React Native:
// Copyright (c) 2015-present, Facebook, Inc.
// Licensed under the MIT License.
using Newtonsoft.Json.Linq;
using ReactNative.UIManager;
using ReactNative.UIManager.Annotations;
using Windows.UI.Xaml;
namespace ReactNative.Views.Slider
{
/// <summary>
/// A view manager responsible for rendering Slider.
/// </summary>
public class ReactSliderManager : BaseViewManager<Windows.UI.Xaml.Controls.Slider, ReactSliderShadowNode>
{
private const double Epsilon = 1e-4;
private const double Undefined = double.NegativeInfinity;
/// <summary>
/// The name of the view manager.
/// </summary>
public override string Name
{
get
{
return "RCTSlider";
}
}
/// <summary>
/// The exported custom direct event types.
/// </summary>
public override JObject CustomDirectEventTypeConstants
{
get
{
return new JObject
{
{
"topSlidingComplete",
new JObject
{
{ "registrationName", "onSlidingComplete" },
}
},
};
}
}
/// <summary>
/// Sets whether a slider is disabled.
/// </summary>
/// <param name="view">a slider view.</param>
/// <param name="disabled">
/// Set to <code>true</code> if the picker should be disabled,
/// otherwise, set to <code>false</code>.
/// </param>
[ReactProp("disabled")]
public void SetDisabled(Windows.UI.Xaml.Controls.Slider view, bool disabled)
{
view.IsEnabled = !disabled;
}
/// <summary>
/// Sets to change slider minimum value.
/// </summary>
/// <param name="view">a slider view.</param>
/// <param name="minimum">The minimum slider value.</param>
[ReactProp("minimumValue")]
public void SetMinimumValue(Windows.UI.Xaml.Controls.Slider view, double minimum)
{
view.Minimum = minimum;
}
/// <summary>
/// Sets to change slider maximum value.
/// </summary>
/// <param name="view">a slider view.</param>
/// <param name="maximum">The maximum slider value.</param>
[ReactProp("maximumValue")]
public void SetMaximumValue(Windows.UI.Xaml.Controls.Slider view, double maximum)
{
view.Maximum = maximum;
}
/// <summary>
/// Sets slider value.
/// </summary>
/// <param name="view">The slider view.</param>
/// <param name="value">Slider value.</param>
[ReactProp(ViewProps.Value)]
public void SetValue(Windows.UI.Xaml.Controls.Slider view, double value)
{
view.ValueChanged -= OnValueChange;
view.Value = value;
view.ValueChanged += OnValueChange;
}
/// <summary>
/// Sets slider step.
/// </summary>
/// <param name="view">The slider view.</param>
/// <param name="step">Slider step.</param>
[ReactProp("step", DefaultDouble = Undefined)]
public void SetStep(Windows.UI.Xaml.Controls.Slider view, double step)
{
if (step != Undefined)
{
if (step == 0)
{
step = Epsilon;
}
view.StepFrequency = step;
}
else
{
view.StepFrequency = 1;
}
}
/// <summary>
/// This method should return the <see cref="ReactSliderShadowNode"/>
/// which will be then used for measuring the position and size of the
/// view.
/// </summary>
/// <returns>The shadow node instance.</returns>
public override ReactSliderShadowNode CreateShadowNodeInstance()
{
return new ReactSliderShadowNode();
}
/// <summary>
/// Called when view is detached from view hierarchy and allows for
/// additional cleanup by the <see cref="IViewManager"/> subclass.
/// </summary>
/// <param name="reactContext">The React context.</param>
/// <param name="view">The view.</param>
public override void OnDropViewInstance(ThemedReactContext reactContext, Windows.UI.Xaml.Controls.Slider view)
{
base.OnDropViewInstance(reactContext, view);
view.ValueChanged -= OnValueChange;
view.PointerReleased -= OnPointerReleased;
view.PointerCaptureLost -= OnPointerReleased;
}
/// <summary>
/// Implement this method to receive optional extra data enqueued from
/// the corresponding instance of <see cref="ReactShadowNode"/> in
/// <see cref="ReactShadowNode.OnCollectExtraUpdates"/>.
/// </summary>
/// <param name="root">The root view.</param>
/// <param name="extraData">The extra data.</param>
public override void UpdateExtraData(Windows.UI.Xaml.Controls.Slider root, object extraData)
{
}
/// <summary>
/// Returns the view instance for <see cref="Slider"/>.
/// </summary>
/// <param name="reactContext"></param>
/// <returns></returns>
protected override Windows.UI.Xaml.Controls.Slider CreateViewInstance(ThemedReactContext reactContext)
{
return new Windows.UI.Xaml.Controls.Slider();
}
/// <summary>
/// Subclasses can override this method to install custom event
/// emitters on the given view.
/// </summary>
/// <param name="reactContext">The React context.</param>
/// <param name="view">The view instance.</param>
protected override void AddEventEmitters(ThemedReactContext reactContext, Windows.UI.Xaml.Controls.Slider view)
{
base.AddEventEmitters(reactContext, view);
view.ValueChanged += OnValueChange;
view.PointerReleased += OnPointerReleased;
view.PointerCaptureLost += OnPointerReleased;
}
private void OnValueChange(object sender, RoutedEventArgs e)
{
var slider = (Windows.UI.Xaml.Controls.Slider)sender;
var reactContext = slider.GetReactContext();
reactContext.GetNativeModule<UIManagerModule>()
.EventDispatcher
.DispatchEvent(
new ReactSliderChangeEvent(
slider.GetTag(),
slider.Value));
}
private void OnPointerReleased(object sender, RoutedEventArgs e)
{
var slider = (Windows.UI.Xaml.Controls.Slider)sender;
var reactContext = slider.GetReactContext();
reactContext.GetNativeModule<UIManagerModule>()
.EventDispatcher
.DispatchEvent(
new ReactSliderCompleteEvent(
slider.GetTag(),
slider.Value));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Tibialyzer {
public partial class SummaryForm : NotificationForm {
public struct ItemRegion {
public TibiaObject item;
public Rectangle region;
}
private int BlockWidth = 200;
private int BlockHeight = 25;
private List<ItemRegion>[] lootRegions = new List<ItemRegion>[20];
private List<ItemRegion>[] wasteRegions = new List<ItemRegion>[20];
private List<ItemRegion>[] recentDropsRegions = new List<ItemRegion>[20];
private ToolTip tooltip;
private object updateLock = new object();
private static System.Timers.Timer updateTimer;
public SummaryForm() {
InitializeComponent();
tooltip = UIManager.CreateTooltip();
this.Name = "Tibialyzer (Summary Form)";
updateTimer = new System.Timers.Timer(500);
updateTimer.AutoReset = false;
updateTimer.Elapsed += (s, e) => {
ActuallyRefreshForm();
};
}
private void ActuallyRefreshForm() {
lock(updateLock) {
if (this.IsDisposed) return;
try {
updateTimer.Stop();
updateTimer.Enabled = false;
this.Invoke((MethodInvoker)delegate {
this.SuspendForm();
this.UpdateLootForm();
this.UpdateSummaryForm();
this.ResumeForm();
});
} catch {
}
}
}
public static void RenderText(Graphics gr, string text, int x, Color fillColor, Color textColor, Color traceColor, int maxHeight = -1, int y = 4, Font font = null, bool center = false, InterpolationMode interpolationMode = InterpolationMode.High, SmoothingMode smoothingMode = SmoothingMode.HighQuality) {
gr.InterpolationMode = interpolationMode;
gr.SmoothingMode = smoothingMode;
gr.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
gr.CompositingQuality = CompositingQuality.HighQuality;
FontFamily family = FontFamily.GenericMonospace;
FontStyle fontStyle = FontStyle.Bold;
float fontSize = 10;
if (font != null) {
family = font.FontFamily;
fontStyle = font.Style;
fontSize = font.SizeInPoints;
}
GraphicsPath p = new GraphicsPath();
p.AddString(
text,
family,
(int)fontStyle,
gr.DpiY * fontSize / 72,
new Point(x, y),
new StringFormat());
if (x < 0 || center) {
if (x < 0) {
x = (int)(Math.Abs(x) - p.GetBounds().Width - 10);
}
if (center) {
y = (int)((maxHeight - (p.GetBounds().Height + p.GetBounds().Y)) / 2);
}
p = new GraphicsPath();
p.AddString(
text,
family,
(int)fontStyle,
gr.DpiY * fontSize / 72,
new Point(x, y),
new StringFormat());
}
maxHeight = maxHeight < 0 ? (int)p.GetBounds().Height : maxHeight;
if (fillColor != Color.Empty) {
using (Brush brush = new SolidBrush(fillColor)) {
gr.FillRectangle(brush, new RectangleF(p.GetBounds().X - 8, 0, p.GetBounds().Width + 16, maxHeight - 1));
}
gr.DrawRectangle(Pens.Black, new Rectangle((int)p.GetBounds().X - 8, 0, (int)p.GetBounds().Width + 16, maxHeight - 1));
}
using (Pen pen = new Pen(traceColor, 2)) {
gr.DrawPath(pen, p);
}
using (SolidBrush brush = new SolidBrush(textColor)) {
gr.FillPath(brush, p);
}
}
public static void RenderImageResized(Graphics gr, Image image, Rectangle targetRectangle) {
if (image == null) return;
lock (image) {
int x = targetRectangle.X, y = targetRectangle.Y;
int width = targetRectangle.Width, height = targetRectangle.Height;
if (image.Width > image.Height) {
height = (int)Math.Floor(height * ((double)image.Height / image.Width));
y += (width - height) / 2;
} else if (image.Height > image.Width) {
width = (int)Math.Floor(width * ((double)image.Width / image.Height));
x += (height - width) / 2;
}
gr.DrawImage(image, new Rectangle(x, y, width, height), new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel);
}
}
public Image CreatureBox(Creature creature, int amount = 0) {
Bitmap bitmap = new Bitmap(BlockWidth, BlockHeight);
using (Graphics gr = Graphics.FromImage(bitmap)) {
Color backColor = StyleManager.GetElementColor(creature.GetStrength());
using (Brush brush = new SolidBrush(backColor)) {
gr.FillRectangle(brush, new Rectangle(0, 0, bitmap.Width, bitmap.Height));
}
gr.DrawRectangle(Pens.Black, new Rectangle(0, 0, bitmap.Width - 1, bitmap.Height - 1));
RenderImageResized(gr, StyleManager.GetImage("item_background.png"), new Rectangle(1, 1, BlockHeight - 2, BlockHeight - 2));
RenderImageResized(gr, creature.GetImage(), new Rectangle(1, 1, BlockHeight - 2, BlockHeight - 2));
RenderText(gr, creature.displayname.ToTitle(), BlockHeight + 2, Color.Empty, StyleManager.NotificationTextColor, Color.Black, BlockHeight);
if (amount > 0) {
RenderText(gr, amount.ToString(), -BlockWidth, Color.FromArgb(backColor.R / 2, backColor.G / 2, backColor.B / 2), StyleManager.NotificationTextColor, Color.Black, BlockHeight);
}
}
return bitmap;
}
public Image SummaryBox(string header, string value, Color textColor) {
Bitmap bitmap = new Bitmap(BlockWidth, BlockHeight);
using (Graphics gr = Graphics.FromImage(bitmap)) {
using (SolidBrush brush = new SolidBrush(StyleManager.MainFormButtonColor)) {
gr.FillRectangle(brush, new RectangleF(0, 0, BlockWidth, BlockHeight));
}
gr.DrawRectangle(Pens.Black, new Rectangle(0, 0, bitmap.Width - 1, bitmap.Height - 1));
RenderText(gr, header, 0, Color.Empty, StyleManager.NotificationTextColor, Color.Black, BlockHeight);
RenderText(gr, value, -BlockWidth, Color.FromArgb(StyleManager.MainFormButtonColor.R / 2, StyleManager.MainFormButtonColor.G / 2, StyleManager.MainFormButtonColor.B / 2), textColor, Color.Black, BlockHeight);
}
return bitmap;
}
public Image SummaryBar(string header, string text, double percentage, Color textColor, Color barColor) {
percentage = Math.Min(Math.Max(percentage, 0), 1);
Bitmap bitmap = new Bitmap(BlockWidth, BlockHeight);
using (Graphics gr = Graphics.FromImage(bitmap)) {
using (SolidBrush brush = new SolidBrush(StyleManager.MainFormButtonColor)) {
gr.FillRectangle(brush, new RectangleF(0, 0, BlockWidth, BlockHeight));
}
using(SolidBrush brush = new SolidBrush(barColor)) {
gr.FillRectangle(brush, new RectangleF(0, 0, (float)(percentage * BlockWidth), BlockHeight));
}
gr.DrawRectangle(Pens.Black, new Rectangle(0, 0, bitmap.Width - 1, bitmap.Height - 1));
RenderText(gr, header, 0, Color.Empty, StyleManager.NotificationTextColor, Color.Black, BlockHeight);
RenderText(gr, text, -BlockWidth, Color.Empty, textColor, Color.Black, BlockHeight);
}
return bitmap;
}
public Image RecentDropsBox(Creature creature, List<Tuple<Item, int>> items, int imageHeight, List<ItemRegion> regions) {
Bitmap bitmap = new Bitmap(BlockWidth, imageHeight);
using (Graphics gr = Graphics.FromImage(bitmap)) {
using (Brush brush = new SolidBrush(StyleManager.MainFormButtonColor)) {
gr.FillRectangle(brush, new Rectangle(0, 0, bitmap.Width, bitmap.Height));
}
gr.DrawRectangle(Pens.Black, new Rectangle(0, 0, bitmap.Width - 1, bitmap.Height - 1));
Rectangle creatureRegion = new Rectangle(1, 1, imageHeight - 1, imageHeight - 1);
RenderImageResized(gr, StyleManager.GetImage("item_background.png"), new Rectangle(1, 1, imageHeight - 2, imageHeight - 2));
RenderImageResized(gr, creature.GetImage(), creatureRegion);
regions.Add(new ItemRegion { item = creature, region = creatureRegion });
int count = 0;
foreach (Tuple<Item, int> item in items) {
Rectangle region = new Rectangle(8 + (imageHeight - 1) * ++count, 1, imageHeight - 2, imageHeight - 2);
regions.Add(new ItemRegion { item = item.Item1, region = region });
RenderImageResized(gr, StyleManager.GetImage("item_background.png"), region);
RenderItemCount(gr, item, region);
}
}
return bitmap;
}
private void CreateHeaderLabel(string title, int x, ref int y, List<Control> controls) {
Label label = new Label();
label.Text = title;
label.Location = new Point(x, y);
label.Size = new Size(BlockWidth, 15);
label.BackColor = Color.Transparent;
label.ForeColor = StyleManager.NotificationTextColor;
label.Font = StyleManager.MainFormLabelFontSmall;
this.Controls.Add(label);
controls.Add(label);
y += 15;
}
private PictureBox CreateSummaryLabel(string title, string value, int x, ref int y, Color color, List<Control> controls) {
Image image = SummaryBox(title, value, color);
PictureBox box = new PictureBox();
box.Size = image.Size;
box.BackColor = Color.Transparent;
box.Location = new Point(x, y);
box.Image = image;
this.Controls.Add(box);
controls.Add(box);
y += box.Height;
return box;
}
private PictureBox CreateSummaryBar(string title, string text, double percentage, int x, ref int y, Color color, Color barColor, List<Control> controls) {
Image image = SummaryBar(title, text, percentage, color, barColor);
PictureBox box = new PictureBox();
box.Size = image.Size;
box.BackColor = Color.Transparent;
box.Location = new Point(x, y);
box.Image = image;
this.Controls.Add(box);
controls.Add(box);
y += box.Height;
return box;
}
private void CreateCreatureBox(Creature creature, int count, int x, ref int y, List<Control> controls) {
Image image = CreatureBox(creature, count);
PictureBox box = new PictureBox();
box.Size = image.Size;
box.BackColor = Color.Transparent;
box.Location = new Point(x, y);
box.Image = image;
box.Name = "creature" + Constants.CommandSymbol + creature.title;
box.Click += CommandClick;
this.Controls.Add(box);
controls.Add(box);
y += box.Height;
}
private PictureBox CreateCreatureDropsBox(Creature creature, List<Tuple<Item, int>> items, string message, int x, ref int y, List<Control> controls, int imageHeight, List<ItemRegion> region = null, int index = 0) {
Image image = RecentDropsBox(creature, items, imageHeight, region);
PictureBox box = new PictureBox();
box.Size = image.Size;
box.BackColor = Color.Transparent;
box.Location = new Point(x, y);
box.Image = image;
box.Name = index.ToString();
this.Controls.Add(box);
controls.Add(box);
// copy button
PictureBox copyButton = new PictureBox();
copyButton.Size = new Size(box.Size.Height - 4, box.Size.Height - 4);
copyButton.BackColor = StyleManager.MainFormButtonColor;
copyButton.Location = new Point(box.Location.X + box.Size.Width - box.Size.Height + 2, y + 2);
copyButton.Click += CopyLootText;
copyButton.Name = message;
copyButton.Image = StyleManager.GetImage("copyicon.png");
copyButton.SizeMode = PictureBoxSizeMode.Zoom;
this.Controls.Add(copyButton);
controls.Add(copyButton);
copyButton.BringToFront();
y += box.Height;
return box;
}
private void CopyLootText(object sender, EventArgs e) {
Clipboard.SetText((sender as Control).Name);
}
private static void RenderItemCount(Graphics gr, Tuple<Item, int> item, Rectangle region) {
if (region.Width > 28) {
RenderImageResized(gr, item.Item1.GetImage(), region);
if (item.Item1.stackable || item.Item2 > 1) {
LootDropForm.DrawCountOnGraphics(gr, item.Item2, region.X + region.Width - 1, region.Y + region.Height - 1);
}
} else {
RenderImageResized(gr, (item.Item1.stackable || item.Item2 > 1) ? LootDropForm.DrawCountOnItem(item.Item1, item.Item2) : item.Item1.GetImage(), region);
}
}
private PictureBox CreateItemList(List<Tuple<Item, int>> items, int x, ref int y, List<Control> controls, int imageHeight, List<ItemRegion> newRegions = null, int boxIndex = 0) {
Image image = new Bitmap(BlockWidth, imageHeight);
using (Graphics gr = Graphics.FromImage(image)) {
int counter = 0;
foreach (Tuple<Item, int> item in items) {
Rectangle region = new Rectangle(x + (counter++) * (imageHeight + 1), 0, imageHeight - 1, imageHeight - 1);
if (newRegions != null) newRegions.Add(new ItemRegion { item = item.Item1, region = region });
RenderImageResized(gr, StyleManager.GetImage("item_background.png"), region);
RenderItemCount(gr, item, region);
}
}
PictureBox box = new PictureBox();
box.Size = image.Size;
box.BackColor = Color.Transparent;
box.Location = new Point(x, y);
box.Image = image;
box.Name = boxIndex.ToString();
this.Controls.Add(box);
controls.Add(box);
y += box.Height;
return box;
}
private void OpenItemWindow(object sender, MouseEventArgs e, List<ItemRegion>[] lootRegions) {
Point mousePoint = new Point(e.X, e.Y);
int index = 0;
int.TryParse((sender as Control).Name, out index);
if (index > lootRegions.Length && lootRegions[index] == null) return;
List<ItemRegion> regions = lootRegions[index];
foreach (ItemRegion reg in regions) {
if (reg.region.Contains(mousePoint)) {
CommandManager.ExecuteCommand(reg.item.GetCommand());
return;
}
}
}
private void OpenLootWindow(object sender, MouseEventArgs e) {
OpenItemWindow(sender, e, lootRegions);
}
private void OpenWasteWindow(object sender, MouseEventArgs e) {
OpenItemWindow(sender, e, wasteRegions);
}
private void OpenRecentDropsWindow(object sender, MouseEventArgs e) {
OpenItemWindow(sender, e, recentDropsRegions);
}
private int x = 5;
private List<Control> summaryControls = new List<Control>();
private List<Control> lootControls = new List<Control>();
private List<Control> damageControls = new List<Control>();
private List<Control> usedItemsControls = new List<Control>();
public override void LoadForm() {
this.SuspendForm();
Label label;
label = new Label();
label.Text = "Summary";
label.Location = new Point(x, 0);
label.Size = new Size(BlockWidth, 30);
label.BackColor = Color.Transparent;
label.ForeColor = StyleManager.NotificationTextColor;
label.Font = StyleManager.MainFormLabelFontSmall;
label.TextAlign = ContentAlignment.MiddleCenter;
this.Controls.Add(label);
this.NotificationInitialize();
this.NotificationFinalize();
this.ResumeForm();
this.RefreshForm();
}
public void ClearControlList(List<Control> list, out int minheight, out int maxheight) {
minheight = int.MaxValue;
maxheight = int.MinValue;
foreach (Control c in list) {
if (c.Location.Y < minheight) {
minheight = c.Location.Y;
}
if (c.Location.Y + c.Height > maxheight) {
maxheight = c.Location.Y + c.Height;
}
this.Controls.Remove(c);
c.Dispose();
}
list.Clear();
}
private long totalValue = 0;
private long averageValue = 0;
private long totalWaste = 0;
public void UpdateSummaryForm() {
int minheight, maxheight;
ClearControlList(summaryControls, out minheight, out maxheight);
int y = maxheight < 0 ? 30 : minheight;
PictureBox loot = CreateSummaryLabel("Loot value (gp)", totalValue.ToString("N0"), x, ref y, StyleManager.ItemGoldColor, summaryControls);
tooltip.SetToolTip(loot, String.Format("Average gold for these creature kills: {0} gold.", averageValue.ToString("N0")));
CreateSummaryLabel("Exp gained", HuntManager.activeHunt.totalExp.ToString("N0"), x, ref y, StyleManager.NotificationTextColor, summaryControls);
CreateSummaryLabel("Time", LootDropForm.TimeToString((long)HuntManager.activeHunt.totalTime), x, ref y, StyleManager.NotificationTextColor, summaryControls);
CreateSummaryLabel("Supplies used (gp)", totalWaste.ToString("N0"), x, ref y, StyleManager.WasteColor, summaryControls);
long profit = totalValue - totalWaste;
CreateSummaryLabel(profit > 0 ? "Profit (gp)" : "Waste (gp)", profit.ToString("N0"), x, ref y, profit > 0 ? StyleManager.ItemGoldColor : StyleManager.WasteColor, summaryControls);
if (ScanningManager.lastResults != null) {
CreateSummaryLabel("Exp/hour", ScanningManager.lastResults.expPerHour.ToString("N0"), x, ref y, StyleManager.NotificationTextColor, summaryControls);
}
if (MemoryReader.experience >= 0) {
long baseExperience = ExperienceBar.GetExperience(MemoryReader.level - 1);
long exp = MemoryReader.experience - baseExperience;
long maxExp = ExperienceBar.GetExperience(MemoryReader.level) - baseExperience;
double percentage = ((double) exp) / ((double) maxExp);
if (percentage >= 0 && percentage <= 1) {
var levelBar = CreateSummaryBar("Level", String.Format("{0:0.}%", percentage * 100), percentage, x, ref y, StyleManager.NotificationTextColor, StyleManager.SummaryExperienceColor, summaryControls);
tooltip.SetToolTip(levelBar, String.Format("Experience to level up: {0}", (maxExp - exp).ToString("N0")));
}
}
}
private void StartUpdateTimer() {
if (this.IsDisposed) return;
lock (updateLock) {
if (!updateTimer.Enabled) {
updateTimer.Start();
}
}
}
public void UpdateLoot() {
StartUpdateTimer();
}
public void UpdateDamage() {
StartUpdateTimer();
}
public void UpdateWaste() {
StartUpdateTimer();
}
public void UpdateLootForm() {
Hunt hunt = HuntManager.activeHunt;
int minheight, maxheight;
ClearControlList(lootControls, out minheight, out maxheight);
int counter;
int y = minheight;
if (maxheight < 0) {
y = 30;
foreach (Control c in summaryControls) {
y = Math.Max(c.Location.Y + c.Height, y);
}
}
var loot = LootDropForm.GenerateLootInformation(hunt, "", null);
totalValue = 0;
foreach (Tuple<Item, int> tpl in loot.Item2) {
totalValue += tpl.Item1.GetMaxValue() * tpl.Item2;
}
averageValue = LootDropForm.GetAverageGold(loot.Item1);
int maxDrops = SettingsManager.getSettingInt("SummaryMaxItemDrops");
if (maxDrops < 0) maxDrops = 5;
if (maxDrops > 0) {
List<ItemRegion> region;
int imageHeight = SettingsManager.getSettingInt("SummaryLootItemSize");
imageHeight = imageHeight < 0 ? BlockHeight : imageHeight;
CreateHeaderLabel("Item Drops", x, ref y, lootControls);
counter = 0;
bool display = true;
int width = 0;
var items = new List<Tuple<Item, int>>();
foreach (Tuple<Item, int> tpl in loot.Item2) {
int amount = tpl.Item2;
while (amount > 0) {
int count = Math.Min(100, amount);
amount -= count;
items.Add(new Tuple<Item, int>(tpl.Item1, count));
width += imageHeight + 2;
if (width > BlockWidth - imageHeight) {
region = new List<ItemRegion>();
CreateItemList(items, x, ref y, lootControls, imageHeight, region, counter).MouseDown += OpenLootWindow;
lootRegions[counter] = region;
items.Clear();
width = 0;
if (++counter >= maxDrops) {
display = false;
break;
}
}
}
if (!display) break;
}
if (items.Count > 0) {
region = new List<ItemRegion>();
CreateItemList(items, x, ref y, lootControls, imageHeight, region, counter).MouseDown += OpenLootWindow;
lootRegions[counter] = region;
items.Clear();
}
}
int maxCreatures = SettingsManager.getSettingInt("SummaryMaxCreatures");
if (maxCreatures < 0) maxCreatures = 5;
if (maxCreatures > 0) {
CreateHeaderLabel("Creature Kills", x, ref y, lootControls);
counter = 0;
foreach (Creature cr in loot.Item1.Keys.OrderByDescending(o => loot.Item1[o] * (1 + o.experience)).ToList<Creature>()) {
CreateCreatureBox(cr, loot.Item1[cr], x, ref y, lootControls);
if (++counter >= maxCreatures) break;
}
}
int maxRecentDrops = SettingsManager.getSettingInt("SummaryMaxRecentDrops");
if (maxRecentDrops < 0) maxRecentDrops = 5;
if (maxRecentDrops > 0) {
CreateHeaderLabel("Recent Drops", x, ref y, lootControls);
int imageHeight = SettingsManager.getSettingInt("SummaryRecentDropsItemSize");
imageHeight = imageHeight < 0 ? BlockHeight : imageHeight;
var recentDrops = ScanningManager.GetRecentDrops(maxRecentDrops);
int index = 0;
foreach (var drops in recentDrops) {
List<ItemRegion> region = new List<ItemRegion>();
CreateCreatureDropsBox(drops.Item1, drops.Item2, drops.Item3, x, ref y, lootControls, imageHeight, region, index).MouseDown += OpenRecentDropsWindow;
recentDropsRegions[index++] = region;
}
}
UpdateDamageForm();
}
public void UpdateDamageForm() {
Hunt hunt = HuntManager.activeHunt;
int minheight, maxheight;
ClearControlList(damageControls, out minheight, out maxheight);
int y = minheight;
y = 30;
foreach (Control c in lootControls.Count > 0 ? lootControls : summaryControls) {
y = Math.Max(c.Location.Y + c.Height, y);
}
int maxDamage = SettingsManager.getSettingInt("SummaryMaxDamagePlayers");
if (maxDamage < 0) maxDamage = 5;
if (maxDamage > 0 && ScanningManager.lastResults != null) {
CreateHeaderLabel("Damage Dealt", x, ref y, damageControls);
var dps = ScanningManager.lastResults.DamagePerSecond;
var damageDealt = DamageChart.GenerateDamageInformation(dps, "").Item2;
for (int i = 0; i < damageDealt.Count; i++) {
damageDealt[i].color = Constants.DamageChartColors[i % Constants.DamageChartColors.Count];
}
int counter = 0;
foreach (DamageObject obj in damageDealt) {
CreateSummaryLabel(obj.name, String.Format("{0:0.0}%", obj.percentage), x, ref y, obj.color, damageControls);
if (++counter >= maxDamage) {
break;
}
}
}
UpdateWasteForm();
}
public void UpdateWasteForm() {
Hunt hunt = HuntManager.activeHunt;
int minheight, maxheight;
ClearControlList(usedItemsControls, out minheight, out maxheight);
int y = 30;
foreach (Control c in damageControls.Count > 0 ? damageControls : (lootControls.Count > 0 ? lootControls : summaryControls)) {
y = Math.Max(c.Location.Y + c.Height, y);
}
totalWaste = 0;
int maxUsedItems = SettingsManager.getSettingInt("SummaryMaxUsedItems");
if (maxUsedItems < 0) maxUsedItems = 5;
if (maxUsedItems > 0) {
List<ItemRegion> region;
int imageHeight = SettingsManager.getSettingInt("SummaryWasteItemSize");
imageHeight = imageHeight < 0 ? BlockHeight : imageHeight;
int counter = 0;
CreateHeaderLabel("Used Items", x, ref y, usedItemsControls);
int width = 0;
var items = new List<Tuple<Item, int>>();
bool display = true;
foreach (Tuple<Item, int> tpl in HuntManager.GetUsedItems(hunt)) {
int amount = tpl.Item2;
totalWaste += amount * tpl.Item1.GetMaxValue();
while (amount > 0 && display) {
int count = Math.Min(100, amount);
amount -= count;
items.Add(new Tuple<Item, int>(tpl.Item1, count));
width += imageHeight + 2;
if (width > BlockWidth - imageHeight) {
region = new List<ItemRegion>();
CreateItemList(items, x, ref y, usedItemsControls, imageHeight, region, counter).MouseDown += OpenWasteWindow;
wasteRegions[counter] = region;
items.Clear();
width = 0;
if (++counter >= maxUsedItems) display = false;
}
}
}
if (items.Count > 0) {
region = new List<ItemRegion>();
CreateItemList(items, x, ref y, usedItemsControls, imageHeight, region, counter).MouseDown += OpenWasteWindow;
wasteRegions[counter] = region;
items.Clear();
}
}
if (y != maxheight) {
this.Size = new Size(BlockWidth + 10, y + 5);
}
}
private void CommandClick(object sender, EventArgs e) {
CommandManager.ExecuteCommand((sender as Control).Name);
}
public override string FormName() {
return "SummaryForm";
}
public override int MinWidth() {
return 210;
}
public override int MaxWidth() {
return 810;
}
public override int WidthInterval() {
return 50;
}
public override void RefreshForm() {
this.SuspendForm();
this.Size = new Size(GetWidth(), this.Size.Height);
BlockWidth = this.Size.Width - 10;
UpdateSummaryForm();
UpdateLootForm();
UpdateDamageForm();
UpdateWasteForm();
//update the summary form again because the loot value is computed in UpdateLootForm()
//and UpdateLootForm() has to be called after UpdateLootForm() because it needs the controls to be added to compute its base y position
UpdateSummaryForm();
this.ResumeForm();
}
}
}
| |
//
// Solver.cs
//
// Author:
// Gabriel Burt <[email protected]>
//
// Copyright 2010 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Linq;
using System.Collections.Generic;
using Mono.Unix;
using Hyena.Data.Sqlite;
using Banshee.Sources;
using Banshee.ServiceStack;
using Banshee.Configuration;
namespace Banshee.Fixup
{
public abstract class Solver : IDisposable
{
private string id;
/* Find the highest TrackNumber for albums where not all tracks have it set */
//SELECT AlbumID, Max(TrackCount) as MaxTrackNum FROM CoreTracks GROUP BY AlbumID HAVING MaxTrackNum > 0 AND MaxTrackNum != Min(TrackCount);
public Solver ()
{
}
internal protected virtual Banshee.Preferences.Section PreferencesSection {
get { return null; }
}
// Total hack to work make unit tests work
internal static bool EnableUnitTests;
public string Id {
get { return id; }
set {
if (id != null) {
throw new InvalidOperationException ("Solver's Id is already set; can't change it");
}
id = value;
if (!EnableUnitTests) {
Generation = DatabaseConfigurationClient.Client.Get<int> ("MetadataFixupGeneration", id, 0);
}
}
}
public string Name { get; set; }
public string Description { get; set; }
public int Generation { get; private set; }
internal protected virtual bool HasTrackDetails {
get { return false; }
}
public void FindProblems ()
{
// Bump the generation number
Generation++;
DatabaseConfigurationClient.Client.Set<int> ("MetadataFixupGeneration", Id, Generation);
// Identify the new issues
IdentifyCore ();
// Unselect any problems that the user had previously unselected
ServiceManager.DbConnection.Execute (
@"UPDATE MetadataProblems SET Selected = 0 WHERE ProblemType = ? AND Generation = ? AND ObjectIds IN
(SELECT ObjectIds FROM MetadataProblems WHERE ProblemType = ? AND Generation = ? AND Selected = 0)",
Id, Generation, Id, Generation - 1
);
// Delete the previous generation's issues
ServiceManager.DbConnection.Execute (
"DELETE FROM MetadataProblems WHERE ProblemType = ? AND Generation = ?",
Id, Generation - 1
);
}
public virtual void Dispose () {}
public void FixSelected ()
{
Fix (Problem.Provider.FetchAllMatching ("Selected = 1"));
}
protected abstract void IdentifyCore ();
public abstract void Fix (IEnumerable<Problem> problems);
public virtual void SetStatus (SourceMessage status_message, string preferences_page_id)
{
}
}
public abstract class DuplicateSolver : Solver
{
private List<HyenaSqliteCommand> find_cmds = new List<HyenaSqliteCommand> ();
public void AddFinder (string value_column, string id_column, string from, string condition, string group_by)
{
/* The val result SQL gives us the first/highest value (in descending
* sort order), so Foo Fighters over foo fighters. Except it ignore all caps
* ASCII values, so given the values Foo, FOO, and foo, they sort as
* FOO, Foo, and foo, but we ignore FOO and pick Foo. But because sqlite's
* lower/upper functions only work for ASCII, our check for whether the
* value is all uppercase involves ensuring that it doesn't also appear to be
* lower case (that is, it may have zero ASCII characters).
*
* TODO: replace with a custom SQLite function
*
*/
find_cmds.Add (new HyenaSqliteCommand (String.Format (@"
INSERT INTO MetadataProblems (ProblemType, TypeOrder, Generation, SolutionValue, SolutionOptions, ObjectIds, ObjectCount)
SELECT
'{0}', {1}, {2},
COALESCE (
NULLIF (
MIN(CASE (upper({3}) = {3} AND NOT lower({3}) = {3})
WHEN 1 THEN '~~~'
ELSE {3} END),
'~~~'),
{3}) as val,
substr(group_concat({3}, ';;'), 1),
substr(group_concat({4}, ','), 1),
count(*) as num
FROM {5}
WHERE {6}
GROUP BY {7} HAVING num > 1
ORDER BY {3}",
Id, 1, "?", // ? is for the Generation variable, which changes
value_column, id_column, from, condition ?? "1=1", group_by))
);
}
protected override void IdentifyCore ()
{
// Prune artists and albums that are no longer used
ServiceManager.DbConnection.Execute (@"
DELETE FROM CoreAlbums WHERE AlbumID NOT IN (SELECT DISTINCT(AlbumID) FROM CoreTracks);
DELETE FROM CoreArtists WHERE
ArtistID NOT IN (SELECT DISTINCT(ArtistID) FROM CoreTracks) AND
ArtistID NOT IN (SELECT DISTINCT(ArtistID) FROM CoreAlbums WHERE ArtistID IS NOT NULL);"
);
foreach (HyenaSqliteCommand cmd in find_cmds) {
ServiceManager.DbConnection.Execute (cmd, Generation);
}
}
}
public static class FixupExtensions
{
public static string NormalizeConjunctions (this string input)
{
return input.Replace (" & ", " and ");
}
public static string RemovePrefixedArticles (this string input)
{
foreach (var prefix in article_prefixes) {
if (input.StartsWith (prefix)) {
input = input.Substring (prefix.Length, input.Length - prefix.Length);
}
}
return input;
}
public static string RemoveSuffixedArticles (this string input)
{
foreach (var suffix in article_suffixes) {
if (input.EndsWith (suffix)) {
input = input.Substring (0, input.Length - suffix.Length);
}
}
return input;
}
static string [] article_prefixes;
static string [] article_suffixes;
static FixupExtensions ()
{
// Translators: These are articles that might be prefixed or suffixed
// on artist names or album titles. You can add as many as you need,
// separated by a pipe (|)
var articles = (Catalog.GetString ("a|an|the") + "|a|an|the").Split ('|').Distinct ();
// Translators: This is the format commonly used in your langauge for
// suffixing an article, eg in English: ", The"
var suffix_format = Catalog.GetString (", {0}");
article_prefixes = articles.Select (a => a + " ")
.ToArray ();
article_suffixes = articles.SelectMany (a =>
new string [] { String.Format (suffix_format, a), ", " + a }
).Distinct ().ToArray ();
}
}
/*public class CompilationSolver : Solver
{
private HyenaSqliteCommand find_cmd;
public CompilationSolver ()
{
Id = "make-compilation";
Name = Catalog.GetString ("Compilation Albums");
ShortDescription = Catalog.GetString ("Find albums that should be marked as compilation albums");
LongDescription = Catalog.GetString ("Find albums that should be marked as compilation albums but are not");
Action = Catalog.GetString ("Mark as compilation");
find_cmd = new HyenaSqliteCommand (String.Format (@"
INSERT INTO MetadataProblems (ProblemType, TypeOrder, Generation, SolutionValue, Options, Summary, Count)
SELECT
'{0}', {1}, {2},
a.Title, a.Title, a.Title, count(*) as numtracks
FROM
CoreTracks t,
CoreAlbums a
WHERE
t.PrimarySourceID = 1 AND
a.IsCompilation = 0 AND
t.AlbumID = a.AlbumID
GROUP BY
a.Title
HAVING
numtracks > 1 AND
t.TrackCount = {3} AND
a.Title != 'Unknown Album' AND
a.Title != 'title' AND
a.Title != 'no title' AND
a.Title != 'Album' AND
a.Title != 'Music' AND (
{5} > 1 AND {5} = {4} AND (
{3} = 0 OR ({3} >= {5}
AND {3} >= numtracks))
OR lower(a.Title) LIKE '%soundtrack%'
OR lower(a.Title) LIKE '%soundtrack%'
)",
Id, Order, Generation,
"max(t.TrackCount)", "count(distinct(t.artistid))", "count(distinct(t.albumid))"
));
}
protected override void IdentifyCore ()
{
ServiceManager.DbConnection.Execute (find_cmd);
}
public override void Fix (IEnumerable<Problem> problems)
{
Console.WriteLine ("Asked to fix compilations..");
}
}*/
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
using Microsoft.WindowsAzure.Common.Internals;
using Microsoft.WindowsAzure.Management.Sql;
using Microsoft.WindowsAzure.Management.Sql.Models;
namespace Microsoft.WindowsAzure.Management.Sql
{
/// <summary>
/// The Azure SQL Database Management API includes operations for managing
/// the server-level Firewall Rules for Azure SQL Database Servers. You
/// cannot manage the database-level firewall rules using the Azure SQL
/// Database Management API; they can only be managed by running the
/// Transact-SQL statements against the master or individual user
/// databases.
/// </summary>
internal partial class FirewallRuleOperations : IServiceOperations<SqlManagementClient>, Microsoft.WindowsAzure.Management.Sql.IFirewallRuleOperations
{
/// <summary>
/// Initializes a new instance of the FirewallRuleOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal FirewallRuleOperations(SqlManagementClient client)
{
this._client = client;
}
private SqlManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.Sql.SqlManagementClient.
/// </summary>
public SqlManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Adds a new server-level Firewall Rule for an Azure SQL Database
/// Server.
/// </summary>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server to which this
/// rule will be applied.
/// </param>
/// <param name='parameters'>
/// Required. The parameters for the Create Firewall Rule operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Contains the response to a Create Firewall Rule operation.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Sql.Models.FirewallRuleCreateResponse> CreateAsync(string serverName, FirewallRuleCreateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.EndIPAddress == null)
{
throw new ArgumentNullException("parameters.EndIPAddress");
}
if (parameters.Name == null)
{
throw new ArgumentNullException("parameters.Name");
}
if (parameters.StartIPAddress == null)
{
throw new ArgumentNullException("parameters.StartIPAddress");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "CreateAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/sqlservers/servers/" + serverName.Trim() + "/firewallrules";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2012-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement serviceResourceElement = new XElement(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure"));
requestDoc.Add(serviceResourceElement);
XElement nameElement = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
nameElement.Value = parameters.Name;
serviceResourceElement.Add(nameElement);
XElement startIPAddressElement = new XElement(XName.Get("StartIPAddress", "http://schemas.microsoft.com/windowsazure"));
startIPAddressElement.Value = parameters.StartIPAddress;
serviceResourceElement.Add(startIPAddressElement);
XElement endIPAddressElement = new XElement(XName.Get("EndIPAddress", "http://schemas.microsoft.com/windowsazure"));
endIPAddressElement.Value = parameters.EndIPAddress;
serviceResourceElement.Add(endIPAddressElement);
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
FirewallRuleCreateResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new FirewallRuleCreateResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement serviceResourceElement2 = responseDoc.Element(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure"));
if (serviceResourceElement2 != null)
{
FirewallRule serviceResourceInstance = new FirewallRule();
result.FirewallRule = serviceResourceInstance;
XElement startIPAddressElement2 = serviceResourceElement2.Element(XName.Get("StartIPAddress", "http://schemas.microsoft.com/windowsazure"));
if (startIPAddressElement2 != null)
{
string startIPAddressInstance = startIPAddressElement2.Value;
serviceResourceInstance.StartIPAddress = startIPAddressInstance;
}
XElement endIPAddressElement2 = serviceResourceElement2.Element(XName.Get("EndIPAddress", "http://schemas.microsoft.com/windowsazure"));
if (endIPAddressElement2 != null)
{
string endIPAddressInstance = endIPAddressElement2.Value;
serviceResourceInstance.EndIPAddress = endIPAddressInstance;
}
XElement nameElement2 = serviceResourceElement2.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement2 != null)
{
string nameInstance = nameElement2.Value;
serviceResourceInstance.Name = nameInstance;
}
XElement typeElement = serviceResourceElement2.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
if (typeElement != null)
{
string typeInstance = typeElement.Value;
serviceResourceInstance.Type = typeInstance;
}
XElement stateElement = serviceResourceElement2.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
if (stateElement != null)
{
string stateInstance = stateElement.Value;
serviceResourceInstance.State = stateInstance;
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Deletes a server-level Firewall Rule from an Azure SQL Database
/// Server.
/// </summary>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server that will have
/// the Firewall Fule removed from it.
/// </param>
/// <param name='ruleName'>
/// Required. The name of the Firewall Fule to delete.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async System.Threading.Tasks.Task<OperationResponse> DeleteAsync(string serverName, string ruleName, CancellationToken cancellationToken)
{
// Validate
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (ruleName == null)
{
throw new ArgumentNullException("ruleName");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("ruleName", ruleName);
Tracing.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/sqlservers/servers/" + serverName.Trim() + "/firewallrules/" + ruleName.Trim();
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2012-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationResponse result = null;
result = new OperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Returns the Firewall rule for an Azure SQL Database Server with a
/// matching name.
/// </summary>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server to query for
/// the Firewall Rule.
/// </param>
/// <param name='ruleName'>
/// Required. The name of the rule to retrieve.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Contains the response from a request to Get Firewall Rule.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Sql.Models.FirewallRuleGetResponse> GetAsync(string serverName, string ruleName, CancellationToken cancellationToken)
{
// Validate
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (ruleName == null)
{
throw new ArgumentNullException("ruleName");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("ruleName", ruleName);
Tracing.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/sqlservers/servers/" + serverName.Trim() + "/firewallrules/" + ruleName.Trim();
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2012-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
FirewallRuleGetResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new FirewallRuleGetResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement serviceResourceElement = responseDoc.Element(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure"));
if (serviceResourceElement != null)
{
FirewallRule serviceResourceInstance = new FirewallRule();
result.FirewallRule = serviceResourceInstance;
XElement startIPAddressElement = serviceResourceElement.Element(XName.Get("StartIPAddress", "http://schemas.microsoft.com/windowsazure"));
if (startIPAddressElement != null)
{
string startIPAddressInstance = startIPAddressElement.Value;
serviceResourceInstance.StartIPAddress = startIPAddressInstance;
}
XElement endIPAddressElement = serviceResourceElement.Element(XName.Get("EndIPAddress", "http://schemas.microsoft.com/windowsazure"));
if (endIPAddressElement != null)
{
string endIPAddressInstance = endIPAddressElement.Value;
serviceResourceInstance.EndIPAddress = endIPAddressInstance;
}
XElement nameElement = serviceResourceElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement != null)
{
string nameInstance = nameElement.Value;
serviceResourceInstance.Name = nameInstance;
}
XElement typeElement = serviceResourceElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
if (typeElement != null)
{
string typeInstance = typeElement.Value;
serviceResourceInstance.Type = typeInstance;
}
XElement stateElement = serviceResourceElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
if (stateElement != null)
{
string stateInstance = stateElement.Value;
serviceResourceInstance.State = stateInstance;
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Returns a list of server-level Firewall Rules for an Azure SQL
/// Database Server.
/// </summary>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server from which to
/// list the Firewall Rules.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Contains the response from a request to List Firewall Rules.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Sql.Models.FirewallRuleListResponse> ListAsync(string serverName, CancellationToken cancellationToken)
{
// Validate
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serverName", serverName);
Tracing.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/sqlservers/servers/" + serverName.Trim() + "/firewallrules";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2012-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
FirewallRuleListResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new FirewallRuleListResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement serviceResourcesSequenceElement = responseDoc.Element(XName.Get("ServiceResources", "http://schemas.microsoft.com/windowsazure"));
if (serviceResourcesSequenceElement != null)
{
foreach (XElement serviceResourcesElement in serviceResourcesSequenceElement.Elements(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure")))
{
FirewallRule serviceResourceInstance = new FirewallRule();
result.FirewallRules.Add(serviceResourceInstance);
XElement startIPAddressElement = serviceResourcesElement.Element(XName.Get("StartIPAddress", "http://schemas.microsoft.com/windowsazure"));
if (startIPAddressElement != null)
{
string startIPAddressInstance = startIPAddressElement.Value;
serviceResourceInstance.StartIPAddress = startIPAddressInstance;
}
XElement endIPAddressElement = serviceResourcesElement.Element(XName.Get("EndIPAddress", "http://schemas.microsoft.com/windowsazure"));
if (endIPAddressElement != null)
{
string endIPAddressInstance = endIPAddressElement.Value;
serviceResourceInstance.EndIPAddress = endIPAddressInstance;
}
XElement nameElement = serviceResourcesElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement != null)
{
string nameInstance = nameElement.Value;
serviceResourceInstance.Name = nameInstance;
}
XElement typeElement = serviceResourcesElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
if (typeElement != null)
{
string typeInstance = typeElement.Value;
serviceResourceInstance.Type = typeInstance;
}
XElement stateElement = serviceResourcesElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
if (stateElement != null)
{
string stateInstance = stateElement.Value;
serviceResourceInstance.State = stateInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Updates an existing server-level Firewall Rule for an Azure SQL
/// Database Server.
/// </summary>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server that has the
/// Firewall Rule to be updated.
/// </param>
/// <param name='ruleName'>
/// Required. The name of the Firewall Rule to be updated.
/// </param>
/// <param name='parameters'>
/// Required. The parameters for the Update Firewall Rule operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the firewall rule update response.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Sql.Models.FirewallRuleUpdateResponse> UpdateAsync(string serverName, string ruleName, FirewallRuleUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (ruleName == null)
{
throw new ArgumentNullException("ruleName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.EndIPAddress == null)
{
throw new ArgumentNullException("parameters.EndIPAddress");
}
if (parameters.Name == null)
{
throw new ArgumentNullException("parameters.Name");
}
if (parameters.StartIPAddress == null)
{
throw new ArgumentNullException("parameters.StartIPAddress");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("ruleName", ruleName);
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "UpdateAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/sqlservers/servers/" + serverName.Trim() + "/firewallrules/" + ruleName.Trim();
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2012-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement serviceResourceElement = new XElement(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure"));
requestDoc.Add(serviceResourceElement);
XElement nameElement = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
nameElement.Value = parameters.Name;
serviceResourceElement.Add(nameElement);
XElement startIPAddressElement = new XElement(XName.Get("StartIPAddress", "http://schemas.microsoft.com/windowsazure"));
startIPAddressElement.Value = parameters.StartIPAddress;
serviceResourceElement.Add(startIPAddressElement);
XElement endIPAddressElement = new XElement(XName.Get("EndIPAddress", "http://schemas.microsoft.com/windowsazure"));
endIPAddressElement.Value = parameters.EndIPAddress;
serviceResourceElement.Add(endIPAddressElement);
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
FirewallRuleUpdateResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new FirewallRuleUpdateResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement serviceResourceElement2 = responseDoc.Element(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure"));
if (serviceResourceElement2 != null)
{
FirewallRule serviceResourceInstance = new FirewallRule();
result.FirewallRule = serviceResourceInstance;
XElement startIPAddressElement2 = serviceResourceElement2.Element(XName.Get("StartIPAddress", "http://schemas.microsoft.com/windowsazure"));
if (startIPAddressElement2 != null)
{
string startIPAddressInstance = startIPAddressElement2.Value;
serviceResourceInstance.StartIPAddress = startIPAddressInstance;
}
XElement endIPAddressElement2 = serviceResourceElement2.Element(XName.Get("EndIPAddress", "http://schemas.microsoft.com/windowsazure"));
if (endIPAddressElement2 != null)
{
string endIPAddressInstance = endIPAddressElement2.Value;
serviceResourceInstance.EndIPAddress = endIPAddressInstance;
}
XElement nameElement2 = serviceResourceElement2.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement2 != null)
{
string nameInstance = nameElement2.Value;
serviceResourceInstance.Name = nameInstance;
}
XElement typeElement = serviceResourceElement2.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
if (typeElement != null)
{
string typeInstance = typeElement.Value;
serviceResourceInstance.Type = typeInstance;
}
XElement stateElement = serviceResourceElement2.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
if (stateElement != null)
{
string stateInstance = stateElement.Value;
serviceResourceInstance.State = stateInstance;
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
namespace System.Linq.Expressions.Interpreter
{
internal abstract class OffsetInstruction : Instruction
{
internal const int Unknown = Int32.MinValue;
internal const int CacheSize = 32;
// the offset to jump to (relative to this instruction):
protected int _offset = Unknown;
public int Offset { get { return _offset; } }
public abstract Instruction[] Cache { get; }
public override string InstructionName
{
get { return "Offset"; }
}
public Instruction Fixup(int offset)
{
Debug.Assert(_offset == Unknown && offset != Unknown);
_offset = offset;
var cache = Cache;
if (cache != null && offset >= 0 && offset < cache.Length)
{
return cache[offset] ?? (cache[offset] = this);
}
return this;
}
public override string ToDebugString(int instructionIndex, object cookie, Func<int, int> labelIndexer, IList<object> objects)
{
return ToString() + (_offset != Unknown ? " -> " + (instructionIndex + _offset) : "");
}
public override string ToString()
{
return InstructionName + (_offset == Unknown ? "(?)" : "(" + _offset + ")");
}
}
internal sealed class BranchFalseInstruction : OffsetInstruction
{
private static Instruction[] s_cache;
public override string InstructionName
{
get { return "BranchFalse"; }
}
public override Instruction[] Cache
{
get
{
if (s_cache == null)
{
s_cache = new Instruction[CacheSize];
}
return s_cache;
}
}
internal BranchFalseInstruction()
{
}
public override int ConsumedStack { get { return 1; } }
public override int Run(InterpretedFrame frame)
{
Debug.Assert(_offset != Unknown);
if (!(bool)frame.Pop())
{
return _offset;
}
return +1;
}
}
internal sealed class BranchTrueInstruction : OffsetInstruction
{
private static Instruction[] s_cache;
public override string InstructionName
{
get { return "BranchTrue"; }
}
public override Instruction[] Cache
{
get
{
if (s_cache == null)
{
s_cache = new Instruction[CacheSize];
}
return s_cache;
}
}
internal BranchTrueInstruction()
{
}
public override int ConsumedStack { get { return 1; } }
public override int Run(InterpretedFrame frame)
{
Debug.Assert(_offset != Unknown);
if ((bool)frame.Pop())
{
return _offset;
}
return +1;
}
}
internal sealed class CoalescingBranchInstruction : OffsetInstruction
{
private static Instruction[] s_cache;
public override string InstructionName
{
get { return "CoalescingBranch"; }
}
public override Instruction[] Cache
{
get
{
if (s_cache == null)
{
s_cache = new Instruction[CacheSize];
}
return s_cache;
}
}
internal CoalescingBranchInstruction()
{
}
public override int ConsumedStack { get { return 1; } }
public override int ProducedStack { get { return 1; } }
public override int Run(InterpretedFrame frame)
{
Debug.Assert(_offset != Unknown);
if (frame.Peek() != null)
{
return _offset;
}
return +1;
}
}
internal class BranchInstruction : OffsetInstruction
{
private static Instruction[][][] s_caches;
public override string InstructionName
{
get { return "Branch"; }
}
public override Instruction[] Cache
{
get
{
if (s_caches == null)
{
s_caches = new Instruction[2][][] { new Instruction[2][], new Instruction[2][] };
}
return s_caches[ConsumedStack][ProducedStack] ?? (s_caches[ConsumedStack][ProducedStack] = new Instruction[CacheSize]);
}
}
internal readonly bool _hasResult;
internal readonly bool _hasValue;
internal BranchInstruction()
: this(false, false)
{
}
public BranchInstruction(bool hasResult, bool hasValue)
{
_hasResult = hasResult;
_hasValue = hasValue;
}
public override int ConsumedStack
{
get { return _hasValue ? 1 : 0; }
}
public override int ProducedStack
{
get { return _hasResult ? 1 : 0; }
}
public override int Run(InterpretedFrame frame)
{
Debug.Assert(_offset != Unknown);
return _offset;
}
}
internal abstract class IndexedBranchInstruction : Instruction
{
protected const int CacheSize = 32;
public override string InstructionName
{
get { return "IndexedBranch"; }
}
internal readonly int _labelIndex;
public IndexedBranchInstruction(int labelIndex)
{
_labelIndex = labelIndex;
}
public RuntimeLabel GetLabel(InterpretedFrame frame)
{
Debug.Assert(_labelIndex != UnknownInstrIndex);
return frame.Interpreter._labels[_labelIndex];
}
public override string ToDebugString(int instructionIndex, object cookie, Func<int, int> labelIndexer, IList<object> objects)
{
Debug.Assert(_labelIndex != UnknownInstrIndex);
int targetIndex = labelIndexer(_labelIndex);
return ToString() + (targetIndex != BranchLabel.UnknownIndex ? " -> " + targetIndex : "");
}
public override string ToString()
{
Debug.Assert(_labelIndex != UnknownInstrIndex);
return InstructionName + "[" + _labelIndex + "]";
}
}
/// <summary>
/// This instruction implements a goto expression that can jump out of any expression.
/// It pops values (arguments) from the evaluation stack that the expression tree nodes in between
/// the goto expression and the target label node pushed and not consumed yet.
/// A goto expression can jump into a node that evaluates arguments only if it carries
/// a value and jumps right after the first argument (the carried value will be used as the first argument).
/// Goto can jump into an arbitrary child of a BlockExpression since the block doesn't accumulate values
/// on evaluation stack as its child expressions are being evaluated.
///
/// Goto needs to execute any finally blocks on the way to the target label.
/// <example>
/// {
/// f(1, 2, try { g(3, 4, try { goto L } finally { ... }, 6) } finally { ... }, 7, 8)
/// L: ...
/// }
/// </example>
/// The goto expression here jumps to label L while having 4 items on evaluation stack (1, 2, 3 and 4).
/// The jump needs to execute both finally blocks, the first one on stack level 4 the
/// second one on stack level 2. So, it needs to jump the first finally block, pop 2 items from the stack,
/// run second finally block and pop another 2 items from the stack and set instruction pointer to label L.
///
/// Goto also needs to rethrow ThreadAbortException iff it jumps out of a catch handler and
/// the current thread is in "abort requested" state.
/// </summary>
internal sealed class GotoInstruction : IndexedBranchInstruction
{
private const int Variants = 8;
private static readonly GotoInstruction[] s_cache = new GotoInstruction[Variants * CacheSize];
public override string InstructionName
{
get { return "Goto"; }
}
private readonly bool _hasResult;
private readonly bool _hasValue;
private readonly bool _labelTargetGetsValue;
// The values should technically be Consumed = 1, Produced = 1 for gotos that target a label whose continuation depth
// is different from the current continuation depth. This is because we will consume one continuation from the _continuations
// and at meantime produce a new _pendingContinuation. However, in case of forward gotos, we don't not know that is the
// case until the label is emitted. By then the consumed and produced stack information is useless.
// The important thing here is that the stack balance is 0.
public override int ConsumedContinuations { get { return 0; } }
public override int ProducedContinuations { get { return 0; } }
public override int ConsumedStack
{
get { return _hasValue ? 1 : 0; }
}
public override int ProducedStack
{
get { return _hasResult ? 1 : 0; }
}
private GotoInstruction(int targetIndex, bool hasResult, bool hasValue, bool labelTargetGetsValue)
: base(targetIndex)
{
_hasResult = hasResult;
_hasValue = hasValue;
_labelTargetGetsValue = labelTargetGetsValue;
}
internal static GotoInstruction Create(int labelIndex, bool hasResult, bool hasValue, bool labelTargetGetsValue)
{
if (labelIndex < CacheSize)
{
var index = Variants * labelIndex | (labelTargetGetsValue ? 4 : 0) | (hasResult ? 2 : 0) | (hasValue ? 1 : 0);
return s_cache[index] ?? (s_cache[index] = new GotoInstruction(labelIndex, hasResult, hasValue, labelTargetGetsValue));
}
return new GotoInstruction(labelIndex, hasResult, hasValue, labelTargetGetsValue);
}
public override int Run(InterpretedFrame frame)
{
// Are we jumping out of catch/finally while aborting the current thread?
#if FEATURE_THREAD_ABORT
Interpreter.AbortThreadIfRequested(frame, _labelIndex);
#endif
// goto the target label or the current finally continuation:
object value = _hasValue ? frame.Pop() : Interpreter.NoValue;
return frame.Goto(_labelIndex, _labelTargetGetsValue ? value : Interpreter.NoValue, gotoExceptionHandler: false);
}
}
internal sealed class EnterTryCatchFinallyInstruction : IndexedBranchInstruction
{
private readonly bool _hasFinally = false;
private TryCatchFinallyHandler _tryHandler;
internal void SetTryHandler(TryCatchFinallyHandler tryHandler)
{
Debug.Assert(_tryHandler == null && tryHandler != null, "the tryHandler can be set only once");
_tryHandler = tryHandler;
}
public override int ProducedContinuations { get { return _hasFinally ? 1 : 0; } }
private EnterTryCatchFinallyInstruction(int targetIndex, bool hasFinally)
: base(targetIndex)
{
_hasFinally = hasFinally;
}
internal static EnterTryCatchFinallyInstruction CreateTryFinally(int labelIndex)
{
return new EnterTryCatchFinallyInstruction(labelIndex, true);
}
internal static EnterTryCatchFinallyInstruction CreateTryCatch()
{
return new EnterTryCatchFinallyInstruction(UnknownInstrIndex, false);
}
public override int Run(InterpretedFrame frame)
{
Debug.Assert(_tryHandler != null, "the tryHandler must be set already");
if (_hasFinally)
{
// Push finally.
frame.PushContinuation(_labelIndex);
}
int prevInstrIndex = frame.InstructionIndex;
frame.InstructionIndex++;
// Start to run the try/catch/finally blocks
var instructions = frame.Interpreter.Instructions.Instructions;
ExceptionHandler exHandler;
try
{
// run the try block
int index = frame.InstructionIndex;
while (index >= _tryHandler.TryStartIndex && index < _tryHandler.TryEndIndex)
{
index += instructions[index].Run(frame);
frame.InstructionIndex = index;
}
// we finish the try block and is about to jump out of the try/catch blocks
if (index == _tryHandler.GotoEndTargetIndex)
{
// run the 'Goto' that jumps out of the try/catch/finally blocks
Debug.Assert(instructions[index] is GotoInstruction, "should be the 'Goto' instruction that jumps out the try/catch/finally");
frame.InstructionIndex += instructions[index].Run(frame);
}
}
catch (RethrowException)
{
// a rethrow instruction in the try handler gets to run
throw;
}
catch (Exception exception) when (_tryHandler.HasHandler(frame, ref exception, out exHandler))
{
frame.InstructionIndex += frame.Goto(exHandler.LabelIndex, exception, gotoExceptionHandler: true);
#if FEATURE_THREAD_ABORT
// stay in the current catch so that ThreadAbortException is not rethrown by CLR:
var abort = exception as ThreadAbortException;
if (abort != null)
{
Interpreter.AnyAbortException = abort;
frame.CurrentAbortHandler = exHandler;
}
#endif
bool rethrow = false;
try
{
// run the catch block
int index = frame.InstructionIndex;
while (index >= exHandler.HandlerStartIndex && index < exHandler.HandlerEndIndex)
{
index += instructions[index].Run(frame);
frame.InstructionIndex = index;
}
// we finish the catch block and is about to jump out of the try/catch blocks
if (index == _tryHandler.GotoEndTargetIndex)
{
// run the 'Goto' that jumps out of the try/catch/finally blocks
Debug.Assert(instructions[index] is GotoInstruction, "should be the 'Goto' instruction that jumps out the try/catch/finally");
frame.InstructionIndex += instructions[index].Run(frame);
}
}
catch (RethrowException)
{
// a rethrow instruction in a catch block gets to run
rethrow = true;
}
if (rethrow) { throw; }
}
finally
{
if (_tryHandler.IsFinallyBlockExist)
{
// We get to the finally block in two paths:
// 1. Jump from the try/catch blocks. This includes two sub-routes:
// a. 'Goto' instruction in the middle of try/catch block
// b. try/catch block runs to its end. Then the 'Goto(end)' will be trigger to jump out of the try/catch block
// 2. Exception thrown from the try/catch blocks
// In the first path, the continuation mechanism works and frame.InstructionIndex will be updated to point to the first instruction of the finally block
// In the second path, the continuation mechanism is not involved and frame.InstructionIndex is not updated
#if DEBUG
bool isFromJump = frame.IsJumpHappened();
Debug.Assert(!isFromJump || (isFromJump && _tryHandler.FinallyStartIndex == frame.InstructionIndex), "we should already jump to the first instruction of the finally");
#endif
// run the finally block
// we cannot jump out of the finally block, and we cannot have an immediate rethrow in it
int index = frame.InstructionIndex = _tryHandler.FinallyStartIndex;
while (index >= _tryHandler.FinallyStartIndex && index < _tryHandler.FinallyEndIndex)
{
index += instructions[index].Run(frame);
frame.InstructionIndex = index;
}
}
}
return frame.InstructionIndex - prevInstrIndex;
}
public override string InstructionName
{
get { return _hasFinally ? "EnterTryFinally" : "EnterTryCatch"; }
}
public override string ToString()
{
return _hasFinally ? "EnterTryFinally[" + _labelIndex + "]" : "EnterTryCatch";
}
}
/// <summary>
/// The first instruction of finally block.
/// </summary>
internal sealed class EnterFinallyInstruction : IndexedBranchInstruction
{
private readonly static EnterFinallyInstruction[] s_cache = new EnterFinallyInstruction[CacheSize];
public override string InstructionName
{
get { return "EnterFinally"; }
}
public override int ProducedStack { get { return 2; } }
public override int ConsumedContinuations { get { return 1; } }
private EnterFinallyInstruction(int labelIndex)
: base(labelIndex)
{
}
internal static EnterFinallyInstruction Create(int labelIndex)
{
if (labelIndex < CacheSize)
{
return s_cache[labelIndex] ?? (s_cache[labelIndex] = new EnterFinallyInstruction(labelIndex));
}
return new EnterFinallyInstruction(labelIndex);
}
public override int Run(InterpretedFrame frame)
{
// If _pendingContinuation == -1 then we were getting into the finally block because an exception was thrown
// in this case we need to set the stack depth
// Else we were getting into this finally block from a 'Goto' jump, and the stack depth is already set properly
if (!frame.IsJumpHappened())
{
frame.SetStackDepth(GetLabel(frame).StackDepth);
}
frame.PushPendingContinuation();
frame.RemoveContinuation();
return 1;
}
}
/// <summary>
/// The last instruction of finally block.
/// </summary>
internal sealed class LeaveFinallyInstruction : Instruction
{
internal static readonly Instruction Instance = new LeaveFinallyInstruction();
public override int ConsumedStack { get { return 2; } }
public override string InstructionName
{
get { return "LeaveFinally"; }
}
private LeaveFinallyInstruction()
{
}
public override int Run(InterpretedFrame frame)
{
frame.PopPendingContinuation();
// If _pendingContinuation == -1 then we were getting into the finally block because an exception was thrown
// In this case we just return 1, and the real instruction index will be calculated by GotoHandler later
if (!frame.IsJumpHappened()) { return 1; }
// jump to goto target or to the next finally:
return frame.YieldToPendingContinuation();
}
}
// no-op: we need this just to balance the stack depth and aid debugging of the instruction list.
internal sealed class EnterExceptionFilterInstruction : Instruction
{
internal static readonly EnterExceptionFilterInstruction Instance = new EnterExceptionFilterInstruction();
private EnterExceptionFilterInstruction()
{
}
public override string InstructionName => "EnterExceptionFilter";
public override int ConsumedStack => 0;
// The exception is pushed onto the stack in the filter runner.
public override int ProducedStack => 1;
[ExcludeFromCodeCoverage] // Known to be a no-op, this instruction is skipped on execution.
public override int Run(InterpretedFrame frame) => 1;
}
// no-op: we need this just to balance the stack depth and aid debugging of the instruction list.
internal sealed class LeaveExceptionFilterInstruction : Instruction
{
internal static readonly LeaveExceptionFilterInstruction Instance = new LeaveExceptionFilterInstruction();
private LeaveExceptionFilterInstruction()
{
}
public override string InstructionName => "LeaveExceptionFilter";
// The boolean result is popped from the stack in the filter runner.
public override int ConsumedStack => 1;
public override int ProducedStack => 0;
[ExcludeFromCodeCoverage] // Known to be a no-op, this instruction is skipped on execution.
public override int Run(InterpretedFrame frame) => 1;
}
// no-op: we need this just to balance the stack depth.
internal sealed class EnterExceptionHandlerInstruction : Instruction
{
internal static readonly EnterExceptionHandlerInstruction Void = new EnterExceptionHandlerInstruction(false);
internal static readonly EnterExceptionHandlerInstruction NonVoid = new EnterExceptionHandlerInstruction(true);
// True if try-expression is non-void.
private readonly bool _hasValue;
public override string InstructionName
{
get { return "EnterExceptionHandler"; }
}
private EnterExceptionHandlerInstruction(bool hasValue)
{
_hasValue = hasValue;
}
// If an exception is throws in try-body the expression result of try-body is not evaluated and loaded to the stack.
// So the stack doesn't contain the try-body's value when we start executing the handler.
// However, while emitting instructions try block falls thru the catch block with a value on stack.
// We need to declare it consumed so that the stack state upon entry to the handler corresponds to the real
// stack depth after throw jumped to this catch block.
public override int ConsumedStack { get { return _hasValue ? 1 : 0; } }
// A variable storing the current exception is pushed to the stack by exception handling.
// Catch handlers: The value is immediately popped and stored into a local.
// Fault handlers: The value is kept on stack during fault handler evaluation.
public override int ProducedStack { get { return 1; } }
[ExcludeFromCodeCoverage] // Known to be a no-op, this instruction is skipped on execution.
public override int Run(InterpretedFrame frame)
{
// nop (the exception value is pushed by the interpreter in HandleCatch)
return 1;
}
}
/// <summary>
/// The last instruction of a catch exception handler.
/// </summary>
internal sealed class LeaveExceptionHandlerInstruction : IndexedBranchInstruction
{
private static LeaveExceptionHandlerInstruction[] s_cache = new LeaveExceptionHandlerInstruction[2 * CacheSize];
private readonly bool _hasValue;
public override string InstructionName
{
get { return "LeaveExceptionHandler"; }
}
// The catch block yields a value if the body is non-void. This value is left on the stack.
public override int ConsumedStack
{
get { return _hasValue ? 1 : 0; }
}
public override int ProducedStack
{
get { return _hasValue ? 1 : 0; }
}
private LeaveExceptionHandlerInstruction(int labelIndex, bool hasValue)
: base(labelIndex)
{
_hasValue = hasValue;
}
internal static LeaveExceptionHandlerInstruction Create(int labelIndex, bool hasValue)
{
if (labelIndex < CacheSize)
{
int index = (2 * labelIndex) | (hasValue ? 1 : 0);
return s_cache[index] ?? (s_cache[index] = new LeaveExceptionHandlerInstruction(labelIndex, hasValue));
}
return new LeaveExceptionHandlerInstruction(labelIndex, hasValue);
}
public override int Run(InterpretedFrame frame)
{
// CLR rethrows ThreadAbortException when leaving catch handler if abort is requested on the current thread.
#if FEATURE_THREAD_ABORT
Interpreter.AbortThreadIfRequested(frame, _labelIndex);
#endif
return GetLabel(frame).Index - frame.InstructionIndex;
}
}
/// <summary>
/// The last instruction of a fault exception handler.
/// </summary>
internal sealed class LeaveFaultInstruction : Instruction
{
internal static readonly Instruction NonVoid = new LeaveFaultInstruction(true);
internal static readonly Instruction Void = new LeaveFaultInstruction(false);
private readonly bool _hasValue;
public override string InstructionName
{
get { return "LeaveFault"; }
}
// The fault block has a value if the body is non-void, but the value is never used.
// We compile the body of a fault block as void.
// However, we keep the exception object that was pushed upon entering the fault block on the stack during execution of the block
// and pop it at the end.
public override int ConsumedStack
{
get { return 1; }
}
// While emitting instructions a non-void try-fault expression is expected to produce a value.
public override int ProducedStack
{
get { return _hasValue ? 1 : 0; }
}
private LeaveFaultInstruction(bool hasValue)
{
_hasValue = hasValue;
}
public override int Run(InterpretedFrame frame)
{
object exception = frame.Pop();
throw new RethrowException();
}
}
internal sealed class ThrowInstruction : Instruction
{
internal static readonly ThrowInstruction Throw = new ThrowInstruction(true, false);
internal static readonly ThrowInstruction VoidThrow = new ThrowInstruction(false, false);
internal static readonly ThrowInstruction Rethrow = new ThrowInstruction(true, true);
internal static readonly ThrowInstruction VoidRethrow = new ThrowInstruction(false, true);
private readonly bool _hasResult, _rethrow;
public override string InstructionName
{
get { return "Throw"; }
}
private ThrowInstruction(bool hasResult, bool isRethrow)
{
_hasResult = hasResult;
_rethrow = isRethrow;
}
public override int ProducedStack
{
get { return _hasResult ? 1 : 0; }
}
public override int ConsumedStack
{
get
{
return 1;
}
}
public override int Run(InterpretedFrame frame)
{
var ex = (Exception)frame.Pop();
if (_rethrow)
{
throw new RethrowException();
}
throw ex;
}
}
internal sealed class IntSwitchInstruction<T> : Instruction
{
private readonly Dictionary<T, int> _cases;
public override string InstructionName
{
get { return "IntSwitch"; }
}
internal IntSwitchInstruction(Dictionary<T, int> cases)
{
Assert.NotNull(cases);
_cases = cases;
}
public override int ConsumedStack { get { return 1; } }
public override int ProducedStack { get { return 0; } }
public override int Run(InterpretedFrame frame)
{
int target;
return _cases.TryGetValue((T)frame.Pop(), out target) ? target : 1;
}
}
internal sealed class StringSwitchInstruction : Instruction
{
private readonly Dictionary<string, int> _cases;
private readonly StrongBox<int> _nullCase;
public override string InstructionName
{
get { return "StringSwitch"; }
}
internal StringSwitchInstruction(Dictionary<string, int> cases, StrongBox<int> nullCase)
{
Assert.NotNull(cases);
Assert.NotNull(nullCase);
_cases = cases;
_nullCase = nullCase;
}
public override int ConsumedStack { get { return 1; } }
public override int ProducedStack { get { return 0; } }
public override int Run(InterpretedFrame frame)
{
object value = frame.Pop();
if (value == null)
{
return _nullCase.Value;
}
int target;
return _cases.TryGetValue((string)value, out target) ? target : 1;
}
}
internal sealed class EnterLoopInstruction : Instruction
{
private readonly int _instructionIndex;
private Dictionary<ParameterExpression, LocalVariable> _variables;
private Dictionary<ParameterExpression, LocalVariable> _closureVariables;
private LoopExpression _loop;
private int _loopEnd;
public override string InstructionName
{
get { return "EnterLoop"; }
}
internal EnterLoopInstruction(LoopExpression loop, LocalVariables locals, int instructionIndex)
{
_loop = loop;
_variables = locals.CopyLocals();
_closureVariables = locals.ClosureVariables;
_instructionIndex = instructionIndex;
}
internal void FinishLoop(int loopEnd)
{
_loopEnd = loopEnd;
}
public override int Run(InterpretedFrame frame)
{
return 1;
}
private bool Compiled
{
get { return _loop == null; }
}
private void Compile(object frameObj)
{
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.ServiceModel.Channels
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Runtime;
using System.ServiceModel.Description;
using Microsoft.Xml;
// was UdpTransportBindingElement
public class UdpTransportBindingElement
: TransportBindingElement,
IPolicyExportExtension,
ITransportPolicyImport,
IWsdlExportExtension
{
private int _duplicateMessageHistoryLength;
private long _maxPendingMessagesTotalSize;
private UdpRetransmissionSettings _retransmissionSettings;
private int _socketReceiveBufferSize;
private int _timeToLive;
[SuppressMessage(FxCop.Category.Usage, FxCop.Rule.DoNotCallOverridableMethodsInConstructors, Justification = "this call is intended")]
public UdpTransportBindingElement()
: base()
{
_duplicateMessageHistoryLength = UdpConstants.Defaults.DuplicateMessageHistoryLength;
_maxPendingMessagesTotalSize = UdpConstants.Defaults.DefaultMaxPendingMessagesTotalSize;
_retransmissionSettings = new UdpRetransmissionSettings();
_socketReceiveBufferSize = UdpConstants.Defaults.SocketReceiveBufferSize;
_timeToLive = UdpConstants.Defaults.TimeToLive;
}
internal UdpTransportBindingElement(UdpTransportBindingElement other)
: base(other)
{
_duplicateMessageHistoryLength = other._duplicateMessageHistoryLength;
_maxPendingMessagesTotalSize = other._maxPendingMessagesTotalSize;
_retransmissionSettings = other._retransmissionSettings.Clone();
_socketReceiveBufferSize = other._socketReceiveBufferSize;
_timeToLive = other._timeToLive;
this.MulticastInterfaceId = other.MulticastInterfaceId;
}
[DefaultValue(UdpConstants.Defaults.DuplicateMessageHistoryLength)]
public int DuplicateMessageHistoryLength
{
get { return _duplicateMessageHistoryLength; }
set
{
const int min = 0;
if (value < min)
{
throw FxTrace.Exception.ArgumentOutOfRange("value", value,
string.Format(SRServiceModel.ArgumentOutOfMinRange, min));
}
_duplicateMessageHistoryLength = value;
}
}
[DefaultValue(UdpConstants.Defaults.DefaultMaxPendingMessagesTotalSize)]
public long MaxPendingMessagesTotalSize
{
get
{
return _maxPendingMessagesTotalSize;
}
set
{
const long min = UdpConstants.MinPendingMessagesTotalSize;
if (value < min)
{
throw FxTrace.Exception.ArgumentOutOfRange("value", value,
string.Format(SRServiceModel.ArgumentOutOfMinRange, min));
}
_maxPendingMessagesTotalSize = value;
}
}
[DefaultValue(UdpConstants.Defaults.MulticastInterfaceId)]
public string MulticastInterfaceId { get; set; }
public UdpRetransmissionSettings RetransmissionSettings
{
get
{
return _retransmissionSettings;
}
set
{
if (value == null)
{
throw FxTrace.Exception.ArgumentNull("value");
}
_retransmissionSettings = value;
}
}
public override string Scheme
{
get { return UdpConstants.Scheme; }
}
[DefaultValue(UdpConstants.Defaults.SocketReceiveBufferSize)]
public int SocketReceiveBufferSize
{
get { return _socketReceiveBufferSize; }
set
{
if (value < UdpConstants.MinReceiveBufferSize)
{
throw FxTrace.Exception.ArgumentOutOfRange("value", value,
string.Format(SRServiceModel.ArgumentOutOfMinRange, UdpConstants.MinReceiveBufferSize));
}
_socketReceiveBufferSize = value;
}
}
[DefaultValue(UdpConstants.Defaults.TimeToLive)]
public int TimeToLive
{
get { return _timeToLive; }
set
{
if (value < UdpConstants.MinTimeToLive || value > UdpConstants.MaxTimeToLive)
{
throw FxTrace.Exception.ArgumentOutOfRange("value", value, "TODO: SR");
// SR.ArgumentOutOfMinMaxRange(UdpConstants.MinTimeToLive, UdpConstants.MaxTimeToLive));
}
_timeToLive = value;
}
}
public override IChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingContext context)
{
throw new NotImplementedException();
}
public override bool CanBuildChannelFactory<TChannel>(BindingContext context)
{
if (context == null)
{
throw FxTrace.Exception.ArgumentNull("context");
}
return (typeof(TChannel) == typeof(IOutputChannel) || typeof(TChannel) == typeof(IDuplexChannel));
}
public override T GetProperty<T>(BindingContext context)
{
if (context == null)
{
throw FxTrace.Exception.ArgumentNull("context");
}
return base.GetProperty<T>(context);
}
public override BindingElement Clone()
{
return new UdpTransportBindingElement(this);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeRetransmissionSettings()
{
return !this.RetransmissionSettings.IsMatch(new UdpRetransmissionSettings()); // only serialize non-default settings
}
[SuppressMessage(FxCop.Category.Design, FxCop.Rule.InterfaceMethodsShouldBeCallableByChildTypes, Justification = "no need to call this from derrived classes")]
void IWsdlExportExtension.ExportContract(WsdlExporter exporter, WsdlContractConversionContext context)
{
}
[SuppressMessage(FxCop.Category.Design, FxCop.Rule.InterfaceMethodsShouldBeCallableByChildTypes, Justification = "no need to call this from derrived classes")]
void IWsdlExportExtension.ExportEndpoint(WsdlExporter exporter, WsdlEndpointConversionContext context)
{
throw new NotImplementedException();
}
[SuppressMessage(FxCop.Category.Design, FxCop.Rule.InterfaceMethodsShouldBeCallableByChildTypes, Justification = "no need to call this from derrived classes")]
void IPolicyExportExtension.ExportPolicy(MetadataExporter exporter, PolicyConversionContext context)
{
throw new NotImplementedException();
}
[SuppressMessage(FxCop.Category.Design, FxCop.Rule.InterfaceMethodsShouldBeCallableByChildTypes, Justification = "no need to call this from derrived classes")]
void ITransportPolicyImport.ImportPolicy(MetadataImporter importer, PolicyConversionContext policyContext)
{
ICollection<XmlElement> bindingAssertions = policyContext.GetBindingAssertions();
XmlElement retransmitAssertion = null;
foreach (XmlElement assertion in bindingAssertions)
{
if (assertion.LocalName.Equals(UdpConstants.RetransmissionEnabled, StringComparison.Ordinal))
{
this.DuplicateMessageHistoryLength = UdpConstants.Defaults.DuplicateMessageHistoryLengthWithRetransmission;
retransmitAssertion = assertion;
}
}
if (retransmitAssertion != null)
{
bindingAssertions.Remove(retransmitAssertion);
}
}
internal override bool IsMatch(BindingElement b)
{
if (!base.IsMatch(b))
{
return false;
}
UdpTransportBindingElement udpTransport = b as UdpTransportBindingElement;
if (udpTransport == null)
{
return false;
}
if (this.DuplicateMessageHistoryLength != udpTransport.DuplicateMessageHistoryLength)
{
return false;
}
if (this.MaxPendingMessagesTotalSize != udpTransport.MaxPendingMessagesTotalSize)
{
return false;
}
if (!String.Equals(this.MulticastInterfaceId, udpTransport.MulticastInterfaceId, StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (!this.RetransmissionSettings.IsMatch(udpTransport.RetransmissionSettings))
{
return false;
}
if (this.TimeToLive != udpTransport.TimeToLive)
{
return false;
}
return true;
}
}
}
| |
/*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
/*
GoogleAnalyticsV3 is an interface for developers to send hits to Google
Analytics.
The class will delegate the hits to the appropriate helper class depending on
the platform being built for - Android, iOS or Measurement Protocol for all
others.
Each method has a simple form with the hit parameters, or developers can
pass a builder to the same method name in order to add custom metrics or
custom dimensions to the hit.
*/
public class GoogleAnalyticsV3 : MonoBehaviour {
private bool initialized = false;
public enum DebugMode {
ERROR,
WARNING,
INFO,
VERBOSE };
[Tooltip("The tracking code to be used for Android. Example value: UA-XXXX-Y.")]
public string androidTrackingCode;
[Tooltip("The tracking code to be used for iOS. Example value: UA-XXXX-Y.")]
public string IOSTrackingCode;
[Tooltip("The tracking code to be used for platforms other than Android and iOS. Example value: UA-XXXX-Y.")]
public string otherTrackingCode;
[Tooltip("The application name. This value should be modified in the " +
"Unity Player Settings.")]
public string productName;
[Tooltip("The application identifier. Example value: com.company.app.")]
public string bundleIdentifier;
[Tooltip("The application version. Example value: 1.2")]
public string bundleVersion;
[RangedTooltip("The dispatch period in seconds. Only required for Android " +
"and iOS.", 0, 3600)]
public int dispatchPeriod = 5;
[RangedTooltip("The sample rate to use. Only required for Android and" +
" iOS.", 0F, 100F)]
public float sampleFrequency = 100.0F;
[Tooltip("The log level. Default is WARNING.")]
public DebugMode logLevel = DebugMode.WARNING;
[Tooltip("If checked, the IP address of the sender will be anonymized.")]
public bool anonymizeIP = false;
[Tooltip("If checked, hits will not be dispatched. Use for testing.")]
public bool dryRun = false;
// TODO: Create conditional textbox attribute
[Tooltip("The amount of time in seconds your application can stay in" +
"the background before the session is ended. Default is 30 minutes" +
" (1800 seconds). A value of -1 will disable session management.")]
public int sessionTimeout = 1800;
public static GoogleAnalyticsV3 instance = null;
[HideInInspector]
public readonly static string currencySymbol = "USD";
public readonly static string EVENT_HIT = "createEvent";
public readonly static string APP_VIEW = "createAppView";
public readonly static string SET = "set";
public readonly static string SET_ALL = "setAll";
public readonly static string SEND = "send";
public readonly static string ITEM_HIT = "createItem";
public readonly static string TRANSACTION_HIT = "createTransaction";
public readonly static string SOCIAL_HIT = "createSocial";
public readonly static string TIMING_HIT = "createTiming";
public readonly static string EXCEPTION_HIT = "createException";
#if UNITY_ANDROID && !UNITY_EDITOR
private GoogleAnalyticsAndroidV3 androidTracker =
new GoogleAnalyticsAndroidV3();
#elif UNITY_IPHONE && !UNITY_EDITOR
private GoogleAnalyticsiOSV3 iosTracker = new GoogleAnalyticsiOSV3();
#else
private GoogleAnalyticsMPV3 mpTracker = new GoogleAnalyticsMPV3();
#endif
// TODO: Error checking on initialization parameters
private void InitializeTracker() {
if (!initialized) {
instance = this;
Debug.Log("Initializing Google Analytics 0.1.");
#if UNITY_ANDROID && !UNITY_EDITOR
androidTracker.SetTrackingCode(androidTrackingCode);
androidTracker.SetAppName(productName);
androidTracker.SetBundleIdentifier(bundleIdentifier);
androidTracker.SetAppVersion(bundleVersion);
androidTracker.SetDispatchPeriod(dispatchPeriod);
androidTracker.SetSampleFrequency(sampleFrequency);
androidTracker.SetLogLevelValue(logLevel);
androidTracker.SetAnonymizeIP(anonymizeIP);
androidTracker.SetDryRun(dryRun);
androidTracker.InitializeTracker();
#elif UNITY_IPHONE && !UNITY_EDITOR
iosTracker.SetTrackingCode(IOSTrackingCode);
iosTracker.SetAppName(productName);
iosTracker.SetBundleIdentifier(bundleIdentifier);
iosTracker.SetAppVersion(bundleVersion);
iosTracker.SetDispatchPeriod(dispatchPeriod);
iosTracker.SetSampleFrequency(sampleFrequency);
iosTracker.SetLogLevelValue(logLevel);
iosTracker.SetAnonymizeIP(anonymizeIP);
iosTracker.SetDryRun(dryRun);
iosTracker.InitializeTracker();
#else
mpTracker.SetTrackingCode(otherTrackingCode);
mpTracker.SetBundleIdentifier(bundleIdentifier);
mpTracker.SetAppName(productName);
mpTracker.SetAppVersion(bundleVersion);
mpTracker.SetLogLevelValue(logLevel);
mpTracker.SetAnonymizeIP(anonymizeIP);
mpTracker.SetDryRun(dryRun);
mpTracker.InitializeTracker();
#endif
initialized = true;
SetOnTracker(Fields.DEVELOPER_ID, "GbOCSs");
}
}
public void SetAppLevelOptOut(bool optOut) {
InitializeTracker();
#if UNITY_ANDROID && !UNITY_EDITOR
androidTracker.SetOptOut(optOut);
#elif UNITY_IPHONE && !UNITY_EDITOR
iosTracker.SetOptOut(optOut);
#else
mpTracker.SetOptOut(optOut);
#endif
}
public void SetUserIDOverride(string userID) {
SetOnTracker(Fields.USER_ID, userID);
}
public void ClearUserIDOverride() {
InitializeTracker();
#if UNITY_ANDROID && !UNITY_EDITOR
androidTracker.ClearUserIDOverride();
#elif UNITY_IPHONE && !UNITY_EDITOR
iosTracker.ClearUserIDOverride();
#else
mpTracker.ClearUserIDOverride();
#endif
}
public void DispatchHits() {
InitializeTracker();
#if UNITY_ANDROID && !UNITY_EDITOR
androidTracker.DispatchHits();
#elif UNITY_IPHONE && !UNITY_EDITOR
iosTracker.DispatchHits();
#else
//Do nothing
#endif
}
public void StartSession() {
InitializeTracker();
#if UNITY_ANDROID && !UNITY_EDITOR
androidTracker.StartSession();
#elif UNITY_IPHONE && !UNITY_EDITOR
iosTracker.StartSession();
#else
mpTracker.StartSession();
#endif
}
public void StopSession() {
InitializeTracker();
#if UNITY_ANDROID && !UNITY_EDITOR
androidTracker.StopSession();
#elif UNITY_IPHONE && !UNITY_EDITOR
iosTracker.StopSession();
#else
mpTracker.StopSession();
#endif
}
// Use values from Fields for the fieldName parameter ie. Fields.SCREEN_NAME
public void SetOnTracker(Field fieldName, object value) {
InitializeTracker();
#if UNITY_ANDROID && !UNITY_EDITOR
androidTracker.SetTrackerVal(fieldName, value);
#elif UNITY_IPHONE && !UNITY_EDITOR
iosTracker.SetTrackerVal(fieldName, value);
#else
mpTracker.SetTrackerVal(fieldName, value);
#endif
}
public void LogScreen(string title) {
AppViewHitBuilder builder = new AppViewHitBuilder().SetScreenName(title);
LogScreen(builder);
}
public void LogScreen(AppViewHitBuilder builder) {
InitializeTracker();
if (builder.Validate() == null) {
return;
}
if (GoogleAnalyticsV3.belowThreshold(logLevel, GoogleAnalyticsV3.DebugMode.VERBOSE)) {
Debug.Log("Logging screen.");
}
#if UNITY_ANDROID && !UNITY_EDITOR
androidTracker.LogScreen(builder);
#elif UNITY_IPHONE && !UNITY_EDITOR
iosTracker.LogScreen(builder);
#else
mpTracker.LogScreen(builder);
#endif
}
public void LogEvent(string eventCategory, string eventAction,
string eventLabel, long value) {
EventHitBuilder builder = new EventHitBuilder()
.SetEventCategory(eventCategory)
.SetEventAction(eventAction)
.SetEventLabel(eventLabel)
.SetEventValue(value);
LogEvent(builder);
}
public void LogEvent(EventHitBuilder builder) {
InitializeTracker();
if (builder.Validate() == null) {
return;
}
if (GoogleAnalyticsV3.belowThreshold(logLevel, GoogleAnalyticsV3.DebugMode.VERBOSE)) {
Debug.Log("Logging event.");
}
#if UNITY_ANDROID && !UNITY_EDITOR
androidTracker.LogEvent (builder);
#elif UNITY_IPHONE && !UNITY_EDITOR
iosTracker.LogEvent(builder);
#else
mpTracker.LogEvent(builder);
#endif
}
public void LogTransaction(string transID, string affiliation,
double revenue, double tax, double shipping) {
LogTransaction (transID, affiliation, revenue, tax, shipping, "");
}
public void LogTransaction(string transID, string affiliation,
double revenue, double tax, double shipping, string currencyCode) {
TransactionHitBuilder builder = new TransactionHitBuilder()
.SetTransactionID(transID)
.SetAffiliation(affiliation)
.SetRevenue(revenue)
.SetTax(tax)
.SetShipping(shipping)
.SetCurrencyCode(currencyCode);
LogTransaction(builder);
}
public void LogTransaction(TransactionHitBuilder builder) {
InitializeTracker();
if (builder.Validate() == null) {
return;
}
if (GoogleAnalyticsV3.belowThreshold(logLevel, GoogleAnalyticsV3.DebugMode.VERBOSE)) {
Debug.Log("Logging transaction.");
}
#if UNITY_ANDROID && !UNITY_EDITOR
androidTracker.LogTransaction(builder);
#elif UNITY_IPHONE && !UNITY_EDITOR
iosTracker.LogTransaction(builder);
#else
mpTracker.LogTransaction(builder);
#endif
}
public void LogItem(string transID, string name, string sku,
string category, double price, long quantity) {
LogItem (transID, name, sku, category, price, quantity, null);
}
public void LogItem(string transID, string name, string sku,
string category, double price, long quantity, string currencyCode) {
ItemHitBuilder builder = new ItemHitBuilder()
.SetTransactionID(transID)
.SetName(name)
.SetSKU(sku)
.SetCategory(category)
.SetPrice(price)
.SetQuantity(quantity)
.SetCurrencyCode(currencyCode);
LogItem(builder);
}
public void LogItem(ItemHitBuilder builder) {
InitializeTracker();
if (builder.Validate() == null) {
return;
}
if (GoogleAnalyticsV3.belowThreshold(logLevel, GoogleAnalyticsV3.DebugMode.VERBOSE)) {
Debug.Log("Logging item.");
}
#if UNITY_ANDROID && !UNITY_EDITOR
androidTracker.LogItem(builder);
#elif UNITY_IPHONE && !UNITY_EDITOR
iosTracker.LogItem(builder);
#else
mpTracker.LogItem(builder);
#endif
}
public void LogException(string exceptionDescription, bool isFatal) {
ExceptionHitBuilder builder = new ExceptionHitBuilder()
.SetExceptionDescription(exceptionDescription)
.SetFatal(isFatal);
LogException(builder);
}
public void LogException(ExceptionHitBuilder builder) {
InitializeTracker();
if (builder.Validate() == null) {
return;
}
if (GoogleAnalyticsV3.belowThreshold(logLevel, GoogleAnalyticsV3.DebugMode.VERBOSE)) {
Debug.Log("Logging exception.");
}
#if UNITY_ANDROID && !UNITY_EDITOR
androidTracker.LogException(builder);
#elif UNITY_IPHONE && !UNITY_EDITOR
iosTracker.LogException(builder);
#else
mpTracker.LogException(builder);
#endif
}
public void LogSocial(string socialNetwork, string socialAction,
string socialTarget) {
SocialHitBuilder builder = new SocialHitBuilder()
.SetSocialNetwork(socialNetwork)
.SetSocialAction(socialAction)
.SetSocialTarget(socialTarget);
LogSocial(builder);
}
public void LogSocial(SocialHitBuilder builder) {
InitializeTracker();
if (builder.Validate() == null) {
return;
}
if (GoogleAnalyticsV3.belowThreshold(logLevel, GoogleAnalyticsV3.DebugMode.VERBOSE)) {
Debug.Log("Logging social.");
}
#if UNITY_ANDROID && !UNITY_EDITOR
androidTracker.LogSocial(builder);
#elif UNITY_IPHONE && !UNITY_EDITOR
iosTracker.LogSocial(builder);
#else
mpTracker.LogSocial(builder);
#endif
}
public void LogTiming(string timingCategory, long timingInterval,
string timingName, string timingLabel) {
TimingHitBuilder builder = new TimingHitBuilder()
.SetTimingCategory(timingCategory)
.SetTimingInterval(timingInterval)
.SetTimingName(timingName)
.SetTimingLabel(timingLabel);
LogTiming(builder);
}
public void LogTiming(TimingHitBuilder builder) {
InitializeTracker();
if (builder.Validate() == null) {
return;
}
if (GoogleAnalyticsV3.belowThreshold(logLevel, GoogleAnalyticsV3.DebugMode.VERBOSE)) {
Debug.Log("Logging timing.");
}
#if UNITY_ANDROID && !UNITY_EDITOR
androidTracker.LogTiming(builder);
#elif UNITY_IPHONE && !UNITY_EDITOR
iosTracker.LogTiming(builder);
#else
mpTracker.LogTiming(builder);
#endif
}
public void Dispose() {
initialized = false;
#if UNITY_ANDROID && !UNITY_EDITOR
androidTracker.Dispose();
#elif UNITY_IPHONE && !UNITY_EDITOR
#else
#endif
}
public static bool belowThreshold(GoogleAnalyticsV3.DebugMode userLogLevel,
GoogleAnalyticsV3.DebugMode comparelogLevel) {
if (comparelogLevel == userLogLevel) {
return true;
} else if (userLogLevel == GoogleAnalyticsV3.DebugMode.ERROR) {
return false;
} else if (userLogLevel == GoogleAnalyticsV3.DebugMode.VERBOSE) {
return true;
} else if (userLogLevel == GoogleAnalyticsV3.DebugMode.WARNING &&
(comparelogLevel == GoogleAnalyticsV3.DebugMode.INFO ||
comparelogLevel == GoogleAnalyticsV3.DebugMode.VERBOSE)) {
return false;
} else if (userLogLevel == GoogleAnalyticsV3.DebugMode.INFO &&
(comparelogLevel == GoogleAnalyticsV3.DebugMode.VERBOSE)) {
return false;
}
return true;
}
// Instance for running Coroutines from platform specific classes
public static GoogleAnalyticsV3 getInstance() {
return instance;
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace System.Numerics.Tests
{
public class op_multiplyTest
{
private static int s_samples = 10;
private static Random s_random = new Random(100);
[Fact]
public static void RunMultiplyPositive()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Multiply Method - One Large BigInteger
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
VerifyMultiplyString(Print(tempByteArray1) + "u*");
}
// Multiply Method - Two Large BigIntegers
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = GetRandomByteArray(s_random);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
}
// Multiply Method - Two Small BigIntegers
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = GetRandomByteArray(s_random, 2);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
}
// Multiply Method - One large and one small BigIntegers
for (int i = 0; i < s_samples; i++)
{
try
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = GetRandomByteArray(s_random, 2);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = GetRandomByteArray(s_random);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
}
catch (IndexOutOfRangeException)
{
// TODO: Refactor this
Console.WriteLine("Array1: " + Print(tempByteArray1));
Console.WriteLine("Array2: " + Print(tempByteArray2));
throw;
}
}
}
[Fact]
public static void RunMultiplyPositiveWith0()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Multiply Method - One large BigIntegers and zero
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = new byte[] { 0 };
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
tempByteArray1 = new byte[] { 0 };
tempByteArray2 = GetRandomByteArray(s_random);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
}
// Multiply Method - One small BigIntegers and zero
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = new byte[] { 0 };
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
tempByteArray1 = new byte[] { 0 };
tempByteArray2 = GetRandomByteArray(s_random, 2);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
}
}
[Fact]
public static void RunMultiplyAxiomXmult1()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Axiom: X*1 = X
VerifyIdentityString(Int32.MaxValue + " " + BigInteger.One + " b*", Int32.MaxValue.ToString());
VerifyIdentityString(Int64.MaxValue + " " + BigInteger.One + " b*", Int64.MaxValue.ToString());
for (int i = 0; i < s_samples; i++)
{
String randBigInt = Print(GetRandomByteArray(s_random));
VerifyIdentityString(randBigInt + BigInteger.One + " b*", randBigInt + "u+");
}
}
[Fact]
public static void RunMultiplyAxiomXmult0()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Axiom: X*0 = 0
VerifyIdentityString(Int32.MaxValue + " " + BigInteger.Zero + " b*", BigInteger.Zero.ToString());
VerifyIdentityString(Int64.MaxValue + " " + BigInteger.Zero + " b*", BigInteger.Zero.ToString());
for (int i = 0; i < s_samples; i++)
{
String randBigInt = Print(GetRandomByteArray(s_random));
VerifyIdentityString(randBigInt + BigInteger.Zero + " b*", BigInteger.Zero.ToString());
}
}
[Fact]
public static void RunMultiplyAxiomComm()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Check interesting cases for boundary conditions
// You'll either be shifting a 0 or 1 across the boundary
// 32 bit boundary n2=0
VerifyMultiplyString(Math.Pow(2, 32) + " 2 b*");
// 32 bit boundary n1=0 n2=1
VerifyMultiplyString(Math.Pow(2, 33) + " 2 b*");
}
[Fact]
public static void RunMultiplyBoundary()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Check interesting cases for boundary conditions
// You'll either be shifting a 0 or 1 across the boundary
// 32 bit boundary n2=0
VerifyMultiplyString(Math.Pow(2, 32) + " 2 b*");
// 32 bit boundary n1=0 n2=1
VerifyMultiplyString(Math.Pow(2, 33) + " 2 b*");
}
[Fact]
public static void RunMultiplyTests()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Multiply Method - One Large BigInteger
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
VerifyMultiplyString(Print(tempByteArray1) + "u*");
}
// Multiply Method - Two Large BigIntegers
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = GetRandomByteArray(s_random);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
}
// Multiply Method - Two Small BigIntegers
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = GetRandomByteArray(s_random, 2);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
}
// Multiply Method - One large and one small BigIntegers
for (int i = 0; i < s_samples; i++)
{
try
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = GetRandomByteArray(s_random, 2);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = GetRandomByteArray(s_random);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
}
catch (IndexOutOfRangeException)
{
// TODO: Refactor this
Console.WriteLine("Array1: " + Print(tempByteArray1));
Console.WriteLine("Array2: " + Print(tempByteArray2));
throw;
}
}
// Multiply Method - One large BigIntegers and zero
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = new byte[] { 0 };
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
tempByteArray1 = new byte[] { 0 };
tempByteArray2 = GetRandomByteArray(s_random);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
}
// Multiply Method - One small BigIntegers and zero
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = new byte[] { 0 };
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
tempByteArray1 = new byte[] { 0 };
tempByteArray2 = GetRandomByteArray(s_random, 2);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
}
// Axiom: X*1 = X
VerifyIdentityString(Int32.MaxValue + " " + BigInteger.One + " b*", Int32.MaxValue.ToString());
VerifyIdentityString(Int64.MaxValue + " " + BigInteger.One + " b*", Int64.MaxValue.ToString());
for (int i = 0; i < s_samples; i++)
{
String randBigInt = Print(GetRandomByteArray(s_random));
VerifyIdentityString(randBigInt + BigInteger.One + " b*", randBigInt + "u+");
}
// Axiom: X*0 = 0
VerifyIdentityString(Int32.MaxValue + " " + BigInteger.Zero + " b*", BigInteger.Zero.ToString());
VerifyIdentityString(Int64.MaxValue + " " + BigInteger.Zero + " b*", BigInteger.Zero.ToString());
for (int i = 0; i < s_samples; i++)
{
String randBigInt = Print(GetRandomByteArray(s_random));
VerifyIdentityString(randBigInt + BigInteger.Zero + " b*", BigInteger.Zero.ToString());
}
// Axiom: a*b = b*a
VerifyIdentityString(Int32.MaxValue + " " + Int64.MaxValue + " b*", Int64.MaxValue + " " + Int32.MaxValue + " b*");
for (int i = 0; i < s_samples; i++)
{
String randBigInt1 = Print(GetRandomByteArray(s_random));
String randBigInt2 = Print(GetRandomByteArray(s_random));
VerifyIdentityString(randBigInt1 + randBigInt2 + "b*", randBigInt2 + randBigInt1 + "b*");
}
// Check interesting cases for boundary conditions
// You'll either be shifting a 0 or 1 across the boundary
// 32 bit boundary n2=0
VerifyMultiplyString(Math.Pow(2, 32) + " 2 b*");
// 32 bit boundary n1=0 n2=1
VerifyMultiplyString(Math.Pow(2, 33) + " 2 b*");
}
private static void VerifyMultiplyString(string opstring)
{
StackCalc sc = new StackCalc(opstring);
while (sc.DoNextOperation())
{
Assert.Equal(sc.snCalc.Peek().ToString(), sc.myCalc.Peek().ToString());
}
}
private static void VerifyIdentityString(string opstring1, string opstring2)
{
StackCalc sc1 = new StackCalc(opstring1);
while (sc1.DoNextOperation())
{
//Run the full calculation
sc1.DoNextOperation();
}
StackCalc sc2 = new StackCalc(opstring2);
while (sc2.DoNextOperation())
{
//Run the full calculation
sc2.DoNextOperation();
}
Assert.Equal(sc1.snCalc.Peek().ToString(), sc2.snCalc.Peek().ToString());
}
private static byte[] GetRandomByteArray(Random random)
{
return GetRandomByteArray(random, random.Next(0, 100));
}
private static byte[] GetRandomByteArray(Random random, int size)
{
return MyBigIntImp.GetRandomByteArray(random, size);
}
private static String Print(byte[] bytes)
{
return MyBigIntImp.Print(bytes);
}
}
}
| |
// 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.Diagnostics;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography;
using System.Text;
using Microsoft.Win32.SafeHandles;
internal static partial class Interop
{
internal static partial class Ssl
{
internal delegate int SslCtxSetVerifyCallback(int preverify_ok, IntPtr x509_ctx);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EnsureLibSslInitialized")]
internal static extern void EnsureLibSslInitialized();
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslV2_3Method")]
internal static extern IntPtr SslV2_3Method();
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslV3Method")]
internal static extern IntPtr SslV3Method();
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_TlsV1Method")]
internal static extern IntPtr TlsV1Method();
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_TlsV1_1Method")]
internal static extern IntPtr TlsV1_1Method();
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_TlsV1_2Method")]
internal static extern IntPtr TlsV1_2Method();
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslCreate")]
internal static extern SafeSslHandle SslCreate(SafeSslContextHandle ctx);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetError")]
internal static extern SslErrorCode SslGetError(SafeSslHandle ssl, int ret);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetError")]
internal static extern SslErrorCode SslGetError(IntPtr ssl, int ret);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslDestroy")]
internal static extern void SslDestroy(IntPtr ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetConnectState")]
internal static extern void SslSetConnectState(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetAcceptState")]
internal static extern void SslSetAcceptState(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetVersion")]
private static extern IntPtr SslGetVersion(SafeSslHandle ssl);
internal static string GetProtocolVersion(SafeSslHandle ssl)
{
return Marshal.PtrToStringAnsi(SslGetVersion(ssl));
}
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetSslConnectionInfo")]
internal static extern bool GetSslConnectionInfo(
SafeSslHandle ssl,
out int dataCipherAlg,
out int keyExchangeAlg,
out int dataHashAlg,
out int dataKeySize,
out int hashKeySize);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslWrite")]
internal static unsafe extern int SslWrite(SafeSslHandle ssl, byte* buf, int num);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslRead")]
internal static extern int SslRead(SafeSslHandle ssl, byte[] buf, int num);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_IsSslRenegotiatePending")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool IsSslRenegotiatePending(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslShutdown")]
internal static extern int SslShutdown(IntPtr ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetBio")]
internal static extern void SslSetBio(SafeSslHandle ssl, SafeBioHandle rbio, SafeBioHandle wbio);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslDoHandshake")]
internal static extern int SslDoHandshake(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_IsSslStateOK")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool IsSslStateOK(SafeSslHandle ssl);
// NOTE: this is just an (unsafe) overload to the BioWrite method from Interop.Bio.cs.
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_BioWrite")]
internal static unsafe extern int BioWrite(SafeBioHandle b, byte* data, int len);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetPeerCertificate")]
internal static extern SafeX509Handle SslGetPeerCertificate(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetPeerCertChain")]
internal static extern SafeSharedX509StackHandle SslGetPeerCertChain(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetStreamSizes")]
internal static extern void GetStreamSizes(out int header, out int trailer, out int maximumMessage);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetPeerFinished")]
internal static extern int SslGetPeerFinished(SafeSslHandle ssl, IntPtr buf, int count);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetFinished")]
internal static extern int SslGetFinished(SafeSslHandle ssl, IntPtr buf, int count);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSessionReused")]
internal static extern bool SslSessionReused(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslAddExtraChainCert")]
internal static extern bool SslAddExtraChainCert(SafeSslHandle ssl, SafeX509Handle x509);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetClientCAList")]
private static extern SafeSharedX509NameStackHandle SslGetClientCAList_private(SafeSslHandle ssl);
internal static SafeSharedX509NameStackHandle SslGetClientCAList(SafeSslHandle ssl)
{
Crypto.CheckValidOpenSslHandle(ssl);
SafeSharedX509NameStackHandle handle = SslGetClientCAList_private(ssl);
if (!handle.IsInvalid)
{
handle.SetParent(ssl);
}
return handle;
}
internal static class SslMethods
{
internal static readonly IntPtr TLSv1_method = TlsV1Method();
internal static readonly IntPtr TLSv1_1_method = TlsV1_1Method();
internal static readonly IntPtr TLSv1_2_method = TlsV1_2Method();
internal static readonly IntPtr SSLv3_method = SslV3Method();
internal static readonly IntPtr SSLv23_method = SslV2_3Method();
}
internal enum SslErrorCode
{
SSL_ERROR_NONE = 0,
SSL_ERROR_SSL = 1,
SSL_ERROR_WANT_READ = 2,
SSL_ERROR_WANT_WRITE = 3,
SSL_ERROR_SYSCALL = 5,
SSL_ERROR_ZERO_RETURN = 6,
// NOTE: this SslErrorCode value doesn't exist in OpenSSL, but
// we use it to distinguish when a renegotiation is pending.
// Choosing an arbitrarily large value that shouldn't conflict
// with any actual OpenSSL error codes
SSL_ERROR_RENEGOTIATE = 29304
}
}
}
namespace Microsoft.Win32.SafeHandles
{
internal sealed class SafeSslHandle : SafeHandle
{
private SafeBioHandle _readBio;
private SafeBioHandle _writeBio;
private bool _isServer;
private bool _handshakeCompleted = false;
public bool IsServer
{
get { return _isServer; }
}
public SafeBioHandle InputBio
{
get
{
return _readBio;
}
}
public SafeBioHandle OutputBio
{
get
{
return _writeBio;
}
}
internal void MarkHandshakeCompleted()
{
_handshakeCompleted = true;
}
public static SafeSslHandle Create(SafeSslContextHandle context, bool isServer)
{
SafeBioHandle readBio = Interop.Crypto.CreateMemoryBio();
if (readBio.IsInvalid)
{
return new SafeSslHandle();
}
SafeBioHandle writeBio = Interop.Crypto.CreateMemoryBio();
if (writeBio.IsInvalid)
{
readBio.Dispose();
return new SafeSslHandle();
}
SafeSslHandle handle = Interop.Ssl.SslCreate(context);
if (handle.IsInvalid)
{
readBio.Dispose();
writeBio.Dispose();
return handle;
}
handle._isServer = isServer;
// After SSL_set_bio, the BIO handles are owned by SSL pointer
// and are automatically freed by SSL_free. To prevent a double
// free, we need to keep the ref counts bumped up till SSL_free
bool gotRef = false;
readBio.DangerousAddRef(ref gotRef);
try
{
bool ignore = false;
writeBio.DangerousAddRef(ref ignore);
}
catch
{
if (gotRef)
{
readBio.DangerousRelease();
}
throw;
}
Interop.Ssl.SslSetBio(handle, readBio, writeBio);
handle._readBio = readBio;
handle._writeBio = writeBio;
if (isServer)
{
Interop.Ssl.SslSetAcceptState(handle);
}
else
{
Interop.Ssl.SslSetConnectState(handle);
}
return handle;
}
public override bool IsInvalid
{
get { return handle == IntPtr.Zero; }
}
protected override bool ReleaseHandle()
{
if (_handshakeCompleted)
{
Disconnect();
}
Interop.Ssl.SslDestroy(handle);
if (_readBio != null)
{
_readBio.SetHandleAsInvalid(); // BIO got freed in SslDestroy
}
if (_writeBio != null)
{
_writeBio.SetHandleAsInvalid(); // BIO got freed in SslDestroy
}
return true;
}
private void Disconnect()
{
Debug.Assert(!IsInvalid, "Expected a valid context in Disconnect");
int retVal = Interop.Ssl.SslShutdown(handle);
if (retVal < 0)
{
//TODO (Issue #4031) check this error
Interop.Ssl.SslGetError(handle, retVal);
}
}
private SafeSslHandle() : base(IntPtr.Zero, true)
{
}
internal SafeSslHandle(IntPtr validSslPointer, bool ownsHandle) : base(IntPtr.Zero, ownsHandle)
{
handle = validSslPointer;
}
}
internal sealed class SafeChannelBindingHandle : SafeHandle
{
[StructLayout(LayoutKind.Sequential)]
private struct SecChannelBindings
{
internal int InitiatorLength;
internal int InitiatorOffset;
internal int AcceptorAddrType;
internal int AcceptorLength;
internal int AcceptorOffset;
internal int ApplicationDataLength;
internal int ApplicationDataOffset;
}
private static readonly byte[] s_tlsServerEndPointByteArray = Encoding.UTF8.GetBytes("tls-server-end-point:");
private static readonly byte[] s_tlsUniqueByteArray = Encoding.UTF8.GetBytes("tls-unique:");
private static readonly int s_secChannelBindingSize = Marshal.SizeOf<SecChannelBindings>();
private readonly int _cbtPrefixByteArraySize;
private const int CertHashMaxSize = 128;
internal int Length
{
get;
private set;
}
internal IntPtr CertHashPtr
{
get;
private set;
}
internal void SetCertHash(byte[] certHashBytes)
{
Debug.Assert(certHashBytes != null, "check certHashBytes is not null");
int length = certHashBytes.Length;
Marshal.Copy(certHashBytes, 0, CertHashPtr, length);
SetCertHashLength(length);
}
private byte[] GetPrefixBytes(ChannelBindingKind kind)
{
if (kind == ChannelBindingKind.Endpoint)
{
return s_tlsServerEndPointByteArray;
}
else if (kind == ChannelBindingKind.Unique)
{
return s_tlsUniqueByteArray;
}
else
{
throw new NotSupportedException();
}
}
internal SafeChannelBindingHandle(ChannelBindingKind kind)
: base(IntPtr.Zero, true)
{
byte[] cbtPrefix = GetPrefixBytes(kind);
_cbtPrefixByteArraySize = cbtPrefix.Length;
handle = Marshal.AllocHGlobal(s_secChannelBindingSize + _cbtPrefixByteArraySize + CertHashMaxSize);
IntPtr cbtPrefixPtr = handle + s_secChannelBindingSize;
Marshal.Copy(cbtPrefix, 0, cbtPrefixPtr, _cbtPrefixByteArraySize);
CertHashPtr = cbtPrefixPtr + _cbtPrefixByteArraySize;
Length = CertHashMaxSize;
}
internal void SetCertHashLength(int certHashLength)
{
int cbtLength = _cbtPrefixByteArraySize + certHashLength;
Length = s_secChannelBindingSize + cbtLength;
SecChannelBindings channelBindings = new SecChannelBindings()
{
ApplicationDataLength = cbtLength,
ApplicationDataOffset = s_secChannelBindingSize
};
Marshal.StructureToPtr(channelBindings, handle, true);
}
public override bool IsInvalid
{
get { return handle == IntPtr.Zero; }
}
protected override bool ReleaseHandle()
{
Marshal.FreeHGlobal(handle);
SetHandle(IntPtr.Zero);
return true;
}
}
}
| |
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using SteamKit2;
using SteamTrade.Exceptions;
namespace SteamTrade
{
public class TradeManager
{
private const int MaxGapTimeDefault = 15;
private const int MaxTradeTimeDefault = 180;
private const int TradePollingIntervalDefault = 800;
private readonly string ApiKey;
private readonly SteamWeb SteamWeb;
private DateTime tradeStartTime;
private DateTime lastOtherActionTime;
private DateTime lastTimeoutMessage;
private Task<Inventory> myInventoryTask;
private Task<Inventory> otherInventoryTask;
/// <summary>
/// Initializes a new instance of the <see cref="SteamTrade.TradeManager"/> class.
/// </summary>
/// <param name='apiKey'>
/// The Steam Web API key. Cannot be null.
/// </param>
/// <param name="steamWeb">
/// The SteamWeb instances for this bot
/// </param>
public TradeManager (string apiKey, SteamWeb steamWeb)
{
if (apiKey == null)
throw new ArgumentNullException ("apiKey");
if (steamWeb == null)
throw new ArgumentNullException ("steamWeb");
SetTradeTimeLimits (MaxTradeTimeDefault, MaxGapTimeDefault, TradePollingIntervalDefault);
ApiKey = apiKey;
SteamWeb = steamWeb;
}
#region Public Properties
/// <summary>
/// Gets or the maximum trading time the bot will take in seconds.
/// </summary>
/// <value>
/// The maximum trade time.
/// </value>
public int MaxTradeTimeSec
{
get;
private set;
}
/// <summary>
/// Gets or the maxmium amount of time the bot will wait between actions.
/// </summary>
/// <value>
/// The maximum action gap.
/// </value>
public int MaxActionGapSec
{
get;
private set;
}
/// <summary>
/// Gets the Trade polling interval in milliseconds.
/// </summary>
public int TradePollingInterval
{
get;
private set;
}
/// <summary>
/// Gets the inventory of the bot.
/// </summary>
/// <value>
/// The bot's inventory fetched via Steam Web API.
/// </value>
public Inventory MyInventory
{
get
{
if(myInventoryTask == null)
return null;
myInventoryTask.Wait();
return myInventoryTask.Result;
}
}
/// <summary>
/// Gets the inventory of the other trade partner.
/// </summary>
/// <value>
/// The other trade partner's inventory fetched via Steam Web API.
/// </value>
public Inventory OtherInventory
{
get
{
if(otherInventoryTask == null)
return null;
otherInventoryTask.Wait();
return otherInventoryTask.Result;
}
}
/// <summary>
/// Gets or sets a value indicating whether the trade thread running.
/// </summary>
/// <value>
/// <c>true</c> if the trade thread running; otherwise, <c>false</c>.
/// </value>
public bool IsTradeThreadRunning
{
get;
internal set;
}
#endregion Public Properties
#region Public Events
/// <summary>
/// Occurs when the trade times out because either the user didn't complete an
/// action in a set amount of time, or they took too long with the whole trade.
/// </summary>
public EventHandler OnTimeout;
#endregion Public Events
#region Public Methods
/// <summary>
/// Sets the trade time limits.
/// </summary>
/// <param name='maxTradeTime'>
/// Max trade time in seconds.
/// </param>
/// <param name='maxActionGap'>
/// Max gap between user action in seconds.
/// </param>
/// <param name='pollingInterval'>The trade polling interval in milliseconds.</param>
public void SetTradeTimeLimits (int maxTradeTime, int maxActionGap, int pollingInterval)
{
MaxTradeTimeSec = maxTradeTime;
MaxActionGapSec = maxActionGap;
TradePollingInterval = pollingInterval;
}
/// <summary>
/// Creates a trade object and returns it for use.
/// Call <see cref="InitializeTrade"/> before using this method.
/// </summary>
/// <returns>
/// The trade object to use to interact with the Steam trade.
/// </returns>
/// <param name='me'>
/// The <see cref="SteamID"/> of the bot.
/// </param>
/// <param name='other'>
/// The <see cref="SteamID"/> of the other trade partner.
/// </param>
/// <remarks>
/// If the needed inventories are <c>null</c> then they will be fetched.
/// </remarks>
public Trade CreateTrade (SteamID me, SteamID other)
{
if (otherInventoryTask == null || myInventoryTask == null)
InitializeTrade (me, other);
var t = new Trade (me, other, SteamWeb, myInventoryTask, otherInventoryTask);
t.OnClose += delegate
{
IsTradeThreadRunning = false;
};
return t;
}
/// <summary>
/// Stops the trade thread.
/// </summary>
/// <remarks>
/// Also, nulls out the inventory objects so they have to be fetched
/// again if a new trade is started.
/// </remarks>
public void StopTrade ()
{
// TODO: something to check that trade was the Trade returned from CreateTrade
otherInventoryTask = null;
myInventoryTask = null;
IsTradeThreadRunning = false;
}
/// <summary>
/// Fetchs the inventories of both the bot and the other user as well as the TF2 item schema.
/// </summary>
/// <param name='me'>
/// The <see cref="SteamID"/> of the bot.
/// </param>
/// <param name='other'>
/// The <see cref="SteamID"/> of the other trade partner.
/// </param>
/// <remarks>
/// This should be done anytime a new user is traded with or the inventories are out of date. It should
/// be done sometime before calling <see cref="CreateTrade"/>.
/// </remarks>
public void InitializeTrade (SteamID me, SteamID other)
{
// fetch other player's inventory from the Steam API.
otherInventoryTask = Task.Factory.StartNew(() => Inventory.FetchInventory(other.ConvertToUInt64(), ApiKey, SteamWeb));
//if (OtherInventory == null)
//{
// throw new InventoryFetchException (other);
//}
// fetch our inventory from the Steam API.
myInventoryTask = Task.Factory.StartNew(() => Inventory.FetchInventory(me.ConvertToUInt64(), ApiKey, SteamWeb));
// check that the schema was already successfully fetched
if (Trade.CurrentSchema == null)
Trade.CurrentSchema = Schema.FetchSchema (ApiKey);
if (Trade.CurrentSchema == null)
throw new TradeException ("Could not download the latest item schema.");
}
#endregion Public Methods
/// <summary>
/// Starts the actual trade-polling thread.
/// </summary>
public void StartTradeThread (Trade trade)
{
// initialize data to use in thread
tradeStartTime = DateTime.Now;
lastOtherActionTime = DateTime.Now;
lastTimeoutMessage = DateTime.Now.AddSeconds(-1000);
var pollThread = new Thread (() =>
{
IsTradeThreadRunning = true;
DebugPrint ("Trade thread starting.");
// main thread loop for polling
try
{
while(IsTradeThreadRunning)
{
bool action = trade.Poll();
if(action)
lastOtherActionTime = DateTime.Now;
if (trade.HasTradeEnded || CheckTradeTimeout(trade))
{
IsTradeThreadRunning = false;
break;
}
Thread.Sleep(TradePollingInterval);
}
}
catch(Exception ex)
{
// TODO: find a new way to do this w/o the trade events
//if (OnError != null)
// OnError("Error Polling Trade: " + e);
// ok then we should stop polling...
IsTradeThreadRunning = false;
DebugPrint("[TRADEMANAGER] general error caught: " + ex);
trade.FireOnErrorEvent("Unknown error occurred: " + ex.ToString());
}
finally
{
DebugPrint("Trade thread shutting down.");
try //Yikes, that's a lot of nested 'try's. Is there some way to clean this up?
{
if(trade.IsTradeAwaitingConfirmation)
trade.FireOnAwaitingConfirmation();
}
catch(Exception ex)
{
trade.FireOnErrorEvent("Unknown error occurred during OnTradeAwaitingConfirmation: " + ex.ToString());
}
finally
{
try
{
//Make sure OnClose is always fired after OnSuccess, even if OnSuccess throws an exception
//(which it NEVER should, but...)
trade.FireOnCloseEvent();
}
catch (Exception e)
{
DebugError("Error occurred during trade.OnClose()! " + e);
throw;
}
}
}
});
pollThread.Start();
}
private bool CheckTradeTimeout (Trade trade)
{
// User has accepted the trade. Disregard time out.
if (trade.OtherUserAccepted)
return false;
var now = DateTime.Now;
DateTime actionTimeout = lastOtherActionTime.AddSeconds (MaxActionGapSec);
int untilActionTimeout = (int)Math.Round ((actionTimeout - now).TotalSeconds);
DebugPrint (String.Format ("{0} {1}", actionTimeout, untilActionTimeout));
DateTime tradeTimeout = tradeStartTime.AddSeconds (MaxTradeTimeSec);
int untilTradeTimeout = (int)Math.Round ((tradeTimeout - now).TotalSeconds);
double secsSinceLastTimeoutMessage = (now - lastTimeoutMessage).TotalSeconds;
if (untilActionTimeout <= 0 || untilTradeTimeout <= 0)
{
DebugPrint ("timed out...");
if (OnTimeout != null)
{
OnTimeout (this, null);
}
trade.CancelTrade ();
return true;
}
else if (untilActionTimeout <= 20 && secsSinceLastTimeoutMessage >= 10)
{
try
{
trade.SendMessage("Are You AFK? The trade will be canceled in " + untilActionTimeout + " seconds if you don't do something.");
}
catch { }
lastTimeoutMessage = now;
}
return false;
}
[Conditional ("DEBUG_TRADE_MANAGER")]
private static void DebugPrint (string output)
{
// I don't really want to add the Logger as a dependecy to TradeManager so I
// print using the console directly. To enable this for debugging put this:
// #define DEBUG_TRADE_MANAGER
// at the first line of this file.
System.Console.WriteLine (output);
}
private static void DebugError(string output)
{
System.Console.WriteLine(output);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Baseline;
using Marten.Internal.Operations;
using Marten.Linq;
using Marten.Linq.Fields;
using Marten.Linq.Filters;
using Marten.Linq.Parsing;
using Marten.Linq.QueryHandlers;
using Marten.Linq.Selectors;
using Marten.Linq.SqlGeneration;
using Weasel.Postgresql;
using Marten.Schema;
using Marten.Services;
using Marten.Storage;
using Marten.Util;
using Npgsql;
using Remotion.Linq;
namespace Marten.Internal.Storage
{
public class SubClassDocumentStorage<T, TRoot, TId>: IDocumentStorage<T, TId>
where T : TRoot
{
private readonly IDocumentStorage<TRoot, TId> _parent;
private readonly SubClassMapping _mapping;
private readonly ISqlFragment _defaultWhere;
private readonly string[] _fields;
public SubClassDocumentStorage(IDocumentStorage<TRoot, TId> parent, SubClassMapping mapping)
{
_parent = parent;
_mapping = mapping;
FromObject = _mapping.TableName.QualifiedName;
_defaultWhere = determineWhereFragment();
_fields = _parent.SelectFields();
}
public void TruncateDocumentStorage(ITenant tenant)
{
tenant.RunSql(
$"delete from {_parent.TableName.QualifiedName} where {SchemaConstants.DocumentTypeColumn} = '{_mapping.Alias}'");
}
public Task TruncateDocumentStorageAsync(ITenant tenant)
{
return tenant.RunSqlAsync(
$"delete from {_parent.TableName.QualifiedName} where {SchemaConstants.DocumentTypeColumn} = '{_mapping.Alias}'");
}
public TenancyStyle TenancyStyle => _parent.TenancyStyle;
object IDocumentStorage<T>.IdentityFor(T document)
{
return _parent.Identity(document);
}
public string FromObject { get; }
public Type SelectedType => typeof(T);
public void WriteSelectClause(CommandBuilder sql)
{
_parent.WriteSelectClause(sql);
}
public string[] SelectFields()
{
return _fields;
}
public ISelector BuildSelector(IMartenSession session)
{
var inner = _parent.BuildSelector(session);
return new CastingSelector<T, TRoot>((ISelector<TRoot>) inner);
}
public IQueryHandler<TResult> BuildHandler<TResult>(IMartenSession session, Statement statement,
Statement currentStatement)
{
var selector = (ISelector<T>)BuildSelector(session);
return LinqHandlerBuilder.BuildHandler<T, TResult>(selector, statement);
}
public ISelectClause UseStatistics(QueryStatistics statistics)
{
return new StatsSelectClause<T>(this, statistics);
}
public Type SourceType => typeof(TRoot);
public IFieldMapping Fields => _mapping.Parent;
public ISqlFragment FilterDocuments(QueryModel model, ISqlFragment query)
{
var extras = extraFilters(query).ToArray();
var extraCompound = new CompoundWhereFragment("and", extras);
return new CompoundWhereFragment("and", query, extraCompound);
}
// TODO -- there's duplication here w/ DocumentStorage
private IEnumerable<ISqlFragment> extraFilters(ISqlFragment query)
{
yield return toBasicWhere();
if (_mapping.DeleteStyle == DeleteStyle.SoftDelete && !query.Contains(SchemaConstants.DeletedColumn))
yield return ExcludeSoftDeletedFilter.Instance;
if (_mapping.Parent.TenancyStyle == TenancyStyle.Conjoined && !query.SpecifiesTenant())
yield return new CurrentTenantFilter();
}
// TODO -- there's duplication here w/ DocumentStorage
private IEnumerable<ISqlFragment> defaultFilters()
{
yield return toBasicWhere();
if (_mapping.Parent.TenancyStyle == TenancyStyle.Conjoined) yield return new CurrentTenantFilter();
if (_mapping.DeleteStyle == DeleteStyle.SoftDelete) yield return ExcludeSoftDeletedFilter.Instance;
}
public ISqlFragment DefaultWhereFragment()
{
return _defaultWhere;
}
public ISqlFragment determineWhereFragment()
{
var defaults = defaultFilters().ToArray();
return defaults.Length switch
{
0 => null,
1 => defaults[0],
_ => new CompoundWhereFragment("and", defaults)
};
}
private WhereFragment toBasicWhere()
{
var aliasValues = _mapping.Aliases.Select(a => $"d.{SchemaConstants.DocumentTypeColumn} = '{a}'").ToArray()
.Join(" or ");
var sql = _mapping.Alias.Length > 1 ? $"({aliasValues})" : aliasValues;
return new WhereFragment(sql);
}
public bool UseOptimisticConcurrency => _parent.UseOptimisticConcurrency;
public IOperationFragment DeleteFragment => _parent.DeleteFragment;
public IOperationFragment HardDeleteFragment { get; }
public DuplicatedField[] DuplicatedFields => _parent.DuplicatedFields;
public DbObjectName TableName => _parent.TableName;
public Type DocumentType => typeof(T);
public Type IdType => typeof(TId);
public Guid? VersionFor(T document, IMartenSession session)
{
return _parent.VersionFor(document, session);
}
public void Store(IMartenSession session, T document)
{
_parent.Store(session, document);
}
public void Store(IMartenSession session, T document, Guid? version)
{
_parent.Store(session, document, version);
}
public void Eject(IMartenSession session, T document)
{
_parent.Eject(session, document);
}
public IStorageOperation Update(T document, IMartenSession session, ITenant tenant)
{
return _parent.Update(document, session, tenant);
}
public IStorageOperation Insert(T document, IMartenSession session, ITenant tenant)
{
return _parent.Insert(document, session, tenant);
}
public IStorageOperation Upsert(T document, IMartenSession session, ITenant tenant)
{
return _parent.Upsert(document, session, tenant);
}
public IStorageOperation Overwrite(T document, IMartenSession session, ITenant tenant)
{
return _parent.Overwrite(document, session, tenant);
}
public IDeletion DeleteForDocument(T document, ITenant tenant)
{
return _parent.DeleteForDocument(document, tenant);
}
public void SetIdentity(T document, TId identity)
{
_parent.SetIdentity(document, identity);
}
public IDeletion DeleteForId(TId id, ITenant tenant)
{
return _parent.DeleteForId(id, tenant);
}
public T Load(TId id, IMartenSession session)
{
var doc = _parent.Load(id, session);
if (doc is T x) return x;
return default;
}
public async Task<T> LoadAsync(TId id, IMartenSession session, CancellationToken token)
{
var doc = await _parent.LoadAsync(id, session, token);
if (doc is T x) return x;
return default;
}
public IReadOnlyList<T> LoadMany(TId[] ids, IMartenSession session)
{
return _parent.LoadMany(ids, session).OfType<T>().ToList();
}
public async Task<IReadOnlyList<T>> LoadManyAsync(TId[] ids, IMartenSession session, CancellationToken token)
{
return (await _parent.LoadManyAsync(ids, session, token)).OfType<T>().ToList();
}
public TId AssignIdentity(T document, ITenant tenant)
{
return _parent.AssignIdentity(document, tenant);
}
public TId Identity(T document)
{
return _parent.Identity(document);
}
public ISqlFragment ByIdFilter(TId id)
{
return _parent.ByIdFilter(id);
}
public IDeletion HardDeleteForId(TId id, ITenant tenant)
{
return _parent.HardDeleteForId(id, tenant);
}
public NpgsqlCommand BuildLoadCommand(TId id, ITenant tenant)
{
return _parent.BuildLoadCommand(id, tenant);
}
public NpgsqlCommand BuildLoadManyCommand(TId[] ids, ITenant tenant)
{
return _parent.BuildLoadManyCommand(ids, tenant);
}
public void EjectById(IMartenSession session, object id)
{
_parent.EjectById(session, id);
}
public void RemoveDirtyTracker(IMartenSession session, object id)
{
_parent.RemoveDirtyTracker(session, id);
}
public IDeletion HardDeleteForDocument(T document, ITenant tenant)
{
return _parent.HardDeleteForDocument(document, tenant);
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using Http2;
using Http2.Hpack;
namespace Http2Tests
{
public static class WriteableStreamTestExtensions
{
public const int WriteTimeout = 200;
public static async Task WriteFrameHeader(
this IWriteAndCloseableByteStream stream,
FrameHeader fh)
{
var headerBytes = new byte[FrameHeader.HeaderSize];
fh.EncodeInto(new ArraySegment<byte>(headerBytes));
await stream.WriteAsync(new ArraySegment<byte>(headerBytes));
}
public static async Task WriteFrameHeaderWithTimeout(
this IWriteAndCloseableByteStream stream,
FrameHeader fh)
{
var writeTask = stream.WriteFrameHeader(fh);
var timeoutTask = Task.Delay(WriteTimeout);
var combined = Task.WhenAny(new Task[]{ writeTask, timeoutTask });
var done = await combined;
if (done == writeTask)
{
await writeTask;
return;
}
throw new TimeoutException();
}
public static async Task WriteWithTimeout(
this IWriteAndCloseableByteStream stream, ArraySegment<byte> buf)
{
var writeTask = stream.WriteAsync(buf);
var timeoutTask = Task.Delay(WriteTimeout);
var combined = Task.WhenAny(new Task[]{ writeTask, timeoutTask });
var done = await combined;
if (done == writeTask)
{
await writeTask;
return;
}
throw new TimeoutException();
}
public static async Task WriteSettings(
this IWriteAndCloseableByteStream stream, Settings settings)
{
var settingsData = new byte[settings.RequiredSize];
var fh = new FrameHeader
{
Type = FrameType.Settings,
Length = settingsData.Length,
Flags = 0,
StreamId = 0,
};
settings.EncodeInto(new ArraySegment<byte>(settingsData));
await stream.WriteFrameHeader(fh);
await stream.WriteAsync(new ArraySegment<byte>(settingsData));
}
public static async Task WriteSettingsAck(
this IWriteAndCloseableByteStream stream)
{
var fh = new FrameHeader
{
Type = FrameType.Settings,
Length = 0,
Flags = (byte)SettingsFrameFlags.Ack,
StreamId = 0,
};
await stream.WriteFrameHeader(fh);
}
public static async Task WritePing(
this IWriteAndCloseableByteStream stream, byte[] data, bool isAck)
{
var pingHeader = new FrameHeader
{
Type = FrameType.Ping,
Flags = isAck ? (byte)PingFrameFlags.Ack : (byte)0,
Length = 8,
StreamId = 0,
};
await stream.WriteFrameHeader(pingHeader);
await stream.WriteAsync(new ArraySegment<byte>(data, 0, 8));
}
public static async Task WritePriority(
this IWriteAndCloseableByteStream stream,
uint streamId, PriorityData prioData)
{
var fh = new FrameHeader
{
Type = FrameType.Priority,
Flags = 0,
Length = PriorityData.Size,
StreamId = streamId,
};
await stream.WriteFrameHeader(fh);
var payload = new byte[PriorityData.Size];
prioData.EncodeInto(new ArraySegment<byte>(payload));
await stream.WriteAsync(new ArraySegment<byte>(payload));
}
public static async Task WriteWindowUpdate(
this IWriteAndCloseableByteStream stream, uint streamId, int amount)
{
var windowUpdateHeader = new FrameHeader
{
Type = FrameType.WindowUpdate,
Flags = 0,
Length = WindowUpdateData.Size,
StreamId = streamId,
};
var data = new WindowUpdateData
{
WindowSizeIncrement = amount,
};
var dataBytes = new byte[WindowUpdateData.Size];
data.EncodeInto(new ArraySegment<byte>(dataBytes));
await stream.WriteFrameHeader(windowUpdateHeader);
await stream.WriteAsync(new ArraySegment<byte>(dataBytes));
}
public static async Task WriteResetStream(
this IWriteAndCloseableByteStream stream, uint streamId, ErrorCode errc)
{
var fh = new FrameHeader
{
Type = FrameType.ResetStream,
Flags = 0,
Length = ResetFrameData.Size,
StreamId = streamId,
};
var data = new ResetFrameData
{
ErrorCode = errc,
};
var dataBytes = new byte[ResetFrameData.Size];
data.EncodeInto(new ArraySegment<byte>(dataBytes));
await stream.WriteFrameHeader(fh);
await stream.WriteAsync(new ArraySegment<byte>(dataBytes));
}
public static async Task WriteGoAway(
this IWriteAndCloseableByteStream stream,
uint lastStreamId,
ErrorCode errc,
byte[] debugData = null)
{
if (debugData == null) debugData = new byte[0];
var goAwayData = new GoAwayFrameData
{
Reason = new GoAwayReason
{
LastStreamId = lastStreamId,
ErrorCode = errc,
DebugData = new ArraySegment<byte>(debugData),
},
};
var fh = new FrameHeader
{
Type = FrameType.GoAway,
Flags = 0,
StreamId = 0,
Length = goAwayData.RequiredSize,
};
var dataBytes = new byte[goAwayData.RequiredSize];
goAwayData.EncodeInto(new ArraySegment<byte>(dataBytes));
await stream.WriteFrameHeader(fh);
await stream.WriteAsync(new ArraySegment<byte>(dataBytes));
}
public static async Task WriteHeaders(
this IWriteAndCloseableByteStream stream,
Encoder encoder,
uint streamId,
bool endOfStream,
IEnumerable<HeaderField> headers,
bool endOfHeaders = true)
{
var outBuf = new byte[Settings.Default.MaxFrameSize];
var result = encoder.EncodeInto(new ArraySegment<byte>(outBuf), headers);
// Check if all headers could be encoded
if (result.FieldCount != headers.Count())
{
throw new Exception("Could not encode all headers");
}
byte flags = 0;
if (endOfHeaders) flags |= (byte)(HeadersFrameFlags.EndOfHeaders);
if (endOfStream) flags |= (byte)HeadersFrameFlags.EndOfStream;
var fh = new FrameHeader
{
Type = FrameType.Headers,
Length = result.UsedBytes,
Flags = flags,
StreamId = streamId,
};
await stream.WriteFrameHeader(fh);
await stream.WriteAsync(
new ArraySegment<byte>(outBuf, 0, result.UsedBytes));
}
public static async Task WriteContinuation(
this IWriteAndCloseableByteStream stream,
Encoder encoder,
uint streamId,
IEnumerable<HeaderField> headers,
bool endOfHeaders = true)
{
var outBuf = new byte[Settings.Default.MaxFrameSize];
var result = encoder.EncodeInto(new ArraySegment<byte>(outBuf), headers);
// Check if all headers could be encoded
if (result.FieldCount != headers.Count())
{
throw new Exception("Could not encode all headers");
}
byte flags = 0;
if (endOfHeaders) flags |= (byte)ContinuationFrameFlags.EndOfHeaders;
var fh = new FrameHeader
{
Type = FrameType.Continuation,
Length = result.UsedBytes,
Flags = flags,
StreamId = streamId,
};
await stream.WriteFrameHeader(fh);
await stream.WriteAsync(
new ArraySegment<byte>(outBuf, 0, result.UsedBytes));
}
public static async Task WriteData(
this IWriteAndCloseableByteStream stream,
uint streamId,
int length,
int? padLen = null,
bool endOfStream = false)
{
byte flags = 0;
if (endOfStream) flags |= (byte)DataFrameFlags.EndOfStream;
if (padLen.HasValue) flags |= (byte)DataFrameFlags.Padded;
var dataLen = length;
if (padLen.HasValue) dataLen += 1 + padLen.Value;
var data = new byte[dataLen];
if (padLen.HasValue) data[0] = (byte)padLen.Value;
var fh = new FrameHeader
{
Type = FrameType.Data,
Length = dataLen,
Flags = flags,
StreamId = streamId,
};
await stream.WriteFrameHeader(fh);
if (dataLen != 0)
{
await stream.WriteWithTimeout(new ArraySegment<byte>(data));
}
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: Int64.cs
**
**
** Purpose: This class will encapsulate a long and provide an
** Object representation of it.
**
**
===========================================================*/
namespace System
{
using System;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
[Microsoft.Zelig.Internals.WellKnownType( "System_Int64" )]
[Serializable]
[StructLayout( LayoutKind.Sequential )]
public struct Int64 : IComparable, IFormattable, IConvertible, IComparable<Int64>, IEquatable<Int64>
{
public const long MaxValue = 0x7FFFFFFFFFFFFFFFL;
public const long MinValue = unchecked( (long)0x8000000000000000L );
internal long m_value;
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type Int64, this method throws an ArgumentException.
//
public int CompareTo( Object value )
{
if(value == null)
{
return 1;
}
if(value is Int64)
{
return CompareTo( (Int64)value );
}
#if EXCEPTION_STRINGS
throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeInt64" ) );
#else
throw new ArgumentException();
#endif
}
public int CompareTo( Int64 value )
{
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
if(m_value < value) return -1;
if(m_value > value) return 1;
return 0;
}
public override bool Equals( Object obj )
{
if(!(obj is Int64))
{
return false;
}
return Equals( (Int64)obj );
}
public bool Equals( Int64 obj )
{
return m_value == obj;
}
// The value of the lower 32 bits XORed with the uppper 32 bits.
public override int GetHashCode()
{
return (unchecked( (int)((long)m_value) ) ^ (int)(m_value >> 32));
}
public override String ToString()
{
return Number.FormatInt64( m_value, /*null,*/ NumberFormatInfo.CurrentInfo );
}
public String ToString( IFormatProvider provider )
{
return Number.FormatInt64( m_value, /*null,*/ NumberFormatInfo.GetInstance( provider ) );
}
public String ToString( String format )
{
return Number.FormatInt64( m_value, format, NumberFormatInfo.CurrentInfo );
}
public String ToString( String format ,
IFormatProvider provider )
{
return Number.FormatInt64( m_value, format, NumberFormatInfo.GetInstance( provider ) );
}
public static long Parse( String s )
{
return Number.ParseInt64( s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo );
}
public static long Parse( String s ,
NumberStyles style )
{
NumberFormatInfo.ValidateParseStyleInteger( style );
return Number.ParseInt64( s, style, NumberFormatInfo.CurrentInfo );
}
public static long Parse( String s ,
IFormatProvider provider )
{
return Number.ParseInt64( s, NumberStyles.Integer, NumberFormatInfo.GetInstance( provider ) );
}
// Parses a long from a String in the given style. If
// a NumberFormatInfo isn't specified, the current culture's
// NumberFormatInfo is assumed.
//
public static long Parse( String s ,
NumberStyles style ,
IFormatProvider provider )
{
NumberFormatInfo.ValidateParseStyleInteger( style );
return Number.ParseInt64( s, style, NumberFormatInfo.GetInstance( provider ) );
}
public static Boolean TryParse( String s ,
out Int64 result )
{
return Number.TryParseInt64( s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result );
}
public static Boolean TryParse( String s ,
NumberStyles style ,
IFormatProvider provider ,
out Int64 result )
{
NumberFormatInfo.ValidateParseStyleInteger( style );
return Number.TryParseInt64( s, style, NumberFormatInfo.GetInstance( provider ), out result );
}
#region IConvertible
public TypeCode GetTypeCode()
{
return TypeCode.Int64;
}
/// <internalonly/>
bool IConvertible.ToBoolean( IFormatProvider provider )
{
return Convert.ToBoolean( m_value );
}
/// <internalonly/>
char IConvertible.ToChar( IFormatProvider provider )
{
return Convert.ToChar( m_value );
}
/// <internalonly/>
sbyte IConvertible.ToSByte( IFormatProvider provider )
{
return Convert.ToSByte( m_value );
}
/// <internalonly/>
byte IConvertible.ToByte( IFormatProvider provider )
{
return Convert.ToByte( m_value );
}
/// <internalonly/>
short IConvertible.ToInt16( IFormatProvider provider )
{
return Convert.ToInt16( m_value );
}
/// <internalonly/>
ushort IConvertible.ToUInt16( IFormatProvider provider )
{
return Convert.ToUInt16( m_value );
}
/// <internalonly/>
int IConvertible.ToInt32( IFormatProvider provider )
{
return Convert.ToInt32( m_value );
}
/// <internalonly/>
uint IConvertible.ToUInt32( IFormatProvider provider )
{
return Convert.ToUInt32( m_value );
}
/// <internalonly/>
long IConvertible.ToInt64( IFormatProvider provider )
{
return m_value;
}
/// <internalonly/>
ulong IConvertible.ToUInt64( IFormatProvider provider )
{
return Convert.ToUInt64( m_value );
}
/// <internalonly/>
float IConvertible.ToSingle( IFormatProvider provider )
{
return Convert.ToSingle( m_value );
}
/// <internalonly/>
double IConvertible.ToDouble( IFormatProvider provider )
{
return Convert.ToDouble( m_value );
}
/// <internalonly/>
Decimal IConvertible.ToDecimal( IFormatProvider provider )
{
return Convert.ToDecimal( m_value );
}
/// <internalonly/>
DateTime IConvertible.ToDateTime( IFormatProvider provider )
{
#if EXCEPTION_STRINGS
throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), "Int64", "DateTime" ) );
#else
throw new InvalidCastException();
#endif
}
/// <internalonly/>
Object IConvertible.ToType( Type type, IFormatProvider provider )
{
return Convert.DefaultToType( (IConvertible)this, type, provider );
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;
using Axiom.Core;
using System.Diagnostics;
namespace Multiverse.ToolBox
{
public class MultiSelectTreeView : TreeView
{
public MultiSelectTreeView()
{
base.DrawMode = TreeViewDrawMode.OwnerDrawText;
}
private List<MultiSelectTreeNode> selectedNodes = new List<MultiSelectTreeNode>();
public List<MultiSelectTreeNode> SelectedNodes
{
get
{
return selectedNodes;
}
set
{
if (value == null)
{
selectedNodes.Clear();
}
else
{
selectedNodes = value;
}
}
}
public void AddToSelectedNodes(MultiSelectTreeNode node)
{
selectedNodes.Add(node);
TreeViewEventArgs e = new TreeViewEventArgs(node);
OnAfterSelect(e);
}
public void AddSelectedNode(MultiSelectTreeNode node)
{
selectedNodes.Add(node);
node.Select(false);
TreeViewEventArgs e = new TreeViewEventArgs(node);
OnAfterSelect(e);
}
public void RemoveSelectedNode(MultiSelectTreeNode node)
{
selectedNodes.Remove(node);
node.UnSelect(false);
TreeViewEventArgs e = new TreeViewEventArgs(node);
OnAfterSelect(e);
}
public void ClearSelectedTreeNodes()
{
for (int i = selectedNodes.Count - 1; i >= 0; i--)
{
selectedNodes[i].UnSelect();
}
}
public MultiSelectTreeNode FindNextNode(MultiSelectTreeNode node)
{
if (node != null)
{
TreeNode nodep = node.Parent;
if (node.IsExpanded && node.Nodes.Count != 0)
{
return node.Nodes[0] as MultiSelectTreeNode;
}
if (nodep != null)
{
int i = nodep.Nodes.IndexOf(node as TreeNode);
if (nodep.Nodes.Count > i + 1)
{
return nodep.Nodes[i + 1] as MultiSelectTreeNode;
}
else
{
if (nodep.Parent != null)
{
return FindNextNode(nodep as MultiSelectTreeNode);
}
}
}
}
return null;
}
public MultiSelectTreeNode FindPrevNode(MultiSelectTreeNode node)
{
if (node != null)
{
TreeNode nodep = node.Parent;
if (nodep != null)
{
int i = nodep.Nodes.IndexOf(node);
if (i > 0)
{
return nodep.Nodes[i - 1] as MultiSelectTreeNode;
}
else
{
return nodep as MultiSelectTreeNode;
}
}
}
return null;
}
protected override void OnDrawNode(DrawTreeNodeEventArgs e)
{
MultiSelectTreeNode multiNode = e.Node as MultiSelectTreeNode;
if (multiNode == null)
{
e.DrawDefault = true;
}
else
{
//LogManager.Instance.Write("Enter MuliNode == null false\n");
Font nodeFont = multiNode.NodeFont;
if (nodeFont == null)
{
//LogManager.Instance.Write("nodeFont == null");
nodeFont = base.Font;
}
Brush backBrush;
Brush foreBrush;
if (multiNode.IsSelected)
{
//LogManager.Instance.Write("multiNode.IsSelected = true");
foreBrush = SystemBrushes.HighlightText;
backBrush = SystemBrushes.Highlight;
}
else
{
//LogManager.Instance.Write("multiNode.IsSelected = false");
if (multiNode.ForeColor != Color.Empty)
{
foreBrush = new SolidBrush(multiNode.ForeColor);
}
else
{
foreBrush = new SolidBrush(multiNode.TreeView.ForeColor);
}
if (multiNode.BackColor != Color.Empty)
{
//LogManager.Instance.Write("multiNode.BackColor = r={0}, g={1}, b={2}", multiNode.BackColor.R, multiNode.BackColor.G, multiNode.BackColor.B);
Color backColor = multiNode.BackColor;
backBrush = new SolidBrush(multiNode.BackColor);
}
else
{
//LogManager.Instance.Write("multiNode.TreeView.BackColor = r={0}, g={1}, b={2}", multiNode.TreeView.BackColor.R.ToString(), multiNode.TreeView.BackColor.G.ToString(), multiNode.TreeView.BackColor.B.ToString());
Color backColor = multiNode.TreeView.BackColor;
backBrush = new SolidBrush(multiNode.TreeView.BackColor);
}
}
PointF point = new PointF(e.Bounds.X, e.Bounds.Y);
//LogManager.Instance.Write(
// "e.Bounds.X = {0}, e.Bounds.y = {1} , e.Bounds.Width = {2}, e.Bounds.Height = {3}, e.Node.Text = {4}\n", e.Bounds.X,
// e.Bounds.Y, e.Bounds.Width, e.Bounds.Height, e.Node.Text);
if (!String.Equals(e.Node.Text, "World: k"))
{
if (e.Bounds.X == -1 && e.Bounds.Y == 0)
{
return;
}
}
e.Graphics.FillRectangle(backBrush, e.Bounds);
StringFormat format = new StringFormat(StringFormatFlags.NoClip | StringFormatFlags.NoWrap);
e.Graphics.DrawString(e.Node.Text, nodeFont, foreBrush, point, format);
//Rectangle bounds = e.Bounds;
//bounds.X += 1;
//e.Graphics.FillRectangle(backBrush, bounds);
//e.Graphics.DrawString(e.Node.Text, nodeFont, foreBrush, e.Bounds.X, e.Bounds.Y);
if ((e.State & TreeNodeStates.Focused) != 0)
{
using (Pen focusPen = new Pen(Color.Black))
{
focusPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;
Rectangle focusBounds = e.Bounds;
focusBounds.Size = new Size(focusBounds.Width - 1, focusBounds.Height - 1);
//LogManager.Instance.Write("focusBounds.X = {0}, FocusBounds.Y = {1}, e.Bounds.Height ={2}, e.Bounds.Width = {3}, focusPen.Color = {4}\n", focusBounds.X.ToString(), focusBounds.Y.ToString(), focusBounds.Height.ToString(), focusBounds.Width.ToString(), focusPen.Color.ToString());
e.Graphics.DrawRectangle(focusPen, focusBounds);
//focusPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;
//Rectangle focusBounds = e.Bounds;
//focusBounds.Size = new Size(focusBounds.Width,
// focusBounds.Height - 1);
//e.Graphics.DrawRectangle(focusPen, focusBounds);
}
}
if (!multiNode.IsSelected)
{
backBrush.Dispose();
foreBrush.Dispose();
}
}
base.OnDrawNode(e);
}
protected override void OnMouseClick(MouseEventArgs e)
{
MultiSelectTreeNode nodeHit = base.HitTest(e.X, e.Y).Node as MultiSelectTreeNode;
if (e.Button == MouseButtons.Left)
{
MultiSelectTreeNode multiNode = nodeHit as MultiSelectTreeNode;
if (multiNode != null && selectedNodes != null)
{
if ((Control.ModifierKeys & Keys.Control) == 0 && selectedNodes.Count != 0)
{
for (int i = 0; i < selectedNodes.Count && selectedNodes.Count != 0; )
{
MultiSelectTreeNode node = selectedNodes[i];
if (node != null && node != multiNode)
{
node.UnSelect();
}
else
{
i++;
}
}
if (!selectedNodes.Contains(multiNode))
{
multiNode.Select();
}
else
{
multiNode.UnSelect();
}
}
else
{
if (multiNode.IsSelected)
{
multiNode.UnSelect();
}
else
{
multiNode.Select();
}
}
}
}
if (e.Button == MouseButtons.Right)
{
MultiSelectTreeNode treeNode = nodeHit as MultiSelectTreeNode;
if ((Control.ModifierKeys & Keys.Control) == 0)
{
//if (SelectedObject.Count = 1)
//{
// if (SelectedObject.Contains(treeNode.WorldObject))
// {
// return;
// }
// else
// {
// SelectedObject[0].Node.UnSelect();
// SelectedObject.Add(treeNode.WorldObject);
// }
//}
if (selectedNodes.Count >= 1)
{
if (selectedNodes.Contains(treeNode))
{
return;
}
for (int i = selectedNodes.Count - 1; i >= 0; i--)
{
selectedNodes[i].UnSelect();
}
}
if (selectedNodes.Count == 0)
{
treeNode.Select();
}
}
else
{
return;
}
}
base.OnMouseClick(e);
}
}
}
| |
#region License
// Copyright (c) 2010-2019, Mark Final
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of BuildAMation nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion // License
using System.Linq;
namespace VSSolutionBuilder
{
/// <summary>
/// Class representing a VisualStudio solution.
/// </summary>
sealed class VSSolution
{
private System.Collections.Generic.Dictionary<System.Type, VSProject> ProjectMap = new System.Collections.Generic.Dictionary<System.Type, VSProject>();
private System.Collections.Generic.Dictionary<string, VSSolutionFolder> SolutionFolders = new System.Collections.Generic.Dictionary<string, VSSolutionFolder>();
private void
AddNestedEntity(
string parentpath,
string currentpath,
VSProject project,
VSSolutionFolder parent = null)
{
var split = currentpath.Split('/');
var path = split[0];
var keyPath = string.Join("/", parentpath, path);
lock (this.SolutionFolders)
{
if (!this.SolutionFolders.ContainsKey(keyPath))
{
this.SolutionFolders.Add(keyPath, new VSSolutionFolder(keyPath, path));
}
}
var folder = this.SolutionFolders[keyPath];
if (null != parent)
{
parent.AppendNestedEntity(folder);
}
if (1 == split.Length)
{
folder.AppendNestedEntity(project);
}
else
{
this.AddNestedEntity(keyPath, string.Join("/", split.Skip(1)), project, folder);
}
}
/// <summary>
/// Ensure that a VisualStudio project exists in the solution.
/// Create it if not, and always return it.
/// The project itself maps to the type of the Module, rather than the Module itself.
/// </summary>
/// <param name="moduleType">Module type representing the project.</param>
/// <param name="environment">Environment in which this project was created.</param>
/// <returns>The project</returns>
public VSProject
EnsureProjectExists(
System.Type moduleType,
Bam.Core.Environment environment)
{
lock (this.ProjectMap)
{
if (!this.ProjectMap.ContainsKey(moduleType))
{
// projects map to multiple Modules (each configuration)
// so just create a path against the first Module found
var module = Bam.Core.Graph.Instance.EncapsulatingModules(environment).First(item => item.GetType() == moduleType);
var projectPath = module.CreateTokenizedString("$(packagebuilddir)/$(modulename).vcxproj");
projectPath.Parse();
var project = new VSProject(this, projectPath);
this.ProjectMap.Add(moduleType, project);
var groups = moduleType.GetCustomAttributes(typeof(Bam.Core.ModuleGroupAttribute), true);
if (groups.Length > 0)
{
var solutionFolderName = (groups as Bam.Core.ModuleGroupAttribute[])[0].GroupName;
this.AddNestedEntity(".", solutionFolderName, project);
}
}
return this.ProjectMap[moduleType];
}
}
/// <summary>
/// Enumerate across all projects in the solution.
/// </summary>
public System.Collections.Generic.IEnumerable<VSProject> Projects
{
get
{
foreach (var project in this.ProjectMap)
{
yield return project.Value;
}
}
}
/// <summary>
/// Serialise the solution to a string.
/// </summary>
/// <param name="solutionPath">Path to which the solution will be written.</param>
/// <returns></returns>
public System.Text.StringBuilder
Serialize(
string solutionPath)
{
var ProjectTypeGuid = System.Guid.Parse("8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942");
var SolutionFolderGuid = System.Guid.Parse("2150E333-8FDC-42A3-9474-1A3956D46DE8");
var content = new System.Text.StringBuilder();
var visualCMeta = Bam.Core.Graph.Instance.PackageMetaData<VisualC.MetaData>("VisualC");
content.AppendLine($@"Microsoft Visual Studio Solution File, Format Version {visualCMeta.SolutionFormatVersion}");
var configs = new Bam.Core.StringArray();
foreach (var project in this.Projects)
{
var relativeProjectPath = Bam.Core.RelativePathUtilities.GetRelativePathFromRoot(
System.IO.Path.GetDirectoryName(solutionPath),
project.ProjectPath
);
content.AppendLine($"Project(\"{ProjectTypeGuid.ToString("B").ToUpper()}\") = \"{System.IO.Path.GetFileNameWithoutExtension(project.ProjectPath)}\", \"{relativeProjectPath}\", \"{project.GuidString}\"");
content.AppendLine("EndProject");
foreach (var config in project.Configurations)
{
configs.AddUnique(config.Value.FullName);
}
}
foreach (var folder in this.SolutionFolders)
{
var folderPath = folder.Value.Path;
var folderGuid = folder.Value.GuidString;
content.AppendLine($"Project(\"{SolutionFolderGuid.ToString("B").ToUpper()}\") = \"{folderPath}\", \"{folderPath}\", \"{folderGuid}\"");
content.AppendLine("EndProject");
}
content.AppendLine("Global");
content.AppendLine("\tGlobalSection(SolutionConfigurationPlatforms) = preSolution");
foreach (var config in configs)
{
// TODO: I'm sure these are not meant to be identical, but I don't know what else to put here
content.AppendLine($"\t\t{config} = {config}");
}
content.AppendLine("\tEndGlobalSection");
content.AppendLine("\tGlobalSection(ProjectConfigurationPlatforms) = postSolution");
foreach (var project in this.Projects)
{
var guid = project.GuidString;
var thisProjectConfigs = new Bam.Core.StringArray();
// write the configurations for which build steps have been defined
foreach (var config in project.Configurations)
{
var configName = config.Value.FullName;
content.AppendLine($"\t\t{guid}.{configName}.ActiveCfg = {configName}");
content.AppendLine($"\t\t{guid}.{configName}.Build.0 = {configName}");
thisProjectConfigs.AddUnique(configName);
}
// now cater for any configurations that the project does not support
var unsupportedConfigs = configs.Complement(thisProjectConfigs) as Bam.Core.StringArray;
foreach (var uConfig in unsupportedConfigs)
{
// a missing "XX.YY.Build.0" line means not configured to build
// also, the remapping between config names seems a little arbitrary, but seems to work
// might be related to the project not having an ProjectConfiguration for the unsupported config
content.AppendLine($"\t\t{guid}.{uConfig}.ActiveCfg = {thisProjectConfigs[0]}");
}
}
content.AppendLine("\tEndGlobalSection");
content.AppendLine("\tGlobalSection(SolutionProperties) = preSolution");
content.AppendLine("\t\tHideSolutionNode = FALSE");
content.AppendLine("\tEndGlobalSection");
if (this.SolutionFolders.Count() > 0)
{
content.AppendLine("\tGlobalSection(NestedProjects) = preSolution");
foreach (var folder in this.SolutionFolders)
{
folder.Value.Serialize(content, 2);
}
content.AppendLine("\tEndGlobalSection");
}
content.AppendLine("EndGlobal");
return content;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Mono.Addins;
using Nini.Config;
using System;
using System.Collections.Generic;
using System.Reflection;
using OpenSim.Framework;
using OpenSim.Server.Base;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using OpenSim.Services.Connectors;
using OpenSim.Services.Connectors.SimianGrid;
using OpenMetaverse;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "HGInventoryBroker")]
public class HGInventoryBroker : ISharedRegionModule, IInventoryService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private static bool m_Enabled = false;
private static IInventoryService m_LocalGridInventoryService;
private Dictionary<string, IInventoryService> m_connectors = new Dictionary<string, IInventoryService>();
// A cache of userIDs --> ServiceURLs, for HGBroker only
protected Dictionary<UUID, string> m_InventoryURLs = new Dictionary<UUID,string>();
private List<Scene> m_Scenes = new List<Scene>();
private InventoryCache m_Cache = new InventoryCache();
/// <summary>
/// Used to serialize inventory requests.
/// </summary>
private object m_Lock = new object();
protected IUserManagement m_UserManagement;
protected IUserManagement UserManagementModule
{
get
{
if (m_UserManagement == null)
{
m_UserManagement = m_Scenes[0].RequestModuleInterface<IUserManagement>();
if (m_UserManagement == null)
m_log.ErrorFormat(
"[HG INVENTORY CONNECTOR]: Could not retrieve IUserManagement module from {0}",
m_Scenes[0].RegionInfo.RegionName);
}
return m_UserManagement;
}
}
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "HGInventoryBroker"; }
}
public void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("InventoryServices", "");
if (name == Name)
{
IConfig inventoryConfig = source.Configs["InventoryService"];
if (inventoryConfig == null)
{
m_log.Error("[HG INVENTORY CONNECTOR]: InventoryService missing from OpenSim.ini");
return;
}
string localDll = inventoryConfig.GetString("LocalGridInventoryService",
String.Empty);
//string HGDll = inventoryConfig.GetString("HypergridInventoryService",
// String.Empty);
if (localDll == String.Empty)
{
m_log.Error("[HG INVENTORY CONNECTOR]: No LocalGridInventoryService named in section InventoryService");
//return;
throw new Exception("Unable to proceed. Please make sure your ini files in config-include are updated according to .example's");
}
Object[] args = new Object[] { source };
m_LocalGridInventoryService =
ServerUtils.LoadPlugin<IInventoryService>(localDll,
args);
if (m_LocalGridInventoryService == null)
{
m_log.Error("[HG INVENTORY CONNECTOR]: Can't load local inventory service");
return;
}
m_Enabled = true;
m_log.InfoFormat("[HG INVENTORY CONNECTOR]: HG inventory broker enabled with inner connector of type {0}", m_LocalGridInventoryService.GetType());
}
}
}
public void PostInitialise()
{
}
public void Close()
{
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
m_Scenes.Add(scene);
scene.RegisterModuleInterface<IInventoryService>(this);
if (m_Scenes.Count == 1)
{
// FIXME: The local connector needs the scene to extract the UserManager. However, it's not enabled so
// we can't just add the region. But this approach is super-messy.
if (m_LocalGridInventoryService is RemoteXInventoryServicesConnector)
{
m_log.DebugFormat(
"[HG INVENTORY BROKER]: Manually setting scene in RemoteXInventoryServicesConnector to {0}",
scene.RegionInfo.RegionName);
((RemoteXInventoryServicesConnector)m_LocalGridInventoryService).Scene = scene;
}
else if (m_LocalGridInventoryService is LocalInventoryServicesConnector)
{
m_log.DebugFormat(
"[HG INVENTORY BROKER]: Manually setting scene in LocalInventoryServicesConnector to {0}",
scene.RegionInfo.RegionName);
((LocalInventoryServicesConnector)m_LocalGridInventoryService).Scene = scene;
}
scene.EventManager.OnClientClosed += OnClientClosed;
}
}
public void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
m_Scenes.Remove(scene);
}
public void RegionLoaded(Scene scene)
{
if (!m_Enabled)
return;
m_log.InfoFormat("[HG INVENTORY CONNECTOR]: Enabled HG inventory for region {0}", scene.RegionInfo.RegionName);
}
#region URL Cache
void OnClientClosed(UUID clientID, Scene scene)
{
if (m_InventoryURLs.ContainsKey(clientID)) // if it's in cache
{
ScenePresence sp = null;
foreach (Scene s in m_Scenes)
{
s.TryGetScenePresence(clientID, out sp);
if ((sp != null) && !sp.IsChildAgent && (s != scene))
{
m_log.DebugFormat("[INVENTORY CACHE]: OnClientClosed in {0}, but user {1} still in sim. Keeping inventoryURL in cache",
scene.RegionInfo.RegionName, clientID);
return;
}
}
DropInventoryServiceURL(clientID);
}
}
/// <summary>
/// Gets the user's inventory URL from its serviceURLs, if the user is foreign,
/// and sticks it in the cache
/// </summary>
/// <param name="userID"></param>
private void CacheInventoryServiceURL(UUID userID)
{
if (UserManagementModule != null && !UserManagementModule.IsLocalGridUser(userID))
{
// The user is not local; let's cache its service URL
string inventoryURL = string.Empty;
ScenePresence sp = null;
foreach (Scene scene in m_Scenes)
{
scene.TryGetScenePresence(userID, out sp);
if (sp != null)
{
AgentCircuitData aCircuit = scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
if (aCircuit == null)
return;
if (aCircuit.ServiceURLs == null)
return;
if (aCircuit.ServiceURLs.ContainsKey("InventoryServerURI"))
{
inventoryURL = aCircuit.ServiceURLs["InventoryServerURI"].ToString();
if (inventoryURL != null && inventoryURL != string.Empty)
{
inventoryURL = inventoryURL.Trim(new char[] { '/' });
m_InventoryURLs[userID] = inventoryURL;
m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Added {0} to the cache of inventory URLs", inventoryURL);
return;
}
}
// else
// {
// m_log.DebugFormat("[HG INVENTORY CONNECTOR]: User {0} does not have InventoryServerURI. OH NOES!", userID);
// return;
// }
}
}
if (sp == null)
{
inventoryURL = UserManagementModule.GetUserServerURL(userID, "InventoryServerURI");
if (!string.IsNullOrEmpty(inventoryURL))
{
inventoryURL = inventoryURL.Trim(new char[] { '/' });
m_InventoryURLs.Add(userID, inventoryURL);
m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Added {0} to the cache of inventory URLs", inventoryURL);
}
}
}
}
private void DropInventoryServiceURL(UUID userID)
{
lock (m_InventoryURLs)
if (m_InventoryURLs.ContainsKey(userID))
{
string url = m_InventoryURLs[userID];
m_InventoryURLs.Remove(userID);
m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Removed {0} from the cache of inventory URLs", url);
}
}
public string GetInventoryServiceURL(UUID userID)
{
if (m_InventoryURLs.ContainsKey(userID))
return m_InventoryURLs[userID];
CacheInventoryServiceURL(userID);
if (m_InventoryURLs.ContainsKey(userID))
return m_InventoryURLs[userID];
return null; //it means that the methods should forward to local grid's inventory
}
#endregion
#region IInventoryService
public bool CreateUserInventory(UUID userID)
{
lock (m_Lock)
return m_LocalGridInventoryService.CreateUserInventory(userID);
}
public List<InventoryFolderBase> GetInventorySkeleton(UUID userID)
{
string invURL = GetInventoryServiceURL(userID);
if (invURL == null) // not there, forward to local inventory connector to resolve
lock (m_Lock)
return m_LocalGridInventoryService.GetInventorySkeleton(userID);
IInventoryService connector = GetConnector(invURL);
return connector.GetInventorySkeleton(userID);
}
public InventoryFolderBase GetRootFolder(UUID userID)
{
//m_log.DebugFormat("[HG INVENTORY CONNECTOR]: GetRootFolder for {0}", userID);
InventoryFolderBase root = m_Cache.GetRootFolder(userID);
if (root != null)
return root;
string invURL = GetInventoryServiceURL(userID);
if (invURL == null) // not there, forward to local inventory connector to resolve
lock (m_Lock)
return m_LocalGridInventoryService.GetRootFolder(userID);
IInventoryService connector = GetConnector(invURL);
root = connector.GetRootFolder(userID);
m_Cache.Cache(userID, root);
return root;
}
public InventoryFolderBase GetFolderForType(UUID userID, FolderType type)
{
//m_log.DebugFormat("[HG INVENTORY CONNECTOR]: GetFolderForType {0} type {1}", userID, type);
InventoryFolderBase f = m_Cache.GetFolderForType(userID, type);
if (f != null)
return f;
string invURL = GetInventoryServiceURL(userID);
if (invURL == null) // not there, forward to local inventory connector to resolve
lock (m_Lock)
return m_LocalGridInventoryService.GetFolderForType(userID, type);
IInventoryService connector = GetConnector(invURL);
f = connector.GetFolderForType(userID, type);
m_Cache.Cache(userID, type, f);
return f;
}
public InventoryCollection GetFolderContent(UUID userID, UUID folderID)
{
//m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolderContent " + folderID);
string invURL = GetInventoryServiceURL(userID);
if (invURL == null) // not there, forward to local inventory connector to resolve
lock (m_Lock)
return m_LocalGridInventoryService.GetFolderContent(userID, folderID);
InventoryCollection c = m_Cache.GetFolderContent(userID, folderID);
if (c != null)
{
m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolderContent found content in cache " + folderID);
return c;
}
IInventoryService connector = GetConnector(invURL);
return connector.GetFolderContent(userID, folderID);
}
public InventoryCollection[] GetMultipleFoldersContent(UUID userID, UUID[] folderIDs)
{
string invURL = GetInventoryServiceURL(userID);
if (invURL == null) // not there, forward to local inventory connector to resolve
lock (m_Lock)
return m_LocalGridInventoryService.GetMultipleFoldersContent(userID, folderIDs);
else
{
InventoryCollection[] coll = new InventoryCollection[folderIDs.Length];
int i = 0;
foreach (UUID fid in folderIDs)
coll[i++] = GetFolderContent(userID, fid);
return coll;
}
}
public List<InventoryItemBase> GetFolderItems(UUID userID, UUID folderID)
{
//m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolderItems " + folderID);
string invURL = GetInventoryServiceURL(userID);
if (invURL == null) // not there, forward to local inventory connector to resolve
lock (m_Lock)
return m_LocalGridInventoryService.GetFolderItems(userID, folderID);
List<InventoryItemBase> items = m_Cache.GetFolderItems(userID, folderID);
if (items != null)
{
m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolderItems found items in cache " + folderID);
return items;
}
IInventoryService connector = GetConnector(invURL);
return connector.GetFolderItems(userID, folderID);
}
public bool AddFolder(InventoryFolderBase folder)
{
if (folder == null)
return false;
//m_log.Debug("[HG INVENTORY CONNECTOR]: AddFolder " + folder.ID);
string invURL = GetInventoryServiceURL(folder.Owner);
if (invURL == null) // not there, forward to local inventory connector to resolve
lock (m_Lock)
return m_LocalGridInventoryService.AddFolder(folder);
IInventoryService connector = GetConnector(invURL);
return connector.AddFolder(folder);
}
public bool UpdateFolder(InventoryFolderBase folder)
{
if (folder == null)
return false;
//m_log.Debug("[HG INVENTORY CONNECTOR]: UpdateFolder " + folder.ID);
string invURL = GetInventoryServiceURL(folder.Owner);
if (invURL == null) // not there, forward to local inventory connector to resolve
lock (m_Lock)
return m_LocalGridInventoryService.UpdateFolder(folder);
IInventoryService connector = GetConnector(invURL);
return connector.UpdateFolder(folder);
}
public bool DeleteFolders(UUID ownerID, List<UUID> folderIDs)
{
if (folderIDs == null)
return false;
if (folderIDs.Count == 0)
return false;
//m_log.Debug("[HG INVENTORY CONNECTOR]: DeleteFolders for " + ownerID);
string invURL = GetInventoryServiceURL(ownerID);
if (invURL == null) // not there, forward to local inventory connector to resolve
lock (m_Lock)
return m_LocalGridInventoryService.DeleteFolders(ownerID, folderIDs);
IInventoryService connector = GetConnector(invURL);
return connector.DeleteFolders(ownerID, folderIDs);
}
public bool MoveFolder(InventoryFolderBase folder)
{
if (folder == null)
return false;
//m_log.Debug("[HG INVENTORY CONNECTOR]: MoveFolder for " + folder.Owner);
string invURL = GetInventoryServiceURL(folder.Owner);
if (invURL == null) // not there, forward to local inventory connector to resolve
lock (m_Lock)
return m_LocalGridInventoryService.MoveFolder(folder);
IInventoryService connector = GetConnector(invURL);
return connector.MoveFolder(folder);
}
public bool PurgeFolder(InventoryFolderBase folder)
{
if (folder == null)
return false;
//m_log.Debug("[HG INVENTORY CONNECTOR]: PurgeFolder for " + folder.Owner);
string invURL = GetInventoryServiceURL(folder.Owner);
if (invURL == null) // not there, forward to local inventory connector to resolve
lock (m_Lock)
return m_LocalGridInventoryService.PurgeFolder(folder);
IInventoryService connector = GetConnector(invURL);
return connector.PurgeFolder(folder);
}
public bool AddItem(InventoryItemBase item)
{
if (item == null)
return false;
//m_log.Debug("[HG INVENTORY CONNECTOR]: AddItem " + item.ID);
string invURL = GetInventoryServiceURL(item.Owner);
if (invURL == null) // not there, forward to local inventory connector to resolve
lock (m_Lock)
return m_LocalGridInventoryService.AddItem(item);
IInventoryService connector = GetConnector(invURL);
return connector.AddItem(item);
}
public bool UpdateItem(InventoryItemBase item)
{
if (item == null)
return false;
//m_log.Debug("[HG INVENTORY CONNECTOR]: UpdateItem " + item.ID);
string invURL = GetInventoryServiceURL(item.Owner);
if (invURL == null) // not there, forward to local inventory connector to resolve
lock (m_Lock)
return m_LocalGridInventoryService.UpdateItem(item);
IInventoryService connector = GetConnector(invURL);
return connector.UpdateItem(item);
}
public bool MoveItems(UUID ownerID, List<InventoryItemBase> items)
{
if (items == null)
return false;
if (items.Count == 0)
return true;
//m_log.Debug("[HG INVENTORY CONNECTOR]: MoveItems for " + ownerID);
string invURL = GetInventoryServiceURL(ownerID);
if (invURL == null) // not there, forward to local inventory connector to resolve
lock (m_Lock)
return m_LocalGridInventoryService.MoveItems(ownerID, items);
IInventoryService connector = GetConnector(invURL);
return connector.MoveItems(ownerID, items);
}
public bool DeleteItems(UUID ownerID, List<UUID> itemIDs)
{
//m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Delete {0} items for user {1}", itemIDs.Count, ownerID);
if (itemIDs == null)
return false;
if (itemIDs.Count == 0)
return true;
string invURL = GetInventoryServiceURL(ownerID);
if (invURL == null) // not there, forward to local inventory connector to resolve
lock (m_Lock)
return m_LocalGridInventoryService.DeleteItems(ownerID, itemIDs);
IInventoryService connector = GetConnector(invURL);
return connector.DeleteItems(ownerID, itemIDs);
}
public InventoryItemBase GetItem(InventoryItemBase item)
{
if (item == null)
return null;
//m_log.Debug("[HG INVENTORY CONNECTOR]: GetItem " + item.ID);
string invURL = GetInventoryServiceURL(item.Owner);
if (invURL == null) // not there, forward to local inventory connector to resolve
lock (m_Lock)
return m_LocalGridInventoryService.GetItem(item);
IInventoryService connector = GetConnector(invURL);
return connector.GetItem(item);
}
public InventoryItemBase[] GetMultipleItems(UUID userID, UUID[] itemIDs)
{
if (itemIDs == null)
return new InventoryItemBase[0];
//m_log.Debug("[HG INVENTORY CONNECTOR]: GetItem " + item.ID);
string invURL = GetInventoryServiceURL(userID);
if (invURL == null) // not there, forward to local inventory connector to resolve
lock (m_Lock)
return m_LocalGridInventoryService.GetMultipleItems(userID, itemIDs);
IInventoryService connector = GetConnector(invURL);
return connector.GetMultipleItems(userID, itemIDs);
}
public InventoryFolderBase GetFolder(InventoryFolderBase folder)
{
if (folder == null)
return null;
//m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolder " + folder.ID);
string invURL = GetInventoryServiceURL(folder.Owner);
if (invURL == null) // not there, forward to local inventory connector to resolve
lock (m_Lock)
return m_LocalGridInventoryService.GetFolder(folder);
IInventoryService connector = GetConnector(invURL);
return connector.GetFolder(folder);
}
public bool HasInventoryForUser(UUID userID)
{
return false;
}
public List<InventoryItemBase> GetActiveGestures(UUID userId)
{
return new List<InventoryItemBase>();
}
public int GetAssetPermissions(UUID userID, UUID assetID)
{
//m_log.Debug("[HG INVENTORY CONNECTOR]: GetAssetPermissions " + assetID);
string invURL = GetInventoryServiceURL(userID);
if (invURL == null) // not there, forward to local inventory connector to resolve
lock (m_Lock)
return m_LocalGridInventoryService.GetAssetPermissions(userID, assetID);
IInventoryService connector = GetConnector(invURL);
return connector.GetAssetPermissions(userID, assetID);
}
#endregion
private IInventoryService GetConnector(string url)
{
IInventoryService connector = null;
lock (m_connectors)
{
if (m_connectors.ContainsKey(url))
{
connector = m_connectors[url];
}
else
{
// Still not as flexible as I would like this to be,
// but good enough for now
string connectorType = new HeloServicesConnector(url).Helo();
m_log.DebugFormat("[HG INVENTORY SERVICE]: HELO returned {0}", connectorType);
if (connectorType == "opensim-simian")
{
connector = new SimianInventoryServiceConnector(url);
}
else
{
RemoteXInventoryServicesConnector rxisc = new RemoteXInventoryServicesConnector(url);
rxisc.Scene = m_Scenes[0];
connector = rxisc;
}
m_connectors.Add(url, connector);
}
}
return connector;
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////#define ENABLE_CROSS_APPDOMAIN
#define ENABLE_CROSS_APPDOMAIN
namespace System.Globalization
{
using System;
using System.Threading;
using System.Collections;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Resources;
[Clarity.ExportStub("System_Globalization_CultureInfo.cpp")]
public class CultureInfo /*: ICloneable , IFormatProvider*/ {
internal NumberFormatInfo numInfo = null;
internal DateTimeFormatInfo dateTimeInfo = null;
internal string m_name = null;
internal ResourceManager m_rm;
[NonSerialized]
private CultureInfo m_parent;
const string c_ResourceBase = "System.Globalization.Resources.CultureInfo";
internal string EnsureStringResource(ref string str, System.Globalization.Resources.CultureInfo.StringResources id)
{
if (str == null)
{
str = (string)ResourceManager.GetObject(m_rm, id);
}
return str;
}
internal string[] EnsureStringArrayResource(ref string[] strArray, System.Globalization.Resources.CultureInfo.StringResources id)
{
if (strArray == null)
{
string str = (string)ResourceManager.GetObject(m_rm, id);
strArray = str.Split('|');
}
return (string[])strArray.Clone();
}
public CultureInfo(string name)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
m_rm = new ResourceManager(c_ResourceBase, typeof(CultureInfo).Assembly, name, true);
m_name = m_rm.m_cultureName;
}
internal CultureInfo(ResourceManager resourceManager)
{
m_rm = resourceManager;
m_name = resourceManager.m_cultureName;
}
public static CultureInfo CurrentUICulture
{
get
{
//only one system-wide culture. We do not currently support per-thread cultures
CultureInfo culture = CurrentUICultureInternal;
if (culture == null)
{
culture = new CultureInfo("");
CurrentUICultureInternal = culture;
}
return culture;
}
}
private extern static CultureInfo CurrentUICultureInternal
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
[MethodImplAttribute(MethodImplOptions.InternalCall)]
set;
}
public virtual CultureInfo Parent
{
get
{
if (m_parent == null)
{
if (m_name == "") //Invariant culture
{
m_parent = this;
}
else
{
string parentName = m_name;
int iDash = m_name.LastIndexOf('-');
if (iDash >= 0)
{
parentName = parentName.Substring(0, iDash);
}
else
{
parentName = "";
}
m_parent = new CultureInfo(parentName);
}
}
return m_parent;
}
}
public static CultureInfo[] GetCultures(CultureTypes types)
{
ArrayList listCultures = new ArrayList();
//Look for all assemblies/satellite assemblies
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
for (int iAssembly = 0; iAssembly < assemblies.Length; iAssembly++)
{
Assembly assembly = assemblies[iAssembly];
string mscorlib = "mscorlib";
string fullName = assembly.FullName;
// consider adding startswith ?
if ((mscorlib.Length <= fullName.Length) && (fullName.Substring(0, mscorlib.Length) == mscorlib))
{
string[] resources = assembly.GetManifestResourceNames();
for (int iResource = 0; iResource < resources.Length; iResource++)
{
string resource = resources[iResource];
string ciResource = c_ResourceBase;
if (ciResource.Length < resource.Length && resource.Substring(0, ciResource.Length) == ciResource)
{
//System.Globalization.Resources.CultureInfo.<culture>.tinyresources
string cultureName = resource.Substring(ciResource.Length, resource.Length - ciResource.Length - System.Resources.ResourceManager.s_fileExtension.Length);
// remove the leading "."
if (cultureName != "")
{
cultureName = cultureName.Substring(1, cultureName.Length - 1);
}
// if GetManifestResourceNames() changes, we need to change this code to ensure the index is the same.
listCultures.Add(new CultureInfo(new ResourceManager(c_ResourceBase, cultureName, iResource, typeof(CultureInfo).Assembly, assembly)));
}
}
}
}
CultureInfo[] result = new CultureInfo[listCultures.Count];
listCultures.CopyTo(result);
return result;
}
public virtual String Name
{
get
{
return m_name;
}
}
public override String ToString()
{
return m_name;
}
// public virtual Object GetFormat(Type formatType) {
// if (formatType == typeof(NumberFormatInfo)) {
// return (NumberFormat);
// }
// if (formatType == typeof(DateTimeFormatInfo)) {
// return (DateTimeFormat);
// }
// return (null);
// }
// internal static void CheckNeutral(CultureInfo culture) {
// if (culture.IsNeutralCulture) {
// BCLDebug.Assert(culture.m_name != null, "[CultureInfo.CheckNeutral]Always expect m_name to be set");
// throw new NotSupportedException(
// Environment.GetResourceString("Argument_CultureInvalidFormat",
// culture.m_name));
// }
// }
// [System.Runtime.InteropServices.ComVisible(false)]
// public CultureTypes CultureTypes
// {
// get
// {
// CultureTypes types = 0;
// if (m_cultureTableRecord.IsNeutralCulture)
// types |= CultureTypes.NeutralCultures;
// else
// types |= CultureTypes.SpecificCultures;
// if (m_cultureTableRecord.IsSynthetic)
// types |= CultureTypes.WindowsOnlyCultures | CultureTypes.InstalledWin32Cultures; // Synthetic is installed culture too.
// else
// {
// // Not Synthetic
// if (CultureTable.IsInstalledLCID(cultureID))
// types |= CultureTypes.InstalledWin32Cultures;
// if (!m_cultureTableRecord.IsCustomCulture || m_cultureTableRecord.IsReplacementCulture)
// types |= CultureTypes.FrameworkCultures;
// }
// if (m_cultureTableRecord.IsCustomCulture)
// {
// types |= CultureTypes.UserCustomCulture;
// if (m_cultureTableRecord.IsReplacementCulture)
// types |= CultureTypes.ReplacementCultures;
// }
// return types;
// }
// }
public virtual NumberFormatInfo NumberFormat {
get {
if(numInfo == null)
{
numInfo = new NumberFormatInfo(this);
}
return numInfo;
}
}
public virtual DateTimeFormatInfo DateTimeFormat
{
get
{
if (dateTimeInfo == null)
{
dateTimeInfo = new DateTimeFormatInfo(this);
}
return dateTimeInfo;
}
}
}
}
| |
/*******************************************************************************
* Copyright 2008-2012, Cypress Semiconductor Corporation. All rights reserved.
* You may use this file only in accordance with the license, terms, conditions,
* disclaimers, and limitations in the end user license agreement accompanying
* the software package with which this file was provided.
********************************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Diagnostics;
namespace CRC_UART_v0_1
{
public partial class CyCRCControl : UserControl
{
private enum CyPolynomEditModes
{
NONE, STANDARD, N, CELL, POLYNOMIAL
};
#region Fields, Properties
public CyCRCParameters m_parameters;
private bool[] m_checkedCells = new bool[64];
private ArrayList[] m_standartPolynomials = new ArrayList[22];
private Bitmap m_polynomBmp;
private CyPolynomEditModes m_editmode = CyPolynomEditModes.NONE;
private int m_n;
private DataGridViewCellStyle m_checkedCellsStyle;
public int N
{
get { return m_n; }
set
{
if ((value <= 64) && (value > 0))
{
m_n = value;
m_parameters.Resolution = m_n;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < dataGridCheck.ColumnCount; j++)
{
if (i * dataGridCheck.ColumnCount + j < N)
{
dataGridCheck[j, i].Value = N - (i * dataGridCheck.ColumnCount + j);
}
else
{
dataGridCheck[j, i].Value = string.Empty;
}
dataGridCheck[j, i].Style = dataGridCheck.DefaultCellStyle;
dataGridCheck[j, i].Style.SelectionBackColor = Color.White;
dataGridCheck[j, i].Style.SelectionForeColor = Color.Black;
m_checkedCells[i * dataGridCheck.ColumnCount + j] = false;
}
}
DrawPolynomBmp();
pictureBoxPolynom.Height = (m_n / 16 + 1) * 22;
groupBoxPolynom.Height = pictureBoxPolynom.Top + pictureBoxPolynom.Height + 3;
pictureBoxPolynom.Invalidate();
string seed = "0";
if (m_parameters.SeedValue.ToString("x").Length <= (N - 1) / 4 + 1)
{
seed = m_parameters.SeedValue.ToString("X");
}
else
{
m_parameters.SeedValue = 0;
}
for (int i = seed.Length; i < (N - 1) / 4 + 1; i++)
{
seed = "0" + seed;
}
textBoxSeed.Text = seed;
}
}
}
#endregion Fields, Properties
#region Constructors
public CyCRCControl()
{
InitializeComponent();
InitStandartPolynomials();
InitDataGrid();
InitBmp();
m_parameters = new CyCRCParameters();
}
public CyCRCControl(CyCRCParameters parameters)
{
InitializeComponent();
InitStandartPolynomials();
InitDataGrid();
InitBmp();
this.m_parameters = parameters;
UpdateControls();
}
#endregion Constructors
public void UpdateControls()
{
try
{
if (m_editmode == CyPolynomEditModes.NONE) m_editmode = CyPolynomEditModes.STANDARD;
textBoxSeed.Text = m_parameters.SeedValue.ToString("X");
comboBoxStandard.Text = m_parameters.PolyName;
if ((m_parameters.PolyValue > 0) && (comboBoxStandard.SelectedIndex < 1))
{
m_editmode = CyPolynomEditModes.POLYNOMIAL;
textBoxResult.Text = m_parameters.PolyValue.ToString("X");
textBoxResult_Validated(textBoxResult, EventArgs.Empty);
}
m_editmode = CyPolynomEditModes.NONE;
}
catch
{
MessageBox.Show(Properties.Resources.MSG_PARAMETER_INITIALIZATION, "Error", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
public UInt64 GetMaxSeedValue()
{
ulong maxSeed = (((ulong)1 << m_parameters.Resolution) - 1);
if (m_parameters.Resolution == 64)
maxSeed = UInt64.MaxValue;
return maxSeed;
}
#region Private functions
private void InitDataGrid()
{
m_checkedCellsStyle = new DataGridViewCellStyle();
m_checkedCellsStyle.BackColor = Color.SkyBlue;
dataGridCheck.Rows.Clear();
for (int i = 0; i < 4; i++)
{
dataGridCheck.Rows.Add();
}
}
private void InitStandartPolynomials()
{
for (int i = 0; i < m_standartPolynomials.Length; i++)
{
m_standartPolynomials[i] = new ArrayList();
}
//CRC-1
m_standartPolynomials[0].Add(1);
m_standartPolynomials[0].Add("Parity");
//CRC-4-ITU
m_standartPolynomials[1].Add(4);
m_standartPolynomials[1].Add(1);
m_standartPolynomials[1].Add("ITU G.704");
//CRC-5-ITU
m_standartPolynomials[2].Add(5);
m_standartPolynomials[2].Add(4);
m_standartPolynomials[2].Add(2);
m_standartPolynomials[2].Add("ITU G.704");
//CRC-5-USB
m_standartPolynomials[3].Add(5);
m_standartPolynomials[3].Add(2);
m_standartPolynomials[3].Add("USB");
//CRC-6-ITU
m_standartPolynomials[4].Add(6);
m_standartPolynomials[4].Add(1);
m_standartPolynomials[4].Add("ITU G.704");
//CRC-7
m_standartPolynomials[5].Add(7);
m_standartPolynomials[5].Add(3);
m_standartPolynomials[5].Add("Telecom systems, MMC");
//CRC-8-ATM
m_standartPolynomials[6].Add(8);
m_standartPolynomials[6].Add(2);
m_standartPolynomials[6].Add(1);
m_standartPolynomials[6].Add("ATM HEC");
//CRC-8-CCITT
m_standartPolynomials[7].Add(8);
m_standartPolynomials[7].Add(7);
m_standartPolynomials[7].Add(3);
m_standartPolynomials[7].Add(2);
m_standartPolynomials[7].Add("1-Wire bus");
//CRC-8-Maxim
m_standartPolynomials[8].Add(8);
m_standartPolynomials[8].Add(5);
m_standartPolynomials[8].Add(4);
m_standartPolynomials[8].Add("1-Wire bus");
//CRC-8
m_standartPolynomials[9].Add(8);
m_standartPolynomials[9].Add(7);
m_standartPolynomials[9].Add(6);
m_standartPolynomials[9].Add(4);
m_standartPolynomials[9].Add(2);
m_standartPolynomials[9].Add("General");
//CRC-8-SAE
m_standartPolynomials[10].Add(8);
m_standartPolynomials[10].Add(4);
m_standartPolynomials[10].Add(3);
m_standartPolynomials[10].Add(2);
m_standartPolynomials[10].Add("SAE J1850");
//CRC-10
m_standartPolynomials[11].Add(10);
m_standartPolynomials[11].Add(9);
m_standartPolynomials[11].Add(5);
m_standartPolynomials[11].Add(4);
m_standartPolynomials[11].Add(1);
m_standartPolynomials[11].Add("General");
//CRC-12
m_standartPolynomials[12].Add(12);
m_standartPolynomials[12].Add(11);
m_standartPolynomials[12].Add(3);
m_standartPolynomials[12].Add(2);
m_standartPolynomials[12].Add(1);
m_standartPolynomials[12].Add("Telecom systems");
//CRC-15-CAN
m_standartPolynomials[13].Add(15);
m_standartPolynomials[13].Add(14);
m_standartPolynomials[13].Add(10);
m_standartPolynomials[13].Add(8);
m_standartPolynomials[13].Add(7);
m_standartPolynomials[13].Add(4);
m_standartPolynomials[13].Add(3);
m_standartPolynomials[13].Add("CAN");
//CRC-16-CCITT
m_standartPolynomials[14].Add(16);
m_standartPolynomials[14].Add(12);
m_standartPolynomials[14].Add(5);
m_standartPolynomials[14].Add("XMODEM,X.25, V.41, Bluetooth, PPP, IrDA, CRC-CCITT");
//CRC-16
m_standartPolynomials[15].Add(16);
m_standartPolynomials[15].Add(15);
m_standartPolynomials[15].Add(2);
m_standartPolynomials[15].Add("USB");
//CRC-24-Radix64
m_standartPolynomials[16].Add(24);
m_standartPolynomials[16].Add(23);
m_standartPolynomials[16].Add(18);
m_standartPolynomials[16].Add(17);
m_standartPolynomials[16].Add(14);
m_standartPolynomials[16].Add(11);
m_standartPolynomials[16].Add(10);
m_standartPolynomials[16].Add(7);
m_standartPolynomials[16].Add(6);
m_standartPolynomials[16].Add(5);
m_standartPolynomials[16].Add(4);
m_standartPolynomials[16].Add(3);
m_standartPolynomials[16].Add(1);
m_standartPolynomials[16].Add("General");
//CRC-32-IEEE802.3
m_standartPolynomials[17].Add(32);
m_standartPolynomials[17].Add(26);
m_standartPolynomials[17].Add(23);
m_standartPolynomials[17].Add(22);
m_standartPolynomials[17].Add(16);
m_standartPolynomials[17].Add(12);
m_standartPolynomials[17].Add(11);
m_standartPolynomials[17].Add(10);
m_standartPolynomials[17].Add(8);
m_standartPolynomials[17].Add(7);
m_standartPolynomials[17].Add(5);
m_standartPolynomials[17].Add(4);
m_standartPolynomials[17].Add(2);
m_standartPolynomials[17].Add(1);
m_standartPolynomials[17].Add("Ethernet, MPEG2");
//CRC-32C
m_standartPolynomials[18].Add(32);
m_standartPolynomials[18].Add(28);
m_standartPolynomials[18].Add(27);
m_standartPolynomials[18].Add(26);
m_standartPolynomials[18].Add(25);
m_standartPolynomials[18].Add(23);
m_standartPolynomials[18].Add(22);
m_standartPolynomials[18].Add(20);
m_standartPolynomials[18].Add(19);
m_standartPolynomials[18].Add(18);
m_standartPolynomials[18].Add(14);
m_standartPolynomials[18].Add(13);
m_standartPolynomials[18].Add(11);
m_standartPolynomials[18].Add(10);
m_standartPolynomials[18].Add(9);
m_standartPolynomials[18].Add(8);
m_standartPolynomials[18].Add(6);
m_standartPolynomials[18].Add("General");
//CRC-32K
m_standartPolynomials[19].Add(32);
m_standartPolynomials[19].Add(30);
m_standartPolynomials[19].Add(29);
m_standartPolynomials[19].Add(28);
m_standartPolynomials[19].Add(26);
m_standartPolynomials[19].Add(20);
m_standartPolynomials[19].Add(19);
m_standartPolynomials[19].Add(17);
m_standartPolynomials[19].Add(16);
m_standartPolynomials[19].Add(15);
m_standartPolynomials[19].Add(11);
m_standartPolynomials[19].Add(10);
m_standartPolynomials[19].Add(7);
m_standartPolynomials[19].Add(6);
m_standartPolynomials[19].Add(4);
m_standartPolynomials[19].Add(2);
m_standartPolynomials[19].Add(1);
m_standartPolynomials[19].Add("General");
//CRC-64-ISO
m_standartPolynomials[20].Add(64);
m_standartPolynomials[20].Add(4);
m_standartPolynomials[20].Add(3);
m_standartPolynomials[20].Add(1);
m_standartPolynomials[20].Add("ISO 3309");
//CRC-64-ECMA
m_standartPolynomials[21].Add(64);
m_standartPolynomials[21].Add(62);
m_standartPolynomials[21].Add(57);
m_standartPolynomials[21].Add(55);
m_standartPolynomials[21].Add(54);
m_standartPolynomials[21].Add(53);
m_standartPolynomials[21].Add(52);
m_standartPolynomials[21].Add(47);
m_standartPolynomials[21].Add(46);
m_standartPolynomials[21].Add(45);
m_standartPolynomials[21].Add(40);
m_standartPolynomials[21].Add(39);
m_standartPolynomials[21].Add(38);
m_standartPolynomials[21].Add(37);
m_standartPolynomials[21].Add(35);
m_standartPolynomials[21].Add(33);
m_standartPolynomials[21].Add(32);
m_standartPolynomials[21].Add(31);
m_standartPolynomials[21].Add(29);
m_standartPolynomials[21].Add(27);
m_standartPolynomials[21].Add(24);
m_standartPolynomials[21].Add(23);
m_standartPolynomials[21].Add(22);
m_standartPolynomials[21].Add(21);
m_standartPolynomials[21].Add(19);
m_standartPolynomials[21].Add(17);
m_standartPolynomials[21].Add(13);
m_standartPolynomials[21].Add(12);
m_standartPolynomials[21].Add(10);
m_standartPolynomials[21].Add(9);
m_standartPolynomials[21].Add(7);
m_standartPolynomials[21].Add(4);
m_standartPolynomials[21].Add(1);
m_standartPolynomials[21].Add("ECMA-182");
}
private UInt64 CalcPolynomial()
{
UInt64 result = 0;
for (int i = N; i > 0; i--)
{
if (m_checkedCells[i - 1])
{
result += Convert.ToUInt64(Math.Pow(2, i - 1));
}
}
m_parameters.PolyValue = result;
string PolyTextHexValue = result.ToString("x");
for (int i = PolyTextHexValue.Length; i < (N - 1) / 4 + 1; i++)
{
PolyTextHexValue = "0" + PolyTextHexValue;
}
textBoxResult.Text = PolyTextHexValue.ToUpper();
return result;
}
private void DrawPolynomBmp()
{
Graphics g = Graphics.FromImage(m_polynomBmp);
int space = m_polynomBmp.Width / 16;//28
int spaceVert = 22;
Point initPos = new Point(5, 3);
Font xFont = new Font("Arial", 10, FontStyle.Bold);
Font degreeFont = new Font("Arial", 7);
StringBuilder str = new StringBuilder();
int realCount = 0;
for (int i = 0; i < N; i++)
{
if (m_checkedCells[i])
{
str.Append("X + ");
}
}
str.Append("1");
g.Clear(Color.White);
SizeF xSize = g.MeasureString("X", xFont);
for (int i = N - 1; i >= 0; i--)
{
if (m_checkedCells[i])
{
g.DrawString("X", xFont, new SolidBrush(Color.Black), space * (realCount % 16), initPos.Y +
spaceVert * (realCount / 16));
g.DrawString("+", xFont, new SolidBrush(Color.Black), space * (realCount % 16) + space * 2 / 3,
initPos.Y + spaceVert * (realCount / 16));
g.DrawString((i + 1).ToString(), degreeFont, new SolidBrush(Color.Black), space * (realCount % 16) +
(int)xSize.Width * 3 / 4, spaceVert * (realCount / 16));
realCount++;
}
}
g.DrawString("1", xFont, new SolidBrush(Color.Black), space * (realCount % 16), initPos.Y +
spaceVert * (realCount / 16));
}
private void InitBmp()
{
pictureBoxPolynom.Image = null;
m_polynomBmp = new Bitmap(pictureBoxPolynom.Width, 120); //450
Graphics g = Graphics.FromImage(m_polynomBmp);
g.Clear(Color.Gray);
pictureBoxPolynom.Image = m_polynomBmp;
}
private void CellClick(int RowIndex, int ColumnIndex)
{
if (RowIndex * dataGridCheck.ColumnCount + ColumnIndex >= N)
{
return;
}
if (!m_checkedCells[N - (RowIndex * dataGridCheck.ColumnCount + ColumnIndex) - 1])
{
dataGridCheck[ColumnIndex, RowIndex].Style = m_checkedCellsStyle;
m_checkedCells[N - (RowIndex * dataGridCheck.ColumnCount + ColumnIndex) - 1] = true;
}
else
{
dataGridCheck[ColumnIndex, RowIndex].Style = dataGridCheck.DefaultCellStyle;
m_checkedCells[N - (RowIndex * dataGridCheck.ColumnCount + ColumnIndex) - 1] = false;
}
if (m_editmode == CyPolynomEditModes.CELL)
{
CalcPolynomial();
}
DrawPolynomBmp();
pictureBoxPolynom.Invalidate();
}
#endregion Private functions
#region Events
private void comboBoxStandard_SelectedIndexChanged(object sender, EventArgs e)
{
if (m_editmode == CyPolynomEditModes.NONE) m_editmode = CyPolynomEditModes.STANDARD;
if (comboBoxStandard.SelectedIndex > 0)
{
int length = m_standartPolynomials[comboBoxStandard.SelectedIndex - 1].Count - 1;
textBoxN.Text = m_standartPolynomials[comboBoxStandard.SelectedIndex - 1][0].ToString();
toolTipDescription.SetToolTip(comboBoxStandard, "Use: " +
(string)(m_standartPolynomials[comboBoxStandard.SelectedIndex - 1][length]));
N = (int)m_standartPolynomials[comboBoxStandard.SelectedIndex - 1][0];
int deg = 0;
for (int i = 0; i < length; i++)
{
deg = (int)(m_standartPolynomials[comboBoxStandard.SelectedIndex - 1][i]);
CellClick((N - deg) / dataGridCheck.ColumnCount, (N - deg) % dataGridCheck.ColumnCount);
}
CalcPolynomial();
}
else
{
toolTipDescription.SetToolTip(comboBoxStandard, "");
}
m_parameters.PolyName = comboBoxStandard.Text;
if (m_editmode == CyPolynomEditModes.STANDARD) m_editmode = CyPolynomEditModes.NONE;
}
#region dataGridCheck
private void dataGridCheck_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex * dataGridCheck.ColumnCount + e.ColumnIndex >= N)
{
return;
}
m_editmode = CyPolynomEditModes.CELL;
comboBoxStandard.SelectedIndex = 0;
CellClick(e.RowIndex, e.ColumnIndex);
m_editmode = CyPolynomEditModes.NONE;
}
private void dataGridCheck_CellEnter(object sender, DataGridViewCellEventArgs e)
{
dataGridCheck.CurrentCell.Selected = false;
}
private void dataGridCheck_CellStateChanged(object sender, DataGridViewCellStateChangedEventArgs e)
{
dataGridCheck.CurrentCell.Selected = false;
}
#endregion dataGridCheck
#region textBoxN
private void textBoxN_KeyPress(object sender, KeyPressEventArgs e)
{
comboBoxStandard.SelectedIndex = 0;
}
private void textBoxN_KeyUp(object sender, KeyEventArgs e)
{
UInt16 res;
m_editmode = CyPolynomEditModes.N;
if (UInt16.TryParse(textBoxN.Text, out res) && (N != res))
{
N = res;
if ((res > 0) && (res <= 64))
{
CellClick(0, 0);
}
CalcPolynomial();
}
else if (textBoxN.Text == "")
{
N = 0;
}
m_editmode = CyPolynomEditModes.NONE;
}
private void textBoxN_TextChanged(object sender, EventArgs e)
{
// ErrorProvider
UInt16 res;
if (UInt16.TryParse(textBoxN.Text, out res))
{
if ((res > 0) && (res <= 64))
{
errorProvider.SetError(textBoxN, string.Empty);
}
else
{
errorProvider.SetError(textBoxN, Properties.Resources.ERROR_N_RANGE);
}
}
else if (textBoxN.Text == string.Empty)
{
errorProvider.SetError(textBoxN, string.Empty);
}
else
{
errorProvider.SetError(textBoxN, Properties.Resources.ERROR_N_RANGE);
}
}
#endregion textBoxN
#region textBoxResult
private void textBoxResult_KeyPress(object sender, KeyPressEventArgs e)
{
m_editmode = CyPolynomEditModes.POLYNOMIAL;
textBox_KeyHexLengthValidation(sender, e);
}
private void textBoxResult_TextChanged(object sender, EventArgs e)
{
if (m_editmode == CyPolynomEditModes.NONE) m_editmode = CyPolynomEditModes.POLYNOMIAL;
try
{
if ((Convert.ToUInt64(textBoxResult.Text, 16) > 0) && (Convert.ToUInt64(textBoxResult.Text, 16)
<= Math.Pow(2, 64)))
{
errorProvider.SetError(textBoxResult, "");
}
else
{
errorProvider.SetError(textBoxResult, Properties.Resources.MSG_POLYNOMIAL_SHOULD_BE_GREATER_ZERO);
}
}
catch
{
errorProvider.SetError(textBoxResult, Properties.Resources.MSG_INVALID_POLYNOMIAL_VALUE);
}
}
private void textBoxResult_Validated(object sender, EventArgs e)
{
if (m_editmode == CyPolynomEditModes.POLYNOMIAL)
{
try
{
comboBoxStandard.SelectedIndex = 0;
if (textBoxResult.Text != string.Empty)
{
UInt64 polyVal = Convert.ToUInt64(textBoxResult.Text, 16);
string s = String.Empty;
if (polyVal >= ((ulong)1 << 63))
{
s = polyVal.ToString("X");
s = Convert.ToString(Convert.ToInt64(s.Substring(0, 4), 16), 2) +
Convert.ToString(Convert.ToInt64(s.Substring(4), 16), 2).PadLeft(48, '0');
}
else
{
s = Convert.ToString(Convert.ToInt64(textBoxResult.Text, 16), 2);
}
if ((s.Length <= 64) && (polyVal > 0))
{
N = s.Length;
textBoxN.Text = N.ToString();
for (int i = 0; i < N; i++)
{
if (s[i] == '1')
CellClick(i / dataGridCheck.ColumnCount, i % dataGridCheck.ColumnCount);
}
m_parameters.PolyValue = polyVal;
}
else if (polyVal == 0)
{
m_parameters.PolyValue = polyVal;
}
}
}
catch
{
}
m_editmode = CyPolynomEditModes.NONE;
}
}
#endregion textBoxResult
#region textBoxSeed
private void textBoxSeed_KeyPress(object sender, KeyPressEventArgs e)
{
textBox_KeyHexLengthValidation(sender, e);
}
private void textBoxSeed_TextChanged(object sender, EventArgs e)
{
try
{
if (Convert.ToUInt64(textBoxSeed.Text, 16) <= GetMaxSeedValue())
{
errorProvider.SetError(textBoxSeed, string.Empty);
}
else
{
errorProvider.SetError(textBoxSeed, string.Format(Properties.Resources.MSG_MAX_VALID_SEED_VALUE,
m_parameters.Resolution, GetMaxSeedValue().ToString("X")));
}
}
catch
{
errorProvider.SetError(textBoxSeed, Properties.Resources.MSG_INVALID_SEED_VALUE);
}
}
private void textBoxSeed_Validated(object sender, EventArgs e)
{
try
{
ulong newSeed = 0;
if (textBoxSeed.Text != "")
{
newSeed = Convert.ToUInt64(textBoxSeed.Text, 16);
}
m_parameters.SeedValue = newSeed;
}
catch
{
}
}
#endregion textBoxSeed
#region Common textBox validation
private void textBox_Validating(object sender, CancelEventArgs e)
{
if (errorProvider.GetError((Control)sender) != String.Empty)
e.Cancel = true;
}
private void textBox_KeyHexLengthValidation(object sender, KeyPressEventArgs e)
{
TextBox tb = (TextBox)sender;
if ((e.KeyChar != (char)Keys.Enter) && (e.KeyChar != (char)Keys.Back))
{
if (((e.KeyChar < '0') || (e.KeyChar > '9')) && ((e.KeyChar < 'A') || (e.KeyChar > 'F')) &&
((e.KeyChar < 'a') || (e.KeyChar > 'f')))
e.Handled = true;
if ((tb.Text.Length >= 16) && (tb.SelectionLength == 0))
e.Handled = true;
}
}
#endregion Common textBox validation
#endregion Events
#region Enter key processing
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Enter)
{
SendKeys.Send("{TAB}");
return true;
}
else
return base.ProcessCmdKey(ref msg, keyData);
}
#endregion Enter key processing
}
}
| |
using System.Collections.Generic;
using dotless.Core.Exceptions;
namespace dotless.Core.Test.Specs
{
using NUnit.Framework;
public class SelectorsFixture : SpecFixtureBase
{
[Test]
public void ParentSelector1()
{
var input =
@"
h1, h2, h3 {
a, p {
&:hover {
color: red;
}
}
}
";
var expected =
@"
h1 a:hover,
h2 a:hover,
h3 a:hover,
h1 p:hover,
h2 p:hover,
h3 p:hover {
color: red;
}
";
AssertLess(input, expected);
}
[Test]
public void ParentSelector2()
{
// Note: http://github.com/cloudhead/less.js/issues/issue/9
var input =
@"
a {
color: red;
&:hover { color: blue; }
div & { color: green; }
p & span { color: yellow; }
}
";
var expected =
@"
a {
color: red;
}
a:hover {
color: blue;
}
div a {
color: green;
}
p a span {
color: yellow;
}
";
AssertLess(input, expected);
}
[Test]
public void ParentSelector3()
{
// Note: http://github.com/cloudhead/less.js/issues/issue/9
var input =
@"
.foo {
.bar, .baz {
& .qux {
display: block;
}
.qux & {
display:inline;
}
}
}
";
var expected =
@"
.foo .bar .qux,
.foo .baz .qux {
display: block;
}
.qux .foo .bar,
.qux .foo .baz {
display: inline;
}
";
AssertLess(input, expected);
}
[Test]
public void ParentSelector4()
{
var input =
@"
.foo {
.bar, .baz {
.qux& {
display:inline;
}
}
}
";
var expected =
@"
.qux.foo .bar,
.qux.foo .baz {
display: inline;
}
";
AssertLess(input, expected);
}
[Test]
public void ParentSelector5()
{
//https://github.com/cloudhead/less.js/issues/774
var input =
@"
.b {
&.c {
.a& {
color: red;
}
}
}
";
var expected =
@"
.a.b.c {
color: red;
}
";
AssertLess(input, expected);
}
[Test]
public void ParentSelector6()
{
// https://github.com/cloudhead/less.js/issues/299
var input =
@"
.margin_between(@above, @below) {
* + & { margin-top: @above; }
legend + & { margin-top: 0; }
& + * { margin-top: @below; }
}
h1 { .margin_between(25px, 10px); }
h2 { .margin_between(20px, 8px); }
h3 { .margin_between(15px, 5px); }";
var expected =
@"
* + h1 {
margin-top: 25px;
}
legend + h1 {
margin-top: 0;
}
h1 + * {
margin-top: 10px;
}
* + h2 {
margin-top: 20px;
}
legend + h2 {
margin-top: 0;
}
h2 + * {
margin-top: 8px;
}
* + h3 {
margin-top: 15px;
}
legend + h3 {
margin-top: 0;
}
h3 + * {
margin-top: 5px;
}
";
AssertLess(input, expected);
}
[Test]
public void ParentSelector7()
{
// https://github.com/cloudhead/less.js/issues/749
var input =
@"
.b {
.c & {
&.a {
color: red;
}
}
}
";
var expected =
@"
.c .b.a {
color: red;
}
";
AssertLess(input, expected);
}
[Test]
public void ParentSelector8()
{
var input = @"
.p {
.foo &.bar {
color: red;
}
}
";
var expected = @"
.foo .p.bar {
color: red;
}
";
AssertLess(input, expected);
}
[Test]
public void ParentSelector9()
{
var input = @"
.p {
.foo&.bar {
color: red;
}
}
";
var expected = @"
.foo.p.bar {
color: red;
}
";
AssertLess(input, expected);
}
[Test]
public void ParentSelectorCombinators()
{
// Note: https://github.com/dotless/dotless/issues/171
var input =
@"
.foo {
.foo + & {
background: amber;
}
& + & {
background: amber;
}
}
";
var expected =
@"
.foo + .foo {
background: amber;
}
.foo + .foo {
background: amber;
}
";
AssertLess(input, expected);
}
[Test]
public void ParentSelectorMultiplied()
{
var input =
@"
.foo, .bar {
& + & {
background: amber;
}
}
";
var expected =
@"
.foo + .foo,
.foo + .bar,
.bar + .foo,
.bar + .bar {
background: amber;
}
";
AssertLess(input, expected);
}
[Test]
public void ParentSelectorMultipliedDouble()
{
var input =
@"
.foo, .bar {
a, b {
& > & {
background: amber;
}
}
}
";
var expected =
@"
.foo a > .foo a,
.foo a > .bar a,
.foo a > .foo b,
.foo a > .bar b,
.bar a > .foo a,
.bar a > .bar a,
.bar a > .foo b,
.bar a > .bar b,
.foo b > .foo a,
.foo b > .bar a,
.foo b > .foo b,
.foo b > .bar b,
.bar b > .foo a,
.bar b > .bar a,
.bar b > .foo b,
.bar b > .bar b {
background: amber;
}
";
AssertLess(input, expected);
}
[Test]
public void IdSelectors()
{
var input =
@"
#all { color: blue; }
#the { color: blue; }
#same { color: blue; }
";
var expected = @"
#all {
color: blue;
}
#the {
color: blue;
}
#same {
color: blue;
}
";
AssertLess(input, expected);
}
[Test]
public void Tag()
{
var input = @"
td {
margin: 0;
padding: 0;
}
";
var expected = @"
td {
margin: 0;
padding: 0;
}
";
AssertLess(input, expected);
}
[Test]
public void TwoTags()
{
var input = @"
td,
input {
line-height: 1em;
}
";
AssertLessUnchanged(input);
}
[Test]
public void MultipleTags()
{
var input =
@"
ul, li, div, q, blockquote, textarea {
margin: 0;
}
";
var expected = @"
ul,
li,
div,
q,
blockquote,
textarea {
margin: 0;
}
";
AssertLess(input, expected);
}
[Test]
public void DecendantSelectorWithTabs()
{
var input = "td \t input { line-height: 1em; }";
var expected = @"
td input {
line-height: 1em;
}
";
AssertLess(input, expected);
}
[Test]
public void NestedCombinedSelector()
{
var input = @"
#parentRuleSet {
.selector1.selector2 { position: fixed; }
}";
var expected = @"
#parentRuleSet .selector1.selector2 {
position: fixed;
}";
AssertLess(input, expected);
}
[Test]
public void DynamicSelectors()
{
var input = @"
@a: 2;
a:nth-child(@a) {
border: 1px;
}";
var expected = @"
a:nth-child(2) {
border: 1px;
}";
AssertLess(input, expected);
}
[Test]
public void PseudoSelectors()
{
// from less.js bug 663
var input = @"
.other ::fnord { color: red }
.other::fnord { color: red }
.other {
::bnord {color: red }
&::bnord {color: red }
}";
var expected = @"
.other ::fnord {
color: red;
}
.other::fnord {
color: red;
}
.other ::bnord {
color: red;
}
.other::bnord {
color: red;
}";
AssertLess(input, expected);
}
[Test]
public void ParentSelectorWhenNoParentExists1()
{
//comes up in bootstrap
var input = @"
.placeholder(@color) {
&:-moz-placeholder {
color: @color;
}
&:-ms-input-placeholder {
color: @color;
}
&::-webkit-input-placeholder {
color: @color;
}
}
.placeholder(red);
";
var expected = @"
:-moz-placeholder {
color: red;
}
:-ms-input-placeholder {
color: red;
}
::-webkit-input-placeholder {
color: red;
}
";
AssertLess(input, expected);
}
[Test]
public void ParentSelectorWhenNoParentExists2()
{
var input = @"
.placeholder(@color) {
.foo &.bar {
color: @color;
}
}
.placeholder(red);
";
var expected = @"
.foo .bar {
color: red;
}
";
AssertLess(input, expected);
}
[Test]
public void VariableSelector()
{
var input = @"// Variables
@mySelector: banner;
// Usage
.@{mySelector} {
font-weight: bold;
line-height: 40px;
margin: 0 auto;
}";
var expected = @".banner {
font-weight: bold;
line-height: 40px;
margin: 0 auto;
}";
AssertLess(input,expected);
}
[Test]
public void VariableSelectorInRecursiveMixin()
{
var input = @"
.span (@index) {
margin: @index;
}
.spanX (@index) when (@index > 0) {
.span@{index} { .span(@index); }
.spanX(@index - 1);
}
.spanX(2);
";
var expected = @"
.span2 {
margin: 2;
}
.span1 {
margin: 1;
}
";
AssertLess(input, expected);
}
[Test]
public void AttributeCharacterTest()
{
var input = @"
.item[data-cra_zy-attr1b-ut3=bold] {
foo: bar;
}";
AssertLessUnchanged(input);
}
[Test]
public void SelectorInterpolation1()
{
var input = @"
@num: 2;
:nth-child(@{num}):nth-child(@num) {
foo: bar;
}";
var expected = @"
:nth-child(2):nth-child(2) {
foo: bar;
}";
AssertLess(input, expected);
}
[Test]
public void SelectorInterpolation2()
{
var input = @"
@theme: blood;
.@{theme} {
foo: bar;
}";
var expected = @"
.blood {
foo: bar;
}";
AssertLess(input, expected);
}
[Test]
public void SelectorInterpolationAndParent()
{
var input = @"
@theme: blood;
.@{theme} {
.red& {
foo: bar;
}
}";
var expected = @"
.red.blood {
foo: bar;
}";
AssertLess(input, expected);
}
[Test]
public void SelectorInterpolationAndParent2()
{
var input = @"
@theme: blood;
.@{theme} {
.red& {
foo: bar;
}
}";
var expected = @"
.red.blood {
foo: bar;
}";
AssertLess(input, expected);
}
[Test]
public void EscapedSelector()
{
var input = @"
#odd\:id,
[odd\.attr] {
foo: bar;
}";
AssertLessUnchanged(input);
}
[Test]
public void MixedCaseAttributeSelector()
{
var input = @"
img[imgType=""sort""] {
foo: bar;
}";
AssertLessUnchanged(input);
}
[Test]
public void MultipleIdenticalSelectorsAreOutputOnlyOnce()
{
var input = @"
.sel1, .sel2 {
float: left;
}
.test:extend(.sel1 all, .sel2 all) { }
";
var expected = @"
.sel1,
.sel2,
.test {
float: left;
}";
AssertLess(input, expected);
}
[Test]
public void ParentSelectorWithVariableInterpolation() {
var input = @"
.test {
@var: 1;
&-@{var} {
color: black;
}
}
";
var expected = @"
.test-1 {
color: black;
}";
AssertLess(input, expected);
}
[Test]
public void ParentSelectorWithVariableInterpolationIsCallable() {
var input = @"
.test {
@var: 1;
&-@{var} {
color: black;
}
}
.call {
.test-1;
}
";
var expected = @"
.test-1 {
color: black;
}
.call {
color: #000000;
}";
AssertLess(input, expected);
}
}
}
| |
using Breeze.Sharp.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Breeze.Sharp {
/// <summary> How to encode query string in URL </summary>
public enum QueryUriStyle {
/// <summary> Odata-style URI, e.g. "Customer?$filter=FirstName%20eq%20'Maria'" </summary>
OData,
/// <summary> JSON-style URI, e.g. "Customer?{where:{FirstName:'Maria'}}" </summary>
JSON
}
/// <summary>
/// A singleton class that provides basic registration mechanisms for a Breeze application.
/// </summary>
public class Configuration {
#region Ctor related
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Configuration() { }
private Configuration() {
QueryUriStyle = QueryUriStyle.OData;
RegisterTypeDiscoveryActionCore(typeof(IEntity), (t) => RegisterStructuralType(t), true);
RegisterTypeDiscoveryActionCore(typeof(IComplexObject), (t) => RegisterStructuralType(t), true);
RegisterTypeDiscoveryActionCore(typeof(Validator), (t) => RegisterValidator(t), true);
RegisterTypeDiscoveryActionCore(typeof(NamingConvention), (t) => RegisterNamingConvention(t), true);
}
/// <summary>
/// The Singleton instance.
/// </summary>
public static Configuration Instance {
get {
return __instance;
}
}
#endregion
#region Public methods
/// <summary>
/// For testing purposes only. - Replaces the current instance with a new one, effectively clearing any
/// previously cached or registered data.
/// </summary>
public static void __Reset() {
lock (__lock) {
var x = __instance._probedAssemblies;
__instance = new Configuration();
}
}
/// <summary> How to encode query string in URL </summary>
public QueryUriStyle QueryUriStyle { get; set; }
/// <summary>
/// Tell's Breeze to probe the specified assemblies and automatically discover any
/// Entity types, Complex types, Validators, NamingConventions and any other types
/// for which a type discovery action is registered.
/// </summary>
/// <param name="assembliesToProbe"></param>
/// <returns></returns>
public bool ProbeAssemblies(params Assembly[] assembliesToProbe) {
lock (_typeDiscoveryActions) {
var assemblies = assembliesToProbe.Except(_probedAssemblies).ToList();
if (assemblies.Any()) {
assemblies.ForEach(asm => {
_probedAssemblies.Add(asm);
_typeDiscoveryActions.Where(tpl => tpl.Item3 == null || tpl.Item3(asm))
.ForEach(tpl => {
var type = tpl.Item1;
var action = tpl.Item2;
TypeFns.GetTypesImplementing(type, asm).ForEach(action);
});
});
return true;
} else {
return false;
}
}
}
/// <summary>
/// Returns the CLR type for a specified structuralTypeName or null if not found.
/// </summary>
/// <param name="structuralTypeName"></param>
/// <returns></returns>
public Type GetClrType(String structuralTypeName) {
lock (_clrTypeMap) {
Type type;
_clrTypeMap.TryGetValue(structuralTypeName, out type);
return type;
}
}
/// <summary>
/// Returns whether the specified CLR type is either an IEntity or a IComplexObject.
/// </summary>
/// <param name="clrType"></param>
/// <returns></returns>
public static bool IsStructuralType(Type clrType) {
return typeof(IStructuralObject).IsAssignableFrom(clrType);
}
/// <summary>
/// Allows for custom actions to be performed as a result of any ProbeAssemblies call.
/// </summary>
/// <param name="type"></param>
/// <param name="action"></param>
public void RegisterTypeDiscoveryAction(Type type, Action<Type> action) {
RegisterTypeDiscoveryActionCore(type, action, false);
}
#endregion
// includeThisAssembly = whether to probe the assembly where 'type' is defined
private void RegisterTypeDiscoveryActionCore(Type type, Action<Type> action, bool includeThisAssembly) {
Func<Assembly, bool> shouldProcessAssembly = (a) => {
return includeThisAssembly ? true : a != this.GetType().GetTypeInfo().Assembly;
};
lock (_typeDiscoveryActions) {
_typeDiscoveryActions.Add(Tuple.Create(type, action, shouldProcessAssembly));
}
}
#region Validator & NamingConvention methods
internal Validator FindOrCreateValidator(JNode jNode) {
// locking is handled internally
return _validatorCache.FindOrCreate(jNode);
}
internal NamingConvention FindOrCreateNamingConvention(JNode jNode) {
// locking is handled internally
return _namingConventionCache.FindOrCreate(jNode);
}
internal Validator InternValidator(Validator validator) {
// locking is handled internally
return _validatorCache.Intern(validator);
}
internal NamingConvention InternNamingConvention(NamingConvention nc) {
// locking is handled internally
return _namingConventionCache.Intern(nc);
}
private void RegisterStructuralType(Type clrType) {
lock (_clrTypeMap) {
var stName = TypeNameInfo.FromClrType(clrType).StructuralTypeName;
_clrTypeMap[stName] = clrType;
}
}
private void RegisterValidator(Type validatorType) {
// locking is handled internally
_validatorCache.Register(validatorType, Validator.Suffix);
}
private void RegisterNamingConvention(Type namingConventionType) {
// locking is handled internally
_namingConventionCache.Register(namingConventionType, NamingConvention.Suffix);
}
#endregion
#region Inner classes
private class InternCache<T> where T : Internable {
public readonly Dictionary<String, Type> TypeMap = new Dictionary<string, Type>();
public readonly Dictionary<JNode, T> JNodeMap = new Dictionary<JNode, T>();
internal T FindOrCreate(JNode jNode) {
try {
lock (TypeMap) {
T internable;
if (JNodeMap.TryGetValue(jNode, out internable)) {
return internable;
}
internable = InternableFromJNode(jNode);
JNodeMap[jNode] = internable;
return internable;
}
} catch (Exception e) {
throw new Exception("Unable to deserialize type: " + typeof(T).Name + " item: " + jNode);
}
}
public T Intern(T internable) {
if (internable.IsInterned) return internable;
var jNode = internable.ToJNode();
lock (TypeMap) {
if (!TypeMap.ContainsKey(internable.Name)) {
TypeMap[internable.Name] = internable.GetType();
}
T cachedInternable;
if (JNodeMap.TryGetValue(jNode, out cachedInternable)) {
cachedInternable.IsInterned = true;
return (T)cachedInternable;
} else {
JNodeMap[jNode] = internable;
internable.IsInterned = true;
return internable;
}
}
}
public void Register(Type internableType, String defaultSuffix) {
var ti = internableType.GetTypeInfo();
if (ti.IsAbstract) return;
if (ti.GenericTypeParameters.Length != 0) return;
var key = UtilFns.TypeToSerializationName(internableType, defaultSuffix);
lock (TypeMap) {
TypeMap[key] = internableType;
}
}
private T InternableFromJNode(JNode jNode) {
var name = jNode.Get<String>("name");
Type type;
if (!TypeMap.TryGetValue(name, out type)) {
return null;
}
// Deserialize the object
var vr = (T)jNode.ToObject(type, true);
return vr;
}
}
#endregion
#region Private and Internal vars
internal static String ANONTYPE_PREFIX = "_IB_";
private static Configuration __instance = new Configuration();
private static readonly Object __lock = new Object();
private readonly AsyncSemaphore _asyncSemaphore = new AsyncSemaphore(1);
private readonly Object _lock = new Object();
private Dictionary<String, Type> _clrTypeMap = new Dictionary<string, Type>();
private readonly HashSet<Assembly> _probedAssemblies = new HashSet<Assembly>();
private readonly List<Tuple<Type, Action<Type>, Func<Assembly, bool>>> _typeDiscoveryActions = new List<Tuple<Type, Action<Type>, Func<Assembly, bool>>>();
private readonly Dictionary<String, String> _shortNameMap = new Dictionary<string, string>();
private InternCache<Validator> _validatorCache = new InternCache<Validator>();
private InternCache<NamingConvention> _namingConventionCache = new InternCache<NamingConvention>();
#endregion
}
}
| |
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using NAppUpdate.Framework.Common;
using NAppUpdate.Framework.Tasks;
namespace NAppUpdate.Framework.Utils
{
/// <summary>
/// Starts the cold update process by extracting the updater app from the library's resources,
/// passing it all the data it needs and terminating the current application
/// </summary>
internal static class NauIpc
{
[Serializable]
internal class NauDto
{
public NauConfigurations Configs { get; set; }
public IList<IUpdateTask> Tasks { get; set; }
public List<Logger.LogItem> LogItems { get; set; }
public string AppPath { get; set; }
public string WorkingDirectory { get; set; }
public bool RelaunchApplication { get; set; }
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern SafeFileHandle CreateNamedPipe(
String pipeName,
uint dwOpenMode,
uint dwPipeMode,
uint nMaxInstances,
uint nOutBufferSize,
uint nInBufferSize,
uint nDefaultTimeOut,
IntPtr lpSecurityAttributes);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern int ConnectNamedPipe(
SafeFileHandle hNamedPipe,
IntPtr lpOverlapped);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern SafeFileHandle CreateFile(
String pipeName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr lpSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplate);
//private const uint DUPLEX = (0x00000003);
private const uint WRITE_ONLY = (0x00000002);
private const uint FILE_FLAG_OVERLAPPED = (0x40000000);
const uint GENERIC_READ = (0x80000000);
//static readonly uint GENERIC_WRITE = (0x40000000);
const uint OPEN_EXISTING = 3;
//Which really isn't an error...
const uint ERROR_PIPE_CONNECTED = 535;
internal static string GetPipeName(string syncProcessName)
{
return string.Format("\\\\.\\pipe\\{0}", syncProcessName);
}
private class State
{
public readonly EventWaitHandle eventWaitHandle;
public int result { get; set; }
public SafeFileHandle clientPipeHandle { get; set; }
public Exception exception;
public State()
{
eventWaitHandle = new ManualResetEvent(false);
}
}
internal static uint BUFFER_SIZE = 4096;
public static Process LaunchProcessAndSendDto(NauDto dto, ProcessStartInfo processStartInfo, string syncProcessName)
{
Process p;
State state = new State();
using (state.clientPipeHandle = CreateNamedPipe(
GetPipeName(syncProcessName),
WRITE_ONLY | FILE_FLAG_OVERLAPPED,
0,
1, // 1 max instance (only the updater utility is expected to connect)
BUFFER_SIZE,
BUFFER_SIZE,
0,
IntPtr.Zero))
{
//failed to create named pipe
if (state.clientPipeHandle.IsInvalid)
{
throw new Exception("Launch process client: Failed to create named pipe, handle is invalid.");
}
// This will throw Win32Exception if the user denies UAC
p = Process.Start(processStartInfo);
ThreadPool.QueueUserWorkItem(ConnectPipe, state);
//A rather arbitary five seconds, perhaps better to be user configurable at some point?
state.eventWaitHandle.WaitOne(10000);
//failed to connect client pipe
if (state.result == 0)
{
throw new Exception("Launch process client: Failed to connect to named pipe", state.exception);
}
//client connection successfull
using (var fStream = new FileStream(state.clientPipeHandle, FileAccess.Write, (int)BUFFER_SIZE, true))
{
new BinaryFormatter().Serialize(fStream, dto);
fStream.Flush();
fStream.Close();
}
}
return p;
}
internal static void ConnectPipe(object stateObject)
{
State state = (State)stateObject;
try
{
state.result = ConnectNamedPipe(state.clientPipeHandle, IntPtr.Zero);
}
catch (Exception e)
{
state.exception = e;
}
int error = Marshal.GetLastWin32Error();
//Check for the oddball: ERROR - PIPE CONNECTED
//Ref: http://msdn.microsoft.com/en-us/library/windows/desktop/aa365146%28v=vs.85%29.aspx
if (error == ERROR_PIPE_CONNECTED)
{
state.result = 1;
}
else if (error != 0)
{
state.exception = new Win32Exception(error);
}
state.eventWaitHandle.Set(); // signal we're done
}
internal static object ReadDto(string syncProcessName)
{
using (SafeFileHandle pipeHandle = CreateFile(
GetPipeName(syncProcessName),
GENERIC_READ,
0,
IntPtr.Zero,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
IntPtr.Zero))
{
if (pipeHandle.IsInvalid)
return null;
using (var fStream = new FileStream(pipeHandle, FileAccess.Read, (int)BUFFER_SIZE, true))
{
return new BinaryFormatter().Deserialize(fStream);
}
}
}
internal static void ExtractUpdaterFromResource(string updaterPath, string hostExeName)
{
if (!Directory.Exists(updaterPath))
Directory.CreateDirectory(updaterPath);
//store the updater temporarily in the designated folder
using (var writer = new BinaryWriter(File.Open(Path.Combine(updaterPath, hostExeName), FileMode.Create)))
writer.Write(Resources.updater);
// Now copy the NAU DLL
var assemblyLocation = typeof(NauIpc).Assembly.Location;
File.Copy(assemblyLocation, Path.Combine(updaterPath, "NAppUpdate.Framework.dll"), true);
// And also all other referenced DLLs (opt-in only)
var assemblyPath = Path.GetDirectoryName(assemblyLocation) ?? string.Empty;
if (UpdateManager.Instance.Config.DependenciesForColdUpdate == null) return;
// TODO Maybe we can back this up with typeof(UpdateStarter).Assembly.GetReferencedAssemblies()
foreach (var dep in UpdateManager.Instance.Config.DependenciesForColdUpdate)
{
string fullPath = Path.Combine(assemblyPath, dep);
if (!File.Exists(fullPath)) continue;
var dest = Path.Combine(updaterPath, dep);
FileSystem.CreateDirectoryStructure(dest);
File.Copy(fullPath, Path.Combine(updaterPath, dep), true);
}
}
}
}
| |
// 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.AcceptanceTestsAzureCompositeModelClient
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// PolymorphismOperations operations.
/// </summary>
internal partial class PolymorphismOperations : IServiceOperations<AzureCompositeModel>, IPolymorphismOperations
{
/// <summary>
/// Initializes a new instance of the PolymorphismOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal PolymorphismOperations(AzureCompositeModel client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AzureCompositeModel
/// </summary>
public AzureCompositeModel Client { get; private set; }
/// <summary>
/// Get complex types that are polymorphic
/// </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<AzureOperationResponse<Fish>> GetValidWithHttpMessagesAsync(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, "GetValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/polymorphism/valid").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Fish>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Fish>(_responseContent, this.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 complex types that are polymorphic
/// </summary>
/// <param name='complexBody'>
/// Please put a salmon that looks like this:
/// {
/// 'fishtype':'Salmon',
/// 'location':'alaska',
/// 'iswild':true,
/// 'species':'king',
/// 'length':1.0,
/// 'siblings':[
/// {
/// 'fishtype':'Shark',
/// 'age':6,
/// 'birthday': '2012-01-05T01:00:00Z',
/// 'length':20.0,
/// 'species':'predator',
/// },
/// {
/// 'fishtype':'Sawshark',
/// 'age':105,
/// 'birthday': '1900-01-05T01:00:00Z',
/// 'length':10.0,
/// 'picture': new Buffer([255, 255, 255, 255,
/// 254]).toString('base64'),
/// 'species':'dangerous',
/// },
/// {
/// 'fishtype': 'goblin',
/// 'age': 1,
/// 'birthday': '2015-08-08T00:00:00Z',
/// 'length': 30.0,
/// 'species': 'scary',
/// 'jawsize': 5
/// }
/// ]
/// };
/// </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>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PutValidWithHttpMessagesAsync(Fish complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (complexBody == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "complexBody");
}
if (complexBody != null)
{
complexBody.Validate();
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/polymorphism/valid").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(complexBody != null)
{
_requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put complex types that are polymorphic, attempting to omit required
/// 'birthday' field - the request should not be allowed from the client
/// </summary>
/// <param name='complexBody'>
/// Please attempt put a sawshark that looks like this, the client should not
/// allow this data to be sent:
/// {
/// "fishtype": "sawshark",
/// "species": "snaggle toothed",
/// "length": 18.5,
/// "age": 2,
/// "birthday": "2013-06-01T01:00:00Z",
/// "location": "alaska",
/// "picture": base64(FF FF FF FF FE),
/// "siblings": [
/// {
/// "fishtype": "shark",
/// "species": "predator",
/// "birthday": "2012-01-05T01:00:00Z",
/// "length": 20,
/// "age": 6
/// },
/// {
/// "fishtype": "sawshark",
/// "species": "dangerous",
/// "picture": base64(FF FF FF FF FE),
/// "length": 10,
/// "age": 105
/// }
/// ]
/// }
/// </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>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PutValidMissingRequiredWithHttpMessagesAsync(Fish complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (complexBody == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "complexBody");
}
if (complexBody != null)
{
complexBody.Validate();
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutValidMissingRequired", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/polymorphism/missingrequired/invalid").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(complexBody != null)
{
_requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Threading;
using Xunit;
namespace System.Linq.Parallel.Tests
{
public class JoinTests
{
private const int KeyFactor = 8;
public static IEnumerable<object[]> JoinData(int[] leftCounts, int[] rightCounts)
{
foreach (object[] parms in UnorderedSources.BinaryRanges(leftCounts, rightCounts))
{
yield return new object[] { ((Labeled<ParallelQuery<int>>)parms[0]).Order(), parms[1], parms[2], parms[3] };
}
}
//
// Join
//
[Theory]
[MemberData("BinaryRanges", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 16 }, MemberType = typeof(UnorderedSources))]
public static void Join_Unordered(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, Math.Min(leftCount, (rightCount + (KeyFactor - 1)) / KeyFactor));
foreach (var p in leftQuery.Join(rightQuery, x => x * KeyFactor, y => y, (x, y) => KeyValuePair.Create(x, y)))
{
Assert.Equal(p.Key * KeyFactor, p.Value);
seen.Add(p.Key);
}
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("BinaryRanges", new int[] { 1024 * 4, 1024 * 8 }, new int[] { 0, 1, 1024 * 8, 1024 * 16 }, MemberType = typeof(UnorderedSources))]
public static void Join_Unordered_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Join_Unordered(left, leftCount, right, rightCount);
}
[Theory]
[MemberData("JoinData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 16 })]
public static void Join(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int seen = 0;
foreach (var p in leftQuery.Join(rightQuery, x => x * KeyFactor, y => y, (x, y) => KeyValuePair.Create(x, y)))
{
Assert.Equal(seen++, p.Key);
Assert.Equal(p.Key * KeyFactor, p.Value);
}
Assert.Equal(Math.Min(leftCount, (rightCount + (KeyFactor - 1)) / KeyFactor), seen);
}
[Theory]
[OuterLoop]
[MemberData("JoinData", new int[] { 1024 * 4, 1024 * 8 }, new int[] { 0, 1, 1024 * 8, 1024 * 16 })]
public static void Join_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Join(left, leftCount, right, rightCount);
}
[Theory]
[MemberData("BinaryRanges", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 16 }, MemberType = typeof(UnorderedSources))]
public static void Join_Unordered_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, Math.Min(leftCount, (rightCount + (KeyFactor - 1)) / KeyFactor));
Assert.All(leftQuery.Join(rightQuery, x => x * KeyFactor, y => y, (x, y) => KeyValuePair.Create(x, y)).ToList(),
p => { Assert.Equal(p.Key * KeyFactor, p.Value); seen.Add(p.Key); });
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("BinaryRanges", new int[] { 1024 * 4, 1024 * 8 }, new int[] { 0, 1, 1024 * 8, 1024 * 16 }, MemberType = typeof(UnorderedSources))]
public static void Join_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Join_Unordered_NotPipelined(left, leftCount, right, rightCount);
}
[Theory]
[MemberData("JoinData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 16 })]
public static void Join_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int seen = 0;
Assert.All(leftQuery.Join(rightQuery, x => x * KeyFactor, y => y, (x, y) => KeyValuePair.Create(x, y)).ToList(),
p => { Assert.Equal(seen++, p.Key); Assert.Equal(p.Key * KeyFactor, p.Value); });
Assert.Equal(Math.Min(leftCount, (rightCount + (KeyFactor - 1)) / KeyFactor), seen);
}
[Theory]
[OuterLoop]
[MemberData("JoinData", new int[] { 1024 * 4, 1024 * 8 }, new int[] { 0, 1, 1024 * 8, 1024 * 16 })]
public static void Join_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Join_NotPipelined(left, leftCount, right, rightCount);
}
[Theory]
[MemberData("BinaryRanges", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 16 }, MemberType = typeof(UnorderedSources))]
public static void Join_Unordered_Multiple(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
IntegerRangeSet seenOuter = new IntegerRangeSet(0, Math.Min(leftCount, (rightCount + (KeyFactor - 1)) / KeyFactor));
IntegerRangeSet seenInner = new IntegerRangeSet(0, Math.Min(leftCount * KeyFactor, rightCount));
Assert.All(leftQuery.Join(rightQuery, x => x, y => y / KeyFactor, (x, y) => KeyValuePair.Create(x, y)),
p =>
{
Assert.Equal(p.Key, p.Value / KeyFactor);
seenInner.Add(p.Value);
if (p.Value % KeyFactor == 0) seenOuter.Add(p.Key);
});
seenOuter.AssertComplete();
seenInner.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("BinaryRanges", new int[] { 1024 * 4, 1024 * 8 }, new int[] { 0, 1, 1024 * 8, 1024 * 16 }, MemberType = typeof(UnorderedSources))]
public static void Join_Unordered_Multiple_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Join_Unordered_Multiple(left, leftCount, right, rightCount);
}
[Theory]
[MemberData("JoinData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 16 })]
// Join doesn't always return items from the right ordered. See Issue #1155
public static void Join_Multiple(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int seenOuter = 0;
int previousOuter = -1;
IntegerRangeSet seenInner = new IntegerRangeSet(0, 0);
Assert.All(leftQuery.Join(rightQuery, x => x, y => y / KeyFactor, (x, y) => KeyValuePair.Create(x, y)),
p =>
{
if (p.Key != previousOuter)
{
Assert.Equal(seenOuter++, p.Key);
seenInner.AssertComplete();
seenInner = new IntegerRangeSet(p.Key * KeyFactor, Math.Min(rightCount - p.Key * KeyFactor, KeyFactor));
previousOuter = p.Key;
}
seenInner.Add(p.Value);
Assert.Equal(p.Key, p.Value / KeyFactor);
});
Assert.Equal(Math.Min(leftCount, (rightCount + (KeyFactor - 1)) / KeyFactor), seenOuter);
seenInner.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("JoinData", new int[] { 1024 * 4, 1024 * 8 }, new int[] { 0, 1, 1024 * 8, 1024 * 16 })]
public static void Join_Multiple_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Join_Multiple(left, leftCount, right, rightCount);
}
[Theory]
[MemberData("BinaryRanges", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 16 }, MemberType = typeof(UnorderedSources))]
public static void Join_Unordered_CustomComparator(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
IntegerRangeCounter seenOuter = new IntegerRangeCounter(0, leftCount);
IntegerRangeCounter seenInner = new IntegerRangeCounter(0, rightCount);
Assert.All(leftQuery.Join(rightQuery, x => x, y => y,
(x, y) => KeyValuePair.Create(x, y), new ModularCongruenceComparer(KeyFactor)),
p =>
{
Assert.Equal(p.Key % KeyFactor, p.Value % KeyFactor);
seenOuter.Add(p.Key);
seenInner.Add(p.Value);
});
if (leftCount == 0 || rightCount == 0)
{
seenOuter.AssertEncountered(0);
seenInner.AssertEncountered(0);
}
else
{
Func<int, int, int> cartesian = (key, other) => (other + (KeyFactor - 1) - key % KeyFactor) / KeyFactor;
Assert.All(seenOuter, kv => Assert.Equal(cartesian(kv.Key, rightCount), kv.Value));
Assert.All(seenInner, kv => Assert.Equal(cartesian(kv.Key, leftCount), kv.Value));
}
}
[Theory]
[OuterLoop]
[MemberData("BinaryRanges", new int[] { 512, 1024 }, new int[] { 0, 1, 1024 }, MemberType = typeof(UnorderedSources))]
public static void Join_Unordered_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Join_Unordered_CustomComparator(left, leftCount, right, rightCount);
}
[Theory]
[MemberData("JoinData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 16 })]
public static void Join_CustomComparator(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int seenOuter = 0;
int previousOuter = -1;
IntegerRangeSet seenInner = new IntegerRangeSet(0, 0);
Assert.All(leftQuery.Join(rightQuery, x => x, y => y,
(x, y) => KeyValuePair.Create(x, y), new ModularCongruenceComparer(KeyFactor)),
p =>
{
if (p.Key != previousOuter)
{
Assert.Equal(seenOuter, p.Key);
// If there aren't sufficient elements in the RHS (< KeyFactor), the LHS skips an entry at the end of the mod cycle.
seenOuter = Math.Min(leftCount, seenOuter + (p.Key % KeyFactor + 1 == rightCount ? 8 - p.Key % KeyFactor : 1));
seenInner.AssertComplete();
previousOuter = p.Key;
seenInner = new IntegerRangeSet(0, (rightCount + (KeyFactor - 1) - p.Key % KeyFactor) / KeyFactor);
}
Assert.Equal(p.Key % KeyFactor, p.Value % KeyFactor);
seenInner.Add(p.Value / KeyFactor);
});
Assert.Equal(rightCount == 0 ? 0 : leftCount, seenOuter);
seenInner.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("JoinData", new int[] { 512, 1024 }, new int[] { 0, 1, 1024 })]
public static void Join_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Join_CustomComparator(left, leftCount, right, rightCount);
}
[Theory]
[MemberData("JoinData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 16 })]
public static void Join_InnerJoin_Ordered(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
ParallelQuery<int> middleQuery = ParallelEnumerable.Range(0, leftCount).AsOrdered();
int seen = 0;
Assert.All(leftQuery.Join(middleQuery.Join(rightQuery, x => x * KeyFactor / 2, y => y, (x, y) => KeyValuePair.Create(x, y)),
z => z * 2, p => p.Key, (x, p) => KeyValuePair.Create(x, p)),
pOuter =>
{
KeyValuePair<int, int> pInner = pOuter.Value;
Assert.Equal(seen++, pOuter.Key);
Assert.Equal(pOuter.Key * 2, pInner.Key);
Assert.Equal(pOuter.Key * KeyFactor, pInner.Value);
});
Assert.Equal(Math.Min((leftCount + 1) / 2, (rightCount + (KeyFactor - 1)) / KeyFactor), seen);
}
[Theory]
[OuterLoop]
[MemberData("JoinData", new int[] { 1024 * 4, 1024 * 8 }, new int[] { 0, 1, 1024 * 8, 1024 * 16 })]
public static void Join_InnerJoin_Ordered_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Join_InnerJoin_Ordered(left, leftCount, right, rightCount);
}
[Fact]
public static void Join_NotSupportedException()
{
#pragma warning disable 618
Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Join(Enumerable.Range(0, 1), i => i, i => i, (i, j) => i));
Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Join(Enumerable.Range(0, 1), i => i, i => i, (i, j) => i, null));
#pragma warning restore 618
}
[Fact]
// Should not get the same setting from both operands.
public static void Join_NoDuplicateSettings()
{
CancellationToken t = new CancellationTokenSource().Token;
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithCancellation(t).Join(ParallelEnumerable.Range(0, 1).WithCancellation(t), x => x, y => y, (l, r) => l));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1).Join(ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1), x => x, y => y, (l, r) => l));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default).Join(ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default), x => x, y => y, (l, r) => l));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default).Join(ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default), x => x, y => y, (l, r) => l));
}
[Fact]
public static void Join_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Join(ParallelEnumerable.Range(0, 1), i => i, i => i, (i, j) => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Join((ParallelQuery<int>)null, i => i, i => i, (i, j) => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Join(ParallelEnumerable.Range(0, 1), (Func<int, int>)null, i => i, (i, j) => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Join(ParallelEnumerable.Range(0, 1), i => i, (Func<int, int>)null, (i, j) => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Join(ParallelEnumerable.Range(0, 1), i => i, i => i, (Func<int, int, int>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Join(ParallelEnumerable.Range(0, 1), i => i, i => i, (i, j) => i, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Join((ParallelQuery<int>)null, i => i, i => i, (i, j) => i, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Join(ParallelEnumerable.Range(0, 1), (Func<int, int>)null, i => i, (i, j) => i, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Join(ParallelEnumerable.Range(0, 1), i => i, (Func<int, int>)null, (i, j) => i, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Join(ParallelEnumerable.Range(0, 1), i => i, i => i, (Func<int, int, int>)null, EqualityComparer<int>.Default));
}
}
}
| |
// This file was contributed to the RDL Project under the MIT License. It was
// modified as part of merging into the RDL Project.
/*
The MIT License
Copyright (c) 2006 Christian Cunlif and Lionel Cuir of Aulofee
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
Software, and to permit persons to whom the Software is furnished to do so, subject
to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
namespace fyiReporting.RDL
{
/// <summary>
/// represents an external file referenced in our parent HTML at the target URL
/// </summary>
class MhtWebFile
{
#region Fields
MhtBuilder _Builder;
string _ContentLocation;
string _ContentType;
byte[] _DownloadedBytes;
Exception _DownloadException = null;
string _DownloadExtension = "";
string _DownloadFilename = "";
string _DownloadFolder = "";
NameValueCollection _ExternalFileCollection;
bool _IsBinary;
Encoding _TextEncoding;
string _Url;
string _UrlFolder;
string _UrlRoot;
string _UrlUnmodified;
bool _UseHtmlFilename = false;
bool _WasDownloaded = false;
public bool WasAppended;
#endregion Fields
#region Constructor
public MhtWebFile(MhtBuilder parent)
{
_Builder = parent;
}
public MhtWebFile(MhtBuilder parent, string url)
{
_Builder = parent;
if (url != "")
this.Url = url;
}
#endregion Constructor
#region Properties
/// <summary>
/// The Content-Type of this file as returned by the server
/// </summary>
public string ContentType
{
get
{
return _ContentType;
}
}
/// <summary>
/// The raw bytes returned from the server for this file
/// </summary>
public byte[] DownloadedBytes
{
get
{
return _DownloadedBytes;
}
}
/// <summary>
/// If not .WasDownloaded, the exception that prevented download is stored here
/// </summary>
public Exception DownloadException
{
get
{
return _DownloadException;
}
}
/// <summary>
/// file type extension to use on downloaded file
/// this property is only used if the DownloadFilename property does not
/// already contain a file extension
/// </summary>
public string DownloadExtension
{
get
{
if (_DownloadExtension == "" && this.WasDownloaded)
_DownloadExtension = this.ExtensionFromContentType();
return _DownloadExtension;
}
set
{
_DownloadExtension = value;
}
}
/// <summary>
/// filename to download this file as
/// if no filename is provided, a filename will be auto-generated based on
/// the URL; if the UseHtmlTitleAsFilename property is true, then the
/// title tag will be used to generate the filename
/// </summary>
public string DownloadFilename
{
get
{
if (_DownloadFilename == "")
{
if (this._UseHtmlFilename && this.WasDownloaded && this.IsHtml)
{
string htmlTitle = this.HtmlTitle;
if (htmlTitle != "")
_DownloadFilename = MakeValidFilename(htmlTitle, false) + ".htm";
}
else
_DownloadFilename = this.FilenameFromUrl();
}
return _DownloadFilename;
}
set
{
_DownloadFilename = value;
}
}
/// <summary>
/// folder to download this file to
/// if no folder is provided, the current application folder will be used
/// </summary>
public string DownloadFolder
{
get
{
if (_DownloadFolder == "")
_DownloadFolder = AppDomain.CurrentDomain.BaseDirectory;
return _DownloadFolder;
}
set
{
this._DownloadFolder = value;
}
}
/// <summary>
/// the folder name used in the DownloadFolder
/// </summary>
public string DownloadFolderName
{
get
{
return Regex.Match(this.DownloadFolder, @"(?<Folder>[^\\]+)\\*$").Groups["Folder"].Value;
}
}
/// <summary>
/// fully qualified path and filename to download this file to
/// </summary>
public string DownloadPath
{
get
{
if (Path.GetExtension(this.DownloadFilename) == "")
return Path.Combine(this.DownloadFolder, this.DownloadFilename + this.DownloadExtension);
return Path.Combine(this.DownloadFolder, this.DownloadFilename);
}
set
{
this._DownloadFilename = Path.GetFileName(value);
if (_DownloadFilename == "")
_DownloadFolder = value;
else
_DownloadFolder = value.Replace(_DownloadFilename, "");
}
}
/// <summary>
/// If this file has external dependencies, the folder they will be stored on disk
/// </summary>
public string ExternalFilesFolder
{
get
{
return (Path.Combine(this.DownloadFolder, Path.GetFileNameWithoutExtension(this.DownloadFilename)) + "_files");
}
}
/// <summary>
/// If this file is HTML, retrieve the <TITLE> tag from the HTML
/// (maximum of 50 characters)
/// </summary>
public string HtmlTitle
{
get
{
// if (!this.IsHtml)
// throw new Exception("This file isn't HTML, so it has no HTML <TITLE> tag.");
string remp = this.ToString();
string s = Regex.Match(this.ToString(), "<title[^>]*?>(?<text>[^<]+)</title>", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups["text"].Value;
if (s.Length > 50)
return s.Substring(0, 50);
return s;
}
}
/// <summary>
/// Does this file contain binary data? If not, it must be text data.
/// </summary>
public bool IsBinary
{
get
{
return _IsBinary;
}
}
/// <summary>
/// Is this file CSS content?
/// </summary>
public bool IsCss
{
get
{
return Regex.IsMatch(_ContentType, "text/css", RegexOptions.IgnoreCase);
}
}
/// <summary>
/// Is this file HTML content?
/// </summary>
public bool IsHtml
{
get
{
return Regex.IsMatch(_ContentType, "text/html", RegexOptions.IgnoreCase);
}
}
/// <summary>
/// If this file is text (eg, it isn't binary), the type of text encoding used
/// </summary>
public Encoding TextEncoding
{
get
{
return _TextEncoding;
}
}
/// <summary>
/// The URL target for this file
/// </summary>
public string Url
{
get
{
return this._Url;
}
set
{
_UrlUnmodified = value;
SetUrl(value, true);
_DownloadedBytes = new byte[1];
_ExternalFileCollection = null;
_DownloadException = null;
_TextEncoding = null;
_ContentType = "";
_ContentLocation = "";
_IsBinary = false;
_WasDownloaded = false;
}
}
/// <summary>
/// The Content-Location of this URL as provided by the server,
/// only if the URL was not fully qualified;
/// eg, http://mywebsite.com/ actually maps to http://mywebsite.com/default.htm
/// </summary>
public string UrlContentLocation
{
get
{
return _ContentLocation;
}
}
/// <summary>
/// The root and folder of the URL, eg, http://mywebsite.com/myfolder
/// </summary>
public string UrlFolder
{
get
{
return this._UrlFolder;
}
}
/// <summary>
/// The root of the URL, eg, http://mywebsite.com/
/// </summary>
public string UrlRoot
{
get
{
return this._UrlRoot;
}
}
/// <summary>
/// The unmodified "raw" URL as originally provided
/// </summary>
public string UrlUnmodified
{
get
{
return _UrlUnmodified;
}
}
/// <summary>
/// If enabled, will use the first 50 characters of the TITLE tag
/// to form the filename when saved to disk
/// </summary>
public bool UseHtmlTitleAsFilename
{
get
{
return this._UseHtmlFilename;
}
set
{
this._UseHtmlFilename = value;
}
}
/// <summary>
/// Was this file successfully downloaded via HTTP?
/// </summary>
public bool WasDownloaded
{
get
{
return _WasDownloaded;
}
}
#endregion Properties
#region Public methods
/// <summary>
/// converts all external Html files (gif, jpg, css, etc) to local refs
/// external ref:
/// <img src="http://mywebsite/myfolder/myimage.gif">
/// into local refs:
/// <img src="mypage_files/myimage.gif">
/// </summary>
public void ConvertReferencesToLocal()
{
if (!this.IsHtml && !this.IsCss)
throw new Exception("Converting references only makes sense for HTML or CSS files; this file is of type '" + this.ContentType + "'");
// get a list of all external references
string html = this.ToString();
NameValueCollection fileCollection = this.ExternalHtmlFiles();
// no external refs? nothing to do
if (fileCollection.Count == 0)
return;
string[] keys = fileCollection.AllKeys;
for (int idx = 0; idx < keys.Length; idx++)
{
string delimitedUrl = keys[idx];
string fileUrl = fileCollection[delimitedUrl];
if (_Builder.WebFiles.Contains(fileUrl))
{
MhtWebFile wf = (MhtWebFile) _Builder.WebFiles[fileUrl];
string newPath = this.ExternalFilesFolder + "/" + wf.DownloadFilename;
string delimitedReplacement = Regex.Replace(delimitedUrl,
@"^(?<StartDelim>""|'|\()*(?<Value>[^'"")]*)(?<EndDelim>""|'|\))*$",
"${StartDelim}" + newPath + "${EndDelim}");
// correct original Url references in Html so they point to our local files
html = html.Replace(delimitedUrl, delimitedReplacement);
}
}
_DownloadedBytes = _TextEncoding.GetBytes(html);
}
/// <summary>
/// Download this file from the target URL
/// </summary>
public void Download()
{
Debug.Write("Downloading " + this._Url + " ..");
DownloadBytes();
if (_DownloadException == null)
Debug.WriteLine("OK");
else
{
Debug.WriteLine("failed: ", "Error");
Debug.WriteLine(" " + _DownloadException.Message, "Error");
return;
}
if (this.IsHtml)
_DownloadedBytes = _TextEncoding.GetBytes(ProcessHtml(this.ToString()));
if (this.IsCss)
_DownloadedBytes = _TextEncoding.GetBytes(ProcessHtml(this.ToString()));
}
/// <summary>
/// download ALL externally referenced files in this file's html, not recursively,
/// to the default download path for this page
/// </summary>
public void DownloadExternalFiles()
{
this.DownloadExternalFiles(this.ExternalFilesFolder, false);
}
/// <summary>
/// download ALL externally referenced files in this file's html, potentially recursively,
/// to the default download path for this page
/// </summary>
public void DownloadExternalFiles(bool recursive)
{
this.DownloadExternalFiles(this.ExternalFilesFolder, recursive);
}
/// <summary>
/// Saves this file to disk as a plain text file
/// </summary>
public void SaveAsTextFile()
{
this.SaveToFile(Path.ChangeExtension(this.DownloadPath, ".txt"), true);
}
/// <summary>
/// Saves this file to disk as a plain text file, to an arbitrary path
/// </summary>
public void SaveAsTextFile(string filePath)
{
this.SaveToFile(filePath, true);
}
/// <summary>
/// writes contents of file to DownloadPath, using appropriate encoding as necessary
/// </summary>
public void SaveToFile()
{
this.SaveToFile(this.DownloadPath, false);
}
/// <summary>
/// writes contents of file to DownloadPath, using appropriate encoding as necessary
/// </summary>
public void SaveToFile(string filePath)
{
this.SaveToFile(filePath, false);
}
/// <summary>
/// Returns a string representation of the data downloaded for this file
/// </summary>
public override string ToString()
{
if (!_WasDownloaded)
Download();
if (!_WasDownloaded || _DownloadedBytes.Length <= 0)
return "";
if (_IsBinary)
return ("[" + _DownloadedBytes.Length.ToString() + " bytes of binary data]");
return this.TextEncoding.GetString(_DownloadedBytes);
}
/// <summary>
/// Returns the plain text representation of the data in this file,
/// stripping out any HTML tags and codes
/// </summary>
public string ToTextString(bool removeWhitespace /* = false */)
{
string html = this.ToString();
// get rid of <script> .. </script>
html = this.StripHtmlTag("script", html);
// get rid of <style> .. </style>
html = this.StripHtmlTag("style", html);
// get rid of all HTML tags
html = Regex.Replace(html,
@"<\w+(\s+[A-Za-z0-9_\-]+\s*=\s*(""([^""]*)""|'([^']*)'))*\s*(/)*>|<[^>]+>",
" ");
// convert escaped HTML to plaintext
html = HtmlDecode(html);
if (removeWhitespace)
{
// clean up whitespace (optional, depends what you want..)
html = Regex.Replace(html, @"[\n\r\f\t]", " ", RegexOptions.Multiline);
html = Regex.Replace(html, " {2,}", " ", RegexOptions.Multiline);
}
return html;
}
#endregion Public methods
#region Private methods
/// <summary>
/// appends key=value named matches in a regular expression
/// to a target NameValueCollection
/// </summary>
void AddMatchesToCollection(string s, Regex r, ref NameValueCollection nvc)
{
bool headerDisplayed = false;
// Regex urlRegex = new Regex(@"^https*://\w+", RegexOptions.IgnoreCase);
Regex urlRegex = new Regex(@"^files*:///\w+", RegexOptions.IgnoreCase);
foreach (Match match in r.Matches(s))
{
if (!headerDisplayed)
{
Debug.WriteLine("Matches added from regex:");
Debug.WriteLine("'" + match.ToString() + "'");
headerDisplayed = true;
}
string key = match.Groups["Key"].ToString();
string val = match.Groups["Value"].ToString();
if (nvc[key] == null)
{
Debug.WriteLine(" Match: " + match.ToString());
Debug.WriteLine(" Key: " + key);
Debug.WriteLine(" Value: " + val);
if (urlRegex.IsMatch(val))
nvc.Add(key, val);
else
Debug.WriteLine("Match discarded; does not appear to be valid fully qualified file:// Url", "Error");
// Debug.WriteLine("Match discarded; does not appear to be valid fully qualified http:// Url", "Error");
}
}
}
/// <summary>
/// converts all relative url references
/// href="myfolder/mypage.htm"
/// into absolute url references
/// href="http://mywebsite/myfolder/mypage.htm"
/// </summary>
string ConvertRelativeToAbsoluteRefs(string html)
{
string urlPattern =
@"(?<attrib>\shref|\ssrc|\sbackground)\s*?=\s*?" +
@"(?<delim1>[""'\\]{0,2})(?!\s*\+|#|http:|ftp:|mailto:|javascript:)" +
@"/(?<url>[^""'>\\]+)(?<delim2>[""'\\]{0,2})";
string cssPattern =
@"(?<attrib>@import\s|\S+-image:|background:)\s*?(url)*['""(]{1,2}" +
@"(?!http)\s*/(?<url>[^""')]+)['"")]{1,2}";
// href="/anything" to href="http://www.web.com/anything"
Regex r = new Regex(urlPattern, RegexOptions.Multiline | RegexOptions.IgnoreCase);
html = r.Replace(html, "${attrib}=${delim1}" + this._UrlRoot + "/${url}${delim2}");
// href="anything" to href="http://www.web.com/folder/anything"
r = new Regex(urlPattern.Replace("/", ""), RegexOptions.Multiline | RegexOptions.IgnoreCase);
html = r.Replace(html, "${attrib}=${delim1}" + this._UrlFolder + "/${url}${delim2}");
// @import(/anything) to @import url(http://www.web.com/anything)
r = new Regex(cssPattern, RegexOptions.Multiline | RegexOptions.IgnoreCase);
html = r.Replace(html, "${attrib} url(" + this._UrlRoot + "/${url})");
// @import(anything) to @import url(http://www.web.com/folder/anything)
r = new Regex(cssPattern.Replace("/", ""), RegexOptions.Multiline | RegexOptions.IgnoreCase);
html = r.Replace(html, "${attrib} url(" + this._UrlFolder + "/${url})");
return html;
}
/// <summary>
/// if the user passed in a directory, form the filename automatically using the Html title tag
/// if the user passed in a filename, make sure the extension matches our desired extension
/// </summary>
string DeriveFilename(string FilePath, string html, string fileExtension)
{
if (IsDirectory(FilePath))
{
string htmlTitle = this.HtmlTitle;
if (htmlTitle == "")
throw new Exception("No filename was provided, and the HTML title tag was not found, so a filename could not be automatically generated. You'll need to provide a filename and not a folder.");
return Path.Combine(Path.GetDirectoryName(FilePath), MakeValidFilename(htmlTitle, false) + fileExtension);
}
if (Path.GetExtension(FilePath) != fileExtension)
return Path.ChangeExtension(FilePath, fileExtension);
return FilePath;
}
/// <summary>
/// download this file from the target URL;
/// place the bytes downloaded in _DownloadedBytes
/// if an exception occurs, capture it in _DownloadException
/// </summary>
void DownloadBytes()
{
if (this.WasDownloaded)
return;
// always download to memory first
try
{
_DownloadedBytes = _Builder.WebClient.DownloadBytes(_Url);
_WasDownloaded = true;
}
catch (WebException ex)
{
_DownloadException = ex;
_Builder.WebClient.ClearDownload();
}
// necessary if the original client URL was imprecise;
// server location is always authoritatitve
if (_Builder.WebClient.ContentLocation != "")
{
_ContentLocation = _Builder.WebClient.ContentLocation;
SetUrl(_ContentLocation, false);
}
_IsBinary = _Builder.WebClient.ResponseIsBinary;
_ContentType = _Builder.WebClient.ResponseContentType;
_TextEncoding = _Builder.WebClient.DetectedEncoding;
_Builder.WebClient.ClearDownload();
}
/// <summary>
/// Download a single externally referenced file (if we haven't already downloaded it)
/// </summary>
void DownloadExternalFile(string url, string targetFolder, bool recursive)
{
bool isNew;
MhtWebFile wf;
// have we already downloaded (or attempted to) this file?
if (_Builder.WebFiles.Contains(url) || _Builder.Url == url)
{
wf = (MhtWebFile) _Builder.WebFiles[url];
isNew = false;
}
else
{
wf = new MhtWebFile(_Builder, url);
isNew = true;
}
wf.Download();
if (isNew)
{
// add this (possibly) downloaded file to our shared collection
_Builder.WebFiles.Add(wf.UrlUnmodified, wf);
// if this is an HTML file, it has dependencies of its own;
// download them into a subfolder
if ((wf.IsHtml || wf.IsCss) && recursive)
wf.DownloadExternalFiles(recursive);
}
}
/// <summary>
/// download ALL externally referenced files in this html, potentially recursively
/// to a specific download path
/// </summary>
void DownloadExternalFiles(string targetFolder, bool recursive)
{
NameValueCollection fileCollection = ExternalHtmlFiles();
if (!fileCollection.HasKeys())
return;
Debug.WriteLine("Downloading all external files collected from URL:");
Debug.WriteLine(" " + this.Url);
foreach (string key in fileCollection.Keys)
DownloadExternalFile(fileCollection[key], targetFolder, recursive);
}
/// <summary>
/// if we weren't given a filename extension, infer it from the download
/// Content-Type header
/// </summary>
/// <remarks>
/// http://www.utoronto.ca/webdocs/HTMLdocs/Book/Book-3ed/appb/mimetype.html
/// </remarks>
string ExtensionFromContentType()
{
switch (Regex.Match(this.ContentType, "^[^ ;]+").Value.ToLower())
{
case "text/html":
return ".htm";
case "image/gif":
return ".gif";
case "image/jpeg":
return ".jpg";
case "text/javascript":
case "application/x-javascript":
return ".js";
case "image/x-png":
return ".png";
case "text/css":
return ".css";
case "text/plain":
return ".txt";
default:
Debug.WriteLine("Unknown content-type '" + this.ContentType + "'", "Error");
return ".htm";
}
}
/// <summary>
/// returns a name/value collection of all external files referenced in HTML:
///
/// "/myfolder/blah.png"
/// 'http://mywebsite/blah.gif'
/// src=blah.jpg
///
/// note that the Key includes the delimiting quotes or parens (if present), but the Value does not
/// this is important because the delimiters are used for matching and replacement to make the
/// match more specific!
/// </summary>
NameValueCollection ExternalHtmlFiles()
{
// avoid doing this work twice, however, be careful that the HTML hasn't
// changed since the last time we called this function
if (_ExternalFileCollection != null)
return _ExternalFileCollection;
_ExternalFileCollection = new NameValueCollection();
string html = this.ToString();
Debug.WriteLine("Resolving all external HTML references from URL:");
Debug.WriteLine(" " + this.Url);
// src='filename.ext' ; background="filename.ext"
// note that we have to test 3 times to catch all quote styles: '', "", and none
Regex r = new Regex(
@"(\ssrc|\sbackground)\s*=\s*((?<Key>'(?<Value>[^']+)')|(?<Key>""(?<Value>[^""]+)"")|(?<Key>(?<Value>[^ \n\r\f]+)))",
RegexOptions.Multiline | RegexOptions.IgnoreCase);
AddMatchesToCollection(html, r, ref _ExternalFileCollection);
// @import "style.css" or @import url(style.css)
r = new Regex(
@"(@import\s|\S+-image:|background:)\s*?(url)*\s*?(?<Key>[""'(]{1,2}(?<Value>[^""')]+)[""')]{1,2})",
RegexOptions.Multiline | RegexOptions.IgnoreCase);
AddMatchesToCollection(html, r, ref _ExternalFileCollection);
// <link rel=stylesheet href="style.css">
r = new Regex(
@"<link[^>]+?href\s*=\s*(?<Key>('|"")*(?<Value>[^'"">]+)('|"")*)",
RegexOptions.Multiline | RegexOptions.IgnoreCase);
AddMatchesToCollection(html, r, ref _ExternalFileCollection);
// <iframe src="mypage.htm"> or <frame src="mypage.aspx">
r = new Regex(
@"<i*frame[^>]+?src\s*=\s*(?<Key>['""]{0,1}(?<Value>[^'""\\>]+)['""]{0,1})",
RegexOptions.Multiline | RegexOptions.IgnoreCase);
AddMatchesToCollection(html, r, ref _ExternalFileCollection);
return _ExternalFileCollection;
}
/// <summary>
/// attempt to get a coherent filename out of the Url
/// </summary>
string FilenameFromUrl()
{
// first, try to get a filename out of the URL itself;
// this means anything past the final slash that doesn't include another slash
// or a question mark, eg http://mywebsite/myfolder/crazy?param=1¶m=2
string filename = Regex.Match(this._Url, "/(?<Filename>[^/?]+)[^/]*$").Groups["Filename"].Value;
if (filename != "")
{
// that worked, but we need to make sure the filename is unique
// if query params were passed to the URL file
Uri u = new Uri(this._Url);
if (u.Query != "")
filename = Path.GetFileNameWithoutExtension(filename) + "_" + u.Query.GetHashCode().ToString() + this.DownloadExtension;
}
// ok, that didn't work; if this file is HTML try to get the TITLE tag
if (filename == "" && this.IsHtml)
{
filename = this.HtmlTitle;
if (filename != "")
filename = filename + ".htm";
}
// now we're really desperate. Hash the URL and make that the filename.
if (filename == "")
filename = _Url.GetHashCode().ToString() + this.DownloadExtension;
return this.MakeValidFilename(filename, false);
}
/// <summary>
/// returns true if this path refers to a directory (vs. a filename)
/// </summary>
bool IsDirectory(string FilePath)
{
return FilePath.EndsWith(@"\");
}
/// <summary>
/// removes all unsafe filesystem characters to form a valid filesystem filename
/// </summary>
string MakeValidFilename(string s, bool enforceLength /* = false */)
{
//if (enforceLength)
//{
//}
//// replace any invalid filesystem chars, plus leading/trailing/doublespaces
//return Regex.Replace(
// Regex.Replace(
// s,
// @"[\/\\\:\*\?\""""\<\>\|]|^\s+|\s+$",
// ""),
// @"\s{2,}",
// " ");
// Replaces any invalid filesystem chars, plus leading/trailing/doublespaces.
string name = Regex.Replace(
Regex.Replace(
s,
@"[\/\\\:\*\?\""""\<\>\|]|^\s+|\s+$",
""),
@"\s{2,}",
" ");
// Enforces the maximum length to 25 characters.
if (name.Length > 25)
{
string ext = Path.GetExtension(name);
name = name.Substring(0, 25 - ext.Length) + ext;
}
return name;
}
/// <summary>
/// Pre-process the CSS using global preference settings
/// </summary>
string ProcessCss(string css)
{
return this.ConvertRelativeToAbsoluteRefs(css);
}
/// <summary>
/// Pre-process the HTML using global preference settings
/// </summary>
string ProcessHtml(string html)
{
Debug.WriteLine("Downloaded content was HTML/CSS -- processing: resolving URLs, getting <base>, etc");
if (_Builder.AddWebMark)
{
// add "mark of the web":
// http://www.microsoft.com/technet/prodtechnol/winxppro/maintain/sp2brows.mspx#XSLTsection133121120120
html = "<!-- saved from url=(" + string.Format("{0:0000}", this._Url.Length) +
")" + this._Url + " -->" + Environment.NewLine + html;
}
// see if we need to strip elements from the HTML
if (_Builder.StripScripts)
html = this.StripHtmlTag("script", html);
if (_Builder.StripIframes)
html = this.StripHtmlTag("iframe", html);
// if we have a <base>, we must use it as the _UrlFolder,
// not what was parsed from the original _Url
string baseUrlFolder = Regex.Match(
html,
"<base[^>]+?href=['\"]{0,1}(?<BaseUrl>[^'\">]+)['\"]{0,1}",
RegexOptions.IgnoreCase).Groups["BaseUrl"].Value;
if (baseUrlFolder != "")
{
if (baseUrlFolder.EndsWith("/"))
_UrlFolder = baseUrlFolder.Substring(0, baseUrlFolder.Length - 1);
else
_UrlFolder = baseUrlFolder;
}
// remove the <base href=''> tag if present; causes problems when viewing locally.
html = Regex.Replace(html, "<base[^>]*?>", "");
// relative URLs are a PITA for the processing we're about to do,
// so convert them all to absolute up front
return this.ConvertRelativeToAbsoluteRefs(html);
}
/// <summary>
/// fully resolves any relative pathing inside the URL, and other URL oddities
/// </summary>
string ResolveUrl(string url)
{
// resolve any relative pathing
try
{
url = new Uri(url).AbsoluteUri;
}
catch (UriFormatException ex)
{
throw new ArgumentException("'" + url + "' does not appear to be a valid URL.", ex);
}
// remove any anchor tags from the end of URLs
if (url.IndexOf("#") > -1)
{
string jump = Regex.Match(url, "/[^/]*?(?<jump>#[^/?.]+$)").Groups["jump"].Value;
if (jump != "")
url = url.Replace(jump, "");
}
return url;
}
/// <summary>
/// sets the DownloadPath and writes contents of file, using appropriate encoding as necessary
/// </summary>
void SaveToFile(string filePath, bool asText)
{
Debug.WriteLine("Saving to file " + filePath);
using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
{
using (BinaryWriter writer = new BinaryWriter(fs))
{
if (this.IsBinary)
writer.Write(_DownloadedBytes);
else if (asText)
writer.Write(this.ToTextString(false));
else
writer.Write(_DownloadedBytes);
}
}
}
void SetUrl(string url, bool validate)
{
if (validate)
this._Url = this.ResolveUrl(url);
else
this._Url = url;
// http://mywebsite
this._UrlRoot = Regex.Match(url, "http://[^/'\"]+", RegexOptions.IgnoreCase).ToString();
// http://mywebsite/myfolder
if (this._Url.LastIndexOf("/") > 7)
this._UrlFolder = this._Url.Substring(0, this._Url.LastIndexOf("/"));
else
this._UrlFolder = this._UrlRoot;
}
/// <summary>
/// perform the regex replacement of all <tagName> .. </tagName> blocks
/// </summary>
string StripHtmlTag(string tagName, string html)
{
Regex r = new Regex(
string.Format(@"<{0}[^>]*?>[\w|\t|\r|\W]*?</{0}>", tagName), RegexOptions.Multiline | RegexOptions.IgnoreCase);
return r.Replace(html, "");
}
#region Html decoding
string HtmlDecode(string s)
{
if (s == null)
return null;
if (s.IndexOf('&') < 0)
return s;
StringBuilder builder = new StringBuilder();
StringWriter writer = new StringWriter(builder);
for (int i = 0; i < s.Length; i++)
{
char currentChar = s[i];
if (currentChar != '&')
{
writer.Write(currentChar);
continue;
}
int pos = s.IndexOf(';', i + 1);
if (pos <= 0)
{
writer.Write(currentChar);
continue;
}
string subText = s.Substring(i + 1, (pos - i) - 1);
if (subText[0] == '#' && subText.Length > 1)
{
try
{
if ((subText[1] == 'x') || (subText[1] == 'X'))
writer.Write((char) ((ushort) int.Parse(subText.Substring(2),
System.Globalization.NumberStyles.AllowHexSpecifier)));
else
writer.Write((char) ((ushort) int.Parse(subText.Substring(1))));
i = pos;
}
catch (FormatException)
{
i++;
}
catch (ArgumentException)
{
i++;
}
}
else
{
i = pos;
currentChar = HtmlLookup(subText);
if (currentChar != '\0')
{
writer.Write(currentChar);
}
else
{
writer.Write('&');
writer.Write(subText);
writer.Write(';');
}
}
}
return builder.ToString();
}
static Hashtable htmlEntitiesTable = null;
char HtmlLookup(string entity)
{
if (htmlEntitiesTable == null)
{
lock (typeof(MhtWebFile))
{
if (htmlEntitiesTable == null)
{
htmlEntitiesTable = new Hashtable();
string[] htmlEntities = new string[]
{
"\"-quot", "&-amp", "<-lt", ">-gt", "\x00a0-nbsp", "\x00a1-iexcl", "\x00a2-cent", "\x00a3-pound", "\x00a4-curren", "\x00a5-yen", "\x00a6-brvbar", "\x00a7-sect", "\x00a8-uml", "\x00a9-copy", "\x00aa-ordf", "\x00ab-laquo",
"\x00ac-not", "\x00ad-shy", "\x00ae-reg", "\x00af-macr", "\x00b0-deg", "\x00b1-plusmn", "\x00b2-sup2", "\x00b3-sup3", "\x00b4-acute", "\x00b5-micro", "\x00b6-para", "\x00b7-middot", "\x00b8-cedil", "\x00b9-sup1", "\x00ba-ordm", "\x00bb-raquo",
"\x00bc-frac14", "\x00bd-frac12", "\x00be-frac34", "\x00bf-iquest", "\x00c0-Agrave", "\x00c1-Aacute", "\x00c2-Acirc", "\x00c3-Atilde", "\x00c4-Auml", "\x00c5-Aring", "\x00c6-AElig", "\x00c7-Ccedil", "\x00c8-Egrave", "\x00c9-Eacute", "\x00ca-Ecirc", "\x00cb-Euml",
"\x00cc-Igrave", "\x00cd-Iacute", "\x00ce-Icirc", "\x00cf-Iuml", "\x00d0-ETH", "\x00d1-Ntilde", "\x00d2-Ograve", "\x00d3-Oacute", "\x00d4-Ocirc", "\x00d5-Otilde", "\x00d6-Ouml", "\x00d7-times", "\x00d8-Oslash", "\x00d9-Ugrave", "\x00da-Uacute", "\x00db-Ucirc",
"\x00dc-Uuml", "\x00dd-Yacute", "\x00de-THORN", "\x00df-szlig", "\x00e0-agrave", "\x00e1-aacute", "\x00e2-acirc", "\x00e3-atilde", "\x00e4-auml", "\x00e5-aring", "\x00e6-aelig", "\x00e7-ccedil", "\x00e8-egrave", "\x00e9-eacute", "\x00ea-ecirc", "\x00eb-euml",
"\x00ec-igrave", "\x00ed-iacute", "\x00ee-icirc", "\x00ef-iuml", "\x00f0-eth", "\x00f1-ntilde", "\x00f2-ograve", "\x00f3-oacute", "\x00f4-ocirc", "\x00f5-otilde", "\x00f6-ouml", "\x00f7-divide", "\x00f8-oslash", "\x00f9-ugrave", "\x00fa-uacute", "\x00fb-ucirc",
"\x00fc-uuml", "\x00fd-yacute", "\x00fe-thorn", "\x00ff-yuml", "\u0152-OElig", "\u0153-oelig", "\u0160-Scaron", "\u0161-scaron", "\u0178-Yuml", "\u0192-fnof", "\u02c6-circ", "\u02dc-tilde", "\u0391-Alpha", "\u0392-Beta", "\u0393-Gamma", "\u0394-Delta",
"\u0395-Epsilon", "\u0396-Zeta", "\u0397-Eta", "\u0398-Theta", "\u0399-Iota", "\u039a-Kappa", "\u039b-Lambda", "\u039c-Mu", "\u039d-Nu", "\u039e-Xi", "\u039f-Omicron", "\u03a0-Pi", "\u03a1-Rho", "\u03a3-Sigma", "\u03a4-Tau", "\u03a5-Upsilon",
"\u03a6-Phi", "\u03a7-Chi", "\u03a8-Psi", "\u03a9-Omega", "\u03b1-alpha", "\u03b2-beta", "\u03b3-gamma", "\u03b4-delta", "\u03b5-epsilon", "\u03b6-zeta", "\u03b7-eta", "\u03b8-theta", "\u03b9-iota", "\u03ba-kappa", "\u03bb-lambda", "\u03bc-mu",
"\u03bd-nu", "\u03be-xi", "\u03bf-omicron", "\u03c0-pi", "\u03c1-rho", "\u03c2-sigmaf", "\u03c3-sigma", "\u03c4-tau", "\u03c5-upsilon", "\u03c6-phi", "\u03c7-chi", "\u03c8-psi", "\u03c9-omega", "\u03d1-thetasym", "\u03d2-upsih", "\u03d6-piv",
"\u2002-ensp", "\u2003-emsp", "\u2009-thinsp", "\u200c-zwnj", "\u200d-zwj", "\u200e-lrm", "\u200f-rlm", "\u2013-ndash", "\u2014-mdash", "\u2018-lsquo", "\u2019-rsquo", "\u201a-sbquo", "\u201c-ldquo", "\u201d-rdquo", "\u201e-bdquo", "\u2020-dagger",
"\u2021-Dagger", "\u2022-bull", "\u2026-hellip", "\u2030-permil", "\u2032-prime", "\u2033-Prime", "\u2039-lsaquo", "\u203a-rsaquo", "\u203e-oline", "\u2044-frasl", "\u20ac-euro", "\u2111-image", "\u2118-weierp", "\u211c-real", "\u2122-trade", "\u2135-alefsym",
"\u2190-larr", "\u2191-uarr", "\u2192-rarr", "\u2193-darr", "\u2194-harr", "\u21b5-crarr", "\u21d0-lArr", "\u21d1-uArr", "\u21d2-rArr", "\u21d3-dArr", "\u21d4-hArr", "\u2200-forall", "\u2202-part", "\u2203-exist", "\u2205-empty", "\u2207-nabla",
"\u2208-isin", "\u2209-notin", "\u220b-ni", "\u220f-prod", "\u2211-sum", "\u2212-minus", "\u2217-lowast", "\u221a-radic", "\u221d-prop", "\u221e-infin", "\u2220-ang", "\u2227-and", "\u2228-or", "\u2229-cap", "\u222a-cup", "\u222b-int",
"\u2234-there4", "\u223c-sim", "\u2245-cong", "\u2248-asymp", "\u2260-ne", "\u2261-equiv", "\u2264-le", "\u2265-ge", "\u2282-sub", "\u2283-sup", "\u2284-nsub", "\u2286-sube", "\u2287-supe", "\u2295-oplus", "\u2297-otimes", "\u22a5-perp",
"\u22c5-sdot", "\u2308-lceil", "\u2309-rceil", "\u230a-lfloor", "\u230b-rfloor", "\u2329-lang", "\u232a-rang", "\u25ca-loz", "\u2660-spades", "\u2663-clubs", "\u2665-hearts", "\u2666-diams"
};
for (int i = 0; i < htmlEntities.Length; i++)
{
string current = htmlEntities[i];
htmlEntitiesTable[current.Substring(2)] = current[0];
}
}
}
}
object oChar = htmlEntitiesTable[entity];
if (oChar != null)
return (char) oChar;
return '\0';
}
#endregion Html decoding
#endregion Private methods
}
}
| |
using NUnit.Framework;
using SharpDiff.Core;
using SharpDiff.FileStructure;
namespace SharpDiff.Tests
{
[TestFixture]
public class PatchTests
{
[Test]
public void EmptyFileWithOneAdditionReturnsTheOneLine()
{
var patch = new Patch(
new Diff(null, new[]
{
new Chunk(
new ChunkRange(new ChangeRange(0, 0), new ChangeRange(1, 1)), new[] {
new AdditionSnippet(new[]
{
new AdditionLine("A LINE!")
})
}),
})
);
patch.File = new StubFileAccessor("");
var output = patch.ApplyTo("fake path");
Assert.That(output, Is.EqualTo("A LINE!\r\n")); // didn't specify that it shouldn't end in a newline
}
[Test]
public void EmptyFileWithTwoAdditionReturnsBothLines()
{
var patch = new Patch(
new Diff(null, new[]
{
new Chunk(
new ChunkRange(new ChangeRange(0, 0), new ChangeRange(1, 2)), new[]
{
new AdditionSnippet(new[]
{
new AdditionLine("A LINE!"),
new AdditionLine("Another line!")
})
})
})
);
patch.File = new StubFileAccessor("");
var output = patch.ApplyTo("fake path");
Assert.That(output, Is.EqualTo("A LINE!\r\nAnother line!\r\n")); // didn't specify that it shouldn't end in a newline
}
[Test]
public void TwoLineFileWithOneLineAddedAtTop()
{
var patch = new Patch(
new Diff(null, new[]
{
new Chunk(
new ChunkRange(new ChangeRange(1, 2), new ChangeRange(1, 3)), new ISnippet[]
{
new AdditionSnippet(new[]
{
new AdditionLine("A LINE!"),
}),
new ContextSnippet(new[]
{
new ContextLine("original first line"),
new ContextLine("original second line")
})
})
})
);
// @@ -1,2 +1,3 @@
// +A LINE!
// original first line
// original second line
patch.File = new StubFileAccessor(
"original first line\r\n" +
"original second line\r\n");
var output = patch.ApplyTo("fake path");
Assert.That(output, Is.EqualTo(
"A LINE!\r\n" +
"original first line\r\n" +
"original second line\r\n"));
}
[Test]
public void TwoLineFileWithLastLineRemoved()
{
var patch = new Patch(
new Diff(null, new[]
{
new Chunk(
new ChunkRange(new ChangeRange(1, 2), new ChangeRange(1, 1)), new ISnippet[]
{
new ContextSnippet(new[]
{
new ContextLine("hello")
}),
new SubtractionSnippet(new[]
{
new SubtractionLine("there")
})
}),
})
);
// @@ -1,2 +1,1 @@
// hello
// -there
patch.File = new StubFileAccessor(
"hello\r\n" +
"there\r\n");
var output = patch.ApplyTo("fake path");
Assert.That(output, Is.EqualTo(
"hello\r\n"));
}
[Test]
public void TwoLineFileWithBothLinesRemoved()
{
var patch = new Patch(
new Diff(null, new[]
{
new Chunk(
new ChunkRange(new ChangeRange(1, 2), new ChangeRange(0, 0)), new[]
{
new SubtractionSnippet(new[]
{
new SubtractionLine("hello"),
new SubtractionLine("there")
})
}),
})
);
// @@ -1,2 +0,0 @@
// -hello
// -there
patch.File = new StubFileAccessor(
"hello\r\n" +
"there");
var output = patch.ApplyTo("fake path");
Assert.That(output, Is.EqualTo(""));
}
[Test]
public void AdditionsAndRemovalsInSingleFile()
{
var patch = new Patch(
new Diff(null, new[]
{
new Chunk(
new ChunkRange(new ChangeRange(3, 9), new ChangeRange(3, 12)), new ISnippet[]
{
new ContextSnippet(new[]
{
new ContextLine("this"),
new ContextLine("is"),
new ContextLine("a")
}),
new AdditionSnippet(new[]
{
new AdditionLine("here"),
new AdditionLine("are")
}),
new ContextSnippet(new[]
{
new ContextLine("load"),
new ContextLine("of")
}),
new SubtractionSnippet(new[]
{
new SubtractionLine("new")
}),
new AdditionSnippet(new[]
{
new AdditionLine("some"),
new AdditionLine("additions")
}),
new ContextSnippet(new[]
{
new ContextLine("lines"),
new ContextLine("for"),
new ContextLine("complicating")
})
}),
})
);
//@@ -3,9 +3,12 @@
// this
// is
// a
//+here
//+are
// load
// of
//-new
//+some
//+additions
// lines
// for
// complicating
patch.File = new StubFileAccessor(
"hello\r\n" +
"there\r\n" +
"this\r\n" +
"is\r\n" +
"a\r\n" +
"load\r\n" +
"of\r\n" +
"new\r\n" +
"lines\r\n" +
"for\r\n" +
"complicating\r\n" +
"matters\r\n");
var output = patch.ApplyTo("fake path");
Assert.That(output, Is.EqualTo(
"hello\r\n" +
"there\r\n" +
"this\r\n" +
"is\r\n" +
"a\r\n" +
"here\r\n" +
"are\r\n" +
"load\r\n" +
"of\r\n" +
"some\r\n" +
"additions\r\n" +
"lines\r\n" +
"for\r\n" +
"complicating\r\n" +
"matters\r\n"));
}
}
internal class StubFileAccessor : IFileAccessor
{
private readonly string contents;
public StubFileAccessor(string contents)
{
this.contents = contents;
}
public string ReadAll(string path)
{
return contents;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using TicketTriangle.Data;
using TicketTriangle.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
namespace TicketTriangle.Controllers
{
enum statut
{
Ferme = 3
}
[Authorize]
public class TicketsController : Controller
{
private readonly TicketContext _context;
private readonly ApplicationDbContext _userContext;
public TicketsController(TicketContext context, ApplicationDbContext userContext)
{
_context = context;
_userContext = userContext;
}
// GET: Tickets
public async Task<IActionResult> Index(string sortOrder, string CurrentIdTicketFilter, string CurrentTitreFilter, string CurrentTechnicienFilter, string CurrentStatutFilter, string CurrentTypeFilter, string CurrentCatFilter,
string CurrentPrioFilter, string CurrentUtilisateurFilter, string CurrentDateOuvFilter, string CurrentDernMAJFilter, string CurrentDateCloFilter,
string searchIdTicketString, string searchTitreString, string searchTechnicienString, string searchStatutString, string searchTypeString, string searchCatString, string searchPrioString,
string searchUtilisateurString, string searchDateOuvString, string searchDernMAJString, string searchDateCloString, int? page)
{
#region Filtre
ViewData["CurrentIdTicketFilter"] = searchIdTicketString;
ViewData["CurrentTitreFilter"] = searchTitreString;
ViewData["CurrentTechnicienFilter"] = searchTechnicienString;
ViewData["CurrentStatutFilter"] = searchStatutString;
ViewData["CurrentTypeFilter"] = searchTypeString;
ViewData["CurrentCatFilter"] = searchCatString;
ViewData["CurrentPrioFilter"] = searchPrioString;
ViewData["CurrentUtilisateurFilter"] = searchUtilisateurString;
ViewData["CurrentDateOuvFilter"] = searchDateOuvString;
ViewData["CurrentDernMAJFilter"] = searchDernMAJString;
ViewData["CurrentDateCloFilter"] = searchDateCloString;
var tickets = from t in _context.tickets
.Include(t => t.technicien)
.Include(t => t.utilisateur)
select t;
// Application des filtres
if (!String.IsNullOrEmpty(searchIdTicketString))
{
tickets = tickets.Where(t => t.idTicket.ToString().ToUpper() == searchIdTicketString.ToUpper());
}
if (!String.IsNullOrEmpty(searchTitreString))
{
tickets = tickets.Where(t => t.titre.ToUpper().Contains(searchTitreString.ToUpper()));
}
if (!String.IsNullOrEmpty(searchTechnicienString))
{
tickets = tickets.Where(t => t.technicien != null && t.technicien.login.ToUpper().Contains(searchTechnicienString.ToUpper()));
}
if (!String.IsNullOrEmpty(searchStatutString) && searchStatutString != "0")
{
tickets = tickets.Where(t => t.idStatut.ToString() == searchStatutString);
}
if (!String.IsNullOrEmpty(searchTypeString) && searchTypeString != "0")
{
tickets = tickets.Where(t => t.idTypeTicket.ToString() == searchTypeString);
}
if (!String.IsNullOrEmpty(searchCatString) && searchCatString != "0")
{
tickets = tickets.Where(t => t.idCategorie.ToString() == searchCatString);
}
if (!String.IsNullOrEmpty(searchPrioString) && searchPrioString != "0")
{
tickets = tickets.Where(t => t.idPriorite.ToString() == searchPrioString);
}
if (!String.IsNullOrEmpty(searchUtilisateurString))
{
tickets = tickets.Where(t => t.utilisateur != null && t.utilisateur.login.ToUpper().Contains(searchUtilisateurString.ToUpper()));
}
if (!String.IsNullOrEmpty(searchDateOuvString))
{
tickets = tickets.Where(t => t.dateOuverture.ToString().ToUpper().Contains(searchDateOuvString.ToUpper()));
}
if (!String.IsNullOrEmpty(searchDernMAJString))
{
tickets = tickets.Where(t => t.dateModif.ToString().ToUpper().Contains(searchDernMAJString.ToUpper()));
}
if (!String.IsNullOrEmpty(searchDateCloString))
{
tickets = tickets.Where(t => t.dateCloture.ToString().ToUpper().Contains(searchDateCloString.ToUpper()));
}
#endregion
#region Trie
ViewData["IdTicketSortParam"] = String.IsNullOrEmpty(sortOrder) ? "idTicket_desc" : "";
ViewData["TitreSortParam"] = sortOrder == "titre" ? "titre_desc" : "titre";
ViewData["TechnicienSortParam"] = sortOrder == "technicien" ? "technicien_desc" : "technicien";
ViewData["StatutSortParam"] = sortOrder == "statut" ? "statut_desc" : "statut";
ViewData["TypeSortParam"] = sortOrder == "type" ? "type_desc" : "type";
ViewData["CategorieSortParam"] = sortOrder == "categorie" ? "categorie_desc" : "categorie";
ViewData["PrioriteSortParam"] = sortOrder == "priorite" ? "priorite_desc" : "priorite";
ViewData["UtilisateurSortParam"] = sortOrder == "utilisateur" ? "utilisateur_desc" : "utilisateur";
ViewData["DateOuvertureSortParam"] = sortOrder == "dateOuverture" ? "dateOuverture_desc" : "dateOuverture";
ViewData["DernModifSortParam"] = sortOrder == "dernModif" ? "dernModif_desc" : "dernModif";
ViewData["DateClotureSortParam"] = sortOrder == "dateCloture" ? "dateCloture_desc" : "dateCloture";
ViewData["CurrentSort"] = sortOrder;
//Application du Trie
switch (sortOrder)
{
case "idTicket_desc":
tickets = tickets.OrderByDescending(t => t.idTicket);
break;
case "titre":
tickets = tickets.OrderBy(t => t.titre);
break;
case "titre_desc":
tickets = tickets.OrderByDescending(t => t.titre);
break;
case "technicien":
tickets = tickets.OrderBy(t => t.technicien.login);
break;
case "technicien_desc":
tickets = tickets.OrderByDescending(t => t.technicien.login);
break;
case "statut":
tickets = tickets.OrderBy(t => t.statut.libelleStatut);
break;
case "statut_desc":
tickets = tickets.OrderByDescending(t => t.statut.libelleStatut);
break;
case "type":
tickets = tickets.OrderBy(t => t.typeTicket.libelleTypeTicket);
break;
case "type_desc":
tickets = tickets.OrderByDescending(t => t.typeTicket.libelleTypeTicket);
break;
case "categorie":
tickets = tickets.OrderBy(t => t.categorie.libelleCategorie);
break;
case "categorie_desc":
tickets = tickets.OrderByDescending(t => t.categorie.libelleCategorie);
break;
case "priorite":
tickets = tickets.OrderBy(t => t.priorite.libellePriorite);
break;
case "priorite_desc":
tickets = tickets.OrderByDescending(t => t.priorite.libellePriorite);
break;
case "utilisateur":
tickets = tickets.OrderBy(t => t.utilisateur.login);
break;
case "utilisateur_desc":
tickets = tickets.OrderByDescending(t => t.utilisateur.login);
break;
case "dateOuverture":
tickets = tickets.OrderBy(t => t.dateOuverture);
break;
case "dateOuverture_desc":
tickets = tickets.OrderByDescending(t => t.dateOuverture);
break;
case "dernModif":
tickets = tickets.OrderBy(t => t.dateModif);
break;
case "dernModif_desc":
tickets = tickets.OrderByDescending(t => t.dateModif);
break;
case "dateCloture":
tickets = tickets.OrderBy(t => t.dateCloture);
break;
case "dateCloture_desc":
tickets = tickets.OrderByDescending(t => t.dateCloture);
break;
default:
tickets = tickets.OrderBy(t => t.idTicket);
break;
}
#endregion
#region pagination
if (searchIdTicketString != null || searchTitreString != null || searchTechnicienString != null || searchStatutString != null || searchTypeString != null
|| searchCatString != null || searchPrioString != null || searchUtilisateurString != null || searchDateOuvString != null || searchDernMAJString != null || searchDateCloString != null)
{
page = 1;
}
else
{
searchIdTicketString = CurrentIdTicketFilter;
searchTitreString = CurrentTitreFilter;
searchTechnicienString = CurrentTechnicienFilter;
searchStatutString = CurrentStatutFilter;
searchTypeString = CurrentTypeFilter;
searchCatString = CurrentCatFilter;
searchPrioString = CurrentPrioFilter;
searchUtilisateurString = CurrentUtilisateurFilter;
searchDateOuvString = CurrentDateOuvFilter;
searchDernMAJString = CurrentDernMAJFilter;
searchDateCloString = CurrentDateCloFilter;
}
var ticketContext = tickets.Include(t => t.utilisateur).Include(t => t.categorie).Include(t => t.priorite).Include(t => t.statut).Include(t => t.technicien).Include(t => t.typeTicket);
//return View(await ticketContext.ToListAsync());
int pageSize = 10;
#endregion
#region chargement des listes box
PopulateCategoriesDropDownList(ViewData["CurrentCatFilter"]);
PopulatePrioritesDropDownList(ViewData["CurrentPrioFilter"]);
PopulateTypeTicketsDropDownList(ViewData["CurrentTypeFilter"]);
PopulateStatutsDropDownList(ViewData["CurrentStatutFilter"]);
#endregion
return View(await PaginatedList<Ticket>.CreateAsync(ticketContext.AsNoTracking(), page ?? 1, pageSize));
}
// GET: Tickets/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var ticket = await _context.tickets
.Include(t => t.statut)
.Include(t => t.typeTicket)
.Include(t => t.technicien)
.Include(t => t.utilisateur)
.Include(t => t.priorite)
.Include(t => t.categorie)
.Include(t => t.messages)
.ThenInclude(m => m.utilisateur)
.SingleOrDefaultAsync(m => m.idTicket == id);
if (ticket == null)
{
return NotFound();
}
return View(ticket);
}
// GET: Tickets/Details/5
public async Task<IActionResult> VueUtilisateur(int? id)
{
if (id == null)
{
return NotFound();
}
var utilisateur = await _context.utilisateurs
.SingleOrDefaultAsync(u => u.idUtilisateur == id);
if (utilisateur == null)
{
return NotFound();
}
return View(utilisateur);
}
// POST: Tickets/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost, ActionName("AddMessage")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddMessage(int id, [Bind("idTicket,dateCloture,dateModif,dateOuverture,idCategorie,idPriorite,idStatut,idTechnicien,idTypeTicket,idUtilisateur,titre,messages")] Ticket ticket)
{
if (!string.IsNullOrEmpty(ModelState["messages"].RawValue.ToString()))
{
//ticket = await _context.tickets.Where(m => m.idTicket == id).SingleOrDefaultAsync();
//ticket.dateModif = DateTime.Now;
//_context.Update(ticket);
//await _context.SaveChangesAsync();
Message mess = new Message();
mess.message = ModelState["messages"].RawValue.ToString();
mess.idTicket = id;
mess.dateMessage = DateTime.Now;
_context.Add(mess);
await _context.SaveChangesAsync();
}
await Edit(id, ticket);
return RedirectToAction("Edit", new { id = id });
}
// GET: Tickets/Create
public IActionResult Create()
{
//ViewData["idCategorie"] = new SelectList(_context.categories, "idCategorie", "idCategorie");
//ViewData["idPriorite"] = new SelectList(_context.priorites, "idPriorite", "idPriorite");
//ViewData["idStatut"] = new SelectList(_context.statuts, "idStatut", "idStatut");
//ViewData["idUtilisateur"] = new SelectList(_context.utilisateurs, "idUtilisateur", "idUtilisateur");
//ViewData["idTypeTicket"] = new SelectList(_context.typesTickets, "idTypeTicket", "idTypeTicket");
PopulateCategoriesDropDownList();
PopulatePrioritesDropDownList();
PopulateTypeTicketsDropDownList();
return View();
}
// POST: Tickets/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("idTicket,idCategorie,idPriorite,idTypeTicket,titre,messages")] Ticket ticket)
{
if (ModelState.IsValid)
{
ticket.dateOuverture = DateTime.Now;
ticket.dateModif = ticket.dateOuverture;
ticket.idStatut = 1;
_context.Add(ticket);
await _context.SaveChangesAsync();
int id = ticket.idTicket;
Message mess = new Message();
mess.message = ModelState["messages"].RawValue.ToString();
mess.idTicket = id;
mess.dateMessage = DateTime.Now;
if (!string.IsNullOrEmpty(mess.message))
{
_context.Add(mess);
await _context.SaveChangesAsync();
}
//ticket.messages.Add(message);
return RedirectToAction("Index");
}
//ViewData["idCategorie"] = new SelectList(_context.categories, "idCategorie", "idCategorie", ticket.idCategorie);
//ViewData["idPriorite"] = new SelectList(_context.priorites, "idPriorite", "idPriorite", ticket.idPriorite);
//ViewData["idTypeTicket"] = new SelectList(_context.typesTickets, "idTypeTicket", "idTypeTicket", ticket.idTypeTicket);
//ViewData["titre"] = new SelectList(_context.tickets, "titre", "titre", ticket.titre);
//ViewData["messages"] = new SelectList(_context.tickets, "messages", "messages", ticket.messages);
//ViewData["idStatus"] = new SelectList(_context.statuts, "idStatut", "idStatut", 1);
PopulateCategoriesDropDownList();
PopulatePrioritesDropDownList();
PopulateTypeTicketsDropDownList();
return View(ticket);
}
// GET: Tickets/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var ticket = await _context.tickets
.Include(t => t.statut)
.Include(t => t.typeTicket)
.Include(t => t.technicien)
.Include(t => t.utilisateur)
.Include(t => t.priorite)
.Include(t => t.categorie)
.Include(t => t.messages)
.ThenInclude(m => m.utilisateur)
.SingleOrDefaultAsync(m => m.idTicket == id);
if (ticket == null)
{
return NotFound();
}
ViewData["idTicket"] = new SelectList(_context.tickets, "idTicket", "idTicket", ticket.idTicket);
PopulateCategoriesDropDownList();
PopulatePrioritesDropDownList();
PopulateStatutsDropDownList();
PopulateUtilisateursDropDownList();
PopulateTypeTicketsDropDownList();
PopulateTechniciensDropDownList();
return View(ticket);
}
// POST: Tickets/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("idTicket,dateCloture,dateModif,dateOuverture,idCategorie,idPriorite,idStatut,idTechnicien,idTypeTicket,idUtilisateur,titre")] Ticket ticket)
{
if (id != ticket.idTicket)
{
return NotFound();
}
//Enregistre les modifs
if (ModelState.IsValid)
{
try
{
Ticket oldTicket = _context.tickets.Where(t => t.idTicket == id).AsNoTracking().SingleOrDefault();
if (oldTicket.idStatut == (int?)statut.Ferme)
{
if (ticket.idStatut != (int?)statut.Ferme)
{
oldTicket.idStatut = ticket.idStatut;
oldTicket.dateCloture = null;
}
ticket = oldTicket;
}
ticket.dateModif = DateTime.Now;
ticket.dateOuverture = oldTicket.dateOuverture;
ticket.idUtilisateur = oldTicket.idUtilisateur;
if (ticket.idStatut == (int?)statut.Ferme)
{
ticket.dateCloture = DateTime.Now;
}
_context.Update(ticket);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!TicketExists(ticket.idTicket))
{
return NotFound();
}
else
{
throw;
}
}
//Recupere le contenu du message a ajouter
Message mess = new Message();
mess.message = string.Format("{0}", Request.Form["message"]);// ModelState["@message"].RawValue.ToString();
mess.idTicket = id;
mess.dateMessage = DateTime.Now;
//Ajoute le message si diffferent de null
if (!string.IsNullOrEmpty(mess.message))
{
_context.Add(mess);
await _context.SaveChangesAsync();
}
}
return RedirectToAction("Edit", new { id = id });
//ViewData["idCategorie"] = new SelectList(_context.categories, "idCategorie", "idCategorie", ticket.idCategorie);
//ViewData["idPriorite"] = new SelectList(_context.priorites, "idPriorite", "idPriorite", ticket.idPriorite);
//ViewData["idStatut"] = new SelectList(_context.statuts, "idStatut", "idStatut", ticket.idStatut);
////ViewData["idUtilisateur"] = new SelectList(_context.utilisateurs, "idUtilisateur", "idUtilisateur", ticket.idUtilisateur);
//ViewData["idTypeTicket"] = new SelectList(_context.typesTickets, "idTypeTicket", "idTypeTicket", ticket.idTypeTicket);
//return View(ticket);
}
// GET: Tickets/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var ticket = await _context.tickets.SingleOrDefaultAsync(m => m.idTicket == id);
if (ticket == null)
{
return NotFound();
}
return View(ticket);
}
// POST: Tickets/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var ticket = await _context.tickets.SingleOrDefaultAsync(m => m.idTicket == id);
_context.tickets.Remove(ticket);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
[Authorize(Roles ="Admin")]
public ActionResult Parametre()
{
var paramsVM = new ParamsViewModel()
{
types = _context.typesTickets,
categories = _context.categories,
statuts = _context.statuts,
priorites = _context.priorites,
};
return View(paramsVM);
}
public async Task<IActionResult> updateParams(int id)
{
string param = Request.Form["params"];
string lib = Request.Form["libelle"];
dynamic elem = null;
switch (param)
{
case "priorite":
elem = new Priorite();
elem.idPriorite = id;
elem.libellePriorite = lib;
break;
case "statut":
elem = new Statut();
elem.idStatut = id;
elem.libelleStatut = lib;
break;
case "type":
elem = new TypeTicket();
elem.idTypeTicket = id;
elem.libelleTypeTicket = lib;
break;
case "categorie":
elem = new Categorie();
elem.idCategorie = id;
elem.libelleCategorie = lib;
break;
}
_context.Update(elem);
await _context.SaveChangesAsync();
return RedirectToAction("Parametre");
}
public async Task<IActionResult> deleteParams(int id)
{
string param = Request.Form["params"];
dynamic elem = null;
switch (param)
{
case "priorite":
elem = new Priorite();
elem.idPriorite = id;
break;
case "statut":
elem = new Statut();
elem.idStatut = id;
break;
case "type":
elem = new TypeTicket();
elem.idTypeTicket = id;
break;
case "categorie":
elem = new Categorie();
elem.idCategorie = id;
break;
}
_context.Remove(elem);
await _context.SaveChangesAsync();
return RedirectToAction("Parametre");
}
public async Task<IActionResult> addParams()
{
string param = Request.Form["params"];
string lib = Request.Form["libelle"];
dynamic elem = null;
switch (param)
{
case "priorite":
elem = new Priorite();
elem.libellePriorite = lib;
break;
case "statut":
elem = new Statut();
elem.libelleStatut = lib;
break;
case "type":
elem = new TypeTicket();
elem.libelleTypeTicket = lib;
break;
case "categorie":
elem = new Categorie();
elem.libelleCategorie = lib;
break;
}
_context.Add(elem);
await _context.SaveChangesAsync();
return RedirectToAction("Parametre");
}
private bool TicketExists(int id)
{
return _context.tickets.Any(e => e.idTicket == id);
}
private void PopulateCategoriesDropDownList(object selectedCategories = null)
{
var categoriesQuery = from c in _context.categories
orderby c.libelleCategorie
select c;
ViewBag.idCategorie = new SelectList(categoriesQuery.AsNoTracking(), "idCategorie", "libelleCategorie", selectedCategories);
}
private void PopulatePrioritesDropDownList(object selectedPriorite = null)
{
var prioritesQuery = from p in _context.priorites
orderby p.idPriorite
select p;
ViewBag.idPriorite = new SelectList(prioritesQuery.AsNoTracking(), "idPriorite", "libellePriorite", selectedPriorite);
}
private void PopulateStatutsDropDownList(object selectedStatut = null)
{
var statutQuery = from s in _context.statuts
orderby s.idStatut
select s;
ViewBag.idStatut = new SelectList(statutQuery.AsNoTracking(), "idStatut", "libelleStatut", selectedStatut);
}
private void PopulateUtilisateursDropDownList(object selectedUtilisateur = null)
{
var utilisateurQuery = from u in _context.utilisateurs
orderby u.login
select new SelectListItem
{
Value = u.idUtilisateur.ToString(),
Text = u.nom + " " + u.prenom + " (" + u.login + ")"
};
ViewBag.idUtilisateur = new SelectList(utilisateurQuery.AsNoTracking(), "Value", "Text", selectedUtilisateur);
}
private void PopulateTechniciensDropDownList(object selectedTechnicien = null)
{
var technicienQuery = from t in _context.techniciens
where t.isTech == true
orderby t.login
select new SelectListItem
{
Value = t.idUtilisateur.ToString(),
Text = t.nom + " " + t.prenom + " (" + t.login + ")"
};
ViewBag.idTechnicien = new SelectList(technicienQuery.AsNoTracking(), "Value", "Text", selectedTechnicien);
}
private void PopulateTypeTicketsDropDownList(object selectedTypeTicket = null)
{
var typeTickectQuery = from t in _context.typesTickets
orderby t.libelleTypeTicket
select t;
ViewBag.idTypeTicket = new SelectList(typeTickectQuery.AsNoTracking(), "idTypeTicket", "libelleTypeTicket", selectedTypeTicket);
}
[Authorize(Roles = "Admin")]
public ActionResult Utilisateurs()
{
var users = _userContext.Users.Include(u => u.Roles);
//var techs = _roleManager.Roles.Where(r => r.Name == "Technicien").SingleOrDefault().Users;
var techRoleID = _userContext.Roles.Where(r => r.Name == "Technicien").SingleOrDefault().Id;
var adminRoleID = _userContext.Roles.Where(r => r.Name == "Admin").SingleOrDefault().Id;
var techs = users.Where(u => u.Roles.Any(r => r.RoleId == techRoleID) );
var admins = users.Where(u => u.Roles.Any(r => r.RoleId == adminRoleID));
//var techs = _userManager.Users.Where(u => u.Roles.Contains(techRole)).ToList();
var userModel = new UsersViewModel() {
utilisateurs = users,
techniciens = techs,
administrateurs = admins
};
return View(userModel);
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.POIFS.FileSystem
{
using System;
using System.IO;
using NPOI.Util;
/**
* Represents an Ole10Native record which is wrapped around certain binary
* files being embedded in OLE2 documents.
*
* @author Rainer Schwarze
*/
internal class Ole10Native
{
// (the fields as they appear in the raw record:)
private int totalSize; // 4 bytes, total size of record not including this field
private short flags1; // 2 bytes, unknown, mostly [02 00]
private String label; // ASCIIZ, stored in this field without the terminating zero
private String fileName; // ASCIIZ, stored in this field without the terminating zero
private short flags2; // 2 bytes, unknown, mostly [00 00]
// private byte unknown1Length; // 1 byte, specifying the length of the following byte array (unknown1)
private byte[] unknown1; // see below
private byte[] unknown2; // 3 bytes, unknown, mostly [00 00 00]
private String command; // ASCIIZ, stored in this field without the terminating zero
private int dataSize; // 4 bytes (if space), size of following buffer
private byte[] dataBuffer; // varying size, the actual native data
private short flags3; // some flags? or zero terminators?, sometimes not there
public static String OLE10_NATIVE = "\x0001Ole10Native";
/**
* Creates an instance of this class from an embedded OLE Object. The OLE Object is expected
* to include a stream "{01}Ole10Native" which Contains the actual
* data relevant for this class.
*
* @param poifs POI Filesystem object
* @return Returns an instance of this class
* @throws IOException on IO error
* @throws Ole10NativeException on invalid or unexcepted data format
*/
public static Ole10Native CreateFromEmbeddedOleObject(POIFSFileSystem poifs)
{
bool plain = false;
try
{
poifs.Root.GetEntry("\x0001Ole10ItemName");
plain = true;
}
catch (FileNotFoundException)
{
plain = false;
}
DocumentInputStream dis = poifs.CreateDocumentInputStream(OLE10_NATIVE);
using (MemoryStream bos = new MemoryStream())
{
IOUtils.Copy(dis, bos);
byte[] data = bos.ToArray();
return new Ole10Native(data, 0, plain);
}
}
/**
* Creates an instance and Fills the fields based on the data in the given buffer.
*
* @param data The buffer Containing the Ole10Native record
* @param offset The start offset of the record in the buffer
* @throws Ole10NativeException on invalid or unexcepted data format
*/
public Ole10Native(byte[] data, int offset):this(data, offset, false)
{
}
/**
* Creates an instance and Fills the fields based on the data in the given buffer.
*
* @param data The buffer Containing the Ole10Native record
* @param offset The start offset of the record in the buffer
* @param plain Specified 'plain' format without filename
* @throws Ole10NativeException on invalid or unexcepted data format
*/
public Ole10Native(byte[] data, int offset, bool plain)
{
int ofs = offset; // current offset, Initialized to start
if (data.Length < offset + 2)
{
throw new Ole10NativeException("data is too small");
}
totalSize = LittleEndian.GetInt(data, ofs);
ofs += LittleEndianConsts.INT_SIZE;
if (plain)
{
dataBuffer = new byte[totalSize - 4];
Array.Copy(data, 4, dataBuffer, 0, dataBuffer.Length);
dataSize = totalSize - 4;
byte[] oleLabel = new byte[8];
Array.Copy(dataBuffer, 0, oleLabel, 0, Math.Min(dataBuffer.Length, 8));
label = "ole-" + HexDump.ToHex(oleLabel);
fileName = label;
command = label;
}
else
{
flags1 = LittleEndian.GetShort(data, ofs);
ofs += LittleEndianConsts.SHORT_SIZE;
int len = GetStringLength(data, ofs);
label = StringUtil.GetFromCompressedUnicode(data, ofs, len - 1);
ofs += len;
len = GetStringLength(data, ofs);
fileName = StringUtil.GetFromCompressedUnicode(data, ofs, len - 1);
ofs += len;
flags2 = LittleEndian.GetShort(data, ofs);
ofs += LittleEndianConsts.SHORT_SIZE;
len = LittleEndian.GetUnsignedByte(data, ofs);
unknown1 = new byte[len];
ofs += len;
len = 3;
unknown2 = new byte[len];
ofs += len;
len = GetStringLength(data, ofs);
command = StringUtil.GetFromCompressedUnicode(data, ofs, len - 1);
ofs += len;
if (totalSize + LittleEndianConsts.INT_SIZE - ofs > LittleEndianConsts.INT_SIZE)
{
dataSize = LittleEndian.GetInt(data, ofs);
ofs += LittleEndianConsts.INT_SIZE;
if (dataSize > totalSize || dataSize < 0)
{
throw new Ole10NativeException("Invalid Ole10Native");
}
dataBuffer = new byte[dataSize];
Array.Copy(data, ofs, dataBuffer, 0, dataSize);
ofs += dataSize;
if (unknown1.Length > 0)
{
flags3 = LittleEndian.GetShort(data, ofs);
ofs += LittleEndianConsts.SHORT_SIZE;
}
else
{
flags3 = 0;
}
}
else
{
throw new Ole10NativeException("Invalid Ole10Native");
}
}
}
/*
* Helper - determine length of zero terminated string (ASCIIZ).
*/
private static int GetStringLength(byte[] data, int ofs)
{
int len = 0;
while (len + ofs < data.Length && data[ofs + len] != 0)
{
len++;
}
len++;
return len;
}
/**
* Returns the value of the totalSize field - the total length of the structure
* is totalSize + 4 (value of this field + size of this field).
*
* @return the totalSize
*/
public int TotalSize
{
get
{
return totalSize;
}
}
/**
* Returns flags1 - currently unknown - usually 0x0002.
*
* @return the flags1
*/
public short GetFlags1()
{
return flags1;
}
/**
* Returns the label field - usually the name of the file (without directory) but
* probably may be any name specified during packaging/embedding the data.
*
* @return the label
*/
public String GetLabel()
{
return label;
}
/**
* Returns the fileName field - usually the name of the file being embedded
* including the full path.
*
* @return the fileName
*/
public String GetFileName()
{
return fileName;
}
/**
* Returns flags2 - currently unknown - mostly 0x0000.
*
* @return the flags2
*/
public short GetFlags2()
{
return flags2;
}
/**
* Returns unknown1 field - currently unknown.
*
* @return the unknown1
*/
public byte[] GetUnknown1()
{
return unknown1;
}
/**
* Returns the unknown2 field - currently being a byte[3] - mostly {0, 0, 0}.
*
* @return the unknown2
*/
public byte[] GetUnknown2()
{
return unknown2;
}
/**
* Returns the command field - usually the name of the file being embedded
* including the full path, may be a command specified during embedding the file.
*
* @return the command
*/
public String GetCommand()
{
return command;
}
/**
* Returns the size of the embedded file. If the size is 0 (zero), no data has been
* embedded. To be sure, that no data has been embedded, check whether
* {@link #getDataBuffer()} returns <code>null</code>.
*
* @return the dataSize
*/
public int GetDataSize()
{
return dataSize;
}
/**
* Returns the buffer Containing the embedded file's data, or <code>null</code>
* if no data was embedded. Note that an embedding may provide information about
* the data, but the actual data is not included. (So label, filename etc. are
* available, but this method returns <code>null</code>.)
*
* @return the dataBuffer
*/
public byte[] GetDataBuffer()
{
return dataBuffer;
}
/**
* Returns the flags3 - currently unknown.
*
* @return the flags3
*/
public short GetFlags3()
{
return flags3;
}
}
}
| |
// 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.Xml.Linq;
using Microsoft.CodeAnalysis.Editor.Commands;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Operations;
using Roslyn.Test.Utilities;
using Xunit;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.Editor.UnitTests
{
internal abstract class AbstractCommandHandlerTestState : IDisposable
{
public readonly TestWorkspace Workspace;
public readonly IEditorOperations EditorOperations;
public readonly ITextUndoHistoryRegistry UndoHistoryRegistry;
private readonly ITextView _textView;
private readonly ITextBuffer _subjectBuffer;
public AbstractCommandHandlerTestState(
XElement workspaceElement,
ComposableCatalog extraParts = null,
bool useMinimumCatalog = false,
string workspaceKind = null)
: this(workspaceElement, GetExportProvider(useMinimumCatalog, extraParts), workspaceKind)
{
}
/// <summary>
/// This can use input files with an (optionally) annotated span 'Selection' and a cursor position ($$),
/// and use it to create a selected span in the TextView.
///
/// For instance, the following will create a TextView that has a multiline selection with the cursor at the end.
///
/// Sub Foo
/// {|Selection:SomeMethodCall()
/// AnotherMethodCall()$$|}
/// End Sub
/// </summary>
public AbstractCommandHandlerTestState(
XElement workspaceElement,
ExportProvider exportProvider,
string workspaceKind)
{
this.Workspace = TestWorkspaceFactory.CreateWorkspace(
workspaceElement,
exportProvider: exportProvider,
workspaceKind: workspaceKind);
var cursorDocument = this.Workspace.Documents.First(d => d.CursorPosition.HasValue);
_textView = cursorDocument.GetTextView();
_subjectBuffer = cursorDocument.GetTextBuffer();
IList<Text.TextSpan> selectionSpanList;
if (cursorDocument.AnnotatedSpans.TryGetValue("Selection", out selectionSpanList))
{
var span = selectionSpanList.First();
var cursorPosition = cursorDocument.CursorPosition.Value;
Assert.True(cursorPosition == span.Start || cursorPosition == span.Start + span.Length,
"cursorPosition wasn't at an endpoint of the 'Selection' annotated span");
_textView.Selection.Select(
new SnapshotSpan(_subjectBuffer.CurrentSnapshot, new Span(span.Start, span.Length)),
isReversed: cursorPosition == span.Start);
if (selectionSpanList.Count > 1)
{
_textView.Selection.Mode = TextSelectionMode.Box;
foreach (var additionalSpan in selectionSpanList.Skip(1))
{
_textView.Selection.Select(
new SnapshotSpan(_subjectBuffer.CurrentSnapshot, new Span(additionalSpan.Start, additionalSpan.Length)),
isReversed: false);
}
}
}
else
{
_textView.Caret.MoveTo(
new SnapshotPoint(
_textView.TextBuffer.CurrentSnapshot,
cursorDocument.CursorPosition.Value));
}
this.EditorOperations = GetService<IEditorOperationsFactoryService>().GetEditorOperations(_textView);
this.UndoHistoryRegistry = GetService<ITextUndoHistoryRegistry>();
}
public void Dispose()
{
Workspace.Dispose();
}
public T GetService<T>()
{
return Workspace.GetService<T>();
}
private static ExportProvider GetExportProvider(bool useMinimumCatalog, ComposableCatalog extraParts)
{
var baseCatalog = useMinimumCatalog
? TestExportProvider.MinimumCatalogWithCSharpAndVisualBasic
: TestExportProvider.EntireAssemblyCatalogWithCSharpAndVisualBasic;
if (extraParts == null)
{
return MinimalTestExportProvider.CreateExportProvider(baseCatalog);
}
return MinimalTestExportProvider.CreateExportProvider(baseCatalog.WithParts(extraParts));
}
public virtual ITextView TextView
{
get { return _textView; }
}
public virtual ITextBuffer SubjectBuffer
{
get { return _subjectBuffer; }
}
#region MEF
public Lazy<TExport, TMetadata> GetExport<TExport, TMetadata>()
{
return (Lazy<TExport, TMetadata>)(object)Workspace.ExportProvider.GetExport<TExport, TMetadata>();
}
public IEnumerable<Lazy<TExport, TMetadata>> GetExports<TExport, TMetadata>()
{
return Workspace.ExportProvider.GetExports<TExport, TMetadata>();
}
public T GetExportedValue<T>()
{
return Workspace.ExportProvider.GetExportedValue<T>();
}
public IEnumerable<T> GetExportedValues<T>()
{
return Workspace.ExportProvider.GetExportedValues<T>();
}
protected static IEnumerable<Lazy<TProvider, OrderableLanguageMetadata>> CreateLazyProviders<TProvider>(
TProvider[] providers,
string languageName)
{
if (providers == null)
{
return Array.Empty<Lazy<TProvider, OrderableLanguageMetadata>>();
}
return providers.Select(p =>
new Lazy<TProvider, OrderableLanguageMetadata>(
() => p,
new OrderableLanguageMetadata(
new Dictionary<string, object> {
{"Language", languageName },
{"Name", string.Empty }}),
true));
}
protected static IEnumerable<Lazy<TProvider, OrderableLanguageAndRoleMetadata>> CreateLazyProviders<TProvider>(
TProvider[] providers,
string languageName,
string[] roles)
{
if (providers == null)
{
return Array.Empty<Lazy<TProvider, OrderableLanguageAndRoleMetadata>>();
}
return providers.Select(p =>
new Lazy<TProvider, OrderableLanguageAndRoleMetadata>(
() => p,
new OrderableLanguageAndRoleMetadata(
new Dictionary<string, object> {
{"Language", languageName },
{"Name", string.Empty },
{"Roles", roles }}),
true));
}
#endregion
#region editor related operation
public void SendBackspace()
{
EditorOperations.Backspace();
}
public void SendDelete()
{
EditorOperations.Delete();
}
public void SendRightKey(bool extendSelection = false)
{
EditorOperations.MoveToNextCharacter(extendSelection);
}
public void SendLeftKey(bool extendSelection = false)
{
EditorOperations.MoveToPreviousCharacter(extendSelection);
}
public void SendMoveToPreviousCharacter(bool extendSelection = false)
{
EditorOperations.MoveToPreviousCharacter(extendSelection);
}
public void SendDeleteWordToLeft()
{
EditorOperations.DeleteWordToLeft();
}
public void SendUndo(int count = 1)
{
var history = UndoHistoryRegistry.GetHistory(SubjectBuffer);
history.Undo(count);
}
#endregion
#region test/information/verification
public ITextSnapshotLine GetLineFromCurrentCaretPosition()
{
var caretPosition = GetCaretPoint();
return SubjectBuffer.CurrentSnapshot.GetLineFromPosition(caretPosition.BufferPosition);
}
public string GetLineTextFromCaretPosition()
{
var caretPosition = Workspace.Documents.Single(d => d.CursorPosition.HasValue).CursorPosition.Value;
return SubjectBuffer.CurrentSnapshot.GetLineFromPosition(caretPosition).GetText();
}
public string GetDocumentText()
{
return SubjectBuffer.CurrentSnapshot.GetText();
}
public CaretPosition GetCaretPoint()
{
return TextView.Caret.Position;
}
/// <summary>
/// Used in synchronous methods to ensure all outstanding <see cref="IAsyncToken"/> work has been
/// completed.
/// </summary>
public void AssertNoAsynchronousOperationsRunning()
{
var waiters = Workspace.ExportProvider.GetExportedValues<IAsynchronousOperationWaiter>();
Assert.False(waiters.Any(x => x.HasPendingWork), "IAsyncTokens unexpectedly alive. Call WaitForAsynchronousOperationsAsync before this method");
}
public async Task WaitForAsynchronousOperationsAsync()
{
var waiters = Workspace.ExportProvider.GetExportedValues<IAsynchronousOperationWaiter>();
await waiters.WaitAllAsync();
}
public void AssertMatchesTextStartingAtLine(int line, string text)
{
var lines = text.Split('\r');
foreach (var expectedLine in lines)
{
Assert.Equal(expectedLine.Trim(), SubjectBuffer.CurrentSnapshot.GetLineFromLineNumber(line).GetText().Trim());
line += 1;
}
}
#endregion
#region command handler
public void SendBackspace(Action<BackspaceKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new BackspaceKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendDelete(Action<DeleteKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new DeleteKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendWordDeleteToStart(Action<WordDeleteToStartCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new WordDeleteToStartCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendEscape(Action<EscapeKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new EscapeKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendUpKey(Action<UpKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new UpKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendDownKey(Action<DownKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new DownKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendTab(Action<TabKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new TabKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendBackTab(Action<BackTabKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new BackTabKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendReturn(Action<ReturnKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new ReturnKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendPageUp(Action<PageUpKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new PageUpKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendPageDown(Action<PageDownKeyCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new PageDownKeyCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendCut(Action<CutCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new CutCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendPaste(Action<PasteCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new PasteCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendInvokeCompletionList(Action<InvokeCompletionListCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new InvokeCompletionListCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendCommitUniqueCompletionListItem(Action<CommitUniqueCompletionListItemCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new CommitUniqueCompletionListItemCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendInsertSnippetCommand(Action<InsertSnippetCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new InsertSnippetCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendSurroundWithCommand(Action<SurroundWithCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new SurroundWithCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendInvokeSignatureHelp(Action<InvokeSignatureHelpCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new InvokeSignatureHelpCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendTypeChar(char typeChar, Action<TypeCharCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new TypeCharCommandArgs(TextView, SubjectBuffer, typeChar), nextHandler);
}
public void SendTypeChars(string typeChars, Action<TypeCharCommandArgs, Action> commandHandler)
{
foreach (var ch in typeChars)
{
var localCh = ch;
SendTypeChar(ch, commandHandler, () => EditorOperations.InsertText(localCh.ToString()));
}
}
public void SendSave(Action<SaveCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new SaveCommandArgs(TextView, SubjectBuffer), nextHandler);
}
public void SendSelectAll(Action<SelectAllCommandArgs, Action> commandHandler, Action nextHandler)
{
commandHandler(new SelectAllCommandArgs(TextView, SubjectBuffer), nextHandler);
}
#endregion
}
}
| |
//
// The MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
namespace Sidekick.SpacedRepetition.Extensions
{
using System;
using Sidekick.Shared.Extensions;
using Sidekick.Shared.Utils;
using Sidekick.SpacedRepetition.Models;
/// <summary>Card review-computations-related extension methods.</summary>
public static class CardReviewExtensions
{
#region Learning
/// <summary>Graduate from learning into due state.</summary>
/// <param name="card">Card instance.</param>
/// <param name="easy">whether answer was graded 'easy'</param>
public static CardAction Graduate(this Card card, bool easy = false)
{
if (card.IsDue())
throw new InvalidOperationException("Card.Graduate invoked with card 'Due' state");
// Regraduating
if (card.Lapses > 0)
card.Interval = Math.Max(
card.Config.LapseMinInterval, (int)(card.Config.LapseIntervalFactor * card.Interval));
// Graduating for the first time
else
{
card.Interval = easy
? card.Config.GraduationEasyInterval
: card.Config.GraduationInterval;
card.EFactor = card.Config.GraduationStartingEase;
}
card.SetDueFromInterval();
card.SetDueState();
return CardAction.Update;
}
/// <summary>
/// Either setup lapsing/learning steps (if reset is set to true), move on to next step,
/// or graduate.
/// </summary>
/// <param name="card">Card instance.</param>
/// <param name="reset">if true, set learning state and lapsing or learning first step.</param>
public static CardAction UpdateLearningStep(this Card card, bool reset = false)
{
// Set learning mode and first step delay
if (reset)
{
card.SetDue(card.LearningOrLapsingSteps[0]);
card.SetLearningState();
}
else if (card.IsDue())
throw new InvalidOperationException(
"Card.UpdateLearningStep invoked with " + nameof(reset)
+ " parameter 'false' and card 'Due' state");
// Graduate
else if (card.IsGraduating())
card.Graduate();
// Move on to next step
else
card.SetDue(card.LearningOrLapsingSteps[card.IncreaseLearningStep()]);
return CardAction.Update;
}
/// <summary>Determines whether current lapsing or learning step is graduating.</summary>
/// <param name="card">Card instance.</param>
/// <returns>Whether current step is graduating</returns>
public static bool IsGraduating(this Card card)
{
if (card.IsDue())
return false;
return card.GetCurrentLearningIndex() >= card.LearningOrLapsingSteps.Length - 1;
}
/// <summary>
/// Increment learning step index, and return new value. Accounts for PracticeState
/// offset.
/// </summary>
/// <param name="card">Card instance.</param>
/// <returns>New step index</returns>
public static int IncreaseLearningStep(this Card card)
{
card.PracticeState++;
return card.GetCurrentLearningIndex();
}
/// <summary>
/// Get current lapsing or learning step index. In the occurence steps settings changed,
/// closest inferior value index is returned. Accounts for PracticeState offset.
/// </summary>
/// <param name="card">Card instance.</param>
/// <returns>Current lapsing or learning index</returns>
public static int GetCurrentLearningIndex(this Card card)
{
if (!card.IsLearning())
throw new InvalidOperationException("Invalid call for State " + card.PracticeState);
// Account for possible config changes
return Math.Min(
card.PracticeState - PracticeState.Learning, card.LearningOrLapsingSteps.Length - 1);
}
/// <summary>Computes review count to graduation. Accounts for PracticeState offset.</summary>
/// <param name="card">Card instance.</param>
/// <returns>Review count to graduation</returns>
/// <exception cref="System.InvalidOperationException">Invalid call for State + PracticeState</exception>
public static int GetLearningStepsLeft(this Card card)
{
if (!card.IsLearning())
throw new InvalidOperationException("Invalid call for State " + card.PracticeState);
return card.LearningOrLapsingSteps.Length - card.GetCurrentLearningIndex();
}
/// <summary>Switch card State to Learning, while retaining misc states.</summary>
/// <param name="card">Card instance.</param>
public static void SetLearningState(this Card card)
{
card.PracticeState = PracticeState.Learning;
}
public static bool IsNew(this Card card)
{
return card.PracticeState == PracticeState.New;
}
public static bool IsLearning(this Card card)
{
return card.PracticeState >= PracticeState.Learning;
}
#endregion
#region Due
/// <summary>Process fail-graded answers for due cards.</summary>
/// <param name="card">Card instance.</param>
/// <param name="grade">Fail grade</param>
public static CardAction Lapse(this Card card, Grade grade)
{
if (grade > Grade.Fail)
throw new ArgumentException("Card.Lapse invoked with invalid grade", nameof(grade));
card.Lapses++;
// TODO: Handle extended grading options
card.EFactor += grade.ReviewEaseModifiers(card.Config);
card.UpdateLearningStep(true);
if (card.IsLeech())
return card.Leech();
return CardAction.Update;
}
/// <summary>
/// Process instances where lapse threshold rules are met and card turns into Leech. Take
/// action accordingly to preferences (suspend or delete card).
/// </summary>
/// <param name="card">Card instance.</param>
public static CardAction Leech(this Card card)
{
switch (card.Config.LeechAction)
{
case CardLeechAction.Suspend:
card.SetSuspendedState();
return CardAction.Update;
case CardLeechAction.Delete:
return CardAction.Delete;
}
throw new ArgumentException("Card.Leech invoked with invalid LeechAction setting");
}
/// <summary>Determines whether lapse threshold rules are met and card leech.</summary>
/// <param name="card">Card instance.</param>
/// <returns>Whether card is a leech</returns>
public static bool IsLeech(this Card card)
{
return card.Config.LeechThreshold > 0 && card.Lapses >= card.Config.LeechThreshold
&& card.Lapses % (int)Math.Ceiling(card.Config.LeechThreshold / 2.0f) == 0;
}
/// <summary>Process pass-graded answers for due cards.</summary>
/// <param name="card">Card instance.</param>
/// <param name="grade">Pass grade</param>
public static CardAction Review(this Card card, Grade grade)
{
if (grade < Grade.Hard)
throw new ArgumentException("Card.Review invoked with invalid grade", nameof(grade));
// Interval computing must happen prior to EFactor update
card.Interval = card.ComputeReviewInterval(grade);
card.EFactor += grade.ReviewEaseModifiers(card.Config);
card.SetDueFromInterval();
return CardAction.Update;
}
/// <summary>Computes the new interval.</summary>
/// <param name="card">Card instance.</param>
/// <param name="grade">The grade.</param>
/// <returns></returns>
public static int ComputeReviewInterval(this Card card, Grade grade)
{
int daysLate = Math.Max(0, (DateTime.Now - card.DueDateTime).Days);
int newInterval = grade.GradeReviewIntervalFormulas(card.Config)(
card.Interval, daysLate, card.EFactor);
return Math.Max(RandomizeInterval(newInterval), card.Interval + 1);
}
/// <summary>Adds some randomness to interval computation.</summary>
/// <param name="interval">The interval.</param>
/// <returns></returns>
public static int RandomizeInterval(int interval)
{
int[] rndRange;
if (interval < 2)
return interval;
if (interval == 2)
rndRange = new[] { 2, 3 };
else
{
float rnd;
if (interval < 7)
rnd = Math.Max(1, interval * 0.25f);
else if (interval < 30)
rnd = Math.Max(2, interval * 0.15f);
else
rnd = Math.Max(4, interval * 0.05f);
rndRange = new[] { interval - (int)rnd, interval + (int)rnd };
}
return new Random().Next(rndRange[0], rndRange[1] + 1);
}
/// <summary>Sets card State to Suspended, while retaining main state.</summary>
/// <param name="card">Card instance.</param>
public static void SetSuspendedState(this Card card)
{
card.MiscState |= CardMiscStateFlag.Suspended;
}
/// <summary>Switch card State to Due, while retaining misc states.</summary>
/// <param name="card">Card instance.</param>
public static void SetDueState(this Card card)
{
card.PracticeState = PracticeState.Due;
}
public static bool IsDue(this Card card)
{
return card.PracticeState == PracticeState.Due;
}
#endregion
#region Misc
public static int ReviewLeftToday(this Card card)
{
if (card.Due >= DateTimeExtensions.Tomorrow.ToUnixTimestamp())
return 0;
switch (card.PracticeState)
{
case PracticeState.New:
return 1;
case PracticeState.Due:
return 1;
case PracticeState.Deleted: // Leech option
return 0;
}
if (card.IsLearning())
return card.GetLearningStepsLeft();
throw new InvalidOperationException("Invalid card state");
}
/// <summary>Build Due time from Interval (which unit is days).</summary>
/// <param name="card">Card instance.</param>
public static void SetDueFromInterval(this Card card)
{
card.SetDue(Delay.FromDays(card.Interval));
}
/// <summary>Build Due time respectively from given Delay and current review time.</summary>
/// <param name="card">Card instance.</param>
/// <param name="delay">The delay</param>
public static void SetDue(this Card card, Delay delay)
{
card.Due = card.CurrentReviewTime + delay;
}
public static bool IsDismissed(this Card card)
{
return (card.MiscState & CardMiscStateFlag.Dismissed) == CardMiscStateFlag.Dismissed;
}
public static bool IsSuspended(this Card card)
{
return (card.MiscState & CardMiscStateFlag.Suspended) == CardMiscStateFlag.Suspended;
}
#if false
public static int ComputeReviewCount( // TODO: This may be useful at some point
ConstSpacedRepetition.PracticeState state,
CollectionConfig config, ConstSpacedRepetition.Grade grade)
{
switch (state)
{
case ConstSpacedRepetition.PracticeState.New:
return grade == ConstSpacedRepetition.Grade.Easy
? 1
: config.LearningSteps.Length;
case ConstSpacedRepetition.PracticeState.Due:
return grade == ConstSpacedRepetition.Grade.Easy
? 1
: config.LearningSteps.Length;
case ConstSpacedRepetition.PracticeState.Learning:
return grade == ConstSpacedRepetition.Grade.Easy
? 1
: config.LearningSteps.Length;
}
/*
(grade == ConstSpacedRepetition.Grade.Easy
? newCards : newCards * config.LearningSteps.Length)
+ (grade == ConstSpacedRepetition.Grade.Easy
? learnCards : learnCards * config.LearningSteps.Length)
+ (grade == ConstSpacedRepetition.Grade.Easy
? lapsingCards : lapsingCards * config.LapseSteps.Length)
+ dueCards;
*/
}
#endif
#endregion
}
}
| |
/*
* Farseer Physics Engine:
* Copyright (c) 2012 Ian Qvist
*
* Original source Box2D:
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using System;
using System.Diagnostics;
using FarseerPhysics.Collision;
using FarseerPhysics.Common;
using Microsoft.Xna.Framework;
namespace FarseerPhysics.Dynamics.Contacts
{
public sealed class ContactPositionConstraint
{
public Vector2[] localPoints = new Vector2[Settings.maxManifoldPoints];
public Vector2 localNormal;
public Vector2 localPoint;
public int indexA;
public int indexB;
public float invMassA, invMassB;
public Vector2 localCenterA, localCenterB;
public float invIA, invIB;
public ManifoldType type;
public float radiusA, radiusB;
public int pointCount;
}
public sealed class VelocityConstraintPoint
{
public Vector2 rA;
public Vector2 rB;
public float normalImpulse;
public float tangentImpulse;
public float normalMass;
public float tangentMass;
public float velocityBias;
}
public sealed class ContactVelocityConstraint
{
public VelocityConstraintPoint[] points = new VelocityConstraintPoint[Settings.maxManifoldPoints];
public Vector2 normal;
public Mat22 normalMass;
public Mat22 K;
public int indexA;
public int indexB;
public float invMassA, invMassB;
public float invIA, invIB;
public float friction;
public float restitution;
public float tangentSpeed;
public int pointCount;
public int contactIndex;
public ContactVelocityConstraint()
{
for( int i = 0; i < Settings.maxManifoldPoints; i++ )
{
points[i] = new VelocityConstraintPoint();
}
}
}
public class ContactSolver
{
public TimeStep _step;
public Position[] _positions;
public Velocity[] _velocities;
public ContactPositionConstraint[] _positionConstraints;
public ContactVelocityConstraint[] _velocityConstraints;
public Contact[] _contacts;
public int _count;
public void reset( TimeStep step, int count, Contact[] contacts, Position[] positions, Velocity[] velocities )
{
_step = step;
_count = count;
_positions = positions;
_velocities = velocities;
_contacts = contacts;
// grow the array
if( _velocityConstraints == null || _velocityConstraints.Length < count )
{
_velocityConstraints = new ContactVelocityConstraint[count * 2];
_positionConstraints = new ContactPositionConstraint[count * 2];
for( int i = 0; i < _velocityConstraints.Length; i++ )
{
_velocityConstraints[i] = new ContactVelocityConstraint();
}
for( int i = 0; i < _positionConstraints.Length; i++ )
{
_positionConstraints[i] = new ContactPositionConstraint();
}
}
// Initialize position independent portions of the constraints.
for( int i = 0; i < _count; ++i )
{
var contact = contacts[i];
var fixtureA = contact.fixtureA;
var fixtureB = contact.fixtureB;
var shapeA = fixtureA.shape;
var shapeB = fixtureB.shape;
var radiusA = shapeA.radius;
var radiusB = shapeB.radius;
var bodyA = fixtureA.body;
var bodyB = fixtureB.body;
var manifold = contact.manifold;
var pointCount = manifold.pointCount;
Debug.Assert( pointCount > 0 );
var vc = _velocityConstraints[i];
vc.friction = contact.friction;
vc.restitution = contact.restitution;
vc.tangentSpeed = contact.tangentSpeed;
vc.indexA = bodyA.islandIndex;
vc.indexB = bodyB.islandIndex;
vc.invMassA = bodyA._invMass;
vc.invMassB = bodyB._invMass;
vc.invIA = bodyA._invI;
vc.invIB = bodyB._invI;
vc.contactIndex = i;
vc.pointCount = pointCount;
vc.K.SetZero();
vc.normalMass.SetZero();
var pc = _positionConstraints[i];
pc.indexA = bodyA.islandIndex;
pc.indexB = bodyB.islandIndex;
pc.invMassA = bodyA._invMass;
pc.invMassB = bodyB._invMass;
pc.localCenterA = bodyA._sweep.localCenter;
pc.localCenterB = bodyB._sweep.localCenter;
pc.invIA = bodyA._invI;
pc.invIB = bodyB._invI;
pc.localNormal = manifold.localNormal;
pc.localPoint = manifold.localPoint;
pc.pointCount = pointCount;
pc.radiusA = radiusA;
pc.radiusB = radiusB;
pc.type = manifold.type;
for( int j = 0; j < pointCount; ++j )
{
var cp = manifold.points[j];
var vcp = vc.points[j];
if( Settings.enableWarmstarting )
{
vcp.normalImpulse = _step.dtRatio * cp.normalImpulse;
vcp.tangentImpulse = _step.dtRatio * cp.tangentImpulse;
}
else
{
vcp.normalImpulse = 0.0f;
vcp.tangentImpulse = 0.0f;
}
vcp.rA = Vector2.Zero;
vcp.rB = Vector2.Zero;
vcp.normalMass = 0.0f;
vcp.tangentMass = 0.0f;
vcp.velocityBias = 0.0f;
pc.localPoints[j] = cp.localPoint;
}
}
}
public void initializeVelocityConstraints()
{
for( int i = 0; i < _count; ++i )
{
ContactVelocityConstraint vc = _velocityConstraints[i];
ContactPositionConstraint pc = _positionConstraints[i];
float radiusA = pc.radiusA;
float radiusB = pc.radiusB;
Manifold manifold = _contacts[vc.contactIndex].manifold;
int indexA = vc.indexA;
int indexB = vc.indexB;
float mA = vc.invMassA;
float mB = vc.invMassB;
float iA = vc.invIA;
float iB = vc.invIB;
Vector2 localCenterA = pc.localCenterA;
Vector2 localCenterB = pc.localCenterB;
Vector2 cA = _positions[indexA].c;
float aA = _positions[indexA].a;
Vector2 vA = _velocities[indexA].v;
float wA = _velocities[indexA].w;
Vector2 cB = _positions[indexB].c;
float aB = _positions[indexB].a;
Vector2 vB = _velocities[indexB].v;
float wB = _velocities[indexB].w;
Debug.Assert( manifold.pointCount > 0 );
Transform xfA = new Transform();
Transform xfB = new Transform();
xfA.q.Set( aA );
xfB.q.Set( aB );
xfA.p = cA - MathUtils.mul( xfA.q, localCenterA );
xfB.p = cB - MathUtils.mul( xfB.q, localCenterB );
Vector2 normal;
FixedArray2<Vector2> points;
WorldManifold.initialize( ref manifold, ref xfA, radiusA, ref xfB, radiusB, out normal, out points );
vc.normal = normal;
int pointCount = vc.pointCount;
for( int j = 0; j < pointCount; ++j )
{
VelocityConstraintPoint vcp = vc.points[j];
vcp.rA = points[j] - cA;
vcp.rB = points[j] - cB;
float rnA = MathUtils.cross( vcp.rA, vc.normal );
float rnB = MathUtils.cross( vcp.rB, vc.normal );
float kNormal = mA + mB + iA * rnA * rnA + iB * rnB * rnB;
vcp.normalMass = kNormal > 0.0f ? 1.0f / kNormal : 0.0f;
Vector2 tangent = MathUtils.cross( vc.normal, 1.0f );
float rtA = MathUtils.cross( vcp.rA, tangent );
float rtB = MathUtils.cross( vcp.rB, tangent );
float kTangent = mA + mB + iA * rtA * rtA + iB * rtB * rtB;
vcp.tangentMass = kTangent > 0.0f ? 1.0f / kTangent : 0.0f;
// Setup a velocity bias for restitution.
vcp.velocityBias = 0.0f;
float vRel = Vector2.Dot( vc.normal, vB + MathUtils.cross( wB, vcp.rB ) - vA - MathUtils.cross( wA, vcp.rA ) );
if( vRel < -Settings.velocityThreshold )
{
vcp.velocityBias = -vc.restitution * vRel;
}
}
// If we have two points, then prepare the block solver.
if( vc.pointCount == 2 )
{
VelocityConstraintPoint vcp1 = vc.points[0];
VelocityConstraintPoint vcp2 = vc.points[1];
float rn1A = MathUtils.cross( vcp1.rA, vc.normal );
float rn1B = MathUtils.cross( vcp1.rB, vc.normal );
float rn2A = MathUtils.cross( vcp2.rA, vc.normal );
float rn2B = MathUtils.cross( vcp2.rB, vc.normal );
float k11 = mA + mB + iA * rn1A * rn1A + iB * rn1B * rn1B;
float k22 = mA + mB + iA * rn2A * rn2A + iB * rn2B * rn2B;
float k12 = mA + mB + iA * rn1A * rn2A + iB * rn1B * rn2B;
// Ensure a reasonable condition number.
const float k_maxConditionNumber = 1000.0f;
if( k11 * k11 < k_maxConditionNumber * ( k11 * k22 - k12 * k12 ) )
{
// K is safe to invert.
vc.K.ex = new Vector2( k11, k12 );
vc.K.ey = new Vector2( k12, k22 );
vc.normalMass = vc.K.Inverse;
}
else
{
// The constraints are redundant, just use one.
// TODO_ERIN use deepest?
vc.pointCount = 1;
}
}
}
}
public void warmStart()
{
// Warm start.
for( int i = 0; i < _count; ++i )
{
ContactVelocityConstraint vc = _velocityConstraints[i];
int indexA = vc.indexA;
int indexB = vc.indexB;
float mA = vc.invMassA;
float iA = vc.invIA;
float mB = vc.invMassB;
float iB = vc.invIB;
int pointCount = vc.pointCount;
Vector2 vA = _velocities[indexA].v;
float wA = _velocities[indexA].w;
Vector2 vB = _velocities[indexB].v;
float wB = _velocities[indexB].w;
Vector2 normal = vc.normal;
Vector2 tangent = MathUtils.cross( normal, 1.0f );
for( int j = 0; j < pointCount; ++j )
{
VelocityConstraintPoint vcp = vc.points[j];
Vector2 P = vcp.normalImpulse * normal + vcp.tangentImpulse * tangent;
wA -= iA * MathUtils.cross( vcp.rA, P );
vA -= mA * P;
wB += iB * MathUtils.cross( vcp.rB, P );
vB += mB * P;
}
_velocities[indexA].v = vA;
_velocities[indexA].w = wA;
_velocities[indexB].v = vB;
_velocities[indexB].w = wB;
}
}
public void solveVelocityConstraints()
{
for( int i = 0; i < _count; ++i )
{
ContactVelocityConstraint vc = _velocityConstraints[i];
int indexA = vc.indexA;
int indexB = vc.indexB;
float mA = vc.invMassA;
float iA = vc.invIA;
float mB = vc.invMassB;
float iB = vc.invIB;
int pointCount = vc.pointCount;
Vector2 vA = _velocities[indexA].v;
float wA = _velocities[indexA].w;
Vector2 vB = _velocities[indexB].v;
float wB = _velocities[indexB].w;
Vector2 normal = vc.normal;
Vector2 tangent = MathUtils.cross( normal, 1.0f );
float friction = vc.friction;
Debug.Assert( pointCount == 1 || pointCount == 2 );
// Solve tangent constraints first because non-penetration is more important
// than friction.
for( int j = 0; j < pointCount; ++j )
{
VelocityConstraintPoint vcp = vc.points[j];
// Relative velocity at contact
Vector2 dv = vB + MathUtils.cross( wB, vcp.rB ) - vA - MathUtils.cross( wA, vcp.rA );
// Compute tangent force
float vt = Vector2.Dot( dv, tangent ) - vc.tangentSpeed;
float lambda = vcp.tangentMass * ( -vt );
// b2Clamp the accumulated force
float maxFriction = friction * vcp.normalImpulse;
float newImpulse = MathUtils.clamp( vcp.tangentImpulse + lambda, -maxFriction, maxFriction );
lambda = newImpulse - vcp.tangentImpulse;
vcp.tangentImpulse = newImpulse;
// Apply contact impulse
Vector2 P = lambda * tangent;
vA -= mA * P;
wA -= iA * MathUtils.cross( vcp.rA, P );
vB += mB * P;
wB += iB * MathUtils.cross( vcp.rB, P );
}
// Solve normal constraints
if( vc.pointCount == 1 )
{
VelocityConstraintPoint vcp = vc.points[0];
// Relative velocity at contact
Vector2 dv = vB + MathUtils.cross( wB, vcp.rB ) - vA - MathUtils.cross( wA, vcp.rA );
// Compute normal impulse
float vn = Vector2.Dot( dv, normal );
float lambda = -vcp.normalMass * ( vn - vcp.velocityBias );
// b2Clamp the accumulated impulse
float newImpulse = Math.Max( vcp.normalImpulse + lambda, 0.0f );
lambda = newImpulse - vcp.normalImpulse;
vcp.normalImpulse = newImpulse;
// Apply contact impulse
Vector2 P = lambda * normal;
vA -= mA * P;
wA -= iA * MathUtils.cross( vcp.rA, P );
vB += mB * P;
wB += iB * MathUtils.cross( vcp.rB, P );
}
else
{
// Block solver developed in collaboration with Dirk Gregorius (back in 01/07 on Box2D_Lite).
// Build the mini LCP for this contact patch
//
// vn = A * x + b, vn >= 0, , vn >= 0, x >= 0 and vn_i * x_i = 0 with i = 1..2
//
// A = J * W * JT and J = ( -n, -r1 x n, n, r2 x n )
// b = vn0 - velocityBias
//
// The system is solved using the "Total enumeration method" (s. Murty). The complementary constraint vn_i * x_i
// implies that we must have in any solution either vn_i = 0 or x_i = 0. So for the 2D contact problem the cases
// vn1 = 0 and vn2 = 0, x1 = 0 and x2 = 0, x1 = 0 and vn2 = 0, x2 = 0 and vn1 = 0 need to be tested. The first valid
// solution that satisfies the problem is chosen.
//
// In order to account of the accumulated impulse 'a' (because of the iterative nature of the solver which only requires
// that the accumulated impulse is clamped and not the incremental impulse) we change the impulse variable (x_i).
//
// Substitute:
//
// x = a + d
//
// a := old total impulse
// x := new total impulse
// d := incremental impulse
//
// For the current iteration we extend the formula for the incremental impulse
// to compute the new total impulse:
//
// vn = A * d + b
// = A * (x - a) + b
// = A * x + b - A * a
// = A * x + b'
// b' = b - A * a;
VelocityConstraintPoint cp1 = vc.points[0];
VelocityConstraintPoint cp2 = vc.points[1];
Vector2 a = new Vector2( cp1.normalImpulse, cp2.normalImpulse );
Debug.Assert( a.X >= 0.0f && a.Y >= 0.0f );
// Relative velocity at contact
Vector2 dv1 = vB + MathUtils.cross( wB, cp1.rB ) - vA - MathUtils.cross( wA, cp1.rA );
Vector2 dv2 = vB + MathUtils.cross( wB, cp2.rB ) - vA - MathUtils.cross( wA, cp2.rA );
// Compute normal velocity
float vn1 = Vector2.Dot( dv1, normal );
float vn2 = Vector2.Dot( dv2, normal );
Vector2 b = new Vector2();
b.X = vn1 - cp1.velocityBias;
b.Y = vn2 - cp2.velocityBias;
// Compute b'
b -= MathUtils.mul( ref vc.K, a );
const float k_errorTol = 1e-3f;
//B2_NOT_USED(k_errorTol);
for( ;;)
{
//
// Case 1: vn = 0
//
// 0 = A * x + b'
//
// Solve for x:
//
// x = - inv(A) * b'
//
Vector2 x = -MathUtils.mul( ref vc.normalMass, b );
if( x.X >= 0.0f && x.Y >= 0.0f )
{
// Get the incremental impulse
Vector2 d = x - a;
// Apply incremental impulse
Vector2 P1 = d.X * normal;
Vector2 P2 = d.Y * normal;
vA -= mA * ( P1 + P2 );
wA -= iA * ( MathUtils.cross( cp1.rA, P1 ) + MathUtils.cross( cp2.rA, P2 ) );
vB += mB * ( P1 + P2 );
wB += iB * ( MathUtils.cross( cp1.rB, P1 ) + MathUtils.cross( cp2.rB, P2 ) );
// Accumulate
cp1.normalImpulse = x.X;
cp2.normalImpulse = x.Y;
#if B2_DEBUG_SOLVER
// Postconditions
dv1 = vB + MathUtils.Cross(wB, cp1.rB) - vA - MathUtils.Cross(wA, cp1.rA);
dv2 = vB + MathUtils.Cross(wB, cp2.rB) - vA - MathUtils.Cross(wA, cp2.rA);
// Compute normal velocity
vn1 = Vector2.Dot(dv1, normal);
vn2 = Vector2.Dot(dv2, normal);
b2Assert(b2Abs(vn1 - cp1.velocityBias) < k_errorTol);
b2Assert(b2Abs(vn2 - cp2.velocityBias) < k_errorTol);
#endif
break;
}
//
// Case 2: vn1 = 0 and x2 = 0
//
// 0 = a11 * x1 + a12 * 0 + b1'
// vn2 = a21 * x1 + a22 * 0 + b2'
//
x.X = -cp1.normalMass * b.X;
x.Y = 0.0f;
vn1 = 0.0f;
vn2 = vc.K.ex.Y * x.X + b.Y;
if( x.X >= 0.0f && vn2 >= 0.0f )
{
// Get the incremental impulse
Vector2 d = x - a;
// Apply incremental impulse
Vector2 P1 = d.X * normal;
Vector2 P2 = d.Y * normal;
vA -= mA * ( P1 + P2 );
wA -= iA * ( MathUtils.cross( cp1.rA, P1 ) + MathUtils.cross( cp2.rA, P2 ) );
vB += mB * ( P1 + P2 );
wB += iB * ( MathUtils.cross( cp1.rB, P1 ) + MathUtils.cross( cp2.rB, P2 ) );
// Accumulate
cp1.normalImpulse = x.X;
cp2.normalImpulse = x.Y;
#if B2_DEBUG_SOLVER
// Postconditions
dv1 = vB + MathUtils.Cross(wB, cp1.rB) - vA - MathUtils.Cross(wA, cp1.rA);
// Compute normal velocity
vn1 = Vector2.Dot(dv1, normal);
b2Assert(b2Abs(vn1 - cp1.velocityBias) < k_errorTol);
#endif
break;
}
//
// Case 3: vn2 = 0 and x1 = 0
//
// vn1 = a11 * 0 + a12 * x2 + b1'
// 0 = a21 * 0 + a22 * x2 + b2'
//
x.X = 0.0f;
x.Y = -cp2.normalMass * b.Y;
vn1 = vc.K.ey.X * x.Y + b.X;
vn2 = 0.0f;
if( x.Y >= 0.0f && vn1 >= 0.0f )
{
// Resubstitute for the incremental impulse
Vector2 d = x - a;
// Apply incremental impulse
Vector2 P1 = d.X * normal;
Vector2 P2 = d.Y * normal;
vA -= mA * ( P1 + P2 );
wA -= iA * ( MathUtils.cross( cp1.rA, P1 ) + MathUtils.cross( cp2.rA, P2 ) );
vB += mB * ( P1 + P2 );
wB += iB * ( MathUtils.cross( cp1.rB, P1 ) + MathUtils.cross( cp2.rB, P2 ) );
// Accumulate
cp1.normalImpulse = x.X;
cp2.normalImpulse = x.Y;
#if B2_DEBUG_SOLVER
// Postconditions
dv2 = vB + MathUtils.Cross(wB, cp2.rB) - vA - MathUtils.Cross(wA, cp2.rA);
// Compute normal velocity
vn2 = Vector2.Dot(dv2, normal);
b2Assert(b2Abs(vn2 - cp2.velocityBias) < k_errorTol);
#endif
break;
}
//
// Case 4: x1 = 0 and x2 = 0
//
// vn1 = b1
// vn2 = b2;
x.X = 0.0f;
x.Y = 0.0f;
vn1 = b.X;
vn2 = b.Y;
if( vn1 >= 0.0f && vn2 >= 0.0f )
{
// Resubstitute for the incremental impulse
Vector2 d = x - a;
// Apply incremental impulse
Vector2 P1 = d.X * normal;
Vector2 P2 = d.Y * normal;
vA -= mA * ( P1 + P2 );
wA -= iA * ( MathUtils.cross( cp1.rA, P1 ) + MathUtils.cross( cp2.rA, P2 ) );
vB += mB * ( P1 + P2 );
wB += iB * ( MathUtils.cross( cp1.rB, P1 ) + MathUtils.cross( cp2.rB, P2 ) );
// Accumulate
cp1.normalImpulse = x.X;
cp2.normalImpulse = x.Y;
break;
}
// No solution, give up. This is hit sometimes, but it doesn't seem to matter.
break;
}
}
_velocities[indexA].v = vA;
_velocities[indexA].w = wA;
_velocities[indexB].v = vB;
_velocities[indexB].w = wB;
}
}
public void storeImpulses()
{
for( int i = 0; i < _count; ++i )
{
ContactVelocityConstraint vc = _velocityConstraints[i];
Manifold manifold = _contacts[vc.contactIndex].manifold;
for( int j = 0; j < vc.pointCount; ++j )
{
ManifoldPoint point = manifold.points[j];
point.normalImpulse = vc.points[j].normalImpulse;
point.tangentImpulse = vc.points[j].tangentImpulse;
manifold.points[j] = point;
}
_contacts[vc.contactIndex].manifold = manifold;
}
}
public bool solvePositionConstraints()
{
float minSeparation = 0.0f;
for( int i = 0; i < _count; ++i )
{
ContactPositionConstraint pc = _positionConstraints[i];
int indexA = pc.indexA;
int indexB = pc.indexB;
Vector2 localCenterA = pc.localCenterA;
float mA = pc.invMassA;
float iA = pc.invIA;
Vector2 localCenterB = pc.localCenterB;
float mB = pc.invMassB;
float iB = pc.invIB;
int pointCount = pc.pointCount;
Vector2 cA = _positions[indexA].c;
float aA = _positions[indexA].a;
Vector2 cB = _positions[indexB].c;
float aB = _positions[indexB].a;
// Solve normal constraints
for( int j = 0; j < pointCount; ++j )
{
Transform xfA = new Transform();
Transform xfB = new Transform();
xfA.q.Set( aA );
xfB.q.Set( aB );
xfA.p = cA - MathUtils.mul( xfA.q, localCenterA );
xfB.p = cB - MathUtils.mul( xfB.q, localCenterB );
Vector2 normal;
Vector2 point;
float separation;
PositionSolverManifold.initialize( pc, xfA, xfB, j, out normal, out point, out separation );
Vector2 rA = point - cA;
Vector2 rB = point - cB;
// Track max constraint error.
minSeparation = Math.Min( minSeparation, separation );
// Prevent large corrections and allow slop.
float C = MathUtils.clamp( Settings.baumgarte * ( separation + Settings.linearSlop ), -Settings.maxLinearCorrection, 0.0f );
// Compute the effective mass.
float rnA = MathUtils.cross( rA, normal );
float rnB = MathUtils.cross( rB, normal );
float K = mA + mB + iA * rnA * rnA + iB * rnB * rnB;
// Compute normal impulse
float impulse = K > 0.0f ? -C / K : 0.0f;
Vector2 P = impulse * normal;
cA -= mA * P;
aA -= iA * MathUtils.cross( rA, P );
cB += mB * P;
aB += iB * MathUtils.cross( rB, P );
}
_positions[indexA].c = cA;
_positions[indexA].a = aA;
_positions[indexB].c = cB;
_positions[indexB].a = aB;
}
// We can't expect minSpeparation >= -b2_linearSlop because we don't
// push the separation above -b2_linearSlop.
return minSeparation >= -3.0f * Settings.linearSlop;
}
// Sequential position solver for position constraints.
public bool solveTOIPositionConstraints( int toiIndexA, int toiIndexB )
{
float minSeparation = 0.0f;
for( int i = 0; i < _count; ++i )
{
ContactPositionConstraint pc = _positionConstraints[i];
int indexA = pc.indexA;
int indexB = pc.indexB;
Vector2 localCenterA = pc.localCenterA;
Vector2 localCenterB = pc.localCenterB;
int pointCount = pc.pointCount;
float mA = 0.0f;
float iA = 0.0f;
if( indexA == toiIndexA || indexA == toiIndexB )
{
mA = pc.invMassA;
iA = pc.invIA;
}
float mB = 0.0f;
float iB = 0.0f;
if( indexB == toiIndexA || indexB == toiIndexB )
{
mB = pc.invMassB;
iB = pc.invIB;
}
Vector2 cA = _positions[indexA].c;
float aA = _positions[indexA].a;
Vector2 cB = _positions[indexB].c;
float aB = _positions[indexB].a;
// Solve normal constraints
for( int j = 0; j < pointCount; ++j )
{
Transform xfA = new Transform();
Transform xfB = new Transform();
xfA.q.Set( aA );
xfB.q.Set( aB );
xfA.p = cA - MathUtils.mul( xfA.q, localCenterA );
xfB.p = cB - MathUtils.mul( xfB.q, localCenterB );
Vector2 normal;
Vector2 point;
float separation;
PositionSolverManifold.initialize( pc, xfA, xfB, j, out normal, out point, out separation );
Vector2 rA = point - cA;
Vector2 rB = point - cB;
// Track max constraint error.
minSeparation = Math.Min( minSeparation, separation );
// Prevent large corrections and allow slop.
float C = MathUtils.clamp( Settings.baumgarte * ( separation + Settings.linearSlop ), -Settings.maxLinearCorrection, 0.0f );
// Compute the effective mass.
float rnA = MathUtils.cross( rA, normal );
float rnB = MathUtils.cross( rB, normal );
float K = mA + mB + iA * rnA * rnA + iB * rnB * rnB;
// Compute normal impulse
float impulse = K > 0.0f ? -C / K : 0.0f;
Vector2 P = impulse * normal;
cA -= mA * P;
aA -= iA * MathUtils.cross( rA, P );
cB += mB * P;
aB += iB * MathUtils.cross( rB, P );
}
_positions[indexA].c = cA;
_positions[indexA].a = aA;
_positions[indexB].c = cB;
_positions[indexB].a = aB;
}
// We can't expect minSpeparation >= -b2_linearSlop because we don't
// push the separation above -b2_linearSlop.
return minSeparation >= -1.5f * Settings.linearSlop;
}
public static class WorldManifold
{
/// <summary>
/// Evaluate the manifold with supplied transforms. This assumes
/// modest motion from the original state. This does not change the
/// point count, impulses, etc. The radii must come from the Shapes
/// that generated the manifold.
/// </summary>
/// <param name="manifold">The manifold.</param>
/// <param name="xfA">The transform for A.</param>
/// <param name="radiusA">The radius for A.</param>
/// <param name="xfB">The transform for B.</param>
/// <param name="radiusB">The radius for B.</param>
/// <param name="normal">World vector pointing from A to B</param>
/// <param name="points">Torld contact point (point of intersection).</param>
public static void initialize( ref Manifold manifold, ref Transform xfA, float radiusA, ref Transform xfB, float radiusB, out Vector2 normal, out FixedArray2<Vector2> points )
{
normal = Vector2.Zero;
points = new FixedArray2<Vector2>();
if( manifold.pointCount == 0 )
return;
switch( manifold.type )
{
case ManifoldType.Circles:
{
normal = new Vector2( 1.0f, 0.0f );
var pointA = MathUtils.mul( ref xfA, manifold.localPoint );
var pointB = MathUtils.mul( ref xfB, manifold.points[0].localPoint );
if( Vector2.DistanceSquared( pointA, pointB ) > Settings.epsilon * Settings.epsilon )
{
normal = pointB - pointA;
Nez.Vector2Ext.normalize( ref normal );
}
var cA = pointA + radiusA * normal;
var cB = pointB - radiusB * normal;
points[0] = 0.5f * ( cA + cB );
break;
}
case ManifoldType.FaceA:
{
normal = MathUtils.mul( xfA.q, manifold.localNormal );
var planePoint = MathUtils.mul( ref xfA, manifold.localPoint );
for( int i = 0; i < manifold.pointCount; ++i )
{
var clipPoint = MathUtils.mul( ref xfB, manifold.points[i].localPoint );
var cA = clipPoint + ( radiusA - Vector2.Dot( clipPoint - planePoint, normal ) ) * normal;
var cB = clipPoint - radiusB * normal;
points[i] = 0.5f * ( cA + cB );
}
break;
}
case ManifoldType.FaceB:
{
normal = MathUtils.mul( xfB.q, manifold.localNormal );
var planePoint = MathUtils.mul( ref xfB, manifold.localPoint );
for( int i = 0; i < manifold.pointCount; ++i )
{
var clipPoint = MathUtils.mul( ref xfA, manifold.points[i].localPoint );
var cB = clipPoint + ( radiusB - Vector2.Dot( clipPoint - planePoint, normal ) ) * normal;
var cA = clipPoint - radiusA * normal;
points[i] = 0.5f * ( cA + cB );
}
// Ensure normal points from A to B.
normal = -normal;
break;
}
}
}
}
static class PositionSolverManifold
{
public static void initialize( ContactPositionConstraint pc, Transform xfA, Transform xfB, int index, out Vector2 normal, out Vector2 point, out float separation )
{
Debug.Assert( pc.pointCount > 0 );
switch( pc.type )
{
case ManifoldType.Circles:
{
var pointA = MathUtils.mul( ref xfA, pc.localPoint );
var pointB = MathUtils.mul( ref xfB, pc.localPoints[0] );
normal = pointB - pointA;
Nez.Vector2Ext.normalize( ref normal );
point = 0.5f * ( pointA + pointB );
separation = Vector2.Dot( pointB - pointA, normal ) - pc.radiusA - pc.radiusB;
break;
}
case ManifoldType.FaceA:
{
normal = MathUtils.mul( xfA.q, pc.localNormal );
var planePoint = MathUtils.mul( ref xfA, pc.localPoint );
var clipPoint = MathUtils.mul( ref xfB, pc.localPoints[index] );
separation = Vector2.Dot( clipPoint - planePoint, normal ) - pc.radiusA - pc.radiusB;
point = clipPoint;
break;
}
case ManifoldType.FaceB:
{
normal = MathUtils.mul( xfB.q, pc.localNormal );
var planePoint = MathUtils.mul( ref xfB, pc.localPoint );
var clipPoint = MathUtils.mul( ref xfA, pc.localPoints[index] );
separation = Vector2.Dot( clipPoint - planePoint, normal ) - pc.radiusA - pc.radiusB;
point = clipPoint;
// Ensure normal points from A to B
normal = -normal;
break;
}
default:
normal = Vector2.Zero;
point = Vector2.Zero;
separation = 0;
break;
}
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="WmlSelectionListAdapter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Globalization;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.MobileControls;
using System.Collections.Specialized;
using System.Text.RegularExpressions;
using System.Collections;
using System.Text;
using System.Diagnostics;
using System.Security.Permissions;
#if COMPILING_FOR_SHIPPED_SOURCE
namespace System.Web.UI.MobileControls.ShippedAdapterSource
#else
namespace System.Web.UI.MobileControls.Adapters
#endif
{
/*
* WmlSelectionListAdapter provides the wml device functionality for SelectionList controls.
*
* Copyright (c) 2000 Microsoft Corporation
*/
/// <include file='doc\WmlSelectionListAdapter.uex' path='docs/doc[@for="WmlSelectionListAdapter"]/*' />
[AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal)]
[Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")]
public class WmlSelectionListAdapter : WmlControlAdapter
{
private String _ivalue = null;
private const String ClientPrefix = "__slst_";
/// <include file='doc\WmlSelectionListAdapter.uex' path='docs/doc[@for="WmlSelectionListAdapter.Control"]/*' />
protected new SelectionList Control
{
get
{
return (SelectionList)base.Control;
}
}
/// <include file='doc\WmlSelectionListAdapter.uex' path='docs/doc[@for="WmlSelectionListAdapter.OnInit"]/*' />
public override void OnInit(EventArgs e)
{
}
/// <include file='doc\WmlSelectionListAdapter.uex' path='docs/doc[@for="WmlSelectionListAdapter.OnPreRender"]/*' />
public override void OnPreRender(EventArgs e)
{
int firstSelectedIndex;
MobileListItemCollection items = Control.Items;
int count = items.Count;
for(firstSelectedIndex = 0; firstSelectedIndex < count; firstSelectedIndex++)
{
if(items[firstSelectedIndex].Selected)
{
break;
}
}
if(firstSelectedIndex < count)
{
StringBuilder ivalue=new StringBuilder();
ivalue.Append((firstSelectedIndex + 1).ToString(CultureInfo.InvariantCulture));
if(Control.IsMultiSelect)
{
for(int i = firstSelectedIndex + 1; i < count; i++)
{
if(items[i].Selected)
{
ivalue.Append(";");
ivalue.Append((i + 1).ToString(CultureInfo.InvariantCulture));
}
}
}
_ivalue = ivalue.ToString();
}
else
{
String defaultValue = null;
if (!Control.IsMultiSelect)
{
// 1 is the first index of a single selection list
defaultValue = "1";
}
else if (Device.CanRenderSetvarZeroWithMultiSelectionList)
{
// 0 means no items have been selected, for MultiSelect case
defaultValue = "0";
}
if (defaultValue != null)
{
_ivalue = defaultValue;
}
}
}
/// <include file='doc\WmlSelectionListAdapter.uex' path='docs/doc[@for="WmlSelectionListAdapter.Render"]/*' />
public override void Render(WmlMobileTextWriter writer)
{
MobileListItemCollection items = Control.Items;
int count = items.Count;
if (count == 0)
{
return;
}
writer.EnterLayout(Style);
bool crossPagePost = !String.IsNullOrEmpty(Control.Form.Action);
if (crossPagePost)
{
if (_ivalue != null)
{
String formVariable = ClientPrefix + Control.ClientID;
writer.AddFormVariable (formVariable, _ivalue, false);
// does not render _ivalue if null or form variables written.
writer.RenderBeginSelect(Control.ClientID, formVariable, _ivalue, Control.Title, Control.IsMultiSelect);
}
else // _ivalue == null
{
writer.RenderBeginSelect(Control.ClientID, null, null, Control.Title, Control.IsMultiSelect);
}
}
else // !crossPagePost
{
if (_ivalue != null)
{
writer.AddFormVariable (Control.ClientID, _ivalue, false);
}
// does not render _ivalue if null or form variables written.
writer.RenderBeginSelect(null, Control.ClientID, _ivalue, Control.Title, Control.IsMultiSelect);
}
foreach (MobileListItem item in items)
{
if (crossPagePost)
{
writer.RenderSelectOption(item.Text, item.Value);
}
else
{
writer.RenderSelectOption(item.Text);
}
}
writer.RenderEndSelect(Control.BreakAfter);
writer.ExitLayout(Style);
}
// Parse the WML posted data appropriately.
/// <include file='doc\WmlSelectionListAdapter.uex' path='docs/doc[@for="WmlSelectionListAdapter.LoadPostData"]/*' />
public override bool LoadPostData(String key,
NameValueCollection data,
Object controlPrivateData,
out bool dataChanged)
{
int[] selectedItemIndices;
String[] selectedItems = data.GetValues(key);
Debug.Assert (String.IsNullOrEmpty(Control.Form.Action),
"Cross page post (!IsPostBack) assumed when Form.Action nonempty." +
"LoadPostData should not have been be called.");
// Note: controlPrivateData is selectedIndices from viewstate.
int[] originalSelectedIndices = (int[])controlPrivateData;
dataChanged = false;
if (selectedItems == null)
{
// This shouldn't happen if we're posting back from the form that
// contains the selection list. It could happen when being called
// as the result of a postback from another form on the page,
// so we just return quietly.
return true;
}
if (Control.Items.Count == 0)
{
return true;
}
// If singleselect && nothing was selected, select
// first elt. (Non-mobile DropDown does same by getting SelectedIndex).
if(!Control.IsMultiSelect &&
originalSelectedIndices.Length == 0 &&
Control.Items.Count > 0)
{
Control.Items[0].Selected = true;
originalSelectedIndices = new int[]{0};
}
// Case where nothing is selected.
if(selectedItems == null ||
(selectedItems.Length == 1 &&
(selectedItems[0] != null && selectedItems[0].Length == 0)) ||
(selectedItems.Length == 1 &&
selectedItems[0] == "0")) // non-selected MultiSelect case
{
selectedItems = new String[]{};
}
// WML multiselect case with more than one selection.
if(selectedItems.Length == 1 && selectedItems[0].IndexOf(';') > -1)
{
String selected = selectedItems[0];
// Eliminate trailing semicolon, if there is one.
selected = Regex.Replace(selected, ";$", "");
selectedItems = Regex.Split(selected, ";");
}
selectedItemIndices = new int[selectedItems.Length];
for(int i = 0; i < selectedItems.Length; i++)
{
// WML iname gives index + 1, so subtract one back out.
selectedItemIndices[i] = Int32.Parse(selectedItems[i], CultureInfo.InvariantCulture) - 1;
}
// Do not assume posted selected indices are ascending.
// We do know originalSelectedIndices are ascending.
Array.Sort(selectedItemIndices);
// Check whether selections have changed.
if(selectedItemIndices.Length != originalSelectedIndices.Length)
{
dataChanged = true;
}
else
{
for(int i = 0; i < selectedItemIndices.Length; i++)
{
if(selectedItemIndices[i] != originalSelectedIndices[i])
{
dataChanged = true;
}
}
}
for (int i = 0; i < Control.Items.Count; i++)
{
Control.Items[i].Selected = false;
}
for(int i = 0; i < selectedItemIndices.Length; i++)
{
Control.Items[selectedItemIndices[i]].Selected = true;
}
return true;
}
/// <include file='doc\WmlSelectionListAdapter.uex' path='docs/doc[@for="WmlSelectionListAdapter.GetPostBackValue"]/*' />
protected override String GetPostBackValue()
{
// Optimization - if viewstate is enabled for this control, and the
// postback returns to this page, we just let it do the trick.
if (Control.Form.Action.Length > 0 || !IsViewStateEnabled())
{
return _ivalue != null ? _ivalue : String.Empty;
}
else
{
return null;
}
}
private bool IsViewStateEnabled()
{
Control ctl = Control;
while (ctl != null)
{
if (!ctl.EnableViewState)
{
return false;
}
ctl = ctl.Parent;
}
return true;
}
}
}
| |
namespace Epi.Windows.Enter
{
/// <summary>
/// The Enter module main form
/// </summary>
partial class EnterMainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
this.viewExplorer = null;
this.canvas = null;
this.currentBackgroundImage = null;
this.currentBackgroundImageLayout = null;
this.bgTable = null;
this.runTimeView = null;
this.view = null;
this.currentProject = null;
if (this.Module != null)
{
this.Module.Dispose();
}
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(EnterMainForm));
this.toolStripContainer1 = new System.Windows.Forms.ToolStripContainer();
this.enterDockManager = new Epi.Windows.Docking.DockManager(this.components);
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.newRecordToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openViewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.editViewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.closeViewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.importDataToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.mnuImportFromPhone = new System.Windows.Forms.ToolStripMenuItem();
this.mnuImportFromWeb = new System.Windows.Forms.ToolStripMenuItem();
this.fromWebEnterToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.mnuImportFromForm = new System.Windows.Forms.ToolStripMenuItem();
this.mnuImportFromDataPackage = new System.Windows.Forms.ToolStripMenuItem();
this.mnuPackageForTransport = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.printToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.recentViewsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.editToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.findToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.markAsDeletedToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.undeleteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.viewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.statusBarToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.epiInfoLogsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.dataDictionaryToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator();
this.compactDatabaseToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator();
this.optionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.enableCheckCodeExecutionToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.enableCheckCodeErrorSupressionToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.copyShortcutToClipboardToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.contentsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.aboutEpiInfoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStrip2 = new System.Windows.Forms.ToolStrip();
this.btnHome = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator9 = new System.Windows.Forms.ToolStripSeparator();
this.btnBack = new System.Windows.Forms.ToolStripButton();
this.toolStrip1 = new System.Windows.Forms.ToolStrip();
this.btiOpen = new System.Windows.Forms.ToolStripButton();
this.btiSave = new System.Windows.Forms.ToolStripButton();
this.btiPrint = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator();
this.btiFind = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator();
this.btiNew = new System.Windows.Forms.ToolStripButton();
this.toolStripFirstButton = new System.Windows.Forms.ToolStripButton();
this.toolStripPreviousButton = new System.Windows.Forms.ToolStripButton();
this.toolStripRecordNumber = new System.Windows.Forms.ToolStripTextBox();
this.toolStripOfLabel = new System.Windows.Forms.ToolStripLabel();
this.toolStripRecordCount = new System.Windows.Forms.ToolStripLabel();
this.toolStripNextButton = new System.Windows.Forms.ToolStripButton();
this.toolStripLastButton = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator8 = new System.Windows.Forms.ToolStripSeparator();
this.btiMarkDeleted = new System.Windows.Forms.ToolStripButton();
this.btiUndelete = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator();
this.LineListingToolStripButton = new System.Windows.Forms.ToolStripSplitButton();
this.gridToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.printableHTMLToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.excelLineListMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.tsbDashboard = new System.Windows.Forms.ToolStripButton();
this.tsbMap = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator10 = new System.Windows.Forms.ToolStripSeparator();
this.btiEditView = new System.Windows.Forms.ToolStripButton();
this.btiHelp = new System.Windows.Forms.ToolStripButton();
this.BottomToolStripPanel = new System.Windows.Forms.ToolStripPanel();
this.TopToolStripPanel = new System.Windows.Forms.ToolStripPanel();
this.RightToolStripPanel = new System.Windows.Forms.ToolStripPanel();
this.LeftToolStripPanel = new System.Windows.Forms.ToolStripPanel();
this.ContentPanel = new System.Windows.Forms.ToolStripContentPanel();
this.toolStripContainer1.ContentPanel.SuspendLayout();
this.toolStripContainer1.TopToolStripPanel.SuspendLayout();
this.toolStripContainer1.SuspendLayout();
this.menuStrip1.SuspendLayout();
this.toolStrip2.SuspendLayout();
this.toolStrip1.SuspendLayout();
this.SuspendLayout();
//
// baseImageList
//
this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream")));
this.baseImageList.Images.SetKeyName(0, "");
this.baseImageList.Images.SetKeyName(1, "");
this.baseImageList.Images.SetKeyName(2, "");
this.baseImageList.Images.SetKeyName(3, "");
this.baseImageList.Images.SetKeyName(4, "");
this.baseImageList.Images.SetKeyName(5, "");
this.baseImageList.Images.SetKeyName(6, "");
this.baseImageList.Images.SetKeyName(7, "");
this.baseImageList.Images.SetKeyName(8, "");
this.baseImageList.Images.SetKeyName(9, "");
this.baseImageList.Images.SetKeyName(10, "");
this.baseImageList.Images.SetKeyName(11, "");
this.baseImageList.Images.SetKeyName(12, "");
this.baseImageList.Images.SetKeyName(13, "");
this.baseImageList.Images.SetKeyName(14, "");
this.baseImageList.Images.SetKeyName(15, "");
this.baseImageList.Images.SetKeyName(16, "");
this.baseImageList.Images.SetKeyName(17, "");
this.baseImageList.Images.SetKeyName(18, "");
this.baseImageList.Images.SetKeyName(19, "");
this.baseImageList.Images.SetKeyName(20, "");
this.baseImageList.Images.SetKeyName(21, "");
this.baseImageList.Images.SetKeyName(22, "");
this.baseImageList.Images.SetKeyName(23, "");
this.baseImageList.Images.SetKeyName(24, "");
this.baseImageList.Images.SetKeyName(25, "");
this.baseImageList.Images.SetKeyName(26, "");
this.baseImageList.Images.SetKeyName(27, "");
this.baseImageList.Images.SetKeyName(28, "");
this.baseImageList.Images.SetKeyName(29, "");
this.baseImageList.Images.SetKeyName(30, "");
this.baseImageList.Images.SetKeyName(31, "");
this.baseImageList.Images.SetKeyName(32, "");
this.baseImageList.Images.SetKeyName(33, "");
this.baseImageList.Images.SetKeyName(34, "");
this.baseImageList.Images.SetKeyName(35, "");
this.baseImageList.Images.SetKeyName(36, "");
this.baseImageList.Images.SetKeyName(37, "");
this.baseImageList.Images.SetKeyName(38, "");
this.baseImageList.Images.SetKeyName(39, "");
this.baseImageList.Images.SetKeyName(40, "");
this.baseImageList.Images.SetKeyName(41, "");
this.baseImageList.Images.SetKeyName(42, "");
this.baseImageList.Images.SetKeyName(43, "");
this.baseImageList.Images.SetKeyName(44, "");
this.baseImageList.Images.SetKeyName(45, "");
this.baseImageList.Images.SetKeyName(46, "");
this.baseImageList.Images.SetKeyName(47, "");
this.baseImageList.Images.SetKeyName(48, "");
this.baseImageList.Images.SetKeyName(49, "");
this.baseImageList.Images.SetKeyName(50, "");
this.baseImageList.Images.SetKeyName(51, "");
this.baseImageList.Images.SetKeyName(52, "");
this.baseImageList.Images.SetKeyName(53, "");
this.baseImageList.Images.SetKeyName(54, "");
this.baseImageList.Images.SetKeyName(55, "");
this.baseImageList.Images.SetKeyName(56, "");
this.baseImageList.Images.SetKeyName(57, "");
this.baseImageList.Images.SetKeyName(58, "");
this.baseImageList.Images.SetKeyName(59, "");
this.baseImageList.Images.SetKeyName(60, "");
this.baseImageList.Images.SetKeyName(61, "");
this.baseImageList.Images.SetKeyName(62, "");
this.baseImageList.Images.SetKeyName(63, "");
this.baseImageList.Images.SetKeyName(64, "");
this.baseImageList.Images.SetKeyName(65, "");
this.baseImageList.Images.SetKeyName(66, "");
this.baseImageList.Images.SetKeyName(67, "");
this.baseImageList.Images.SetKeyName(68, "");
this.baseImageList.Images.SetKeyName(69, "");
this.baseImageList.Images.SetKeyName(70, "");
this.baseImageList.Images.SetKeyName(71, "");
this.baseImageList.Images.SetKeyName(72, "");
this.baseImageList.Images.SetKeyName(73, "");
this.baseImageList.Images.SetKeyName(74, "");
this.baseImageList.Images.SetKeyName(75, "");
this.baseImageList.Images.SetKeyName(76, "");
this.baseImageList.Images.SetKeyName(77, "");
this.baseImageList.Images.SetKeyName(78, "");
this.baseImageList.Images.SetKeyName(79, "");
this.baseImageList.Images.SetKeyName(80, "");
this.baseImageList.Images.SetKeyName(81, "");
this.baseImageList.Images.SetKeyName(82, "");
this.baseImageList.Images.SetKeyName(83, "");
this.baseImageList.Images.SetKeyName(84, "");
this.baseImageList.Images.SetKeyName(85, "");
this.baseImageList.Images.SetKeyName(86, "");
this.baseImageList.Images.SetKeyName(87, "");
this.baseImageList.Images.SetKeyName(88, "");
this.baseImageList.Images.SetKeyName(89, "");
this.baseImageList.Images.SetKeyName(90, "");
this.baseImageList.Images.SetKeyName(91, "");
this.baseImageList.Images.SetKeyName(92, "");
this.baseImageList.Images.SetKeyName(93, "");
this.baseImageList.Images.SetKeyName(94, "");
this.baseImageList.Images.SetKeyName(95, "");
this.baseImageList.Images.SetKeyName(96, "");
//
// toolStripContainer1
//
//
// toolStripContainer1.ContentPanel
//
this.toolStripContainer1.ContentPanel.Controls.Add(this.enterDockManager);
resources.ApplyResources(this.toolStripContainer1.ContentPanel, "toolStripContainer1.ContentPanel");
resources.ApplyResources(this.toolStripContainer1, "toolStripContainer1");
this.toolStripContainer1.Name = "toolStripContainer1";
//
// toolStripContainer1.TopToolStripPanel
//
this.toolStripContainer1.TopToolStripPanel.Controls.Add(this.toolStrip1);
this.toolStripContainer1.TopToolStripPanel.Controls.Add(this.toolStrip2);
this.toolStripContainer1.TopToolStripPanel.Controls.Add(this.menuStrip1);
//
// enterDockManager
//
this.enterDockManager.BackColor = System.Drawing.Color.Transparent;
resources.ApplyResources(this.enterDockManager, "enterDockManager");
this.enterDockManager.DockBorder = 20;
this.enterDockManager.DockType = Epi.Windows.Docking.DockContainerType.Document;
this.enterDockManager.FastDrawing = true;
this.enterDockManager.Name = "enterDockManager";
this.enterDockManager.ShowIcons = true;
this.enterDockManager.SplitterWidth = 4;
this.enterDockManager.VisualStyle = Epi.Windows.Docking.DockVisualStyle.VS2003;
//
// menuStrip1
//
resources.ApplyResources(this.menuStrip1, "menuStrip1");
this.menuStrip1.ImageScalingSize = new System.Drawing.Size(20, 20);
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.editToolStripMenuItem,
this.viewToolStripMenuItem,
this.toolsToolStripMenuItem,
this.helpToolStripMenuItem});
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.menuStrip1_ItemClicked);
this.menuStrip1.Click += new System.EventHandler(this.menuStrip1_Click);
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.newRecordToolStripMenuItem,
this.openViewToolStripMenuItem,
this.editViewToolStripMenuItem,
this.closeViewToolStripMenuItem,
this.toolStripSeparator1,
this.saveToolStripMenuItem,
this.importDataToolStripMenuItem,
this.mnuPackageForTransport,
this.toolStripSeparator2,
this.printToolStripMenuItem,
this.toolStripSeparator3,
this.recentViewsToolStripMenuItem,
this.toolStripSeparator4,
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
resources.ApplyResources(this.fileToolStripMenuItem, "fileToolStripMenuItem");
//
// newRecordToolStripMenuItem
//
resources.ApplyResources(this.newRecordToolStripMenuItem, "newRecordToolStripMenuItem");
this.newRecordToolStripMenuItem.Name = "newRecordToolStripMenuItem";
this.newRecordToolStripMenuItem.Click += new System.EventHandler(this.newRecordToolStripMenuItem_Click);
//
// openViewToolStripMenuItem
//
this.openViewToolStripMenuItem.Name = "openViewToolStripMenuItem";
resources.ApplyResources(this.openViewToolStripMenuItem, "openViewToolStripMenuItem");
this.openViewToolStripMenuItem.Click += new System.EventHandler(this.openViewToolStripMenuItem_Click);
//
// editViewToolStripMenuItem
//
resources.ApplyResources(this.editViewToolStripMenuItem, "editViewToolStripMenuItem");
this.editViewToolStripMenuItem.Name = "editViewToolStripMenuItem";
this.editViewToolStripMenuItem.Click += new System.EventHandler(this.editViewToolStripMenuItem_Click);
//
// closeViewToolStripMenuItem
//
resources.ApplyResources(this.closeViewToolStripMenuItem, "closeViewToolStripMenuItem");
this.closeViewToolStripMenuItem.Name = "closeViewToolStripMenuItem";
this.closeViewToolStripMenuItem.Click += new System.EventHandler(this.closeViewToolStripMenuItem_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
resources.ApplyResources(this.toolStripSeparator1, "toolStripSeparator1");
//
// saveToolStripMenuItem
//
resources.ApplyResources(this.saveToolStripMenuItem, "saveToolStripMenuItem");
this.saveToolStripMenuItem.Name = "saveToolStripMenuItem";
this.saveToolStripMenuItem.Click += new System.EventHandler(this.saveToolStripMenuItem_Click);
//
// importDataToolStripMenuItem
//
this.importDataToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnuImportFromPhone,
this.mnuImportFromWeb,
this.fromWebEnterToolStripMenuItem,
this.mnuImportFromForm,
this.mnuImportFromDataPackage});
this.importDataToolStripMenuItem.Name = "importDataToolStripMenuItem";
resources.ApplyResources(this.importDataToolStripMenuItem, "importDataToolStripMenuItem");
//
// mnuImportFromPhone
//
resources.ApplyResources(this.mnuImportFromPhone, "mnuImportFromPhone");
this.mnuImportFromPhone.Image = global::Epi.Enter.Properties.Resources.android_icon;
this.mnuImportFromPhone.Name = "mnuImportFromPhone";
this.mnuImportFromPhone.Click += new System.EventHandler(this.mnuImportFromPhone_Click);
//
// mnuImportFromWeb
//
resources.ApplyResources(this.mnuImportFromWeb, "mnuImportFromWeb");
this.mnuImportFromWeb.Name = "mnuImportFromWeb";
this.mnuImportFromWeb.Click += new System.EventHandler(this.mnuImportFromWebToolStripMenuItem_Click);
//
// fromWebEnterToolStripMenuItem
//
resources.ApplyResources(this.fromWebEnterToolStripMenuItem, "fromWebEnterToolStripMenuItem");
this.fromWebEnterToolStripMenuItem.Name = "fromWebEnterToolStripMenuItem";
this.fromWebEnterToolStripMenuItem.Click += new System.EventHandler(this.fromWebEnterToolStripMenuItem_Click);
//
// mnuImportFromForm
//
resources.ApplyResources(this.mnuImportFromForm, "mnuImportFromForm");
this.mnuImportFromForm.Name = "mnuImportFromForm";
this.mnuImportFromForm.Click += new System.EventHandler(this.mnuImportFromProjectToolStripMenuItem_Click);
//
// mnuImportFromDataPackage
//
resources.ApplyResources(this.mnuImportFromDataPackage, "mnuImportFromDataPackage");
this.mnuImportFromDataPackage.Name = "mnuImportFromDataPackage";
this.mnuImportFromDataPackage.Click += new System.EventHandler(this.mnuImportFromDataPackage_Click);
//
// mnuPackageForTransport
//
resources.ApplyResources(this.mnuPackageForTransport, "mnuPackageForTransport");
this.mnuPackageForTransport.Name = "mnuPackageForTransport";
this.mnuPackageForTransport.Click += new System.EventHandler(this.mnuPackageForTransportToolStripMenuItem_Click);
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
resources.ApplyResources(this.toolStripSeparator2, "toolStripSeparator2");
//
// printToolStripMenuItem
//
resources.ApplyResources(this.printToolStripMenuItem, "printToolStripMenuItem");
this.printToolStripMenuItem.Name = "printToolStripMenuItem";
this.printToolStripMenuItem.Click += new System.EventHandler(this.printToolStripMenuItem_Click);
//
// toolStripSeparator3
//
this.toolStripSeparator3.Name = "toolStripSeparator3";
resources.ApplyResources(this.toolStripSeparator3, "toolStripSeparator3");
//
// recentViewsToolStripMenuItem
//
this.recentViewsToolStripMenuItem.Name = "recentViewsToolStripMenuItem";
resources.ApplyResources(this.recentViewsToolStripMenuItem, "recentViewsToolStripMenuItem");
//
// toolStripSeparator4
//
this.toolStripSeparator4.Name = "toolStripSeparator4";
resources.ApplyResources(this.toolStripSeparator4, "toolStripSeparator4");
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
resources.ApplyResources(this.exitToolStripMenuItem, "exitToolStripMenuItem");
this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
//
// editToolStripMenuItem
//
this.editToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.findToolStripMenuItem,
this.markAsDeletedToolStripMenuItem,
this.undeleteToolStripMenuItem});
this.editToolStripMenuItem.Name = "editToolStripMenuItem";
resources.ApplyResources(this.editToolStripMenuItem, "editToolStripMenuItem");
//
// findToolStripMenuItem
//
resources.ApplyResources(this.findToolStripMenuItem, "findToolStripMenuItem");
this.findToolStripMenuItem.Name = "findToolStripMenuItem";
this.findToolStripMenuItem.Click += new System.EventHandler(this.findToolStripMenuItem_Click);
//
// markAsDeletedToolStripMenuItem
//
resources.ApplyResources(this.markAsDeletedToolStripMenuItem, "markAsDeletedToolStripMenuItem");
this.markAsDeletedToolStripMenuItem.Name = "markAsDeletedToolStripMenuItem";
this.markAsDeletedToolStripMenuItem.Click += new System.EventHandler(this.markAsDeletedToolStripMenuItem_Click);
//
// undeleteToolStripMenuItem
//
resources.ApplyResources(this.undeleteToolStripMenuItem, "undeleteToolStripMenuItem");
this.undeleteToolStripMenuItem.Name = "undeleteToolStripMenuItem";
this.undeleteToolStripMenuItem.Click += new System.EventHandler(this.undeleteToolStripMenuItem_Click);
//
// viewToolStripMenuItem
//
this.viewToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.statusBarToolStripMenuItem,
this.epiInfoLogsToolStripMenuItem});
this.viewToolStripMenuItem.Name = "viewToolStripMenuItem";
resources.ApplyResources(this.viewToolStripMenuItem, "viewToolStripMenuItem");
//
// statusBarToolStripMenuItem
//
this.statusBarToolStripMenuItem.Name = "statusBarToolStripMenuItem";
resources.ApplyResources(this.statusBarToolStripMenuItem, "statusBarToolStripMenuItem");
this.statusBarToolStripMenuItem.Click += new System.EventHandler(this.statusBarToolStripMenuItem_Click);
//
// epiInfoLogsToolStripMenuItem
//
this.epiInfoLogsToolStripMenuItem.Name = "epiInfoLogsToolStripMenuItem";
resources.ApplyResources(this.epiInfoLogsToolStripMenuItem, "epiInfoLogsToolStripMenuItem");
this.epiInfoLogsToolStripMenuItem.Click += new System.EventHandler(this.epiInfoLogsToolStripMenuItem_Click);
//
// toolsToolStripMenuItem
//
this.toolsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.dataDictionaryToolStripMenuItem,
this.toolStripMenuItem1,
this.compactDatabaseToolStripMenuItem,
this.toolStripMenuItem2,
this.optionsToolStripMenuItem,
this.enableCheckCodeExecutionToolStripMenuItem,
this.enableCheckCodeErrorSupressionToolStripMenuItem,
this.copyShortcutToClipboardToolStripMenuItem});
this.toolsToolStripMenuItem.Name = "toolsToolStripMenuItem";
resources.ApplyResources(this.toolsToolStripMenuItem, "toolsToolStripMenuItem");
//
// dataDictionaryToolStripMenuItem
//
this.dataDictionaryToolStripMenuItem.Name = "dataDictionaryToolStripMenuItem";
resources.ApplyResources(this.dataDictionaryToolStripMenuItem, "dataDictionaryToolStripMenuItem");
this.dataDictionaryToolStripMenuItem.Click += new System.EventHandler(this.dataDictionaryToolStripMenuItem_Click);
//
// toolStripMenuItem1
//
this.toolStripMenuItem1.Name = "toolStripMenuItem1";
resources.ApplyResources(this.toolStripMenuItem1, "toolStripMenuItem1");
//
// compactDatabaseToolStripMenuItem
//
resources.ApplyResources(this.compactDatabaseToolStripMenuItem, "compactDatabaseToolStripMenuItem");
this.compactDatabaseToolStripMenuItem.Name = "compactDatabaseToolStripMenuItem";
this.compactDatabaseToolStripMenuItem.Click += new System.EventHandler(this.compactDatabaseToolStripMenuItem_Click);
//
// toolStripMenuItem2
//
this.toolStripMenuItem2.Name = "toolStripMenuItem2";
resources.ApplyResources(this.toolStripMenuItem2, "toolStripMenuItem2");
//
// optionsToolStripMenuItem
//
this.optionsToolStripMenuItem.Name = "optionsToolStripMenuItem";
resources.ApplyResources(this.optionsToolStripMenuItem, "optionsToolStripMenuItem");
this.optionsToolStripMenuItem.Click += new System.EventHandler(this.optionsToolStripMenuItem_Click);
//
// enableCheckCodeExecutionToolStripMenuItem
//
this.enableCheckCodeExecutionToolStripMenuItem.Checked = true;
this.enableCheckCodeExecutionToolStripMenuItem.CheckOnClick = true;
this.enableCheckCodeExecutionToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked;
this.enableCheckCodeExecutionToolStripMenuItem.Name = "enableCheckCodeExecutionToolStripMenuItem";
resources.ApplyResources(this.enableCheckCodeExecutionToolStripMenuItem, "enableCheckCodeExecutionToolStripMenuItem");
this.enableCheckCodeExecutionToolStripMenuItem.Click += new System.EventHandler(this.enableCheckCodeExecutionToolStripMenuItem_Click);
//
// enableCheckCodeErrorSupressionToolStripMenuItem
//
this.enableCheckCodeErrorSupressionToolStripMenuItem.Checked = true;
this.enableCheckCodeErrorSupressionToolStripMenuItem.CheckOnClick = true;
this.enableCheckCodeErrorSupressionToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked;
this.enableCheckCodeErrorSupressionToolStripMenuItem.Name = "enableCheckCodeErrorSupressionToolStripMenuItem";
resources.ApplyResources(this.enableCheckCodeErrorSupressionToolStripMenuItem, "enableCheckCodeErrorSupressionToolStripMenuItem");
this.enableCheckCodeErrorSupressionToolStripMenuItem.Click += new System.EventHandler(this.enableCheckCodeErrorSupressionToolStripMenuItem_Click);
//
// copyShortcutToClipboardToolStripMenuItem
//
this.copyShortcutToClipboardToolStripMenuItem.Name = "copyShortcutToClipboardToolStripMenuItem";
resources.ApplyResources(this.copyShortcutToClipboardToolStripMenuItem, "copyShortcutToClipboardToolStripMenuItem");
this.copyShortcutToClipboardToolStripMenuItem.Click += new System.EventHandler(this.copyShortcutToClipboardToolStripMenuItem_Click);
//
// helpToolStripMenuItem
//
this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.contentsToolStripMenuItem,
this.aboutEpiInfoToolStripMenuItem});
this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
resources.ApplyResources(this.helpToolStripMenuItem, "helpToolStripMenuItem");
//
// contentsToolStripMenuItem
//
this.contentsToolStripMenuItem.Name = "contentsToolStripMenuItem";
resources.ApplyResources(this.contentsToolStripMenuItem, "contentsToolStripMenuItem");
this.contentsToolStripMenuItem.Click += new System.EventHandler(this.contentsToolStripMenuItem_Click);
//
// aboutEpiInfoToolStripMenuItem
//
this.aboutEpiInfoToolStripMenuItem.Name = "aboutEpiInfoToolStripMenuItem";
resources.ApplyResources(this.aboutEpiInfoToolStripMenuItem, "aboutEpiInfoToolStripMenuItem");
this.aboutEpiInfoToolStripMenuItem.Click += new System.EventHandler(this.aboutEpiInfoToolStripMenuItem_Click);
//
// toolStrip2
//
resources.ApplyResources(this.toolStrip2, "toolStrip2");
this.toolStrip2.ImageScalingSize = new System.Drawing.Size(20, 20);
this.toolStrip2.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.btnHome,
this.toolStripSeparator9,
this.btnBack});
this.toolStrip2.Name = "toolStrip2";
//
// btnHome
//
this.btnHome.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
resources.ApplyResources(this.btnHome, "btnHome");
this.btnHome.Name = "btnHome";
this.btnHome.Click += new System.EventHandler(this.btnHome_Click);
//
// toolStripSeparator9
//
this.toolStripSeparator9.Name = "toolStripSeparator9";
resources.ApplyResources(this.toolStripSeparator9, "toolStripSeparator9");
//
// btnBack
//
this.btnBack.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
resources.ApplyResources(this.btnBack, "btnBack");
this.btnBack.Name = "btnBack";
this.btnBack.Click += new System.EventHandler(this.btnBack_Click);
//
// toolStrip1
//
resources.ApplyResources(this.toolStrip1, "toolStrip1");
this.toolStrip1.ImageScalingSize = new System.Drawing.Size(20, 20);
this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.btiOpen,
this.btiSave,
this.btiPrint,
this.toolStripSeparator5,
this.btiFind,
this.toolStripSeparator6,
this.btiNew,
this.toolStripFirstButton,
this.toolStripPreviousButton,
this.toolStripRecordNumber,
this.toolStripOfLabel,
this.toolStripRecordCount,
this.toolStripNextButton,
this.toolStripLastButton,
this.toolStripSeparator8,
this.btiMarkDeleted,
this.btiUndelete,
this.toolStripSeparator7,
this.LineListingToolStripButton,
this.tsbDashboard,
this.tsbMap,
this.toolStripSeparator10,
this.btiEditView,
this.btiHelp});
this.toolStrip1.Name = "toolStrip1";
this.toolStrip1.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.toolStrip1_ItemClicked);
//
// btiOpen
//
resources.ApplyResources(this.btiOpen, "btiOpen");
this.btiOpen.Name = "btiOpen";
this.btiOpen.Click += new System.EventHandler(this.openViewToolStripMenuItem_Click);
//
// btiSave
//
resources.ApplyResources(this.btiSave, "btiSave");
this.btiSave.Name = "btiSave";
this.btiSave.Click += new System.EventHandler(this.saveToolStripMenuItem_Click);
//
// btiPrint
//
resources.ApplyResources(this.btiPrint, "btiPrint");
this.btiPrint.Name = "btiPrint";
this.btiPrint.Click += new System.EventHandler(this.printToolStripMenuItem_Click);
//
// toolStripSeparator5
//
this.toolStripSeparator5.Name = "toolStripSeparator5";
resources.ApplyResources(this.toolStripSeparator5, "toolStripSeparator5");
//
// btiFind
//
resources.ApplyResources(this.btiFind, "btiFind");
this.btiFind.Name = "btiFind";
this.btiFind.Click += new System.EventHandler(this.findToolStripMenuItem_Click);
//
// toolStripSeparator6
//
this.toolStripSeparator6.Name = "toolStripSeparator6";
resources.ApplyResources(this.toolStripSeparator6, "toolStripSeparator6");
//
// btiNew
//
this.btiNew.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
resources.ApplyResources(this.btiNew, "btiNew");
this.btiNew.Name = "btiNew";
this.btiNew.Click += new System.EventHandler(this.newRecordToolStripMenuItem_Click);
//
// toolStripFirstButton
//
this.toolStripFirstButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
resources.ApplyResources(this.toolStripFirstButton, "toolStripFirstButton");
this.toolStripFirstButton.Name = "toolStripFirstButton";
this.toolStripFirstButton.Click += new System.EventHandler(this.toolStripFirstButton_Click);
//
// toolStripPreviousButton
//
this.toolStripPreviousButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
resources.ApplyResources(this.toolStripPreviousButton, "toolStripPreviousButton");
this.toolStripPreviousButton.Name = "toolStripPreviousButton";
this.toolStripPreviousButton.Click += new System.EventHandler(this.toolStripPreviousButton_Click);
//
// toolStripRecordNumber
//
this.toolStripRecordNumber.AcceptsReturn = true;
this.toolStripRecordNumber.AcceptsTab = true;
resources.ApplyResources(this.toolStripRecordNumber, "toolStripRecordNumber");
this.toolStripRecordNumber.Name = "toolStripRecordNumber";
this.toolStripRecordNumber.Leave += new System.EventHandler(this.toolStripPageNumber_Leave);
this.toolStripRecordNumber.KeyDown += new System.Windows.Forms.KeyEventHandler(this.toolStripRecordNumber_KeyDown);
//
// toolStripOfLabel
//
resources.ApplyResources(this.toolStripOfLabel, "toolStripOfLabel");
this.toolStripOfLabel.Name = "toolStripOfLabel";
//
// toolStripRecordCount
//
resources.ApplyResources(this.toolStripRecordCount, "toolStripRecordCount");
this.toolStripRecordCount.Name = "toolStripRecordCount";
//
// toolStripNextButton
//
this.toolStripNextButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
resources.ApplyResources(this.toolStripNextButton, "toolStripNextButton");
this.toolStripNextButton.Name = "toolStripNextButton";
this.toolStripNextButton.Click += new System.EventHandler(this.toolStripNextButton_Click);
//
// toolStripLastButton
//
this.toolStripLastButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
resources.ApplyResources(this.toolStripLastButton, "toolStripLastButton");
this.toolStripLastButton.Name = "toolStripLastButton";
this.toolStripLastButton.Click += new System.EventHandler(this.toolStripLastButton_Click);
//
// toolStripSeparator8
//
this.toolStripSeparator8.Name = "toolStripSeparator8";
resources.ApplyResources(this.toolStripSeparator8, "toolStripSeparator8");
//
// btiMarkDeleted
//
this.btiMarkDeleted.BackColor = System.Drawing.SystemColors.Control;
resources.ApplyResources(this.btiMarkDeleted, "btiMarkDeleted");
this.btiMarkDeleted.Name = "btiMarkDeleted";
this.btiMarkDeleted.Click += new System.EventHandler(this.markAsDeletedToolStripMenuItem_Click);
//
// btiUndelete
//
resources.ApplyResources(this.btiUndelete, "btiUndelete");
this.btiUndelete.Name = "btiUndelete";
this.btiUndelete.Click += new System.EventHandler(this.undeleteToolStripMenuItem_Click);
//
// toolStripSeparator7
//
this.toolStripSeparator7.Name = "toolStripSeparator7";
resources.ApplyResources(this.toolStripSeparator7, "toolStripSeparator7");
//
// LineListingToolStripButton
//
this.LineListingToolStripButton.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.gridToolStripMenuItem,
this.printableHTMLToolStripMenuItem,
this.excelLineListMenuItem});
resources.ApplyResources(this.LineListingToolStripButton, "LineListingToolStripButton");
this.LineListingToolStripButton.Name = "LineListingToolStripButton";
this.LineListingToolStripButton.ButtonClick += new System.EventHandler(this.gridToolStripMenuItem_Click);
//
// gridToolStripMenuItem
//
resources.ApplyResources(this.gridToolStripMenuItem, "gridToolStripMenuItem");
this.gridToolStripMenuItem.Name = "gridToolStripMenuItem";
this.gridToolStripMenuItem.Click += new System.EventHandler(this.gridToolStripMenuItem_Click);
//
// printableHTMLToolStripMenuItem
//
resources.ApplyResources(this.printableHTMLToolStripMenuItem, "printableHTMLToolStripMenuItem");
this.printableHTMLToolStripMenuItem.Name = "printableHTMLToolStripMenuItem";
this.printableHTMLToolStripMenuItem.Click += new System.EventHandler(this.printableHTMLToolStripMenuItem_Click);
//
// excelLineListMenuItem
//
resources.ApplyResources(this.excelLineListMenuItem, "excelLineListMenuItem");
this.excelLineListMenuItem.Name = "excelLineListMenuItem";
this.excelLineListMenuItem.Click += new System.EventHandler(this.excelLineListMenuItem_Click);
//
// tsbDashboard
//
resources.ApplyResources(this.tsbDashboard, "tsbDashboard");
this.tsbDashboard.Name = "tsbDashboard";
this.tsbDashboard.Click += new System.EventHandler(this.tsbDashboard_Click);
//
// tsbMap
//
resources.ApplyResources(this.tsbMap, "tsbMap");
this.tsbMap.Name = "tsbMap";
this.tsbMap.Click += new System.EventHandler(this.tsbMap_Click);
//
// toolStripSeparator10
//
this.toolStripSeparator10.Name = "toolStripSeparator10";
resources.ApplyResources(this.toolStripSeparator10, "toolStripSeparator10");
//
// btiEditView
//
resources.ApplyResources(this.btiEditView, "btiEditView");
this.btiEditView.Name = "btiEditView";
this.btiEditView.Click += new System.EventHandler(this.editViewToolStripMenuItem_Click);
//
// btiHelp
//
resources.ApplyResources(this.btiHelp, "btiHelp");
this.btiHelp.Name = "btiHelp";
this.btiHelp.Click += new System.EventHandler(this.btnHelp_Click);
//
// BottomToolStripPanel
//
resources.ApplyResources(this.BottomToolStripPanel, "BottomToolStripPanel");
this.BottomToolStripPanel.Name = "BottomToolStripPanel";
this.BottomToolStripPanel.Orientation = System.Windows.Forms.Orientation.Horizontal;
this.BottomToolStripPanel.RowMargin = new System.Windows.Forms.Padding(3, 0, 0, 0);
//
// TopToolStripPanel
//
resources.ApplyResources(this.TopToolStripPanel, "TopToolStripPanel");
this.TopToolStripPanel.Name = "TopToolStripPanel";
this.TopToolStripPanel.Orientation = System.Windows.Forms.Orientation.Horizontal;
this.TopToolStripPanel.RowMargin = new System.Windows.Forms.Padding(3, 0, 0, 0);
//
// RightToolStripPanel
//
resources.ApplyResources(this.RightToolStripPanel, "RightToolStripPanel");
this.RightToolStripPanel.Name = "RightToolStripPanel";
this.RightToolStripPanel.Orientation = System.Windows.Forms.Orientation.Horizontal;
this.RightToolStripPanel.RowMargin = new System.Windows.Forms.Padding(3, 0, 0, 0);
//
// LeftToolStripPanel
//
resources.ApplyResources(this.LeftToolStripPanel, "LeftToolStripPanel");
this.LeftToolStripPanel.Name = "LeftToolStripPanel";
this.LeftToolStripPanel.Orientation = System.Windows.Forms.Orientation.Horizontal;
this.LeftToolStripPanel.RowMargin = new System.Windows.Forms.Padding(3, 0, 0, 0);
//
// ContentPanel
//
resources.ApplyResources(this.ContentPanel, "ContentPanel");
//
// EnterMainForm
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.toolStripContainer1);
this.KeyPreview = true;
this.MainMenuStrip = this.menuStrip1;
this.Name = "EnterMainForm";
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Enter_FormClosing);
this.Load += new System.EventHandler(this.Enter_Load);
this.Controls.SetChildIndex(this.toolStripContainer1, 0);
this.toolStripContainer1.ContentPanel.ResumeLayout(false);
this.toolStripContainer1.TopToolStripPanel.ResumeLayout(false);
this.toolStripContainer1.TopToolStripPanel.PerformLayout();
this.toolStripContainer1.ResumeLayout(false);
this.toolStripContainer1.PerformLayout();
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.toolStrip2.ResumeLayout(false);
this.toolStrip2.PerformLayout();
this.toolStrip1.ResumeLayout(false);
this.toolStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
#region Private Members
private System.Windows.Forms.ToolStripPanel BottomToolStripPanel;
private System.Windows.Forms.ToolStripPanel TopToolStripPanel;
private System.Windows.Forms.ToolStrip toolStrip1;
private System.Windows.Forms.ToolStripButton btiNew;
private System.Windows.Forms.ToolStripButton btiOpen;
private System.Windows.Forms.ToolStripButton btiSave;
private System.Windows.Forms.ToolStripButton btiPrint;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator5;
private System.Windows.Forms.ToolStripButton btiFind;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator6;
private System.Windows.Forms.ToolStripButton btiMarkDeleted;
private System.Windows.Forms.ToolStripButton btiUndelete;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator7;
private System.Windows.Forms.ToolStripButton btiHelp;
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem newRecordToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem openViewToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem closeViewToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripMenuItem saveToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripMenuItem printToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
private System.Windows.Forms.ToolStripMenuItem recentViewsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem editToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem findToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem markAsDeletedToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem undeleteToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem toolsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem compactDatabaseToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem optionsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem contentsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem aboutEpiInfoToolStripMenuItem;
private System.Windows.Forms.ToolStripPanel RightToolStripPanel;
private System.Windows.Forms.ToolStripPanel LeftToolStripPanel;
private System.Windows.Forms.ToolStripContentPanel ContentPanel;
private System.Windows.Forms.ToolStripContainer toolStripContainer1;
private Epi.Windows.Docking.DockManager enterDockManager;
private ViewExplorer viewExplorer;
private Canvas canvas;
private PresentationLogic.GuiMediator mediator;
private View view;
private View homeView;
private string recordId;
public bool isViewOpened = false;
private System.Windows.Forms.ToolStripButton toolStripFirstButton;
private System.Windows.Forms.ToolStripButton toolStripPreviousButton;
private System.Windows.Forms.ToolStripTextBox toolStripRecordNumber;
private System.Windows.Forms.ToolStripLabel toolStripOfLabel;
private System.Windows.Forms.ToolStripButton toolStripNextButton;
private System.Windows.Forms.ToolStripButton toolStripLastButton;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator8;
private System.Windows.Forms.ToolStripLabel toolStripRecordCount;
private System.Windows.Forms.ToolStripMenuItem editViewToolStripMenuItem;
private System.Windows.Forms.ToolStripButton btiEditView;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator4;
private System.Windows.Forms.ToolStripMenuItem viewToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem statusBarToolStripMenuItem;
private System.Windows.Forms.ToolStrip toolStrip2;
private System.Windows.Forms.ToolStripButton btnHome;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator9;
private System.Windows.Forms.ToolStripButton btnBack;
#endregion //Private Members
private System.Windows.Forms.ToolStripMenuItem epiInfoLogsToolStripMenuItem;
private System.Windows.Forms.ToolStripSplitButton LineListingToolStripButton;
private System.Windows.Forms.ToolStripMenuItem gridToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem printableHTMLToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator10;
private System.Windows.Forms.ToolStripMenuItem enableCheckCodeExecutionToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem enableCheckCodeErrorSupressionToolStripMenuItem;
private System.Windows.Forms.ToolStripButton tsbDashboard;
private System.Windows.Forms.ToolStripButton tsbMap;
private System.Windows.Forms.ToolStripMenuItem excelLineListMenuItem;
private System.Windows.Forms.ToolStripMenuItem dataDictionaryToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem2;
private System.Windows.Forms.ToolStripMenuItem mnuPackageForTransport;
private System.Windows.Forms.ToolStripMenuItem importDataToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem mnuImportFromWeb;
private System.Windows.Forms.ToolStripMenuItem mnuImportFromForm;
private System.Windows.Forms.ToolStripMenuItem mnuImportFromPhone;
private System.Windows.Forms.ToolStripMenuItem mnuImportFromDataPackage;
private System.Windows.Forms.ToolStripMenuItem copyShortcutToClipboardToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem fromWebEnterToolStripMenuItem;
}
}
| |
using Pathfinding;
using Pathfinding.Util;
using System.Collections.Generic;
using UnityEngine;
namespace Pathfinding
{
/** Contains useful functions for working with paths and nodes.
* This class works a lot with the Node class, a useful function to get nodes is AstarPath.GetNearest.
* \see AstarPath.GetNearest
* \see Pathfinding.Utils.GraphUpdateUtilities
* \since Added in version 3.2
* \ingroup utils
*
*/
public static class PathUtilities {
/** Returns if there is a walkable path from \a n1 to \a n2.
* If you are making changes to the graph, areas must first be recaculated using FloodFill()
* \note This might return true for small areas even if there is no possible path if AstarPath.minAreaSize is greater than zero (0).
* So when using this, it is recommended to set AstarPath.minAreaSize to 0. (A* Inspector -> Settings -> Pathfinding)
* \see AstarPath.GetNearest
*/
public static bool IsPathPossible (GraphNode n1, GraphNode n2) {
return n1.Walkable && n2.Walkable && n1.Area == n2.Area;
}
/** Returns if there are walkable paths between all nodes.
* If you are making changes to the graph, areas must first be recaculated using FloodFill()
* \note This might return true for small areas even if there is no possible path if AstarPath.minAreaSize is greater than zero (0).
* So when using this, it is recommended to set AstarPath.minAreaSize to 0. (A* Inspector -> Settings -> Pathfinding)
*
* Returns true for empty lists
*
* \see AstarPath.GetNearest
*/
public static bool IsPathPossible (List<GraphNode> nodes) {
if (nodes.Count == 0) return true;
uint area = nodes[0].Area;
for (int i=0;i<nodes.Count;i++) if (!nodes[i].Walkable || nodes[i].Area != area) return false;
return true;
}
/** Returns if there are walkable paths between all nodes.
* If you are making changes to the graph, areas should first be recaculated using FloodFill()
*
* This method will actually only check if the first node can reach all other nodes. However this is
* equivalent in 99% of the cases since almost always the graph connections are bidirectional.
* If you are not aware of any cases where you explicitly create unidirectional connections
* this method can be used without worries.
*
* Returns true for empty lists
*
* \warning This method is significantly slower than the IsPathPossible method which does not take a tagMask
*
* \see AstarPath.GetNearest
*/
public static bool IsPathPossible (List<GraphNode> nodes, int tagMask) {
if (nodes.Count == 0) return true;
// Make sure that the first node has a valid tag
if (((tagMask >> (int)nodes[0].Tag) & 1) == 0) return false;
// Fast check first
if (!IsPathPossible(nodes)) return false;
// Make sure that the first node can reach all other nodes
var reachable = GetReachableNodes(nodes[0], tagMask);
bool result = true;
// Make sure that the first node can reach all other nodes
for (int i=1;i<nodes.Count;i++) {
if (!reachable.Contains(nodes[i])) {
result = false;
break;
}
}
// Pool the temporary list
ListPool<GraphNode>.Release(reachable);
return result;
}
/** Returns all nodes reachable from the seed node.
* This function performs a BFS (breadth-first-search) or flood fill of the graph and returns all nodes which can be reached from
* the seed node. In almost all cases this will be identical to returning all nodes which have the same area as the seed node.
* In the editor areas are displayed as different colors of the nodes.
* The only case where it will not be so is when there is a one way path from some part of the area to the seed node
* but no path from the seed node to that part of the graph.
*
* The returned list is sorted by node distance from the seed node
* i.e distance is measured in the number of nodes the shortest path from \a seed to that node would pass through.
* Note that the distance measurement does not take heuristics, penalties or tag penalties.
*
* Depending on the number of reachable nodes, this function can take quite some time to calculate
* so don't use it too often or it might affect the framerate of your game.
*
* \param seed The node to start the search from
* \param tagMask Optional mask for tags. This is a bitmask.
*
* \returns A List<Node> containing all nodes reachable from the seed node.
* For better memory management the returned list should be pooled, see Pathfinding.Util.ListPool
*/
public static List<GraphNode> GetReachableNodes (GraphNode seed, int tagMask = -1) {
Stack<GraphNode> stack = StackPool<GraphNode>.Claim ();
List<GraphNode> list = ListPool<GraphNode>.Claim ();
/** \todo Pool */
var map = new HashSet<GraphNode>();
GraphNodeDelegate callback;
if (tagMask == -1) {
callback = delegate (GraphNode node) {
if (node.Walkable && map.Add (node)) {
list.Add (node);
stack.Push (node);
}
};
} else {
callback = delegate (GraphNode node) {
if (node.Walkable && ((tagMask >> (int)node.Tag) & 0x1) != 0 && map.Add (node)) {
list.Add (node);
stack.Push (node);
}
};
}
callback (seed);
while (stack.Count > 0) {
stack.Pop ().GetConnections (callback);
}
StackPool<GraphNode>.Release (stack);
return list;
}
static Queue<GraphNode> BFSQueue;
static Dictionary<GraphNode,int> BFSMap;
/** Returns all nodes up to a given node-distance from the seed node.
* This function performs a BFS (breadth-first-search) or flood fill of the graph and returns all nodes within a specified node distance which can be reached from
* the seed node. In almost all cases when \a depth is large enough this will be identical to returning all nodes which have the same area as the seed node.
* In the editor areas are displayed as different colors of the nodes.
* The only case where it will not be so is when there is a one way path from some part of the area to the seed node
* but no path from the seed node to that part of the graph.
*
* The returned list is sorted by node distance from the seed node
* i.e distance is measured in the number of nodes the shortest path from \a seed to that node would pass through.
* Note that the distance measurement does not take heuristics, penalties or tag penalties.
*
* Depending on the number of nodes, this function can take quite some time to calculate
* so don't use it too often or it might affect the framerate of your game.
*
* \param seed The node to start the search from.
* \param depth The maximum node-distance from the seed node.
* \param tagMask Optional mask for tags. This is a bitmask.
*
* \returns A List<Node> containing all nodes reachable up to a specified node distance from the seed node.
* For better memory management the returned list should be pooled, see Pathfinding.Util.ListPool
*
* \warning This method is not thread safe. Only use it from the Unity thread (i.e normal game code).
*/
public static List<GraphNode> BFS (GraphNode seed, int depth, int tagMask = -1) {
BFSQueue = BFSQueue ?? new Queue<GraphNode>();
var que = BFSQueue;
BFSMap = BFSMap ?? new Dictionary<GraphNode,int>();
var map = BFSMap;
// Even though we clear at the end of this function, it is good to
// do it here as well in case the previous invocation of the method
// threw an exception for some reason
// and didn't clear the que and map
que.Clear ();
map.Clear ();
List<GraphNode> result = ListPool<GraphNode>.Claim ();
int currentDist = -1;
GraphNodeDelegate callback;
if (tagMask == -1) {
callback = node => {
if (node.Walkable && !map.ContainsKey (node)) {
map.Add (node, currentDist+1);
result.Add (node);
que.Enqueue (node);
}
};
} else {
callback = node => {
if (node.Walkable && ((tagMask >> (int)node.Tag) & 0x1) != 0 && !map.ContainsKey (node)) {
map.Add (node, currentDist+1);
result.Add (node);
que.Enqueue (node);
}
};
}
callback (seed);
while (que.Count > 0 ) {
GraphNode n = que.Dequeue ();
currentDist = map[n];
if ( currentDist >= depth ) break;
n.GetConnections (callback);
}
que.Clear ();
map.Clear ();
return result;
}
/** Returns points in a spiral centered around the origin with a minimum clearance from other points.
* The points are laid out on the involute of a circle
* \see http://en.wikipedia.org/wiki/Involute
* Which has some nice properties.
* All points are separated by \a clearance world units.
* This method is O(n), yes if you read the code you will see a binary search, but that binary search
* has an upper bound on the number of steps, so it does not yield a log factor.
*
* \note Consider recycling the list after usage to reduce allocations.
* \see Pathfinding.Util.ListPool
*/
public static List<Vector3> GetSpiralPoints (int count, float clearance) {
List<Vector3> pts = ListPool<Vector3>.Claim(count);
// The radius of the smaller circle used for generating the involute of a circle
// Calculated from the separation distance between the turns
float a = clearance/(2*Mathf.PI);
float t = 0;
pts.Add (InvoluteOfCircle(a, t));
for (int i=0;i<count;i++) {
Vector3 prev = pts[pts.Count-1];
// d = -t0/2 + sqrt( t0^2/4 + 2d/a )
// Minimum angle (radians) which would create an arc distance greater than clearance
float d = -t/2 + Mathf.Sqrt (t*t/4 + 2*clearance/a);
// Binary search for separating this point and the previous one
float mn = t + d;
float mx = t + 2*d;
while (mx - mn > 0.01f) {
float mid = (mn + mx)/2;
Vector3 p = InvoluteOfCircle (a, mid);
if ((p - prev).sqrMagnitude < clearance*clearance) {
mn = mid;
} else {
mx = mid;
}
}
pts.Add ( InvoluteOfCircle (a, mx) );
t = mx;
}
return pts;
}
/** Returns the XZ coordinate of the involute of circle.
* \see http://en.wikipedia.org/wiki/Involute
*/
private static Vector3 InvoluteOfCircle (float a, float t) {
return new Vector3(a*(Mathf.Cos(t) + t*Mathf.Sin(t)), 0, a*(Mathf.Sin(t) - t*Mathf.Cos(t)));
}
/** Will calculate a number of points around \a p which are on the graph and are separated by \a clearance from each other.
* This is like GetPointsAroundPoint except that \a previousPoints are treated as being in world space.
* The average of the points will be found and then that will be treated as the group center.
*/
public static void GetPointsAroundPointWorld (Vector3 p, IRaycastableGraph g, List<Vector3> previousPoints, float radius, float clearanceRadius) {
if ( previousPoints.Count == 0 ) return;
Vector3 avg = Vector3.zero;
for ( int i = 0; i < previousPoints.Count; i++ ) avg += previousPoints[i];
avg /= previousPoints.Count;
for ( int i = 0; i < previousPoints.Count; i++ ) previousPoints[i] -= avg;
GetPointsAroundPoint ( p, g, previousPoints, radius, clearanceRadius );
}
/** Will calculate a number of points around \a p which are on the graph and are separated by \a clearance from each other.
* The maximum distance from \a p to any point will be \a radius.
* Points will first be tried to be laid out as \a previousPoints and if that fails, random points will be selected.
* This is great if you want to pick a number of target points for group movement. If you pass all current agent points from e.g the group's average position
* this method will return target points so that the units move very little within the group, this is often aesthetically pleasing and reduces jitter if using
* some kind of local avoidance.
*
* \param p The point to generate points around
* \param g The graph to use for linecasting. If you are only using one graph, you can get this by AstarPath.active.graphs[0] as IRaycastableGraph.
* Note that not all graphs are raycastable, recast, navmesh and grid graphs are raycastable. On recast and navmesh it works the best.
* \param previousPoints The points to use for reference. Note that these should not be in world space. They are treated as relative to \a p.
* \param radius The final points will be at most this distance from \a p.
* \param clearanceRadius The points will if possible be at least this distance from each other.
*/
public static void GetPointsAroundPoint (Vector3 p, IRaycastableGraph g, List<Vector3> previousPoints, float radius, float clearanceRadius) {
if (g == null) throw new System.ArgumentNullException ("g");
var graph = g as NavGraph;
if (graph == null) throw new System.ArgumentException ("g is not a NavGraph");
NNInfo nn = graph.GetNearestForce (p, NNConstraint.Default);
p = nn.clampedPosition;
if (nn.node == null) {
// No valid point to start from
return;
}
// Make sure the enclosing circle has a radius which can pack circles with packing density 0.5
radius = Mathf.Max (radius, 1.4142f*clearanceRadius*Mathf.Sqrt(previousPoints.Count));//Mathf.Sqrt(previousPoints.Count*clearanceRadius*2));
clearanceRadius *= clearanceRadius;
for (int i=0;i<previousPoints.Count;i++) {
Vector3 dir = previousPoints[i];
float magn = dir.magnitude;
if (magn > 0) dir /= magn;
float newMagn = radius;//magn > radius ? radius : magn;
dir *= newMagn;
bool worked = false;
GraphHitInfo hit;
int tests = 0;
do {
Vector3 pt = p + dir;
if (g.Linecast (p, pt, nn.node, out hit)) {
pt = hit.point;
}
for (float q = 0.1f; q <= 1.0f; q+= 0.05f) {
Vector3 qt = (pt - p)*q + p;
worked = true;
for (int j=0;j<i;j++) {
if ((previousPoints[j] - qt).sqrMagnitude < clearanceRadius) {
worked = false;
break;
}
}
if (worked) {
previousPoints[i] = qt;
break;
}
}
if (!worked) {
// Abort after 8 tries
if (tests > 8) {
worked = true;
} else {
clearanceRadius *= 0.9f;
// This will pick points in 2D closer to the edge of the circle with a higher probability
dir = Random.onUnitSphere * Mathf.Lerp (newMagn, radius, tests / 5);
dir.y = 0;
tests++;
}
}
} while (!worked);
}
}
/** Returns randomly selected points on the specified nodes with each point being separated by \a clearanceRadius from each other.
* Selecting points ON the nodes only works for TriangleMeshNode (used by Recast Graph and Navmesh Graph) and GridNode (used by GridGraph).
* For other node types, only the positions of the nodes will be used.
*
* clearanceRadius will be reduced if no valid points can be found.
*/
public static List<Vector3> GetPointsOnNodes (List<GraphNode> nodes, int count, float clearanceRadius = 0) {
if (nodes == null) throw new System.ArgumentNullException ("nodes");
if (nodes.Count == 0) throw new System.ArgumentException ("no nodes passed");
var rnd = new System.Random();
List<Vector3> pts = ListPool<Vector3>.Claim(count);
// Square
clearanceRadius *= clearanceRadius;
if (nodes[0] is TriangleMeshNode
|| nodes[0] is GridNode
) {
//Assume all nodes are triangle nodes or grid nodes
List<float> accs = ListPool<float>.Claim(nodes.Count);
float tot = 0;
for (int i=0;i<nodes.Count;i++) {
var tnode = nodes[i] as TriangleMeshNode;
if (tnode != null) {
/** \bug Doesn't this need to be divided by 2? */
float a = System.Math.Abs(Polygon.TriangleArea2(tnode.GetVertex(0), tnode.GetVertex(1), tnode.GetVertex(2)));
tot += a;
accs.Add (tot);
}
else {
var gnode = nodes[i] as GridNode;
if (gnode != null) {
GridGraph gg = GridNode.GetGridGraph (gnode.GraphIndex);
float a = gg.nodeSize*gg.nodeSize;
tot += a;
accs.Add (tot);
} else {
accs.Add(tot);
}
}
}
for (int i=0;i<count;i++) {
//Pick point
int testCount = 0;
int testLimit = 10;
bool worked = false;
while (!worked) {
worked = true;
//If no valid points can be found, progressively lower the clearance radius until such a point is found
if (testCount >= testLimit) {
clearanceRadius *= 0.8f;
testLimit += 10;
if (testLimit > 100) clearanceRadius = 0;
}
float tg = (float)rnd.NextDouble()*tot;
int v = accs.BinarySearch(tg);
if (v < 0) v = ~v;
if (v >= nodes.Count) {
// This shouldn't happen, due to NextDouble being smaller than 1... but I don't trust floating point arithmetic.
worked = false;
continue;
}
var node = nodes[v] as TriangleMeshNode;
Vector3 p;
if (node != null) {
// Find a random point inside the triangle
float v1;
float v2;
do {
v1 = (float)rnd.NextDouble();
v2 = (float)rnd.NextDouble();
} while (v1+v2 > 1);
p = ((Vector3)(node.GetVertex(1)-node.GetVertex(0)))*v1 + ((Vector3)(node.GetVertex(2)-node.GetVertex(0)))*v2 + (Vector3)node.GetVertex(0);
} else {
var gnode = nodes[v] as GridNode;
if (gnode != null) {
GridGraph gg = GridNode.GetGridGraph (gnode.GraphIndex);
float v1 = (float)rnd.NextDouble();
float v2 = (float)rnd.NextDouble();
p = (Vector3)gnode.position + new Vector3(v1 - 0.5f, 0, v2 - 0.5f) * gg.nodeSize;
} else
{
//Point nodes have no area, so we break directly instead
pts.Add ((Vector3)nodes[v].position);
break;
}
}
// Test if it is some distance away from the other points
if (clearanceRadius > 0) {
for (int j=0;j<pts.Count;j++) {
if ((pts[j]-p).sqrMagnitude < clearanceRadius) {
worked = false;
break;
}
}
}
if (worked) {
pts.Add (p);
break;
}
testCount++;
}
}
ListPool<float>.Release(accs);
} else {
for (int i=0;i<count;i++) {
pts.Add ((Vector3)nodes[rnd.Next (nodes.Count)].position);
}
}
return pts;
}
}
}
| |
// 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.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Threading;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.GenerateMember.GenerateMethod;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.GenerateMember.GenerateParameterizedMember
{
[ExportLanguageService(typeof(IGenerateConversionService), LanguageNames.CSharp), Shared]
internal partial class CSharpGenerateConversionService :
AbstractGenerateConversionService<CSharpGenerateConversionService, SimpleNameSyntax, ExpressionSyntax, InvocationExpressionSyntax>
{
protected override bool IsImplicitConversionGeneration(SyntaxNode node)
{
return node is ExpressionSyntax &&
(node.Parent is AssignmentExpressionSyntax || node.Parent is EqualsValueClauseSyntax) &&
!(node is CastExpressionSyntax) &&
!(node is MemberAccessExpressionSyntax);
}
protected override bool IsExplicitConversionGeneration(SyntaxNode node)
{
return node is CastExpressionSyntax;
}
protected override bool ContainingTypesOrSelfHasUnsafeKeyword(INamedTypeSymbol containingType)
{
return containingType.ContainingTypesOrSelfHasUnsafeKeyword();
}
protected override AbstractInvocationInfo CreateInvocationMethodInfo(
SemanticDocument document, AbstractGenerateParameterizedMemberService<CSharpGenerateConversionService, SimpleNameSyntax, ExpressionSyntax, InvocationExpressionSyntax>.State state)
{
return new CSharpGenerateParameterizedMemberService<CSharpGenerateConversionService>.InvocationExpressionInfo(document, state);
}
protected override bool AreSpecialOptionsActive(SemanticModel semanticModel)
{
return CSharpCommonGenerationServiceMethods.AreSpecialOptionsActive(semanticModel);
}
protected override bool IsValidSymbol(ISymbol symbol, SemanticModel semanticModel)
{
return CSharpCommonGenerationServiceMethods.IsValidSymbol(symbol, semanticModel);
}
protected override bool TryInitializeImplicitConversionState(
SemanticDocument document,
SyntaxNode expression,
ISet<TypeKind> classInterfaceModuleStructTypes,
CancellationToken cancellationToken,
out SyntaxToken identifierToken,
out IMethodSymbol methodSymbol,
out INamedTypeSymbol typeToGenerateIn)
{
if (TryGetConversionMethodAndTypeToGenerateIn(document, expression, classInterfaceModuleStructTypes, cancellationToken, out methodSymbol, out typeToGenerateIn))
{
identifierToken = SyntaxFactory.Token(
default(SyntaxTriviaList),
SyntaxKind.ImplicitKeyword,
WellKnownMemberNames.ImplicitConversionName,
WellKnownMemberNames.ImplicitConversionName,
default(SyntaxTriviaList));
return true;
}
identifierToken = default(SyntaxToken);
methodSymbol = null;
typeToGenerateIn = null;
return false;
}
protected override bool TryInitializeExplicitConversionState(
SemanticDocument document,
SyntaxNode expression,
ISet<TypeKind> classInterfaceModuleStructTypes,
CancellationToken cancellationToken,
out SyntaxToken identifierToken,
out IMethodSymbol methodSymbol,
out INamedTypeSymbol typeToGenerateIn)
{
if (TryGetConversionMethodAndTypeToGenerateIn(document, expression, classInterfaceModuleStructTypes, cancellationToken, out methodSymbol, out typeToGenerateIn))
{
identifierToken = SyntaxFactory.Token(
default(SyntaxTriviaList),
SyntaxKind.ImplicitKeyword,
WellKnownMemberNames.ExplicitConversionName,
WellKnownMemberNames.ExplicitConversionName,
default(SyntaxTriviaList));
return true;
}
identifierToken = default(SyntaxToken);
methodSymbol = null;
typeToGenerateIn = null;
return false;
}
private bool TryGetConversionMethodAndTypeToGenerateIn(
SemanticDocument document,
SyntaxNode expression,
ISet<TypeKind> classInterfaceModuleStructTypes,
CancellationToken cancellationToken,
out IMethodSymbol methodSymbol,
out INamedTypeSymbol typeToGenerateIn)
{
var castExpression = expression as CastExpressionSyntax;
if (castExpression != null)
{
return TryGetExplicitConversionMethodAndTypeToGenerateIn(
document,
castExpression,
classInterfaceModuleStructTypes,
cancellationToken,
out methodSymbol,
out typeToGenerateIn);
}
return TryGetImplicitConversionMethodAndTypeToGenerateIn(
document,
expression,
classInterfaceModuleStructTypes,
cancellationToken,
out methodSymbol,
out typeToGenerateIn);
}
private bool TryGetExplicitConversionMethodAndTypeToGenerateIn(
SemanticDocument document,
CastExpressionSyntax castExpression,
ISet<TypeKind> classInterfaceModuleStructTypes,
CancellationToken cancellationToken,
out IMethodSymbol methodSymbol,
out INamedTypeSymbol typeToGenerateIn)
{
methodSymbol = null;
typeToGenerateIn = document.SemanticModel.GetTypeInfo(castExpression.Type, cancellationToken).Type as INamedTypeSymbol;
var parameterSymbol = document.SemanticModel.GetTypeInfo(castExpression.Expression, cancellationToken).Type as INamedTypeSymbol;
if (typeToGenerateIn == null || parameterSymbol == null || typeToGenerateIn.IsErrorType() || parameterSymbol.IsErrorType())
{
return false;
}
methodSymbol = GenerateMethodSymbol(typeToGenerateIn, parameterSymbol);
if (!ValidateTypeToGenerateIn(
document.Project.Solution,
typeToGenerateIn,
true,
classInterfaceModuleStructTypes,
cancellationToken))
{
typeToGenerateIn = parameterSymbol;
}
return true;
}
private bool TryGetImplicitConversionMethodAndTypeToGenerateIn(
SemanticDocument document,
SyntaxNode expression,
ISet<TypeKind> classInterfaceModuleStructTypes,
CancellationToken cancellationToken,
out IMethodSymbol methodSymbol,
out INamedTypeSymbol typeToGenerateIn)
{
methodSymbol = null;
typeToGenerateIn = document.SemanticModel.GetTypeInfo(expression, cancellationToken).ConvertedType as INamedTypeSymbol;
var parameterSymbol = document.SemanticModel.GetTypeInfo(expression, cancellationToken).Type as INamedTypeSymbol;
if (typeToGenerateIn == null || parameterSymbol == null || typeToGenerateIn.IsErrorType() || parameterSymbol.IsErrorType())
{
return false;
}
methodSymbol = GenerateMethodSymbol(typeToGenerateIn, parameterSymbol);
if (!ValidateTypeToGenerateIn(
document.Project.Solution,
typeToGenerateIn,
true,
classInterfaceModuleStructTypes,
cancellationToken))
{
typeToGenerateIn = parameterSymbol;
}
return true;
}
private static IMethodSymbol GenerateMethodSymbol(
INamedTypeSymbol typeToGenerateIn, INamedTypeSymbol parameterSymbol)
{
// Remove any generic parameters
if (typeToGenerateIn.IsGenericType)
{
typeToGenerateIn = typeToGenerateIn.ConstructUnboundGenericType().ConstructedFrom;
}
return CodeGenerationSymbolFactory.CreateMethodSymbol(
attributes: ImmutableArray<AttributeData>.Empty,
accessibility: default(Accessibility),
modifiers: default(DeclarationModifiers),
returnType: typeToGenerateIn,
returnsByRef: false,
explicitInterfaceSymbol: null,
name: null,
typeParameters: ImmutableArray<ITypeParameterSymbol>.Empty,
parameters: ImmutableArray.Create(CodeGenerationSymbolFactory.CreateParameterSymbol(parameterSymbol, "v")),
methodKind: MethodKind.Conversion);
}
protected override string GetImplicitConversionDisplayText(AbstractGenerateParameterizedMemberService<CSharpGenerateConversionService, SimpleNameSyntax, ExpressionSyntax, InvocationExpressionSyntax>.State state)
{
return string.Format(CSharpFeaturesResources.Generate_implicit_conversion_operator_in_0, state.TypeToGenerateIn.Name);
}
protected override string GetExplicitConversionDisplayText(AbstractGenerateParameterizedMemberService<CSharpGenerateConversionService, SimpleNameSyntax, ExpressionSyntax, InvocationExpressionSyntax>.State state)
{
return string.Format(CSharpFeaturesResources.Generate_explicit_conversion_operator_in_0, state.TypeToGenerateIn.Name);
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Dispatcher
{
using System.Globalization;
using System.Runtime;
using System.Xml.XPath;
internal enum AxisDirection : byte
{
Forward,
Reverse
}
internal enum QueryNodeType : byte
{
Any = 0x00,
Root = 0x01,
Attribute = 0x02,
Element = 0x04,
Text = 0x08,
Comment = 0x10,
Processing = 0x20,
Namespace = 0x40,
Multiple = 0x80,
ChildNodes = (QueryNodeType.Multiple | QueryNodeType.Element | QueryNodeType.Comment | QueryNodeType.Text | QueryNodeType.Processing),
Ancestor = (QueryNodeType.Multiple | QueryNodeType.Element | QueryNodeType.Root),
All = (QueryNodeType.Multiple | QueryNodeType.Element | QueryNodeType.Attribute | QueryNodeType.Namespace | QueryNodeType.Root | QueryNodeType.Comment | QueryNodeType.Text | QueryNodeType.Processing)
}
internal enum QueryAxisType : byte
{
None = 0,
Ancestor = 1,
AncestorOrSelf = 2,
Attribute = 3,
Child = 4,
Descendant = 5,
DescendantOrSelf = 6,
Following = 7,
FollowingSibling = 8,
Namespace = 9,
Parent = 10,
Preceding = 11,
PrecedingSibling = 12,
Self = 13
}
// 4 bytes - each element is a byte
internal struct QueryAxis
{
AxisDirection direction;
QueryNodeType principalNode;
QueryAxisType type;
QueryNodeType validNodeTypes;
internal QueryAxis(QueryAxisType type, AxisDirection direction, QueryNodeType principalNode, QueryNodeType validNodeTypes)
{
this.direction = direction;
this.principalNode = principalNode;
this.type = type;
this.validNodeTypes = validNodeTypes;
}
#if NO
internal AxisDirection Direction
{
get
{
return this.direction;
}
}
#endif
internal QueryNodeType PrincipalNodeType
{
get
{
return this.principalNode;
}
}
internal QueryAxisType Type
{
get
{
return this.type;
}
}
internal QueryNodeType ValidNodeTypes
{
get
{
return this.validNodeTypes;
}
}
internal bool IsSupported()
{
switch (this.type)
{
default:
return false;
case QueryAxisType.DescendantOrSelf:
case QueryAxisType.Descendant:
case QueryAxisType.Attribute:
case QueryAxisType.Child:
case QueryAxisType.Self:
break;
}
return true;
}
}
/// <summary>
/// Information about a qname
/// </summary>
internal enum NodeQNameType : byte
{
// QName has neither name nor namespace. Entirely empty
Empty = 0x00,
// QName has a regular name
Name = 0x01,
// QName has regular namespace
Namespace = 0x02,
// QName has both name and namespace
Standard = NodeQNameType.Name | NodeQNameType.Namespace,
// QName has a wildcard name
NameWildcard = 0x04,
// QName has a wildcard namespace
NamespaceWildcard = 0x08,
// QName is entirely wildcard
Wildcard = NodeQNameType.NameWildcard | NodeQNameType.NamespaceWildcard
}
/// <summary>
/// We'll use our own class to store QNames instead of XmlQualifiedName because:
/// 1. Our is a struct. No allocations required. We have to dynamically create QNames in several places and
/// and don't want to do allocations
/// 2. Our equality tests are frequently faster. XmlQualifiedName implements .Equal with the assumption that
/// strings are atomized using a shared name table, which in the case of arbitrary object graphs, they almost
/// never will be.
/// </summary>
internal struct NodeQName
{
internal static NodeQName Empty = new NodeQName(string.Empty, string.Empty);
internal string name;
internal string ns;
internal NodeQName(string name)
: this(name, string.Empty)
{
}
internal NodeQName(string name, string ns)
{
this.name = (null == name) ? string.Empty : name;
this.ns = (null == ns) ? string.Empty : ns;
}
#if NO
internal NodeQName(string name, string ns, string defaultNS)
{
Fx.Assert(null != defaultNS, "");
this.name = (null == name) ? string.Empty : name;
this.ns = (null == ns) ? defaultNS : ns;
}
internal NodeQName(XmlQualifiedName qname)
{
this.name = qname.Name;
this.ns = qname.Namespace;
}
internal bool HasWildcard
{
get
{
return (this.IsNameWildcard || this.IsNamespaceWildcard);
}
}
#endif
internal bool IsEmpty
{
get
{
return (this.name.Length == 0 && this.ns.Length == 0);
}
}
internal bool IsNameDefined
{
get
{
return (this.name.Length > 0);
}
}
internal bool IsNameWildcard
{
get
{
return object.ReferenceEquals(this.name, QueryDataModel.Wildcard);
}
}
internal bool IsNamespaceDefined
{
get
{
return (this.ns.Length > 0);
}
}
internal bool IsNamespaceWildcard
{
get
{
return object.ReferenceEquals(this.ns, QueryDataModel.Wildcard);
}
}
internal string Name
{
get
{
return this.name;
}
#if NO
set
{
Fx.Assert(null != value, "");
this.name = value;
}
#endif
}
internal string Namespace
{
get
{
return this.ns;
}
#if NO
set
{
Fx.Assert(null != value, "");
this.ns = value;
}
#endif
}
/// <summary>
/// If this qname's strings are == to the constants defined in NodeQName, replace the strings with the
/// constants
/// </summary>
#if NO
internal bool Atomize()
{
return false;
}
#endif
internal bool EqualsName(string name)
{
return (name == this.name);
}
#if NO
internal bool Equals(string name)
{
return this.EqualsName(name);
}
internal bool Equals(string name, string ns)
{
return ( (name.Length == this.name.Length && name == this.name) && (ns.Length == this.ns.Length && ns == this.ns));
}
#endif
internal bool Equals(NodeQName qname)
{
return ((qname.name.Length == this.name.Length && qname.name == this.name) && (qname.ns.Length == this.ns.Length && qname.ns == this.ns));
}
#if NO
internal bool Equals(SeekableXPathNavigator navigator)
{
string str = navigator.LocalName;
if (this.name.Length == str.Length && this.name == str)
{
str = navigator.NamespaceURI;
return (this.ns.Length == str.Length && this.ns == str);
}
return false;
}
#endif
internal bool EqualsNamespace(string ns)
{
return (ns == this.ns);
}
#if NO
internal bool EqualsReference(NodeQName qname)
{
return (object.ReferenceEquals(qname.name, this.name) && object.ReferenceEquals(qname.ns, this.ns));
}
internal string QName()
{
return this.ns + ':' + this.name;
}
#endif
/// <summary>
/// Return this qname's type - whether the name is defined, whether the name is a wildcard etc
/// </summary>
internal NodeQNameType GetQNameType()
{
NodeQNameType type = NodeQNameType.Empty;
if (this.IsNameDefined)
{
if (this.IsNameWildcard)
{
type |= NodeQNameType.NameWildcard;
}
else
{
type |= NodeQNameType.Name;
}
}
if (this.IsNamespaceDefined)
{
if (this.IsNamespaceWildcard)
{
type |= NodeQNameType.NamespaceWildcard;
}
else
{
type |= NodeQNameType.Namespace;
}
}
return type;
}
}
internal static class QueryDataModel
{
internal static QueryAxis[] axes;
internal static string Wildcard = "*";
static QueryDataModel()
{
// Init axes table
QueryDataModel.axes = new QueryAxis[] {
new QueryAxis(QueryAxisType.None, AxisDirection.Forward, QueryNodeType.Any, QueryNodeType.Any),
new QueryAxis(QueryAxisType.Ancestor, AxisDirection.Reverse, QueryNodeType.Element, QueryNodeType.Ancestor),
new QueryAxis(QueryAxisType.AncestorOrSelf, AxisDirection.Reverse, QueryNodeType.Element, QueryNodeType.All),
new QueryAxis(QueryAxisType.Attribute, AxisDirection.Forward, QueryNodeType.Attribute, QueryNodeType.Attribute),
new QueryAxis(QueryAxisType.Child, AxisDirection.Forward, QueryNodeType.Element, QueryNodeType.ChildNodes),
new QueryAxis(QueryAxisType.Descendant, AxisDirection.Forward, QueryNodeType.Element, QueryNodeType.ChildNodes),
new QueryAxis(QueryAxisType.DescendantOrSelf, AxisDirection.Forward, QueryNodeType.Element, QueryNodeType.All),
new QueryAxis(QueryAxisType.Following, AxisDirection.Forward, QueryNodeType.Element, QueryNodeType.ChildNodes),
new QueryAxis(QueryAxisType.FollowingSibling, AxisDirection.Forward, QueryNodeType.Element, QueryNodeType.ChildNodes),
new QueryAxis(QueryAxisType.Namespace, AxisDirection.Forward, QueryNodeType.Namespace, QueryNodeType.Namespace),
new QueryAxis(QueryAxisType.Parent, AxisDirection.Reverse, QueryNodeType.Element, QueryNodeType.Ancestor),
new QueryAxis(QueryAxisType.Preceding, AxisDirection.Reverse, QueryNodeType.Element, QueryNodeType.ChildNodes),
new QueryAxis(QueryAxisType.PrecedingSibling, AxisDirection.Reverse, QueryNodeType.Element, QueryNodeType.All),
new QueryAxis(QueryAxisType.Self, AxisDirection.Forward, QueryNodeType.Element, QueryNodeType.All),
};
}
/// <summary>
/// XPath does not interpret namespace declarations as attributes
/// Any attributes that not qualified by the XmlNamespaces namespaces is therefore kosher
/// </summary>
internal static bool IsAttribute(string ns)
{
return (0 != string.CompareOrdinal("http://www.w3.org/2000/xmlns/", ns));
}
#if NO
internal static bool IsDigit(char ch)
{
return char.IsDigit(ch);
}
internal static bool IsLetter(char ch)
{
return char.IsLetter(ch);
}
internal static bool IsLetterOrDigit(char ch)
{
return char.IsLetterOrDigit(ch);
}
internal static bool IsWhitespace(char ch)
{
return char.IsWhiteSpace(ch);
}
#endif
internal static QueryAxis GetAxis(QueryAxisType type)
{
return QueryDataModel.axes[(int)type];
}
#if NO
internal static QueryNodeType GetNodeType(XPathNodeType type)
{
QueryNodeType nodeType;
switch (type)
{
default:
nodeType = QueryNodeType.Any;
break;
case XPathNodeType.Root:
nodeType = QueryNodeType.Root;
break;
case XPathNodeType.Attribute:
nodeType = QueryNodeType.Attribute;
break;
case XPathNodeType.Element:
nodeType = QueryNodeType.Element;
break;
case XPathNodeType.Comment:
nodeType = QueryNodeType.Comment;
break;
case XPathNodeType.Text:
case XPathNodeType.Whitespace:
case XPathNodeType.SignificantWhitespace:
nodeType = QueryNodeType.Text;
break;
case XPathNodeType.ProcessingInstruction:
nodeType = QueryNodeType.Processing;
break;
}
return nodeType;
}
internal static XPathNodeType GetXPathNodeType(QueryNodeType type)
{
XPathNodeType nodeType = XPathNodeType.All;
switch(type)
{
default:
break;
case QueryNodeType.Attribute:
nodeType = XPathNodeType.Attribute;
break;
case QueryNodeType.Root:
nodeType = XPathNodeType.Root;
break;
case QueryNodeType.Namespace:
nodeType = XPathNodeType.Namespace;
break;
case QueryNodeType.Element:
nodeType = XPathNodeType.Element;
break;
case QueryNodeType.Comment:
nodeType = XPathNodeType.Comment;
break;
case QueryNodeType.Text:
nodeType = XPathNodeType.Text;
break;
case QueryNodeType.Processing:
nodeType = XPathNodeType.ProcessingInstruction;
break;
}
return nodeType;
}
// Is it possible to select nodes matching the given criteria from nodes of the given type
internal static bool IsSelectPossible(QueryNodeType nodeType, NodeSelectCriteria desc)
{
if (0 != (nodeType & QueryNodeType.Attribute))
{
switch(desc.Axis.Type)
{
default:
return false;
// Navigation is possible from attributes on these axes
case QueryAxisType.Self:
case QueryAxisType.Ancestor:
case QueryAxisType.AncestorOrSelf:
case QueryAxisType.Parent:
return true;
}
}
else if (0 != (nodeType & QueryNodeType.Root))
{
if (AxisDirection.Reverse == desc.Axis.Direction)
{
return false;
}
switch(desc.Axis.Type)
{
default:
return true;
// Navigation is possible from attributes on these axes
case QueryAxisType.Attribute:
case QueryAxisType.Namespace:
return false;
}
}
return true;
}
#endif
}
internal static class QueryValueModel
{
/*
Conversions
The following EXACTLY follow the XPath 1.0 spec. Some conversions may seem ----/inefficient, but
we prefer to adhere to the spec and shall leave them be unless performance becomes an issue.
*/
internal static bool Boolean(string val)
{
Fx.Assert(null != val, "");
return (val.Length > 0);
}
internal static bool Boolean(double dblVal)
{
return (dblVal != 0 && !double.IsNaN(dblVal));
}
internal static bool Boolean(NodeSequence sequence)
{
Fx.Assert(null != sequence, "");
return sequence.IsNotEmpty;
}
internal static bool Boolean(XPathNodeIterator iterator)
{
Fx.Assert(null != iterator, "");
return (iterator.Count > 0);
}
internal static double Double(bool val)
{
return (val ? 1 : 0);
}
internal static double Double(string val)
{
// XPath does not convert numbers the same way .NET does. A string preceeded by + is actually converted
// to NAN! Go figure.. Anyway, we have to do this manually.
val = val.TrimStart();
if (val.Length > 0 && val[0] != '+')
{
double dblVal;
if (double.TryParse(val,
NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowTrailingWhite,
NumberFormatInfo.InvariantInfo,
out dblVal))
{
return dblVal;
}
}
return double.NaN;
}
internal static double Double(NodeSequence sequence)
{
Fx.Assert(null != sequence, "");
return QueryValueModel.Double(sequence.StringValue());
}
internal static double Double(XPathNodeIterator iterator)
{
Fx.Assert(null != iterator, "");
return QueryValueModel.Double(QueryValueModel.String(iterator));
}
#if NO
internal static string String(object val)
{
return val.ToString();
}
#endif
internal static string String(bool val)
{
return val ? "true" : "false"; // XPath requires all lower case. bool.ToString() returns 'False' and 'True'
}
internal static string String(double val)
{
return val.ToString(CultureInfo.InvariantCulture);
}
internal static string String(NodeSequence sequence)
{
Fx.Assert(null != sequence, "");
return sequence.StringValue();
}
internal static string String(XPathNodeIterator iterator)
{
Fx.Assert(null != iterator, "");
if (iterator.Count == 0)
{
return string.Empty;
}
else if (iterator.CurrentPosition == 0)
{
iterator.MoveNext();
return iterator.Current.Value;
}
else if (iterator.CurrentPosition == 1)
{
return iterator.Current.Value;
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InvalidOperationException(SR.GetString(SR.QueryCantGetStringForMovedIterator)));
}
}
// OPTIMIZE Comparisons in general!!
internal static bool Compare(bool x, bool y, RelationOperator op)
{
switch (op)
{
default:
return QueryValueModel.Compare(QueryValueModel.Double(x), QueryValueModel.Double(y), op);
case RelationOperator.Eq:
return (x == y);
case RelationOperator.Ne:
return (x != y);
}
}
internal static bool Compare(bool x, double y, RelationOperator op)
{
switch (op)
{
default:
return QueryValueModel.Compare(QueryValueModel.Double(x), y, op);
case RelationOperator.Eq:
return (x == QueryValueModel.Boolean(y));
case RelationOperator.Ne:
return (x != QueryValueModel.Boolean(y));
}
}
internal static bool Compare(bool x, string y, RelationOperator op)
{
Fx.Assert(null != y, "");
switch (op)
{
default:
return QueryValueModel.Compare(QueryValueModel.Double(x), QueryValueModel.Double(y), op);
case RelationOperator.Eq:
return (x == QueryValueModel.Boolean(y));
case RelationOperator.Ne:
return (x != QueryValueModel.Boolean(y));
}
}
internal static bool Compare(bool x, NodeSequence y, RelationOperator op)
{
Fx.Assert(null != y, "");
return QueryValueModel.Compare(x, QueryValueModel.Boolean(y), op);
}
internal static bool Compare(double x, bool y, RelationOperator op)
{
switch (op)
{
default:
return QueryValueModel.Compare(x, QueryValueModel.Double(y), op);
case RelationOperator.Eq:
return (QueryValueModel.Boolean(x) == y);
case RelationOperator.Ne:
return (QueryValueModel.Boolean(x) != y);
}
}
internal static bool Compare(double x, double y, RelationOperator op)
{
switch (op)
{
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperCritical(new QueryProcessingException(QueryProcessingError.TypeMismatch));
case RelationOperator.Eq:
return (x == y);
case RelationOperator.Ge:
return (x >= y);
case RelationOperator.Gt:
return (x > y);
case RelationOperator.Le:
return (x <= y);
case RelationOperator.Lt:
return (x < y);
case RelationOperator.Ne:
return (x != y);
}
}
internal static bool Compare(double x, string y, RelationOperator op)
{
Fx.Assert(null != y, "");
return QueryValueModel.Compare(x, QueryValueModel.Double(y), op);
}
internal static bool Compare(double x, NodeSequence y, RelationOperator op)
{
Fx.Assert(null != y, "");
switch (op)
{
default:
return y.Compare(x, op);
case RelationOperator.Ge:
return y.Compare(x, RelationOperator.Le);
case RelationOperator.Gt:
return y.Compare(x, RelationOperator.Lt);
case RelationOperator.Le:
return y.Compare(x, RelationOperator.Ge);
case RelationOperator.Lt:
return y.Compare(x, RelationOperator.Gt);
}
}
internal static bool Compare(string x, bool y, RelationOperator op)
{
Fx.Assert(null != x, "");
switch (op)
{
default:
return QueryValueModel.Compare(QueryValueModel.Double(x), QueryValueModel.Double(y), op);
case RelationOperator.Eq:
return (y == QueryValueModel.Boolean(x));
case RelationOperator.Ne:
return (y != QueryValueModel.Boolean(x));
}
}
internal static bool Compare(string x, double y, RelationOperator op)
{
Fx.Assert(null != x, "");
return QueryValueModel.Compare(QueryValueModel.Double(x), y, op);
}
internal static bool Compare(string x, string y, RelationOperator op)
{
Fx.Assert(null != x && null != y, "");
switch (op)
{
default:
Fx.Assert("Invalid RelationOperator");
break;
case RelationOperator.Eq:
return QueryValueModel.Equals(x, y);
case RelationOperator.Ge:
case RelationOperator.Gt:
case RelationOperator.Le:
case RelationOperator.Lt:
return QueryValueModel.Compare(QueryValueModel.Double(x), QueryValueModel.Double(y), op);
case RelationOperator.Ne:
return (x.Length != y.Length || 0 != string.CompareOrdinal(x, y));
}
return false;
}
internal static bool Compare(string x, NodeSequence y, RelationOperator op)
{
Fx.Assert(null != y, "");
switch (op)
{
default:
return y.Compare(x, op);
case RelationOperator.Ge:
return y.Compare(x, RelationOperator.Le);
case RelationOperator.Gt:
return y.Compare(x, RelationOperator.Lt);
case RelationOperator.Le:
return y.Compare(x, RelationOperator.Ge);
case RelationOperator.Lt:
return y.Compare(x, RelationOperator.Gt);
}
}
internal static bool Compare(NodeSequence x, bool y, RelationOperator op)
{
Fx.Assert(null != x, "");
return QueryValueModel.Compare(QueryValueModel.Boolean(x), y, op);
}
internal static bool Compare(NodeSequence x, double y, RelationOperator op)
{
Fx.Assert(null != x, "");
return x.Compare(y, op);
}
internal static bool Compare(NodeSequence x, string y, RelationOperator op)
{
Fx.Assert(null != x, "");
return x.Compare(y, op);
}
internal static bool Compare(NodeSequence x, NodeSequence y, RelationOperator op)
{
Fx.Assert(null != x, "");
return x.Compare(y, op);
}
internal static bool CompileTimeCompare(object x, object y, RelationOperator op)
{
Fx.Assert(null != x && null != y, "");
if (x is string)
{
if (y is double)
{
return QueryValueModel.Compare((string)x, (double)y, op);
}
else if (y is string)
{
return QueryValueModel.Compare((string)x, (string)y, op);
}
}
else if (x is double)
{
if (y is double)
{
return QueryValueModel.Compare((double)x, (double)y, op);
}
else if (y is string)
{
return QueryValueModel.Compare((double)x, (string)y, op);
}
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new QueryCompileException(QueryCompileError.InvalidComparison));
}
internal static bool Equals(bool x, string y)
{
return (x == QueryValueModel.Boolean(y));
}
internal static bool Equals(double x, string y)
{
return (x == QueryValueModel.Double(y));
}
internal static bool Equals(string x, string y)
{
return (x.Length == y.Length && x == y);
}
internal static bool Equals(NodeSequence x, string y)
{
return x.Equals(y);
}
internal static bool Equals(bool x, double y)
{
return (x == QueryValueModel.Boolean(y));
}
internal static bool Equals(double x, double y)
{
return (x == y);
}
internal static bool Equals(NodeSequence x, double y)
{
return x.Equals(y);
}
internal static double Round(double val)
{
// Math.Round does bankers rounding, which is IEEE 754, section 4.
// If a is halfway between two whole numbers, one of which by definition is even and the other odd, then
// the even number is returned. Thus Round(3.5) == Round(4.5) == 4.0
// XPath has different rules.. which is Math.Floor(a + 0.5)... with two exceptions (see below)
// The round function returns the number that is closest to the argument and that is an integer.
// If there are two such numbers, then the one that is closest to positive infinity is returned.
// If the argument is NaN, then NaN is returned.
// If the argument is positive infinity, then positive infinity is returned.
// If the argument is negative infinity, then negative infinity is returned.
// If the argument is positive zero, then positive zero is returned.
// If the argument is negative zero, then negative zero is returned.
// If the argument is less than zero, but greater than or equal to -0.5, then negative zero is returned.
// For these last two cases, the result of calling the round function is not the same as the result of
// adding 0.5 and then calling the floor function.
// Note: .NET has no positive or negative zero... so we give up and use Math.Round...
// For all other cases, we use Floor to Round...
return (-0.5 <= val && val <= 0.0) ? Math.Round(val) : Math.Floor(val + 0.5);
}
#if NO
internal static XPathResultType ResultType(ValueDataType dataType)
{
switch (dataType)
{
default:
break;
case ValueDataType.Boolean:
return XPathResultType.Boolean;
case ValueDataType.Double:
return XPathResultType.Number;
case ValueDataType.Sequence:
return XPathResultType.NodeSet;
case ValueDataType.String:
return XPathResultType.String;
}
return XPathResultType.Any;
}
#endif
}
}
| |
// Copyright 2013 Kim Christensen, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using NLog.Config;
using NLog.Targets;
namespace NLog.Windows.Forms
{
/// <summary>
/// Log text a Rich Text Box control in an existing or new form.
/// </summary>
/// <seealso href="https://github.com/nlog/nlog/wiki/RichTextBox-target">Documentation on NLog Wiki</seealso>
/// <example>
/// <p>
/// To set up the target in the <a href="config.html">configuration file</a>,
/// use the following syntax:
/// </p><code lang="XML" source="examples/targets/Configuration File/RichTextBox/Simple/NLog.config">
/// </code>
/// <p>
/// The result is:
/// </p><img src="examples/targets/Screenshots/RichTextBox/Simple.gif"/><p>
/// To set up the target with coloring rules in the <a href="config.html">configuration file</a>,
/// use the following syntax:
/// </p><code lang="XML" source="examples/targets/Configuration File/RichTextBox/RowColoring/NLog.config">
/// </code>
/// <code lang="XML" source="examples/targets/Configuration File/RichTextBox/WordColoring/NLog.config">
/// </code>
/// <p>
/// The result is:
/// </p><img src="examples/targets/Screenshots/RichTextBox/RowColoring.gif"/><img src="examples/targets/Screenshots/RichTextBox/WordColoring.gif"/><p>
/// To set up the log target programmatically similar to above use code like this:
/// </p><code lang="C#" source="examples/targets/Configuration API/RichTextBox/Simple/Form1.cs">
/// </code>
/// ,
/// <code lang="C#" source="examples/targets/Configuration API/RichTextBox/RowColoring/Form1.cs">
/// </code>
/// for RowColoring,
/// <code lang="C#" source="examples/targets/Configuration API/RichTextBox/WordColoring/Form1.cs">
/// </code>
/// for WordColoring
/// </example>
[Target("RichTextBox")]
public sealed class RichTextBoxTarget : TargetWithLayout
{
private int lineCount;
/// <summary>
/// Initializes static members of the RichTextBoxTarget class.
/// </summary>
/// <remarks>
/// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code>
/// </remarks>
static RichTextBoxTarget()
{
var rules = new List<RichTextBoxRowColoringRule>()
{
new RichTextBoxRowColoringRule("level == LogLevel.Fatal", "White", "Red", FontStyle.Bold),
new RichTextBoxRowColoringRule("level == LogLevel.Error", "Red", "Empty", FontStyle.Bold | FontStyle.Italic),
new RichTextBoxRowColoringRule("level == LogLevel.Warn", "Orange", "Empty", FontStyle.Underline),
new RichTextBoxRowColoringRule("level == LogLevel.Info", "Black", "Empty"),
new RichTextBoxRowColoringRule("level == LogLevel.Debug", "Gray", "Empty"),
new RichTextBoxRowColoringRule("level == LogLevel.Trace", "DarkGray", "Empty", FontStyle.Italic),
};
DefaultRowColoringRules = rules.AsReadOnly();
}
/// <summary>
/// Initializes a new instance of the <see cref="RichTextBoxTarget" /> class.
/// </summary>
/// <remarks>
/// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code>
/// </remarks>
public RichTextBoxTarget()
{
WordColoringRules = new List<RichTextBoxWordColoringRule>();
RowColoringRules = new List<RichTextBoxRowColoringRule>();
ToolWindow = true;
}
private delegate void DelSendTheMessageToRichTextBox(string logMessage, RichTextBoxRowColoringRule rule);
private delegate void FormCloseDelegate();
/// <summary>
/// Gets the default set of row coloring rules which applies when <see cref="UseDefaultRowColoringRules"/> is set to true.
/// </summary>
public static ReadOnlyCollection<RichTextBoxRowColoringRule> DefaultRowColoringRules { get; private set; }
/// <summary>
/// Gets or sets the Name of RichTextBox to which Nlog will write.
/// </summary>
/// <docgen category='Form Options' order='10' />
public string ControlName { get; set; }
/// <summary>
/// Gets or sets the name of the Form on which the control is located.
/// If there is no open form of a specified name than NLog will create a new one.
/// </summary>
/// <docgen category='Form Options' order='10' />
public string FormName { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to use default coloring rules.
/// </summary>
/// <docgen category='Highlighting Options' order='10' />
[DefaultValue(false)]
public bool UseDefaultRowColoringRules { get; set; }
/// <summary>
/// Gets the row coloring rules.
/// </summary>
/// <docgen category='Highlighting Options' order='10' />
[ArrayParameter(typeof(RichTextBoxRowColoringRule), "row-coloring")]
public IList<RichTextBoxRowColoringRule> RowColoringRules { get; private set; }
/// <summary>
/// Gets the word highlighting rules.
/// </summary>
/// <docgen category='Highlighting Options' order='10' />
[ArrayParameter(typeof(RichTextBoxWordColoringRule), "word-coloring")]
public IList<RichTextBoxWordColoringRule> WordColoringRules { get; private set; }
/// <summary>
/// Gets or sets a value indicating whether the created window will be a tool window.
/// </summary>
/// <remarks>
/// This parameter is ignored when logging to existing form control.
/// Tool windows have thin border, and do not show up in the task bar.
/// </remarks>
/// <docgen category='Form Options' order='10' />
[DefaultValue(true)]
public bool ToolWindow { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the created form will be initially minimized.
/// </summary>
/// <remarks>
/// This parameter is ignored when logging to existing form control.
/// </remarks>
/// <docgen category='Form Options' order='10' />
public bool ShowMinimized { get; set; }
/// <summary>
/// Gets or sets the initial width of the form with rich text box.
/// </summary>
/// <remarks>
/// This parameter is ignored when logging to existing form control.
/// </remarks>
/// <docgen category='Form Options' order='10' />
public int Width { get; set; }
/// <summary>
/// Gets or sets the initial height of the form with rich text box.
/// </summary>
/// <remarks>
/// This parameter is ignored when logging to existing form control.
/// </remarks>
/// <docgen category='Form Options' order='10' />
public int Height { get; set; }
/// <summary>
/// Gets or sets a value indicating whether scroll bar will be moved automatically to show most recent log entries.
/// </summary>
/// <docgen category='Form Options' order='10' />
public bool AutoScroll { get; set; }
/// <summary>
/// Gets or sets the maximum number of lines the rich text box will store (or 0 to disable this feature).
/// </summary>
/// <remarks>
/// After exceeding the maximum number, first line will be deleted.
/// </remarks>
/// <docgen category='Form Options' order='10' />
public int MaxLines { get; set; }
/// <summary>
/// Gets or sets the form to log to.
/// </summary>
public Form TargetForm { get; set; }
/// <summary>
/// Gets or sets the rich text box to log to.
/// </summary>
public RichTextBox TargetRichTextBox { get; set; }
public bool CreatedForm { get; set; }
/// <summary>
/// Initializes the target. Can be used by inheriting classes
/// to initialize logging.
/// </summary>
protected override void InitializeTarget()
{
if (FormName == null)
{
FormName = "NLogForm" + Guid.NewGuid().ToString("N");
}
var openFormByName = Application.OpenForms[FormName];
if (openFormByName != null)
{
TargetForm = openFormByName;
if (string.IsNullOrEmpty(ControlName))
{
throw new NLogConfigurationException("Rich text box control name must be specified for " + GetType().Name + ".");
}
CreatedForm = false;
TargetRichTextBox = FormHelper.FindControl<RichTextBox>(ControlName, TargetForm);
if (TargetRichTextBox == null)
{
throw new NLogConfigurationException("Rich text box control '" + ControlName + "' cannot be found on form '" + FormName + "'.");
}
}
else
{
TargetForm = FormHelper.CreateForm(FormName, Width, Height, true, ShowMinimized, ToolWindow);
TargetRichTextBox = FormHelper.CreateRichTextBox(ControlName, TargetForm);
CreatedForm = true;
}
}
/// <summary>
/// Closes the target and releases any unmanaged resources.
/// </summary>
protected override void CloseTarget()
{
if (CreatedForm)
{
TargetForm.BeginInvoke((FormCloseDelegate)TargetForm.Close);
TargetForm = null;
}
}
/// <summary>
/// Log message to RichTextBox.
/// </summary>
/// <param name="logEvent">The logging event.</param>
protected override void Write(LogEventInfo logEvent)
{
RichTextBoxRowColoringRule matchingRule = null;
foreach (RichTextBoxRowColoringRule rr in RowColoringRules)
{
if (rr.CheckCondition(logEvent))
{
matchingRule = rr;
break;
}
}
if (UseDefaultRowColoringRules && matchingRule == null)
{
foreach (RichTextBoxRowColoringRule rr in DefaultRowColoringRules)
{
if (rr.CheckCondition(logEvent))
{
matchingRule = rr;
break;
}
}
}
if (matchingRule == null)
{
matchingRule = RichTextBoxRowColoringRule.Default;
}
string logMessage = Layout.Render(logEvent);
TargetRichTextBox.BeginInvoke(new DelSendTheMessageToRichTextBox(SendTheMessageToRichTextBox), logMessage, matchingRule);
}
private static Color GetColorFromString(string color, Color defaultColor)
{
if (color == "Empty")
{
return defaultColor;
}
return Color.FromName(color);
}
private void SendTheMessageToRichTextBox(string logMessage, RichTextBoxRowColoringRule rule)
{
RichTextBox rtbx = TargetRichTextBox;
int startIndex = rtbx.Text.Length;
rtbx.SelectionStart = startIndex;
rtbx.SelectionBackColor = GetColorFromString(rule.BackgroundColor, rtbx.BackColor);
rtbx.SelectionColor = GetColorFromString(rule.FontColor, rtbx.ForeColor);
rtbx.SelectionFont = new Font(rtbx.SelectionFont, rtbx.SelectionFont.Style ^ rule.Style);
rtbx.AppendText(logMessage + "\n");
rtbx.SelectionLength = rtbx.Text.Length - rtbx.SelectionStart;
// find word to color
foreach (RichTextBoxWordColoringRule wordRule in WordColoringRules)
{
MatchCollection mc = wordRule.CompiledRegex.Matches(rtbx.Text, startIndex);
foreach (Match m in mc)
{
rtbx.SelectionStart = m.Index;
rtbx.SelectionLength = m.Length;
rtbx.SelectionBackColor = GetColorFromString(wordRule.BackgroundColor, rtbx.BackColor);
rtbx.SelectionColor = GetColorFromString(wordRule.FontColor, rtbx.ForeColor);
rtbx.SelectionFont = new Font(rtbx.SelectionFont, rtbx.SelectionFont.Style ^ wordRule.Style);
}
}
if (MaxLines > 0)
{
lineCount++;
if (lineCount > MaxLines)
{
rtbx.SelectionStart = 0;
rtbx.SelectionLength = rtbx.GetFirstCharIndexFromLine(1);
rtbx.SelectedRtf = "{\\rtf1\\ansi}";
lineCount--;
}
}
if (AutoScroll)
{
rtbx.Select(rtbx.TextLength, 0);
rtbx.ScrollToCaret();
}
}
}
}
| |
/*
* 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.Net;
using log4net.Config;
using Nini.Config;
using NUnit.Framework;
using OpenMetaverse;
using OpenMetaverse.Packets;
using OpenSim.Framework;
using OpenSim.Framework.Monitoring;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Tests.Common;
using OpenSim.Tests.Common.Mock;
namespace OpenSim.Region.ClientStack.LindenUDP.Tests
{
/// <summary>
/// This will contain basic tests for the LindenUDP client stack
/// </summary>
[TestFixture]
public class BasicCircuitTests : OpenSimTestCase
{
private Scene m_scene;
private TestLLUDPServer m_udpServer;
[TestFixtureSetUp]
public void FixtureInit()
{
// Don't allow tests to be bamboozled by asynchronous events. Execute everything on the same thread.
Util.FireAndForgetMethod = FireAndForgetMethod.RegressionTest;
}
[TestFixtureTearDown]
public void TearDown()
{
// We must set this back afterwards, otherwise later tests will fail since they're expecting multiple
// threads. Possibly, later tests should be rewritten so none of them require async stuff (which regression
// tests really shouldn't).
Util.FireAndForgetMethod = Util.DefaultFireAndForgetMethod;
}
[SetUp]
public override void SetUp()
{
base.SetUp();
m_scene = new SceneHelpers().SetupScene();
StatsManager.SimExtraStats = new SimExtraStatsCollector();
}
/// <summary>
/// Build an object name packet for test purposes
/// </summary>
/// <param name="objectLocalId"></param>
/// <param name="objectName"></param>
private ObjectNamePacket BuildTestObjectNamePacket(uint objectLocalId, string objectName)
{
ObjectNamePacket onp = new ObjectNamePacket();
ObjectNamePacket.ObjectDataBlock odb = new ObjectNamePacket.ObjectDataBlock();
odb.LocalID = objectLocalId;
odb.Name = Utils.StringToBytes(objectName);
onp.ObjectData = new ObjectNamePacket.ObjectDataBlock[] { odb };
onp.Header.Zerocoded = false;
return onp;
}
private void AddUdpServer()
{
AddUdpServer(new IniConfigSource());
}
private void AddUdpServer(IniConfigSource configSource)
{
uint port = 0;
AgentCircuitManager acm = m_scene.AuthenticateHandler;
m_udpServer = new TestLLUDPServer(IPAddress.Any, ref port, 0, false, configSource, acm);
m_udpServer.AddScene(m_scene);
}
/// <summary>
/// Used by tests that aren't testing this stage.
/// </summary>
private ScenePresence AddClient()
{
UUID myAgentUuid = TestHelpers.ParseTail(0x1);
UUID mySessionUuid = TestHelpers.ParseTail(0x2);
uint myCircuitCode = 123456;
IPEndPoint testEp = new IPEndPoint(IPAddress.Loopback, 999);
UseCircuitCodePacket uccp = new UseCircuitCodePacket();
UseCircuitCodePacket.CircuitCodeBlock uccpCcBlock
= new UseCircuitCodePacket.CircuitCodeBlock();
uccpCcBlock.Code = myCircuitCode;
uccpCcBlock.ID = myAgentUuid;
uccpCcBlock.SessionID = mySessionUuid;
uccp.CircuitCode = uccpCcBlock;
byte[] uccpBytes = uccp.ToBytes();
UDPPacketBuffer upb = new UDPPacketBuffer(testEp, uccpBytes.Length);
upb.DataLength = uccpBytes.Length; // God knows why this isn't set by the constructor.
Buffer.BlockCopy(uccpBytes, 0, upb.Data, 0, uccpBytes.Length);
AgentCircuitData acd = new AgentCircuitData();
acd.AgentID = myAgentUuid;
acd.SessionID = mySessionUuid;
m_scene.AuthenticateHandler.AddNewCircuit(myCircuitCode, acd);
m_udpServer.PacketReceived(upb);
return m_scene.GetScenePresence(myAgentUuid);
}
/// <summary>
/// Test adding a client to the stack
/// </summary>
[Test]
public void TestAddClient()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
AddUdpServer();
UUID myAgentUuid = TestHelpers.ParseTail(0x1);
UUID mySessionUuid = TestHelpers.ParseTail(0x2);
uint myCircuitCode = 123456;
IPEndPoint testEp = new IPEndPoint(IPAddress.Loopback, 999);
UseCircuitCodePacket uccp = new UseCircuitCodePacket();
UseCircuitCodePacket.CircuitCodeBlock uccpCcBlock
= new UseCircuitCodePacket.CircuitCodeBlock();
uccpCcBlock.Code = myCircuitCode;
uccpCcBlock.ID = myAgentUuid;
uccpCcBlock.SessionID = mySessionUuid;
uccp.CircuitCode = uccpCcBlock;
byte[] uccpBytes = uccp.ToBytes();
UDPPacketBuffer upb = new UDPPacketBuffer(testEp, uccpBytes.Length);
upb.DataLength = uccpBytes.Length; // God knows why this isn't set by the constructor.
Buffer.BlockCopy(uccpBytes, 0, upb.Data, 0, uccpBytes.Length);
m_udpServer.PacketReceived(upb);
// Presence shouldn't exist since the circuit manager doesn't know about this circuit for authentication yet
Assert.That(m_scene.GetScenePresence(myAgentUuid), Is.Null);
AgentCircuitData acd = new AgentCircuitData();
acd.AgentID = myAgentUuid;
acd.SessionID = mySessionUuid;
m_scene.AuthenticateHandler.AddNewCircuit(myCircuitCode, acd);
m_udpServer.PacketReceived(upb);
// Should succeed now
ScenePresence sp = m_scene.GetScenePresence(myAgentUuid);
Assert.That(sp.UUID, Is.EqualTo(myAgentUuid));
Assert.That(m_udpServer.PacketsSent.Count, Is.EqualTo(1));
Packet packet = m_udpServer.PacketsSent[0];
Assert.That(packet, Is.InstanceOf(typeof(PacketAckPacket)));
PacketAckPacket ackPacket = packet as PacketAckPacket;
Assert.That(ackPacket.Packets.Length, Is.EqualTo(1));
Assert.That(ackPacket.Packets[0].ID, Is.EqualTo(0));
}
[Test]
public void TestLogoutClientDueToAck()
{
TestHelpers.InMethod();
TestHelpers.EnableLogging();
IniConfigSource ics = new IniConfigSource();
IConfig config = ics.AddConfig("ClientStack.LindenUDP");
config.Set("AckTimeout", -1);
AddUdpServer(ics);
ScenePresence sp = AddClient();
m_udpServer.ClientOutgoingPacketHandler(sp.ControllingClient, true, false, false);
ScenePresence spAfterAckTimeout = m_scene.GetScenePresence(sp.UUID);
Assert.That(spAfterAckTimeout, Is.Null);
}
// /// <summary>
// /// Test removing a client from the stack
// /// </summary>
// [Test]
// public void TestRemoveClient()
// {
// TestHelper.InMethod();
//
// uint myCircuitCode = 123457;
//
// TestLLUDPServer testLLUDPServer;
// TestLLPacketServer testLLPacketServer;
// AgentCircuitManager acm;
// SetupStack(new MockScene(), out testLLUDPServer, out testLLPacketServer, out acm);
// AddClient(myCircuitCode, new IPEndPoint(IPAddress.Loopback, 1000), testLLUDPServer, acm);
//
// testLLUDPServer.RemoveClientCircuit(myCircuitCode);
// Assert.IsFalse(testLLUDPServer.HasCircuit(myCircuitCode));
//
// // Check that removing a non-existent circuit doesn't have any bad effects
// testLLUDPServer.RemoveClientCircuit(101);
// Assert.IsFalse(testLLUDPServer.HasCircuit(101));
// }
//
// /// <summary>
// /// Make sure that the client stack reacts okay to malformed packets
// /// </summary>
// [Test]
// public void TestMalformedPacketSend()
// {
// TestHelper.InMethod();
//
// uint myCircuitCode = 123458;
// EndPoint testEp = new IPEndPoint(IPAddress.Loopback, 1001);
// MockScene scene = new MockScene();
//
// TestLLUDPServer testLLUDPServer;
// TestLLPacketServer testLLPacketServer;
// AgentCircuitManager acm;
// SetupStack(scene, out testLLUDPServer, out testLLPacketServer, out acm);
// AddClient(myCircuitCode, testEp, testLLUDPServer, acm);
//
// byte[] data = new byte[] { 0x01, 0x02, 0x03, 0x04 };
//
// // Send two garbled 'packets' in succession
// testLLUDPServer.LoadReceive(data, testEp);
// testLLUDPServer.LoadReceive(data, testEp);
// testLLUDPServer.ReceiveData(null);
//
// // Check that we are still here
// Assert.IsTrue(testLLUDPServer.HasCircuit(myCircuitCode));
// Assert.That(testLLPacketServer.GetTotalPacketsReceived(), Is.EqualTo(0));
//
// // Check that sending a valid packet to same circuit still succeeds
// Assert.That(scene.ObjectNameCallsReceived, Is.EqualTo(0));
//
// testLLUDPServer.LoadReceive(BuildTestObjectNamePacket(1, "helloooo"), testEp);
// testLLUDPServer.ReceiveData(null);
//
// Assert.That(testLLPacketServer.GetTotalPacketsReceived(), Is.EqualTo(1));
// Assert.That(testLLPacketServer.GetPacketsReceivedFor(PacketType.ObjectName), Is.EqualTo(1));
// }
//
// /// <summary>
// /// Test that the stack continues to work even if some client has caused a
// /// SocketException on Socket.BeginReceive()
// /// </summary>
// [Test]
// public void TestExceptionOnBeginReceive()
// {
// TestHelper.InMethod();
//
// MockScene scene = new MockScene();
//
// uint circuitCodeA = 130000;
// EndPoint epA = new IPEndPoint(IPAddress.Loopback, 1300);
// UUID agentIdA = UUID.Parse("00000000-0000-0000-0000-000000001300");
// UUID sessionIdA = UUID.Parse("00000000-0000-0000-0000-000000002300");
//
// uint circuitCodeB = 130001;
// EndPoint epB = new IPEndPoint(IPAddress.Loopback, 1301);
// UUID agentIdB = UUID.Parse("00000000-0000-0000-0000-000000001301");
// UUID sessionIdB = UUID.Parse("00000000-0000-0000-0000-000000002301");
//
// TestLLUDPServer testLLUDPServer;
// TestLLPacketServer testLLPacketServer;
// AgentCircuitManager acm;
// SetupStack(scene, out testLLUDPServer, out testLLPacketServer, out acm);
// AddClient(circuitCodeA, epA, agentIdA, sessionIdA, testLLUDPServer, acm);
// AddClient(circuitCodeB, epB, agentIdB, sessionIdB, testLLUDPServer, acm);
//
// testLLUDPServer.LoadReceive(BuildTestObjectNamePacket(1, "packet1"), epA);
// testLLUDPServer.LoadReceive(BuildTestObjectNamePacket(1, "packet2"), epB);
// testLLUDPServer.LoadReceiveWithBeginException(epA);
// testLLUDPServer.LoadReceive(BuildTestObjectNamePacket(2, "packet3"), epB);
// testLLUDPServer.ReceiveData(null);
//
// Assert.IsFalse(testLLUDPServer.HasCircuit(circuitCodeA));
//
// Assert.That(testLLPacketServer.GetTotalPacketsReceived(), Is.EqualTo(3));
// Assert.That(testLLPacketServer.GetPacketsReceivedFor(PacketType.ObjectName), Is.EqualTo(3));
// }
}
}
| |
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
[CanEditMultipleObjects]
[CustomEditor(typeof(SgtAtmosphereLighting))]
public class SgtAtmosphereLighting_Editor : SgtEditor<SgtAtmosphereLighting>
{
protected override void OnInspector()
{
var updateTexture = false;
var updateApply = false;
BeginError(Any(t => t.Atmosphere == null));
DrawDefault("Atmosphere", ref updateApply);
EndError();
BeginError(Any(t => t.Width <= 1));
DrawDefault("Width", ref updateTexture);
EndError();
DrawDefault("Format", ref updateTexture);
Separator();
DrawDefault("SunsetEase", ref updateTexture);
BeginError(Any(t => t.SunsetStart >= t.SunsetEnd));
DrawDefault("SunsetStart", ref updateTexture);
DrawDefault("SunsetEnd", ref updateTexture);
EndError();
BeginError(Any(t => t.SunsetPowerR < 1.0f));
DrawDefault("SunsetPowerR", ref updateTexture);
EndError();
BeginError(Any(t => t.SunsetPowerG < 1.0f));
DrawDefault("SunsetPowerG", ref updateTexture);
EndError();
BeginError(Any(t => t.SunsetPowerB < 1.0f));
DrawDefault("SunsetPowerB", ref updateTexture);
EndError();
if (updateTexture == true) DirtyEach(t => t.UpdateTextures());
if (updateApply == true) DirtyEach(t => t.UpdateApply ());
}
}
#endif
[ExecuteInEditMode]
[AddComponentMenu(SgtHelper.ComponentMenuPrefix + "Atmosphere Lighting")]
public class SgtAtmosphereLighting : MonoBehaviour
{
[Tooltip("The atmosphere this texture will be applied to")]
public SgtAtmosphere Atmosphere;
[Tooltip("The resolution of the day/sunset/night color transition in pixels")]
public int Width = 256;
[Tooltip("The texture format of the textures")]
public TextureFormat Format = TextureFormat.ARGB32;
[Tooltip("The transition style between the day and night")]
public SgtEase.Type SunsetEase = SgtEase.Type.Smoothstep;
[Tooltip("The start point of the day/sunset transition (0 = dark side, 1 = light side)")]
[Range(0.0f, 1.0f)]
public float SunsetStart = 0.4f;
[Tooltip("The end point of the sunset/night transition (0 = dark side, 1 = light side)")]
[Range(0.0f, 1.0f)]
public float SunsetEnd = 0.6f;
[Tooltip("The power of the sunset red channel transition")]
public float SunsetPowerR = 2.0f;
[Tooltip("The power of the sunset green channel transition")]
public float SunsetPowerG = 2.0f;
[Tooltip("The power of the sunset blue channel transition")]
public float SunsetPowerB = 2.0f;
[System.NonSerialized]
private Texture2D generatedTexture;
[SerializeField]
private bool startCalled;
public Texture2D GeneratedTexture
{
get
{
return generatedTexture;
}
}
#if UNITY_EDITOR
[ContextMenu("Export Texture")]
public void ExportTexture()
{
var importer = SgtHelper.ExportTextureDialog(generatedTexture, "Atmosphere Lighting");
if (importer != null)
{
importer.textureCompression = TextureImporterCompression.Uncompressed;
importer.alphaSource = TextureImporterAlphaSource.FromInput;
importer.wrapMode = TextureWrapMode.Clamp;
importer.filterMode = FilterMode.Trilinear;
importer.anisoLevel = 16;
importer.alphaIsTransparency = true;
importer.SaveAndReimport();
}
}
#endif
[ContextMenu("Update Textures")]
public void UpdateTextures()
{
if (Width > 0)
{
// Destroy if invalid
if (generatedTexture != null)
{
if (generatedTexture.width != Width || generatedTexture.height != 1 || generatedTexture.format != Format)
{
generatedTexture = SgtHelper.Destroy(generatedTexture);
}
}
// Create?
if (generatedTexture == null)
{
generatedTexture = SgtHelper.CreateTempTexture2D("Atmosphere Lighting (Generated)", Width, 1, Format);
generatedTexture.wrapMode = TextureWrapMode.Clamp;
UpdateApply();
}
var stepX = 1.0f / (Width - 1);
for (var x = 0; x < Width; x++)
{
var u = x * stepX;
WriteTexture(u, x);
}
generatedTexture.Apply();
}
}
private void WriteTexture(float u, int x)
{
var sunsetU = Mathf.InverseLerp(SunsetEnd, SunsetStart, u);
var color = default(Color);
color.r = SgtEase.Evaluate(SunsetEase, 1.0f - Mathf.Pow(sunsetU, SunsetPowerR));
color.g = SgtEase.Evaluate(SunsetEase, 1.0f - Mathf.Pow(sunsetU, SunsetPowerG));
color.b = SgtEase.Evaluate(SunsetEase, 1.0f - Mathf.Pow(sunsetU, SunsetPowerB));
color.a = 0.0f;
generatedTexture.SetPixel(x, 0, color);
}
[ContextMenu("Update Apply")]
public void UpdateApply()
{
if (Atmosphere != null)
{
if (generatedTexture != null)
{
if (Atmosphere.LightingTex != generatedTexture)
{
Atmosphere.LightingTex = generatedTexture;
Atmosphere.UpdateLightingTex();
}
}
}
}
protected virtual void OnEnable()
{
if (startCalled == true)
{
CheckUpdateCalls();
}
}
protected virtual void Start()
{
if (startCalled == false)
{
startCalled = true;
if (Atmosphere == null)
{
Atmosphere = GetComponent<SgtAtmosphere>();
}
CheckUpdateCalls();
}
}
protected virtual void OnDestroy()
{
SgtHelper.Destroy(generatedTexture);
}
private void CheckUpdateCalls()
{
if (generatedTexture == null)
{
UpdateTextures();
}
UpdateApply();
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
using Xunit;
namespace System.Numerics.Tests
{
public class Matrix3x2Tests
{
static Matrix3x2 GenerateMatrixNumberFrom1To6()
{
Matrix3x2 a = new Matrix3x2();
a.M11 = 1.0f;
a.M12 = 2.0f;
a.M21 = 3.0f;
a.M22 = 4.0f;
a.M31 = 5.0f;
a.M32 = 6.0f;
return a;
}
static Matrix3x2 GenerateTestMatrix()
{
Matrix3x2 m = Matrix3x2.CreateRotation(MathHelper.ToRadians(30.0f));
m.Translation = new Vector2(111.0f, 222.0f);
return m;
}
// A test for Identity
[Fact]
public void Matrix3x2IdentityTest()
{
Matrix3x2 val = new Matrix3x2();
val.M11 = val.M22 = 1.0f;
Assert.True(MathHelper.Equal(val, Matrix3x2.Identity), "Matrix3x2.Indentity was not set correctly.");
}
// A test for Determinant
[Fact]
public void Matrix3x2DeterminantTest()
{
Matrix3x2 target = Matrix3x2.CreateRotation(MathHelper.ToRadians(30.0f));
float val = 1.0f;
float det = target.GetDeterminant();
Assert.True(MathHelper.Equal(val, det), "Matrix3x2.Determinant was not set correctly.");
}
// A test for Determinant
// Determinant test |A| = 1 / |A'|
[Fact]
public void Matrix3x2DeterminantTest1()
{
Matrix3x2 a = new Matrix3x2();
a.M11 = 5.0f;
a.M12 = 2.0f;
a.M21 = 12.0f;
a.M22 = 6.8f;
a.M31 = 6.5f;
a.M32 = 1.0f;
Matrix3x2 i;
Assert.True(Matrix3x2.Invert(a, out i));
float detA = a.GetDeterminant();
float detI = i.GetDeterminant();
float t = 1.0f / detI;
// only accurate to 3 precision
Assert.True(System.Math.Abs(detA - t) < 1e-3, "Matrix3x2.Determinant was not set correctly.");
// sanity check against 4x4 version
Assert.Equal(new Matrix4x4(a).GetDeterminant(), detA);
Assert.Equal(new Matrix4x4(i).GetDeterminant(), detI);
}
// A test for Invert (Matrix3x2)
[Fact]
public void Matrix3x2InvertTest()
{
Matrix3x2 mtx = Matrix3x2.CreateRotation(MathHelper.ToRadians(30.0f));
Matrix3x2 expected = new Matrix3x2();
expected.M11 = 0.8660254f;
expected.M12 = -0.5f;
expected.M21 = 0.5f;
expected.M22 = 0.8660254f;
expected.M31 = 0;
expected.M32 = 0;
Matrix3x2 actual;
Assert.True(Matrix3x2.Invert(mtx, out actual));
Assert.True(MathHelper.Equal(expected, actual), "Matrix3x2.Invert did not return the expected value.");
Matrix3x2 i = mtx * actual;
Assert.True(MathHelper.Equal(i, Matrix3x2.Identity), "Matrix3x2.Invert did not return the expected value.");
}
// A test for Invert (Matrix3x2)
[Fact]
public void Matrix3x2InvertIdentityTest()
{
Matrix3x2 mtx = Matrix3x2.Identity;
Matrix3x2 actual;
Assert.True(Matrix3x2.Invert(mtx, out actual));
Assert.True(MathHelper.Equal(actual, Matrix3x2.Identity));
}
// A test for Invert (Matrix3x2)
[Fact]
public void Matrix3x2InvertTranslationTest()
{
Matrix3x2 mtx = Matrix3x2.CreateTranslation(23, 42);
Matrix3x2 actual;
Assert.True(Matrix3x2.Invert(mtx, out actual));
Matrix3x2 i = mtx * actual;
Assert.True(MathHelper.Equal(i, Matrix3x2.Identity));
}
// A test for Invert (Matrix3x2)
[Fact]
public void Matrix3x2InvertRotationTest()
{
Matrix3x2 mtx = Matrix3x2.CreateRotation(2);
Matrix3x2 actual;
Assert.True(Matrix3x2.Invert(mtx, out actual));
Matrix3x2 i = mtx * actual;
Assert.True(MathHelper.Equal(i, Matrix3x2.Identity));
}
// A test for Invert (Matrix3x2)
[Fact]
public void Matrix3x2InvertScaleTest()
{
Matrix3x2 mtx = Matrix3x2.CreateScale(23, -42);
Matrix3x2 actual;
Assert.True(Matrix3x2.Invert(mtx, out actual));
Matrix3x2 i = mtx * actual;
Assert.True(MathHelper.Equal(i, Matrix3x2.Identity));
}
// A test for Invert (Matrix3x2)
[Fact]
public void Matrix3x2InvertAffineTest()
{
Matrix3x2 mtx = Matrix3x2.CreateRotation(2) *
Matrix3x2.CreateScale(23, -42) *
Matrix3x2.CreateTranslation(17, 53);
Matrix3x2 actual;
Assert.True(Matrix3x2.Invert(mtx, out actual));
Matrix3x2 i = mtx * actual;
Assert.True(MathHelper.Equal(i, Matrix3x2.Identity));
}
// A test for CreateRotation (float)
[Fact]
public void Matrix3x2CreateRotationTest()
{
float radians = MathHelper.ToRadians(50.0f);
Matrix3x2 expected = new Matrix3x2();
expected.M11 = 0.642787635f;
expected.M12 = 0.766044438f;
expected.M21 = -0.766044438f;
expected.M22 = 0.642787635f;
Matrix3x2 actual;
actual = Matrix3x2.CreateRotation(radians);
Assert.True(MathHelper.Equal(expected, actual), "Matrix3x2.CreateRotation did not return the expected value.");
}
// A test for CreateRotation (float, Vector2f)
[Fact]
public void Matrix3x2CreateRotationCenterTest()
{
float radians = MathHelper.ToRadians(30.0f);
Vector2 center = new Vector2(23, 42);
Matrix3x2 rotateAroundZero = Matrix3x2.CreateRotation(radians, Vector2.Zero);
Matrix3x2 rotateAroundZeroExpected = Matrix3x2.CreateRotation(radians);
Assert.True(MathHelper.Equal(rotateAroundZero, rotateAroundZeroExpected));
Matrix3x2 rotateAroundCenter = Matrix3x2.CreateRotation(radians, center);
Matrix3x2 rotateAroundCenterExpected = Matrix3x2.CreateTranslation(-center) * Matrix3x2.CreateRotation(radians) * Matrix3x2.CreateTranslation(center);
Assert.True(MathHelper.Equal(rotateAroundCenter, rotateAroundCenterExpected));
}
// A test for CreateRotation (float)
[Fact]
public void Matrix3x2CreateRotationRightAngleTest()
{
// 90 degree rotations must be exact!
Matrix3x2 actual = Matrix3x2.CreateRotation(0);
Assert.Equal(new Matrix3x2(1, 0, 0, 1, 0, 0), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi / 2);
Assert.Equal(new Matrix3x2(0, 1, -1, 0, 0, 0), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi);
Assert.Equal(new Matrix3x2(-1, 0, 0, -1, 0, 0), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi * 3 / 2);
Assert.Equal(new Matrix3x2(0, -1, 1, 0, 0, 0), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi * 2);
Assert.Equal(new Matrix3x2(1, 0, 0, 1, 0, 0), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi * 5 / 2);
Assert.Equal(new Matrix3x2(0, 1, -1, 0, 0, 0), actual);
actual = Matrix3x2.CreateRotation(-MathHelper.Pi / 2);
Assert.Equal(new Matrix3x2(0, -1, 1, 0, 0, 0), actual);
// But merely close-to-90 rotations should not be excessively clamped.
float delta = MathHelper.ToRadians(0.01f);
actual = Matrix3x2.CreateRotation(MathHelper.Pi + delta);
Assert.False(MathHelper.Equal(new Matrix3x2(-1, 0, 0, -1, 0, 0), actual));
actual = Matrix3x2.CreateRotation(MathHelper.Pi - delta);
Assert.False(MathHelper.Equal(new Matrix3x2(-1, 0, 0, -1, 0, 0), actual));
}
// A test for CreateRotation (float, Vector2f)
[Fact]
public void Matrix3x2CreateRotationRightAngleCenterTest()
{
Vector2 center = new Vector2(3, 7);
// 90 degree rotations must be exact!
Matrix3x2 actual = Matrix3x2.CreateRotation(0, center);
Assert.Equal(new Matrix3x2(1, 0, 0, 1, 0, 0), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi / 2, center);
Assert.Equal(new Matrix3x2(0, 1, -1, 0, 10, 4), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi, center);
Assert.Equal(new Matrix3x2(-1, 0, 0, -1, 6, 14), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi * 3 / 2, center);
Assert.Equal(new Matrix3x2(0, -1, 1, 0, -4, 10), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi * 2, center);
Assert.Equal(new Matrix3x2(1, 0, 0, 1, 0, 0), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi * 5 / 2, center);
Assert.Equal(new Matrix3x2(0, 1, -1, 0, 10, 4), actual);
actual = Matrix3x2.CreateRotation(-MathHelper.Pi / 2, center);
Assert.Equal(new Matrix3x2(0, -1, 1, 0, -4, 10), actual);
// But merely close-to-90 rotations should not be excessively clamped.
float delta = MathHelper.ToRadians(0.01f);
actual = Matrix3x2.CreateRotation(MathHelper.Pi + delta, center);
Assert.False(MathHelper.Equal(new Matrix3x2(-1, 0, 0, -1, 6, 14), actual));
actual = Matrix3x2.CreateRotation(MathHelper.Pi - delta, center);
Assert.False(MathHelper.Equal(new Matrix3x2(-1, 0, 0, -1, 6, 14), actual));
}
// A test for Invert (Matrix3x2)
// Non invertible matrix - determinant is zero - singular matrix
[Fact]
public void Matrix3x2InvertTest1()
{
Matrix3x2 a = new Matrix3x2();
a.M11 = 0.0f;
a.M12 = 2.0f;
a.M21 = 0.0f;
a.M22 = 4.0f;
a.M31 = 5.0f;
a.M32 = 6.0f;
float detA = a.GetDeterminant();
Assert.True(MathHelper.Equal(detA, 0.0f), "Matrix3x2.Invert did not return the expected value.");
Matrix3x2 actual;
Assert.False(Matrix3x2.Invert(a, out actual));
// all the elements in Actual is NaN
Assert.True(
float.IsNaN(actual.M11) && float.IsNaN(actual.M12) &&
float.IsNaN(actual.M21) && float.IsNaN(actual.M22) &&
float.IsNaN(actual.M31) && float.IsNaN(actual.M32)
, "Matrix3x2.Invert did not return the expected value.");
}
// A test for Lerp (Matrix3x2, Matrix3x2, float)
[Fact]
public void Matrix3x2LerpTest()
{
Matrix3x2 a = new Matrix3x2();
a.M11 = 11.0f;
a.M12 = 12.0f;
a.M21 = 21.0f;
a.M22 = 22.0f;
a.M31 = 31.0f;
a.M32 = 32.0f;
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
float t = 0.5f;
Matrix3x2 expected = new Matrix3x2();
expected.M11 = a.M11 + (b.M11 - a.M11) * t;
expected.M12 = a.M12 + (b.M12 - a.M12) * t;
expected.M21 = a.M21 + (b.M21 - a.M21) * t;
expected.M22 = a.M22 + (b.M22 - a.M22) * t;
expected.M31 = a.M31 + (b.M31 - a.M31) * t;
expected.M32 = a.M32 + (b.M32 - a.M32) * t;
Matrix3x2 actual;
actual = Matrix3x2.Lerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Matrix3x2.Lerp did not return the expected value.");
}
// A test for operator - (Matrix3x2)
[Fact]
public void Matrix3x2UnaryNegationTest()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2();
expected.M11 = -1.0f;
expected.M12 = -2.0f;
expected.M21 = -3.0f;
expected.M22 = -4.0f;
expected.M31 = -5.0f;
expected.M32 = -6.0f;
Matrix3x2 actual = -a;
Assert.True(MathHelper.Equal(expected, actual), "Matrix3x2.operator - did not return the expected value.");
}
// A test for operator - (Matrix3x2, Matrix3x2)
[Fact]
public void Matrix3x2SubtractionTest()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2();
Matrix3x2 actual = a - b;
Assert.True(MathHelper.Equal(expected, actual), "Matrix3x2.operator - did not return the expected value.");
}
// A test for operator * (Matrix3x2, Matrix3x2)
[Fact]
public void Matrix3x2MultiplyTest1()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2();
expected.M11 = a.M11 * b.M11 + a.M12 * b.M21;
expected.M12 = a.M11 * b.M12 + a.M12 * b.M22;
expected.M21 = a.M21 * b.M11 + a.M22 * b.M21;
expected.M22 = a.M21 * b.M12 + a.M22 * b.M22;
expected.M31 = a.M31 * b.M11 + a.M32 * b.M21 + b.M31;
expected.M32 = a.M31 * b.M12 + a.M32 * b.M22 + b.M32;
Matrix3x2 actual = a * b;
Assert.True(MathHelper.Equal(expected, actual), "Matrix3x2.operator * did not return the expected value.");
// Sanity check by comparison with 4x4 multiply.
a = Matrix3x2.CreateRotation(MathHelper.ToRadians(30)) * Matrix3x2.CreateTranslation(23, 42);
b = Matrix3x2.CreateScale(3, 7) * Matrix3x2.CreateTranslation(666, -1);
actual = a * b;
Matrix4x4 a44 = new Matrix4x4(a);
Matrix4x4 b44 = new Matrix4x4(b);
Matrix4x4 expected44 = a44 * b44;
Matrix4x4 actual44 = new Matrix4x4(actual);
Assert.True(MathHelper.Equal(expected44, actual44), "Matrix3x2.operator * did not return the expected value.");
}
// A test for operator * (Matrix3x2, Matrix3x2)
// Multiply with identity matrix
[Fact]
public void Matrix3x2MultiplyTest4()
{
Matrix3x2 a = new Matrix3x2();
a.M11 = 1.0f;
a.M12 = 2.0f;
a.M21 = 5.0f;
a.M22 = -6.0f;
a.M31 = 9.0f;
a.M32 = 10.0f;
Matrix3x2 b = new Matrix3x2();
b = Matrix3x2.Identity;
Matrix3x2 expected = a;
Matrix3x2 actual = a * b;
Assert.True(MathHelper.Equal(expected, actual), "Matrix3x2.operator * did not return the expected value.");
}
// A test for operator + (Matrix3x2, Matrix3x2)
[Fact]
public void Matrix3x2AdditionTest()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2();
expected.M11 = a.M11 + b.M11;
expected.M12 = a.M12 + b.M12;
expected.M21 = a.M21 + b.M21;
expected.M22 = a.M22 + b.M22;
expected.M31 = a.M31 + b.M31;
expected.M32 = a.M32 + b.M32;
Matrix3x2 actual;
actual = a + b;
Assert.True(MathHelper.Equal(expected, actual), "Matrix3x2.operator + did not return the expected value.");
}
// A test for ToString ()
[Fact]
public void Matrix3x2ToStringTest()
{
Matrix3x2 a = new Matrix3x2();
a.M11 = 11.0f;
a.M12 = -12.0f;
a.M21 = 21.0f;
a.M22 = 22.0f;
a.M31 = 31.0f;
a.M32 = 32.0f;
string expected = "{ {M11:11 M12:-12} " +
"{M21:21 M22:22} " +
"{M31:31 M32:32} }";
string actual;
actual = a.ToString();
Assert.Equal(expected, actual);
}
// A test for Add (Matrix3x2, Matrix3x2)
[Fact]
public void Matrix3x2AddTest()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2();
expected.M11 = a.M11 + b.M11;
expected.M12 = a.M12 + b.M12;
expected.M21 = a.M21 + b.M21;
expected.M22 = a.M22 + b.M22;
expected.M31 = a.M31 + b.M31;
expected.M32 = a.M32 + b.M32;
Matrix3x2 actual;
actual = Matrix3x2.Add(a, b);
Assert.Equal(expected, actual);
}
// A test for Equals (object)
[Fact]
public void Matrix3x2EqualsTest()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
// case 1: compare between same values
object obj = b;
bool expected = true;
bool actual = a.Equals(obj);
Assert.Equal(expected, actual);
// case 2: compare between different values
b.M11 = 11.0f;
obj = b;
expected = false;
actual = a.Equals(obj);
Assert.Equal(expected, actual);
// case 3: compare between different types.
obj = new Vector4();
expected = false;
actual = a.Equals(obj);
Assert.Equal(expected, actual);
// case 3: compare against null.
obj = null;
expected = false;
actual = a.Equals(obj);
Assert.Equal(expected, actual);
}
// A test for GetHashCode ()
[Fact]
public void Matrix3x2GetHashCodeTest()
{
Matrix3x2 target = GenerateMatrixNumberFrom1To6();
int expected = target.M11.GetHashCode() + target.M12.GetHashCode() +
target.M21.GetHashCode() + target.M22.GetHashCode() +
target.M31.GetHashCode() + target.M32.GetHashCode();
int actual;
actual = target.GetHashCode();
Assert.Equal(expected, actual);
}
// A test for Multiply (Matrix3x2, Matrix3x2)
[Fact]
public void Matrix3x2MultiplyTest3()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2();
expected.M11 = a.M11 * b.M11 + a.M12 * b.M21;
expected.M12 = a.M11 * b.M12 + a.M12 * b.M22;
expected.M21 = a.M21 * b.M11 + a.M22 * b.M21;
expected.M22 = a.M21 * b.M12 + a.M22 * b.M22;
expected.M31 = a.M31 * b.M11 + a.M32 * b.M21 + b.M31;
expected.M32 = a.M31 * b.M12 + a.M32 * b.M22 + b.M32;
Matrix3x2 actual;
actual = Matrix3x2.Multiply(a, b);
Assert.Equal(expected, actual);
// Sanity check by comparison with 4x4 multiply.
a = Matrix3x2.CreateRotation(MathHelper.ToRadians(30)) * Matrix3x2.CreateTranslation(23, 42);
b = Matrix3x2.CreateScale(3, 7) * Matrix3x2.CreateTranslation(666, -1);
actual = Matrix3x2.Multiply(a, b);
Matrix4x4 a44 = new Matrix4x4(a);
Matrix4x4 b44 = new Matrix4x4(b);
Matrix4x4 expected44 = Matrix4x4.Multiply(a44, b44);
Matrix4x4 actual44 = new Matrix4x4(actual);
Assert.True(MathHelper.Equal(expected44, actual44), "Matrix3x2.Multiply did not return the expected value.");
}
// A test for Multiply (Matrix3x2, float)
[Fact]
public void Matrix3x2MultiplyTest5()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2(3, 6, 9, 12, 15, 18);
Matrix3x2 actual = Matrix3x2.Multiply(a, 3);
Assert.Equal(expected, actual);
}
// A test for Multiply (Matrix3x2, float)
[Fact]
public void Matrix3x2MultiplyTest6()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2(3, 6, 9, 12, 15, 18);
Matrix3x2 actual = a * 3;
Assert.Equal(expected, actual);
}
// A test for Negate (Matrix3x2)
[Fact]
public void Matrix3x2NegateTest()
{
Matrix3x2 m = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2();
expected.M11 = -1.0f;
expected.M12 = -2.0f;
expected.M21 = -3.0f;
expected.M22 = -4.0f;
expected.M31 = -5.0f;
expected.M32 = -6.0f;
Matrix3x2 actual;
actual = Matrix3x2.Negate(m);
Assert.Equal(expected, actual);
}
// A test for operator != (Matrix3x2, Matrix3x2)
[Fact]
public void Matrix3x2InequalityTest()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
// case 1: compare between same values
bool expected = false;
bool actual = a != b;
Assert.Equal(expected, actual);
// case 2: compare between different values
b.M11 = 11.0f;
expected = true;
actual = a != b;
Assert.Equal(expected, actual);
}
// A test for operator == (Matrix3x2, Matrix3x2)
[Fact]
public void Matrix3x2EqualityTest()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
// case 1: compare between same values
bool expected = true;
bool actual = a == b;
Assert.Equal(expected, actual);
// case 2: compare between different values
b.M11 = 11.0f;
expected = false;
actual = a == b;
Assert.Equal(expected, actual);
}
// A test for Subtract (Matrix3x2, Matrix3x2)
[Fact]
public void Matrix3x2SubtractTest()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2();
Matrix3x2 actual;
actual = Matrix3x2.Subtract(a, b);
Assert.Equal(expected, actual);
}
// A test for CreateScale (Vector2f)
[Fact]
public void Matrix3x2CreateScaleTest1()
{
Vector2 scales = new Vector2(2.0f, 3.0f);
Matrix3x2 expected = new Matrix3x2(
2.0f, 0.0f,
0.0f, 3.0f,
0.0f, 0.0f);
Matrix3x2 actual = Matrix3x2.CreateScale(scales);
Assert.Equal(expected, actual);
}
// A test for CreateScale (Vector2f, Vector2f)
[Fact]
public void Matrix3x2CreateScaleCenterTest1()
{
Vector2 scale = new Vector2(3, 4);
Vector2 center = new Vector2(23, 42);
Matrix3x2 scaleAroundZero = Matrix3x2.CreateScale(scale, Vector2.Zero);
Matrix3x2 scaleAroundZeroExpected = Matrix3x2.CreateScale(scale);
Assert.True(MathHelper.Equal(scaleAroundZero, scaleAroundZeroExpected));
Matrix3x2 scaleAroundCenter = Matrix3x2.CreateScale(scale, center);
Matrix3x2 scaleAroundCenterExpected = Matrix3x2.CreateTranslation(-center) * Matrix3x2.CreateScale(scale) * Matrix3x2.CreateTranslation(center);
Assert.True(MathHelper.Equal(scaleAroundCenter, scaleAroundCenterExpected));
}
// A test for CreateScale (float)
[Fact]
public void Matrix3x2CreateScaleTest2()
{
float scale = 2.0f;
Matrix3x2 expected = new Matrix3x2(
2.0f, 0.0f,
0.0f, 2.0f,
0.0f, 0.0f);
Matrix3x2 actual = Matrix3x2.CreateScale(scale);
Assert.Equal(expected, actual);
}
// A test for CreateScale (float, Vector2f)
[Fact]
public void Matrix3x2CreateScaleCenterTest2()
{
float scale = 5;
Vector2 center = new Vector2(23, 42);
Matrix3x2 scaleAroundZero = Matrix3x2.CreateScale(scale, Vector2.Zero);
Matrix3x2 scaleAroundZeroExpected = Matrix3x2.CreateScale(scale);
Assert.True(MathHelper.Equal(scaleAroundZero, scaleAroundZeroExpected));
Matrix3x2 scaleAroundCenter = Matrix3x2.CreateScale(scale, center);
Matrix3x2 scaleAroundCenterExpected = Matrix3x2.CreateTranslation(-center) * Matrix3x2.CreateScale(scale) * Matrix3x2.CreateTranslation(center);
Assert.True(MathHelper.Equal(scaleAroundCenter, scaleAroundCenterExpected));
}
// A test for CreateScale (float, float)
[Fact]
public void Matrix3x2CreateScaleTest3()
{
float xScale = 2.0f;
float yScale = 3.0f;
Matrix3x2 expected = new Matrix3x2(
2.0f, 0.0f,
0.0f, 3.0f,
0.0f, 0.0f);
Matrix3x2 actual = Matrix3x2.CreateScale(xScale, yScale);
Assert.Equal(expected, actual);
}
// A test for CreateScale (float, float, Vector2f)
[Fact]
public void Matrix3x2CreateScaleCenterTest3()
{
Vector2 scale = new Vector2(3, 4);
Vector2 center = new Vector2(23, 42);
Matrix3x2 scaleAroundZero = Matrix3x2.CreateScale(scale.X, scale.Y, Vector2.Zero);
Matrix3x2 scaleAroundZeroExpected = Matrix3x2.CreateScale(scale.X, scale.Y);
Assert.True(MathHelper.Equal(scaleAroundZero, scaleAroundZeroExpected));
Matrix3x2 scaleAroundCenter = Matrix3x2.CreateScale(scale.X, scale.Y, center);
Matrix3x2 scaleAroundCenterExpected = Matrix3x2.CreateTranslation(-center) * Matrix3x2.CreateScale(scale.X, scale.Y) * Matrix3x2.CreateTranslation(center);
Assert.True(MathHelper.Equal(scaleAroundCenter, scaleAroundCenterExpected));
}
// A test for CreateTranslation (Vector2f)
[Fact]
public void Matrix3x2CreateTranslationTest1()
{
Vector2 position = new Vector2(2.0f, 3.0f);
Matrix3x2 expected = new Matrix3x2(
1.0f, 0.0f,
0.0f, 1.0f,
2.0f, 3.0f);
Matrix3x2 actual = Matrix3x2.CreateTranslation(position);
Assert.Equal(expected, actual);
}
// A test for CreateTranslation (float, float)
[Fact]
public void Matrix3x2CreateTranslationTest2()
{
float xPosition = 2.0f;
float yPosition = 3.0f;
Matrix3x2 expected = new Matrix3x2(
1.0f, 0.0f,
0.0f, 1.0f,
2.0f, 3.0f);
Matrix3x2 actual = Matrix3x2.CreateTranslation(xPosition, yPosition);
Assert.Equal(expected, actual);
}
// A test for Translation
[Fact]
public void Matrix3x2TranslationTest()
{
Matrix3x2 a = GenerateTestMatrix();
Matrix3x2 b = a;
// Transformed vector that has same semantics of property must be same.
Vector2 val = new Vector2(a.M31, a.M32);
Assert.Equal(val, a.Translation);
// Set value and get value must be same.
val = new Vector2(1.0f, 2.0f);
a.Translation = val;
Assert.Equal(val, a.Translation);
// Make sure it only modifies expected value of matrix.
Assert.True(
a.M11 == b.M11 && a.M12 == b.M12 &&
a.M21 == b.M21 && a.M22 == b.M22 &&
a.M31 != b.M31 && a.M32 != b.M32,
"Matrix3x2.Translation modified unexpected value of matrix.");
}
// A test for Equals (Matrix3x2)
[Fact]
public void Matrix3x2EqualsTest1()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
// case 1: compare between same values
bool expected = true;
bool actual = a.Equals(b);
Assert.Equal(expected, actual);
// case 2: compare between different values
b.M11 = 11.0f;
expected = false;
actual = a.Equals(b);
Assert.Equal(expected, actual);
}
// A test for CreateSkew (float, float)
[Fact]
public void Matrix3x2CreateSkewIdentityTest()
{
Matrix3x2 expected = Matrix3x2.Identity;
Matrix3x2 actual = Matrix3x2.CreateSkew(0, 0);
Assert.Equal(expected, actual);
}
// A test for CreateSkew (float, float)
[Fact]
public void Matrix3x2CreateSkewXTest()
{
Matrix3x2 expected = new Matrix3x2(1, 0, -0.414213562373095f, 1, 0, 0);
Matrix3x2 actual = Matrix3x2.CreateSkew(-MathHelper.Pi / 8, 0);
Assert.True(MathHelper.Equal(expected, actual));
expected = new Matrix3x2(1, 0, 0.414213562373095f, 1, 0, 0);
actual = Matrix3x2.CreateSkew(MathHelper.Pi / 8, 0);
Assert.True(MathHelper.Equal(expected, actual));
Vector2 result = Vector2.Transform(new Vector2(0, 0), actual);
Assert.True(MathHelper.Equal(new Vector2(0, 0), result));
result = Vector2.Transform(new Vector2(0, 1), actual);
Assert.True(MathHelper.Equal(new Vector2(0.414213568f, 1), result));
result = Vector2.Transform(new Vector2(0, -1), actual);
Assert.True(MathHelper.Equal(new Vector2(-0.414213568f, -1), result));
result = Vector2.Transform(new Vector2(3, 10), actual);
Assert.True(MathHelper.Equal(new Vector2(7.14213568f, 10), result));
}
// A test for CreateSkew (float, float)
[Fact]
public void Matrix3x2CreateSkewYTest()
{
Matrix3x2 expected = new Matrix3x2(1, -0.414213562373095f, 0, 1, 0, 0);
Matrix3x2 actual = Matrix3x2.CreateSkew(0, -MathHelper.Pi / 8);
Assert.True(MathHelper.Equal(expected, actual));
expected = new Matrix3x2(1, 0.414213562373095f, 0, 1, 0, 0);
actual = Matrix3x2.CreateSkew(0, MathHelper.Pi / 8);
Assert.True(MathHelper.Equal(expected, actual));
Vector2 result = Vector2.Transform(new Vector2(0, 0), actual);
Assert.True(MathHelper.Equal(new Vector2(0, 0), result));
result = Vector2.Transform(new Vector2(1, 0), actual);
Assert.True(MathHelper.Equal(new Vector2(1, 0.414213568f), result));
result = Vector2.Transform(new Vector2(-1, 0), actual);
Assert.True(MathHelper.Equal(new Vector2(-1, -0.414213568f), result));
result = Vector2.Transform(new Vector2(10, 3), actual);
Assert.True(MathHelper.Equal(new Vector2(10, 7.14213568f), result));
}
// A test for CreateSkew (float, float)
[Fact]
public void Matrix3x2CreateSkewXYTest()
{
Matrix3x2 expected = new Matrix3x2(1, -0.414213562373095f, 1, 1, 0, 0);
Matrix3x2 actual = Matrix3x2.CreateSkew(MathHelper.Pi / 4, -MathHelper.Pi / 8);
Assert.True(MathHelper.Equal(expected, actual));
Vector2 result = Vector2.Transform(new Vector2(0, 0), actual);
Assert.True(MathHelper.Equal(new Vector2(0, 0), result));
result = Vector2.Transform(new Vector2(1, 0), actual);
Assert.True(MathHelper.Equal(new Vector2(1, -0.414213562373095f), result));
result = Vector2.Transform(new Vector2(0, 1), actual);
Assert.True(MathHelper.Equal(new Vector2(1, 1), result));
result = Vector2.Transform(new Vector2(1, 1), actual);
Assert.True(MathHelper.Equal(new Vector2(2, 0.585786437626905f), result));
}
// A test for CreateSkew (float, float, Vector2f)
[Fact]
public void Matrix3x2CreateSkewCenterTest()
{
float skewX = 1, skewY = 2;
Vector2 center = new Vector2(23, 42);
Matrix3x2 skewAroundZero = Matrix3x2.CreateSkew(skewX, skewY, Vector2.Zero);
Matrix3x2 skewAroundZeroExpected = Matrix3x2.CreateSkew(skewX, skewY);
Assert.True(MathHelper.Equal(skewAroundZero, skewAroundZeroExpected));
Matrix3x2 skewAroundCenter = Matrix3x2.CreateSkew(skewX, skewY, center);
Matrix3x2 skewAroundCenterExpected = Matrix3x2.CreateTranslation(-center) * Matrix3x2.CreateSkew(skewX, skewY) * Matrix3x2.CreateTranslation(center);
Assert.True(MathHelper.Equal(skewAroundCenter, skewAroundCenterExpected));
}
// A test for IsIdentity
[Fact]
public void Matrix3x2IsIdentityTest()
{
Assert.True(Matrix3x2.Identity.IsIdentity);
Assert.True(new Matrix3x2(1, 0, 0, 1, 0, 0).IsIdentity);
Assert.False(new Matrix3x2(0, 0, 0, 1, 0, 0).IsIdentity);
Assert.False(new Matrix3x2(1, 1, 0, 1, 0, 0).IsIdentity);
Assert.False(new Matrix3x2(1, 0, 1, 1, 0, 0).IsIdentity);
Assert.False(new Matrix3x2(1, 0, 0, 0, 0, 0).IsIdentity);
Assert.False(new Matrix3x2(1, 0, 0, 1, 1, 0).IsIdentity);
Assert.False(new Matrix3x2(1, 0, 0, 1, 0, 1).IsIdentity);
}
// A test for Matrix3x2 comparison involving NaN values
[Fact]
public void Matrix3x2EqualsNanTest()
{
Matrix3x2 a = new Matrix3x2(float.NaN, 0, 0, 0, 0, 0);
Matrix3x2 b = new Matrix3x2(0, float.NaN, 0, 0, 0, 0);
Matrix3x2 c = new Matrix3x2(0, 0, float.NaN, 0, 0, 0);
Matrix3x2 d = new Matrix3x2(0, 0, 0, float.NaN, 0, 0);
Matrix3x2 e = new Matrix3x2(0, 0, 0, 0, float.NaN, 0);
Matrix3x2 f = new Matrix3x2(0, 0, 0, 0, 0, float.NaN);
Assert.False(a == new Matrix3x2());
Assert.False(b == new Matrix3x2());
Assert.False(c == new Matrix3x2());
Assert.False(d == new Matrix3x2());
Assert.False(e == new Matrix3x2());
Assert.False(f == new Matrix3x2());
Assert.True(a != new Matrix3x2());
Assert.True(b != new Matrix3x2());
Assert.True(c != new Matrix3x2());
Assert.True(d != new Matrix3x2());
Assert.True(e != new Matrix3x2());
Assert.True(f != new Matrix3x2());
Assert.False(a.Equals(new Matrix3x2()));
Assert.False(b.Equals(new Matrix3x2()));
Assert.False(c.Equals(new Matrix3x2()));
Assert.False(d.Equals(new Matrix3x2()));
Assert.False(e.Equals(new Matrix3x2()));
Assert.False(f.Equals(new Matrix3x2()));
Assert.False(a.IsIdentity);
Assert.False(b.IsIdentity);
Assert.False(c.IsIdentity);
Assert.False(d.IsIdentity);
Assert.False(e.IsIdentity);
Assert.False(f.IsIdentity);
// Counterintuitive result - IEEE rules for NaN comparison are weird!
Assert.False(a.Equals(a));
Assert.False(b.Equals(b));
Assert.False(c.Equals(c));
Assert.False(d.Equals(d));
Assert.False(e.Equals(e));
Assert.False(f.Equals(f));
}
// A test to make sure these types are blittable directly into GPU buffer memory layouts
[Fact]
public unsafe void Matrix3x2SizeofTest()
{
Assert.Equal(24, sizeof(Matrix3x2));
Assert.Equal(48, sizeof(Matrix3x2_2x));
Assert.Equal(28, sizeof(Matrix3x2PlusFloat));
Assert.Equal(56, sizeof(Matrix3x2PlusFloat_2x));
}
[StructLayout(LayoutKind.Sequential)]
struct Matrix3x2_2x
{
private Matrix3x2 _a;
private Matrix3x2 _b;
}
[StructLayout(LayoutKind.Sequential)]
struct Matrix3x2PlusFloat
{
private Matrix3x2 _v;
private float _f;
}
[StructLayout(LayoutKind.Sequential)]
struct Matrix3x2PlusFloat_2x
{
private Matrix3x2PlusFloat _a;
private Matrix3x2PlusFloat _b;
}
// A test to make sure the fields are laid out how we expect
[Fact]
public unsafe void Matrix3x2FieldOffsetTest()
{
Matrix3x2 mat = new Matrix3x2();
float* basePtr = &mat.M11; // Take address of first element
Matrix3x2* matPtr = &mat; // Take address of whole matrix
Assert.Equal(new IntPtr(basePtr), new IntPtr(matPtr));
Assert.Equal(new IntPtr(basePtr + 0), new IntPtr(&mat.M11));
Assert.Equal(new IntPtr(basePtr + 1), new IntPtr(&mat.M12));
Assert.Equal(new IntPtr(basePtr + 2), new IntPtr(&mat.M21));
Assert.Equal(new IntPtr(basePtr + 3), new IntPtr(&mat.M22));
Assert.Equal(new IntPtr(basePtr + 4), new IntPtr(&mat.M31));
Assert.Equal(new IntPtr(basePtr + 5), new IntPtr(&mat.M32));
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="CompilerParameters.cs" company="Microsoft">
//
// <OWNER>[....]</OWNER>
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.CodeDom.Compiler {
using System;
using System.CodeDom;
using System.Collections;
using System.Collections.Specialized;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Security.Policy;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
/// <devdoc>
/// <para>
/// Represents the parameters used in to invoke the compiler.
/// </para>
/// </devdoc>
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
[Serializable]
public class CompilerParameters {
[OptionalField]
private string coreAssemblyFileName = String.Empty;
private StringCollection assemblyNames = new StringCollection();
[OptionalField]
private StringCollection embeddedResources = new StringCollection();
[OptionalField]
private StringCollection linkedResources = new StringCollection();
private string outputName;
private string mainClass;
private bool generateInMemory = false;
private bool includeDebugInformation = false;
private int warningLevel = -1; // -1 means not set (use compiler default)
private string compilerOptions;
private string win32Resource;
private bool treatWarningsAsErrors = false;
private bool generateExecutable = false;
private TempFileCollection tempFiles;
[NonSerializedAttribute]
private SafeUserTokenHandle userToken;
private Evidence evidence = null;
/// <devdoc>
/// <para>
/// Initializes a new instance of <see cref='System.CodeDom.Compiler.CompilerParameters'/>.
/// </para>
/// </devdoc>
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
public CompilerParameters() :
this(null, null) {
}
/// <devdoc>
/// <para>
/// Initializes a new instance of <see cref='System.CodeDom.Compiler.CompilerParameters'/> using the specified
/// assembly names.
/// </para>
/// </devdoc>
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
public CompilerParameters(string[] assemblyNames) :
this(assemblyNames, null, false) {
}
/// <devdoc>
/// <para>
/// Initializes a new instance of <see cref='System.CodeDom.Compiler.CompilerParameters'/> using the specified
/// assembly names and output name.
/// </para>
/// </devdoc>
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public CompilerParameters(string[] assemblyNames, string outputName) :
this(assemblyNames, outputName, false) {
}
/// <devdoc>
/// <para>
/// Initializes a new instance of <see cref='System.CodeDom.Compiler.CompilerParameters'/> using the specified
/// assembly names, output name and a whether to include debug information flag.
/// </para>
/// </devdoc>
[ResourceExposure(ResourceScope.Machine)]
public CompilerParameters(string[] assemblyNames, string outputName, bool includeDebugInformation) {
if (assemblyNames != null) {
ReferencedAssemblies.AddRange(assemblyNames);
}
this.outputName = outputName;
this.includeDebugInformation = includeDebugInformation;
}
/// <summary>
/// The "core" or "standard" assembly that contains basic types such as <code>Object</code>, <code>Int32</code> and the like
/// that is to be used for the compilation.<br />
/// If the value of this property is an empty string (or <code>null</code>), the default core assembly will be used by the
/// compiler (depending on the compiler version this may be <code>mscorlib.dll</code> or <code>System.Runtime.dll</code> in
/// a Framework or reference assembly directory).<br />
/// If the value of this property is not empty, CodeDOM will emit compiler options to not reference <em>any</em> assemblies
/// implicitly during compilation. It will also explicitly reference the assembly file specified in this property.<br />
/// For compilers that only implicitly reference the "core" or "standard" assembly by default, this option can be used on its own.
/// For compilers that implicitly reference more assemblies on top of the "core" / "standard" assembly, using this option may require
/// specifying additional entries in the <code>System.CodeDom.Compiler.<bold>ReferencedAssemblies</bold></code> collection.<br />
/// Note: An <code>ICodeCompiler</code> / <code>CoodeDomProvider</code> implementation may choose to ignore this property.
/// </summary>
public string CoreAssemblyFileName {
get {
return coreAssemblyFileName;
}
set {
coreAssemblyFileName = value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets whether to generate an executable.
/// </para>
/// </devdoc>
public bool GenerateExecutable {
get {
return generateExecutable;
}
set {
generateExecutable = value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets whether to generate in memory.
/// </para>
/// </devdoc>
public bool GenerateInMemory {
get {
return generateInMemory;
}
set {
generateInMemory = value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the assemblies referenced by the source to compile.
/// </para>
/// </devdoc>
public StringCollection ReferencedAssemblies {
get {
return assemblyNames;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the main class.
/// </para>
/// </devdoc>
public string MainClass {
get {
return mainClass;
}
set {
mainClass = value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the output assembly.
/// </para>
/// </devdoc>
public string OutputAssembly {
[ResourceExposure(ResourceScope.Machine)]
get {
return outputName;
}
[ResourceExposure(ResourceScope.Machine)]
set {
outputName = value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the temp files.
/// </para>
/// </devdoc>
public TempFileCollection TempFiles {
get {
if (tempFiles == null)
tempFiles = new TempFileCollection();
return tempFiles;
}
set {
tempFiles = value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets whether to include debug information in the compiled
/// executable.
/// </para>
/// </devdoc>
public bool IncludeDebugInformation {
get {
return includeDebugInformation;
}
set {
includeDebugInformation = value;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public bool TreatWarningsAsErrors {
get {
return treatWarningsAsErrors;
}
set {
treatWarningsAsErrors = value;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public int WarningLevel {
get {
return warningLevel;
}
set {
warningLevel = value;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public string CompilerOptions {
get {
return compilerOptions;
}
set {
compilerOptions = value;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public string Win32Resource {
get {
return win32Resource;
}
set {
win32Resource = value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the resources to be compiled into the target
/// </para>
/// </devdoc>
[ComVisible(false)]
public StringCollection EmbeddedResources {
get {
return embeddedResources;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the linked resources
/// </para>
/// </devdoc>
[ComVisible(false)]
public StringCollection LinkedResources {
get {
return linkedResources;
}
}
/// <devdoc>
/// <para>
/// Gets or sets user token to be employed when creating the compiler process.
/// </para>
/// </devdoc>
public IntPtr UserToken {
get {
if (userToken != null)
return userToken.DangerousGetHandle();
else
return IntPtr.Zero;
}
set {
if (userToken != null)
userToken.Close();
userToken = new SafeUserTokenHandle(value, false);
}
}
internal SafeUserTokenHandle SafeUserToken {
get {
return userToken;
}
}
/// <devdoc>
/// <para>
/// Set the evidence for partially trusted scenarios.
/// </para>
/// </devdoc>
[Obsolete("CAS policy is obsolete and will be removed in a future release of the .NET Framework."
+ " Please see http://go2.microsoft.com/fwlink/?LinkId=131738 for more information.")]
public Evidence Evidence {
get {
Evidence e = null;
if (evidence != null)
e = evidence.Clone();
return e;
}
[SecurityPermissionAttribute( SecurityAction.Demand, ControlEvidence = true )]
set {
if (value != null)
evidence = value.Clone();
else
evidence = null;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System.Collections.Generic;
namespace Microsoft.Azure.Management.Network.Fluent
{
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.Network.Fluent.ExpressRouteCircuitPeering.Definition;
using Microsoft.Azure.Management.Network.Fluent.ExpressRouteCircuitPeering.Update;
using Microsoft.Azure.Management.Network.Fluent.Models;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50Lm5ldHdvcmsuaW1wbGVtZW50YXRpb24uRXhwcmVzc1JvdXRlQ2lyY3VpdFBlZXJpbmdJbXBs
internal partial class ExpressRouteCircuitPeeringImpl :
IndependentChildImpl<
IExpressRouteCircuitPeering,
IExpressRouteCircuit,
ExpressRouteCircuitPeeringInner,
ExpressRouteCircuitPeeringImpl,
IHasId,
IUpdate,
INetworkManager>,
IExpressRouteCircuitPeering,
IDefinition,
IUpdate
{
private IExpressRouteCircuitPeeringsOperations client;
private IExpressRouteCircuit parent;
private ExpressRouteCircuitStatsImpl stats;
///GENMHASH:CE19D6E1BE71E1233D9525A7E026BFC7:0DAA02A6E6149A594F1E611CEDA41775
public string SharedKey()
{
return Inner.SharedKey;
}
///GENMHASH:A50652422920394C30CADC3C3B5EB9A5:980EAF291C4225092A307D0171005F28
public string PrimaryAzurePort()
{
return Inner.PrimaryAzurePort;
}
///GENMHASH:F205630E75FA1148988CE1BB2312093B:B8A6D650BDAC3E4817F9DA420D6A8783
public Ipv6ExpressRouteCircuitPeeringConfig IPv6PeeringConfig()
{
return Inner.Ipv6PeeringConfig;
}
///GENMHASH:19E661FAB103F9F616D6E254F778F73A:D5E1AB9448B90D30C563BF0F3A2B2BBF
public string SecondaryAzurePort()
{
return Inner.SecondaryAzurePort;
}
///GENMHASH:C31CAD48396B22242629B56D7CF4C752:1C4FA0FB0A4C7AFB05F85FB74776EF31
public ExpressRouteCircuitPeeringImpl WithPrimaryPeerAddressPrefix(string addressPrefix)
{
Inner.PrimaryPeerAddressPrefix = addressPrefix;
return this;
}
///GENMHASH:F39264C98D411F14A45DA1D84E9F98DE:BE4F1022441334645B5E05DE48196994
private ExpressRouteCircuitPeeringConfig EnsureMicrosoftPeeringConfig()
{
if (Inner.MicrosoftPeeringConfig == null)
{
Inner.MicrosoftPeeringConfig = new ExpressRouteCircuitPeeringConfig();
}
return Inner.MicrosoftPeeringConfig;
}
///GENMHASH:8102636A111E22807C7BD05E4AD19D5F:E29C120BDBF04F95AF1826A1AFEE43C6
public int AzureAsn()
{
return Inner.AzureASN.HasValue ? Inner.AzureASN.Value : 0;
}
///GENMHASH:5AD91481A0966B059A478CD4E9DD9466:754810EA5144700BBB078C6E55E8C153
protected override async Task<Models.ExpressRouteCircuitPeeringInner> GetInnerAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return await client.GetAsync(parent.ResourceGroupName, parent.Name, Name);
}
///GENMHASH:B6A90BC231E9AF66CAE249DC54C16CE2:F78E367CA168F9A4650E2F8DD85F5907
public string SecondaryPeerAddressPrefix()
{
return Inner.SecondaryPeerAddressPrefix;
}
///GENMHASH:BA5CADB8C4D605E61A861FD937CC31A4:95B26F498B39D7FE039475F86AE24983
public ExpressRouteCircuitStatsImpl Stats()
{
return stats;
}
///GENMHASH:B411D8F65E0E6A8CB7A68775237D2253:88DD115259C0B2EE67A037B376BF5885
public ExpressRouteCircuitPeeringImpl WithSecondaryPeerAddressPrefix(string addressPrefix)
{
Inner.SecondaryPeerAddressPrefix = addressPrefix;
return this;
}
///GENMHASH:BC7AEF2CB64C2D427124B07846346ACF:65C532C06CDE074161D2DD0F0A8FA440
public string PrimaryPeerAddressPrefix()
{
return Inner.PrimaryPeerAddressPrefix;
}
///GENMHASH:ACA2D5620579D8158A29586CA1FF4BC6:A3CF7B3DC953F353AAE8083D72F74056
public override string Id
{
get
{
return Inner.Id;
}
}
///GENMHASH:AEE17FD09F624712647F5EBCEC141EA5:A2B4C8D5515FE0A160E2214A60FB99A6
public ExpressRoutePeeringState State()
{
return Inner.State;
}
///GENMHASH:0202A00A1DCF248D2647DBDBEF2CA865:4FC30E0F6EB4AA975F91CB9D7C798AFE
protected override async Task<Microsoft.Azure.Management.Network.Fluent.IExpressRouteCircuitPeering> CreateChildResourceAsync(CancellationToken cancellationToken = default(CancellationToken))
{
SetInner(await client.CreateOrUpdateAsync(parent.ResourceGroupName, parent.Name, this.Name, Inner));
stats = new ExpressRouteCircuitStatsImpl(Inner.Stats);
if (parent != null)
{
await parent.RefreshAsync(cancellationToken);
}
return this;
}
///GENMHASH:485C72CDD911A007F5A804436A3BCA68:FF479A489725561C2045B0642CCBCCED
public ExpressRoutePeeringType PeeringType()
{
return Inner.PeeringType;
}
///GENMHASH:5B4E75310952352A341A438C97BCDE27:43D5810028C5A1E8F807D845A5FC84BD
public ExpressRouteCircuitPeeringImpl WithVlanId(int vlanId)
{
Inner.VlanId = vlanId;
return this;
}
///GENMHASH:E9EDBD2E8DC2C547D1386A58778AA6B9:30C5ADA0233BA39DBC78FE6130CA9DC1
public string ResourceGroupName()
{
return parent.ResourceGroupName;
}
///GENMHASH:391F9005AD1C2F7A853CA2864862ED4F:DB3150F8D0E08097844D717E6619C2E3
public int VlanId()
{
return Inner.VlanId.HasValue ? Inner.VlanId.Value : 0;
}
///GENMHASH:F4BB98513D1B9E2571D1DD50496A5427:EB26B49EC1F5226DDE798B857F8726A7
public string LastModifiedBy()
{
return Inner.LastModifiedBy;
}
///GENMHASH:99D5BF64EA8AA0E287C9B6F77AAD6FC4:3DB04077E6BABC0FB5A5ACDA19D11309
public string ProvisioningState()
{
return Inner.ProvisioningState;
}
///GENMHASH:4F6F8EB53B615AA4FDE4C8CD06427C19:655E227778C880919192F106CB2F1726
public long PeerAsn()
{
return Inner.PeerASN.HasValue ? Inner.PeerASN.Value : 0;
}
///GENMHASH:BEA39F3632F73FBF1B8AF536983EFFFF:405C74E71663212A8907A343554332A4
public ExpressRouteCircuitPeeringImpl WithAdvertisedPublicPrefixes(string publicPrefix)
{
EnsureMicrosoftPeeringConfig().AdvertisedPublicPrefixes = new List<string> { publicPrefix };
return this;
}
///GENMHASH:781AA51279F5B129E87598D4CD0AA7A2:FB9DCC9BF2304804D68997EC6E1F8CFB
public ExpressRouteCircuitPeeringImpl WithPeerAsn(int peerAsn)
{
Inner.PeerASN = peerAsn;
return this;
}
///GENMHASH:631CF8EC2CF9DF06C92074E58975650B:53E334DA0EAD642691037F7A14026758
public ExpressRouteCircuitPeeringConfig MicrosoftPeeringConfig()
{
return Inner.MicrosoftPeeringConfig;
}
///GENMHASH:F1FF74FECF7AD81993920CCBF4D96B40:34F765B181E581705C5B1FEB895758A1
internal ExpressRouteCircuitPeeringImpl(ExpressRouteCircuitImpl parent, ExpressRouteCircuitPeeringInner innerObject, IExpressRouteCircuitPeeringsOperations client, ExpressRoutePeeringType type)
: base(type.Value, innerObject, parent.Manager)
{
this.client = client;
this.parent = parent;
stats = new ExpressRouteCircuitStatsImpl(innerObject.Stats);
Inner.PeeringType = type;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using gov.va.medora.mdo.exceptions;
using gov.va.medora.utils;
using gov.va.medora.mdo.dao.sql.UserValidation;
using gov.va.medora.mdo.src.mdo;
using gov.va.medora.mdo.conf;
namespace gov.va.medora.mdo.dao.vista
{
public class VistaAccount : AbstractAccount
{
internal static Dictionary<string, string> administrativeDfns = new MdoConfiguration
(true, ConfigFileConstants.CONFIG_FILE_NAME).AllConfigs[ConfigFileConstants.SERVICE_ACCOUNT_CONFIG_SECTION];
public VistaAccount(AbstractConnection cxn) : base(cxn) { }
//public override string authenticate(AbstractCredentials credentials)
//{
// return authenticate(credentials, null);
//}
public override string authenticate(AbstractCredentials credentials, DataSource validationDataSource = null)
{
if (Cxn == null || !Cxn.IsConnected)
{
throw new MdoException(MdoExceptionCode.USAGE_NO_CONNECTION, "Must have connection");
}
if (credentials == null)
{
throw new MdoException(MdoExceptionCode.ARGUMENT_NULL, "Missing credentials");
}
if (string.IsNullOrEmpty(AuthenticationMethod))
{
throw new MdoException(MdoExceptionCode.ARGUMENT_NULL, "Missing Account AuthenticationMethod");
}
if (AuthenticationMethod == VistaConstants.LOGIN_CREDENTIALS)
{
return login(credentials);
}
// Temporarily disabled - will do only V2WEB for now
//else if (AuthenticationMethod == VistaConstants.BSE_CREDENTIALS_V2V)
//{
// VisitTemplate visitTemplate = new BseVista2VistaVisit(this, credentials);
// return visitTemplate.visit();
//}
else if (AuthenticationMethod == VistaConstants.BSE_CREDENTIALS_V2WEB)
{
VisitTemplate visitTemplate = new BseVista2WebVisit(this, credentials, validationDataSource);
return visitTemplate.visit();
}
else if (AuthenticationMethod == VistaConstants.NON_BSE_CREDENTIALS)
{
VisitTemplate visitTemplate = new NonBseVisit(this, credentials);
return visitTemplate.visit();
}
else
{
throw new ArgumentException("Invalid credentials");
}
}
internal string login(AbstractCredentials credentials)
{
if (String.IsNullOrEmpty(credentials.AccountName))
{
throw new MdoException(MdoExceptionCode.ARGUMENT_NULL, "Missing Access Code");
}
if (String.IsNullOrEmpty(credentials.AccountPassword))
{
throw new MdoException(MdoExceptionCode.ARGUMENT_NULL, "Missing Verify Code");
}
VistaQuery vq = new VistaQuery("XUS SIGNON SETUP");
string rtn = (string)Cxn.query(vq);
if (rtn == null)
{
throw new UnexpectedDataException("Unable to setup authentication");
}
vq = new VistaQuery("XUS AV CODE");
// This is here so we can test with MockConnection
if (Cxn.GetType().Name != "MockConnection")
{
vq.addEncryptedParameter(vq.LITERAL, credentials.AccountName + ';' + credentials.AccountPassword);
}
else
{
vq.addParameter(vq.LITERAL, credentials.AccountName + ';' + credentials.AccountPassword);
}
rtn = (string)Cxn.query(vq);
//TODO - need to catch renew verify id error
string[] flds = StringUtils.split(rtn, StringUtils.CRLF);
if (flds[0] == "0")
{
throw new UnauthorizedAccessException(flds[3]);
}
AccountId = flds[0];
// Set the connection's UID
Cxn.Uid = AccountId;
// Save the credentials
credentials.LocalUid = AccountId;
credentials.AuthenticationSource = Cxn.DataSource;
credentials.AuthenticationToken = Cxn.DataSource.SiteId.Id + '_' + AccountId;
IsAuthenticated = true;
Cxn.IsRemote = false;
// Set the greeting if there is one
if (flds.Length > 7)
{
return flds[7];
}
return "OK";
}
public override User authorize(AbstractCredentials credentials, AbstractPermission permission)
{
if (permission == null)
{
throw new ArgumentNullException("permission");
}
checkAuthorizeReadiness();
checkPermissionString(permission.Name);
doTheAuthorize(credentials, permission);
return toUser(credentials);
}
internal void doTheAuthorize(AbstractCredentials credentials, AbstractPermission permission)
{
//// if we are requesting CPRS context with a visit and user does not have it - add it to their account
if (permission.Name == VistaConstants.CPRS_CONTEXT &&
!hasPermission(this.Cxn.Account.Permissions, new MenuOption(VistaConstants.CPRS_CONTEXT)) &&
!Cxn.Account.AuthenticationMethod.Equals(VistaConstants.LOGIN_CREDENTIALS))
{
addContextInVista(Cxn.Uid, permission);
}
if (permission != null && !String.IsNullOrEmpty(permission.Name))
{
setContext(permission);
}
if (String.IsNullOrEmpty(Cxn.Uid))
{
if (String.IsNullOrEmpty(credentials.FederatedUid))
{
throw new MdoException("Missing federated UID, cannot get local UID");
}
VistaUserDao dao = new VistaUserDao(Cxn);
Cxn.Uid = dao.getUserIdBySsn(credentials.FederatedUid);
if (String.IsNullOrEmpty(Cxn.Uid))
{
throw new MdoException("Unable to get local UID for federated ID " + credentials.FederatedUid);
}
}
if (!credentials.Complete)
{
VistaUserDao dao = new VistaUserDao(Cxn);
dao.addVisitorInfo(credentials);
}
}
internal User toUser(AbstractCredentials credentials)
{
User u = new User();
u.Uid = Cxn.Uid;
u.Name = new PersonName(credentials.SubjectName);
u.SSN = new SocSecNum(credentials.FederatedUid);
u.LogonSiteId = Cxn.DataSource.SiteId;
return u;
}
internal void checkAuthorizeReadiness()
{
if (Cxn == null || !Cxn.IsConnected)
{
throw new ConnectionException("Must have connection");
}
if (!isAuthenticated)
{
throw new UnauthorizedAccessException("Account must be authenticated");
}
}
internal void checkPermissionString(string permission)
{
if (String.IsNullOrEmpty(permission))
{
throw new UnauthorizedAccessException("Must have a context");
}
}
internal void setContext(AbstractPermission permission)
{
if (permission == null || string.IsNullOrEmpty(permission.Name))
{
throw new ArgumentNullException("permission");
}
MdoQuery request = buildSetContextRequest(permission.Name);
string response = "";
try
{
response = (string)Cxn.query(request);
}
catch (MdoException e)
{
response = e.Message;
}
if (response != "1")
{
throw getException(response);
}
if (!hasPermission(Cxn.Account.Permissions, permission))
{
Cxn.Account.Permissions.Add(permission.Name, permission);
}
isAuthorized = isAuthorized || permission.IsPrimary;
}
internal MdoQuery buildSetContextRequest(string context)
{
VistaQuery vq = new VistaQuery("XWB CREATE CONTEXT");
if (Cxn.GetType().Name != "MockConnection")
{
vq.addEncryptedParameter(vq.LITERAL, context);
}
else
{
vq.addParameter(vq.LITERAL, context);
}
return vq;
}
internal Exception getException(string result)
{
if (result.IndexOf("The context") != -1 &&
result.IndexOf("does not exist on server") != -1)
{
return new PermissionNotFoundException(result);
}
if (result.IndexOf("User") != -1 &&
result.IndexOf("does not have access to option") != -1)
{
return new UnauthorizedAccessException(result);
}
if (result.StartsWith("Option locked"))
{
return new PermissionLockedException(result);
}
return new Exception(result);
}
//internal void setVisitorContext(AbstractPermission requestedContext, string DUZ)
//{
// try
// {
// setContext(requestedContext);
// return;
// }
// catch (UnauthorizedAccessException uae)
// {
// addContextInVista(DUZ, requestedContext);
// setContext(requestedContext);
// }
// catch (Exception e)
// {
// throw;
// }
//}
// This is how the visitor gets the requested context - typically
// OR CPRS GUI CHART. The visitor comes back from VistA with CAPRI
// context only.
internal void addContextInVista(string duz, AbstractPermission requestedContext)
{
//if (!Permissions.ContainsKey(VistaConstants.MDWS_CONTEXT) && !Permissions.ContainsKey(VistaConstants.DDR_CONTEXT))
//{
// throw new ArgumentException("User does not have correct menu options to add new context");
//}
if (hasPermission(this.Cxn.Account.Permissions, requestedContext))
{
return;
}
//setContext(Permissions[VistaConstants.DDR_CONTEXT]); // tbd - needed? i think this is superfluous
VistaUserDao dao = new VistaUserDao(Cxn);
// try/catch should fix: http://trac.medora.va.gov/web/ticket/2288
try
{
setContext(requestedContext);
}
catch (Exception)
{
try
{
// will get CONTEXT HAS NOT BEEN CREATED if we don't set this again after failed attempt
setContext(new MenuOption(VistaConstants.DDR_CONTEXT));
dao.addPermission(duz, requestedContext);
setContext(requestedContext);
}
catch (Exception)
{
throw;
}
}
}
internal bool hasPermission(Dictionary<string, AbstractPermission> permissions, AbstractPermission permission)
{
bool found = false;
// turns out this permissions collection has not been implemented consistently. in some places, the permission
// name is used as the key. in others, most notably the call to get a user's list of options from Vista, the
// IEN is used as the key. so, this method should check both possible locations
if (permissions.ContainsKey(permission.Name))
{
return true;
}
foreach (AbstractPermission perm in permissions.Values)
{
if (String.Equals(perm.Name, permission.Name, StringComparison.CurrentCultureIgnoreCase))
{
found = true;
break;
}
}
return found;
}
//public override string authenticateAndAuthorize(CredentialSet credentials, string permissionString)
//{
// string duz = authenticate();
// authorize("");
// return duz;
//}
public override User authenticateAndAuthorize(AbstractCredentials credentials, AbstractPermission permission, DataSource validationDataSource = null)
{
string msg = authenticate(credentials, validationDataSource);
User u = authorize(credentials, permission);
u.Greeting = msg;
return u;
}
//public void addDdrContext(AbstractCredentials credentials, AbstractConnection currentCxn)
//{
// if (credentials.AuthenticationMethod == VistaConstants.LOGIN_CREDENTIALS)
// {
// throw new UnauthorizedAccessException("Wrong credential type");
// }
// VistaConnection cxn = new VistaConnection(currentCxn.DataSource);
// cxn.connect();
// cxn.Account.authenticate(credentials);
// cxn.disconnect();
//}
public string getAuthenticationTokenFromVista()
{
VistaQuery vq = new VistaQuery("XUS SET VISITOR");
return (string)Cxn.query(vq);
}
public string makeAuthenticationTokenInVista(string duz)
{
string token1 = getAuthenticationTokenFromVista2();
string token2 = setAuthenticationTokenInVista(token1, duz);
token2 = getXtmpToken(token1);
return token1;
}
internal string getXtmpToken(string token)
{
string arg = "$G(^XTMP(\"" + token + "\",1))";
return VistaUtils.getVariableValue(Cxn, arg);
}
internal string setAuthenticationTokenInVista(string token, string duz)
{
DdrLister query = buildSetAuthenticationTokenInVistaQuery(token, duz);
string[] response = query.execute();
if (response.Length != 1)
{
throw new MdoException(MdoExceptionCode.DATA_UNEXPECTED_FORMAT);
}
return response[0];
}
internal string getAuthenticationTokenFromVista2()
{
DdrLister query = buildGetAuthenticationTokenFromVista2Query();
string[] response = query.execute();
if (response == null || response.Length != 1)
{
throw new MdoException(MdoExceptionCode.DATA_UNEXPECTED_FORMAT);
}
string[] flds = response[0].Split(new char[] { '^' });
if (flds.Length != 3)
{
throw new MdoException(MdoExceptionCode.DATA_UNEXPECTED_FORMAT);
}
return flds[2];
}
internal DdrLister buildGetAuthenticationTokenFromVista2Query()
{
DdrLister query = new DdrLister(Cxn);
query.File = "200";
query.Fields = ".01";
query.Flags = "IP";
query.Max = "1";
query.Xref = "#";
query.Id = "D EN^DDIOL($$HANDLE^XUSRB4(\"XUSBSE\",1))";
return query;
}
internal DdrLister buildSetAuthenticationTokenInVistaQuery(string token, string duz)
{
DdrLister query = new DdrLister(Cxn);
query.File = "200";
query.Fields = ".01";
query.Flags = "IP";
query.Max = "1";
query.Xref = "#";
query.Id = "S ^XTMP(\"" + token + "\",1)=$$GET^XUESSO1(" + duz + ")";
//"D EN^DDIOL(\"^XMTP(\"" + token + "\",1)";
return query;
}
public static string getAdminLocalUid(string siteId)
{
if (administrativeDfns.ContainsKey(siteId))
{
return administrativeDfns[siteId];
}
else
{
return "1";
}
}
}
abstract class VisitTemplate
{
protected VistaAccount acct;
protected AbstractConnection cxn;
protected AbstractCredentials creds;
public VisitTemplate(VistaAccount acct, AbstractCredentials credentials)
{
this.acct = acct;
cxn = acct.Cxn;
creds = credentials;
}
public abstract void setupVisit();
public abstract MdoQuery buildVisitRequest();
public abstract bool success(string[] flds);
public string visit()
{
if (creds.FederatedUid == VistaConstants.ADMINISTRATIVE_FEDERATED_UID)
{
creds.LocalUid = VistaAccount.getAdminLocalUid(creds.AuthenticationSource.SiteId.Id);
}
validateCredentials();
setupVisit();
MdoQuery request = buildVisitRequest();
string response = (string)cxn.query(request);
string[] flds = StringUtils.split(response, StringUtils.CRLF);
if (!success(flds))
{
throw new UnauthorizedAccessException("Visit failed: Invalid credentials?");
}
if (flds.Length >= 8)
{
cxn.IsTestSource = (flds[7] == "0");
}
acct.IsAuthenticated = true;
cxn.IsRemote = true;
//creds.AuthenticatorId = cxn.DataSource.SiteId.Id;
//creds.AuthenticatorName = cxn.DataSource.SiteId.Name;
return "OK";
}
internal void validateCredentials()
{
// Need an app password (the security phrase)...
if (String.IsNullOrEmpty(creds.SecurityPhrase))
{
throw new UnauthorizedAccessException("Missing application password");
}
// BSE visit uses just the authentication token, so...
if (String.IsNullOrEmpty(creds.AuthenticationToken))
{
throw new UnauthorizedAccessException("Cannot visit without authentication token");
}
//string[] flds = creds.AuthenticationToken.Split(new char[] { '_' });
//if (flds.Length != 2)
//{
// throw new UnauthorizedAccessException("Invalid authentication token");
//}
if (String.IsNullOrEmpty(creds.SubjectPhone))
{
creds.SubjectPhone = "No phone";
}
if (String.IsNullOrEmpty(creds.FederatedUid))
{
throw new UnauthorizedAccessException("Missing FederatedUid");
}
if (String.IsNullOrEmpty(creds.SubjectName))
{
throw new UnauthorizedAccessException("Mising SubjectName");
}
if (creds.AuthenticationSource == null)
{
throw new UnauthorizedAccessException("Missing AuthenticationSource");
}
if (creds.AuthenticationSource.SiteId == null)
{
throw new UnauthorizedAccessException("Missing AuthenticationSource.SiteId");
}
if (String.IsNullOrEmpty(creds.AuthenticationSource.SiteId.Id))
{
throw new UnauthorizedAccessException("Missing AuthenticatorId");
}
if (String.IsNullOrEmpty(creds.AuthenticationSource.SiteId.Name))
{
throw new UnauthorizedAccessException("Missing AuthenticatorName");
}
if (String.IsNullOrEmpty(creds.LocalUid))
{
throw new UnauthorizedAccessException("Missing LocalUid");
}
if (String.IsNullOrEmpty(creds.SubjectPhone))
{
throw new UnauthorizedAccessException("Missing SubjectPhone");
}
// Is the connection to a production system with a test visitor from a different site?
if (!cxn.IsTestSource && creds.AreTest && creds.AuthenticationSource.SiteId.Id != cxn.DataSource.SiteId.Id)
{
throw new UnauthorizedAccessException("Cannot visit production system with test credentials");
}
}
}
// Temporarily disabled - only V2WEB BSE visits for now.
//class BseVista2VistaVisit : VisitTemplate
//{
// public BseVista2VistaVisit(VistaAccount acct, AbstractCredentials creds) : base(acct, creds) { }
// public override void setupVisit() { }
// public override MdoQuery buildVisitRequest()
// {
// VistaQuery vq = new VistaQuery("XUS SIGNON SETUP");
// string phrase = creds.SecurityPhrase + '^' +
// creds.AuthenticationToken + '^' +
// creds.AuthenticationSource.SiteId.Id + '^' +
// creds.AuthenticationSource.Port;
// string arg = "-35^" + VistaUtils.encrypt(phrase);
// vq.addParameter(vq.LITERAL, arg);
// return vq;
// }
// public override bool success(string[] flds)
// {
// if (String.IsNullOrEmpty(creds.AuthenticationMethod))
// {
// creds.AuthenticationMethod = VistaConstants.BSE_CREDENTIALS_V2V;
// }
// // NB: Do NOT remove this code. It is the only way to detect that a BSE visit has
// // failed. If this is bypassed, the subsequent context call seems to succeed when
// // it doesn't.
// if (flds.Length < 6 || flds[5] != "1")
// {
// return false;
// }
// return true;
// }
//}
class BseVista2WebVisit : VisitTemplate
{
DataSource _validatorDataSource;
public BseVista2WebVisit(VistaAccount acct, AbstractCredentials creds, DataSource validatorDataSource)
: base(acct, creds)
{
if (validatorDataSource != null)
{
_validatorDataSource = validatorDataSource;
}
}
public override void setupVisit()
{
insertUserValidationRecord();
}
public override MdoQuery buildVisitRequest()
{
VistaQuery vq = new VistaQuery("XUS SIGNON SETUP");
string token = SSTCryptographer.Encrypt(creds.AuthenticationToken, VistaConstants.ENCRYPTION_KEY);
token = UserValidationDao.escapeString(token);
string arg = "-35^" + VistaUtils.encrypt(creds.SecurityPhrase + '^' + token);
vq.addParameter(vq.LITERAL, arg);
return vq;
}
public override bool success(string[] flds)
{
// NB: Do NOT remove this code. It is the only way to detect that a BSE visit has
// failed. If this is bypassed, the subsequent context call seems to succeed when
// it doesn't.
if (flds.Length < 6 || flds[5] != "1")
{
deleteUserValidationRecord();
return false;
}
return true;
}
internal void insertUserValidationRecord()
{
UserValidationDao dao = new UserValidationDao(new UserValidationConnection(_validatorDataSource));
dao.addRecord(creds, VistaConstants.ENCRYPTION_KEY);
}
internal void deleteUserValidationRecord()
{
UserValidationDao dao = new UserValidationDao(new UserValidationConnection(_validatorDataSource));
dao.deleteRecord(creds.AuthenticationToken, VistaConstants.ENCRYPTION_KEY);
}
}
class NonBseVisit : VisitTemplate
{
public NonBseVisit(VistaAccount acct, AbstractCredentials creds) : base(acct, creds) { }
public override void setupVisit() { }
public override MdoQuery buildVisitRequest()
{
string arg = "-31^DVBA_^";
arg += creds.FederatedUid + '^' +
creds.SubjectName + '^' +
creds.AuthenticationSource.SiteId.Name + '^' +
creds.AuthenticationSource.SiteId.Id + '^' +
creds.LocalUid + '^' +
creds.SubjectPhone;
VistaQuery vq = new VistaQuery("XUS SIGNON SETUP");
vq.addParameter(vq.LITERAL, arg);
return vq;
}
public override bool success(string[] flds)
{
// Set DDR context in order to add the requested context
AbstractPermission ddrContext = new MenuOption(VistaConstants.DDR_CONTEXT);
acct.setContext(ddrContext);
// Get the UID while we have DDR context set anyway
VistaUserDao dao = new VistaUserDao(cxn);
cxn.Uid = dao.getUserIdBySsn(creds.FederatedUid);
// Add the requested context to the user's account
//acct.addContextInVista(cxn.Uid, acct.PrimaryPermission);
return true;
}
}
}
| |
// cassandra-sharp - high performance .NET driver for Apache Cassandra
// Copyright (c) 2011-2014 Pierre Chalamet
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace CassandraSharpUnitTests.CQLPoco
{
using CassandraSharp;
using CassandraSharp.Exceptions;
using CassandraSharp.CQLBinaryProtocol;
using CassandraSharp.CQLPoco;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using CassandraSharp.Extensibility;
[TestFixture]
public class DataMapperTest
{
private readonly ValueSerializer<string> stringSerializer = new ValueSerializer<string>();
private readonly ValueSerializer<PocoPoint> pointSerializer = new ValueSerializer<PocoPoint>();
private DataMapper<TestPoco> dataMapper;
private TestPoco pocoInstance;
[SetUp]
public void SetUp()
{
dataMapper = new DataMapper<TestPoco>();
pocoInstance = new TestPoco
{
ComplexType = new PocoPoint { X = 1, Y = 2 },
DifferentName = "Another",
TestProperty = "Property",
TestField = "Field"
};
}
[Test]
public void MapToColumns_Existing_MappedAndSerialized()
{
var columnSpecs = new List<IColumnSpec>
{
CreateColumnSpec("TestField"),
CreateColumnSpec("ComplexType"),
CreateColumnSpec("AnotherColumn")
};
var columnData = dataMapper.MapToColumns(pocoInstance, columnSpecs).ToList();
// Colums should come in same order, as requested
Assert.AreEqual(columnSpecs[0], columnData[0].ColumnSpec);
Assert.AreEqual(columnSpecs[1], columnData[1].ColumnSpec);
Assert.AreEqual(columnSpecs[2], columnData[2].ColumnSpec);
// Data should be mapped and serialized using correct serializer
Assert.AreEqual(pocoInstance.TestField, stringSerializer.Deserialize(columnData[0].RawData));
var pocoPoint = (PocoPoint)pointSerializer.Deserialize(columnData[1].RawData);
Assert.AreEqual(pocoInstance.ComplexType.X, pocoPoint.X);
Assert.AreEqual(pocoInstance.ComplexType.Y, pocoPoint.Y);
Assert.AreEqual(pocoInstance.DifferentName, stringSerializer.Deserialize(columnData[2].RawData));
}
[Test]
public void MapToColumns_ShouldBeUnderscoreAndCaseInsensitive()
{
var columnSpecs = new List<IColumnSpec>
{
CreateColumnSpec("Test_Field"),
CreateColumnSpec("complex_Type"),
CreateColumnSpec("another_Column")
};
var columnData = dataMapper.MapToColumns(pocoInstance, columnSpecs).ToList();
// Colums should come in same order, as requested
Assert.AreEqual(columnSpecs[0], columnData[0].ColumnSpec);
Assert.AreEqual(columnSpecs[1], columnData[1].ColumnSpec);
Assert.AreEqual(columnSpecs[2], columnData[2].ColumnSpec);
// Data should be mapped and serialized using correct serializer
Assert.AreEqual(pocoInstance.TestField, stringSerializer.Deserialize(columnData[0].RawData));
var pocoPoint = (PocoPoint)pointSerializer.Deserialize(columnData[1].RawData);
Assert.AreEqual(pocoInstance.ComplexType.X, pocoPoint.X);
Assert.AreEqual(pocoInstance.ComplexType.Y, pocoPoint.Y);
Assert.AreEqual(pocoInstance.DifferentName, stringSerializer.Deserialize(columnData[2].RawData));
}
[Test]
public void MapToObject_Existing_DeserializedAndMapped()
{
var pocoPoint = new PocoPoint { X = 100, Y = 200 };
var columnData = new List<IColumnData>
{
new ColumnData(CreateColumnSpec("TestField"), stringSerializer.Serialize("abcde")),
new ColumnData(CreateColumnSpec("ComplexType"), pointSerializer.Serialize(pocoPoint)),
new ColumnData(CreateColumnSpec("AnotherColumn"), stringSerializer.Serialize("qwerty"))
};
var poco = (TestPoco)dataMapper.MapToObject(columnData);
Assert.AreEqual("abcde", poco.TestField);
Assert.AreEqual("qwerty", poco.DifferentName);
Assert.AreEqual(100, poco.ComplexType.X);
Assert.AreEqual(200, poco.ComplexType.Y);
}
[Test]
public void MapToObject__ShouldBeUnderscoreAndCaseInsensitive()
{
var pocoPoint = new PocoPoint { X = 100, Y = 200 };
var columnData = new List<IColumnData>
{
new ColumnData(CreateColumnSpec("test_Field"), stringSerializer.Serialize("abcde")),
new ColumnData(CreateColumnSpec("complex_Type"), pointSerializer.Serialize(pocoPoint)),
new ColumnData(CreateColumnSpec("Another_Column"), stringSerializer.Serialize("qwerty"))
};
var poco = (TestPoco)dataMapper.MapToObject(columnData);
Assert.AreEqual("abcde", poco.TestField);
Assert.AreEqual("qwerty", poco.DifferentName);
Assert.AreEqual(100, poco.ComplexType.X);
Assert.AreEqual(200, poco.ComplexType.Y);
}
[Test]
public void MapToColumns_NotExisting_ThrowsException()
{
var columnSpecs = new List<IColumnSpec>
{
CreateColumnSpec("WontFindMe"),
CreateColumnSpec("ComplexType"),
CreateColumnSpec("AnotherColumn")
};
Assert.Throws<DataMappingException>(() => dataMapper.MapToColumns(pocoInstance, columnSpecs).ToList());
}
[Test]
public void MapToObject_NotExisting_SilentlyIgnores()
{
var columnData = new List<IColumnData>
{
new ColumnData(CreateColumnSpec("WontFindMe"), stringSerializer.Serialize("abcde")),
new ColumnData(CreateColumnSpec("AnotherColumn"), stringSerializer.Serialize("qwerty"))
};
var poco = (TestPoco)dataMapper.MapToObject(columnData);
Assert.IsNotNull(poco);
}
private IColumnSpec CreateColumnSpec(string columnName)
{
return new ColumnSpec(0, null, null, columnName, ColumnType.Custom, null, ColumnType.Custom, ColumnType.Custom);
}
#region Test types
private class TestPoco
{
public string TestField;
public string TestProperty { get; set; }
[CqlColumn("AnotherColumn")]
public string DifferentName { get; set; }
public PocoPoint ComplexType { get; set; }
}
[CassandraTypeSerializer(typeof(PocoPointSerializer))]
private class PocoPoint
{
public int X { get; set; }
public int Y { get; set; }
}
private class PocoPointSerializer : ICassandraTypeSerializer
{
public byte[] Serialize(object value)
{
var val = value as PocoPoint;
if (val == null)
{
return null;
}
return BitConverter.GetBytes(val.X).Concat(BitConverter.GetBytes(val.Y)).ToArray();
}
public object Deserialize(byte[] data)
{
if (data == null || data.Length != 8)
{
return null;
}
return new PocoPoint
{
X = BitConverter.ToInt32(data, 0),
Y = BitConverter.ToInt32(data, 4)
};
}
}
#endregion
}
}
| |
// 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.Xml.XPath;
using FT = MS.Internal.Xml.XPath.Function.FunctionType;
namespace MS.Internal.Xml.XPath
{
internal sealed class QueryBuilder
{
// Note: Up->Doun, Down->Up:
// For operators order is normal: 1 + 2 --> Operator+(1, 2)
// For paths order is reversed: a/b -> ChildQuery_B(input: ChildQuery_A(input: ContextQuery()))
// Input flags. We pass them Up->Down.
// Using them upper query set states which controls how inner query will be built.
enum Flags
{
None = 0x00,
SmartDesc = 0x01,
PosFilter = 0x02, // Node has this flag set when it has position predicate applied to it
Filter = 0x04, // Subtree we compiling will be filtered. i.e. Flag not set on rightmost filter.
}
// Output props. We return them Down->Up.
// These are properties of Query tree we have built already.
// These properties are closely related to QueryProps exposed by Query node itself.
// They have the following difference:
// QueryProps describe property of node they are (belong like Reverse)
// these Props describe accumulated properties of the tree (like nonFlat)
enum Props
{
None = 0x00,
PosFilter = 0x01, // This filter or inner filter was positional: foo[1] or foo[1][true()]
HasPosition = 0x02, // Expression may ask position() of the context
HasLast = 0x04, // Expression may ask last() of the context
NonFlat = 0x08, // Some nodes may be descendent of others
}
// comment are approximate. This is my best understanding:
private string query;
private bool allowVar;
private bool allowKey;
private bool allowCurrent;
private bool needContext;
private BaseAxisQuery firstInput; // Input of the leftmost predicate. Set by leftmost predicate, used in rightmost one
private void Reset()
{
parseDepth = 0;
needContext = false;
}
private Query ProcessAxis(Axis root, Flags flags, out Props props)
{
Query result = null;
if (root.Prefix.Length > 0)
{
needContext = true;
}
firstInput = null;
Query qyInput;
{
if (root.Input != null)
{
Flags inputFlags = Flags.None;
if ((flags & Flags.PosFilter) == 0)
{
Axis input = root.Input as Axis;
if (input != null)
{
if (
root.TypeOfAxis == Axis.AxisType.Child &&
input.TypeOfAxis == Axis.AxisType.DescendantOrSelf && input.NodeType == XPathNodeType.All
)
{
Query qyGrandInput;
if (input.Input != null)
{
qyGrandInput = ProcessNode(input.Input, Flags.SmartDesc, out props);
}
else
{
qyGrandInput = new ContextQuery();
props = Props.None;
}
result = new DescendantQuery(qyGrandInput, root.Name, root.Prefix, root.NodeType, false, input.AbbrAxis);
if ((props & Props.NonFlat) != 0)
{
result = new DocumentOrderQuery(result);
}
props |= Props.NonFlat;
return result;
}
}
if (root.TypeOfAxis == Axis.AxisType.Descendant || root.TypeOfAxis == Axis.AxisType.DescendantOrSelf)
{
inputFlags |= Flags.SmartDesc;
}
}
qyInput = ProcessNode(root.Input, inputFlags, out props);
}
else
{
qyInput = new ContextQuery();
props = Props.None;
}
}
switch (root.TypeOfAxis)
{
case Axis.AxisType.Ancestor:
result = new XPathAncestorQuery(qyInput, root.Name, root.Prefix, root.NodeType, false);
props |= Props.NonFlat;
break;
case Axis.AxisType.AncestorOrSelf:
result = new XPathAncestorQuery(qyInput, root.Name, root.Prefix, root.NodeType, true);
props |= Props.NonFlat;
break;
case Axis.AxisType.Child:
if ((props & Props.NonFlat) != 0)
{
result = new CacheChildrenQuery(qyInput, root.Name, root.Prefix, root.NodeType);
}
else
{
result = new ChildrenQuery(qyInput, root.Name, root.Prefix, root.NodeType);
}
break;
case Axis.AxisType.Parent:
result = new ParentQuery(qyInput, root.Name, root.Prefix, root.NodeType);
break;
case Axis.AxisType.Descendant:
if ((flags & Flags.SmartDesc) != 0)
{
result = new DescendantOverDescendantQuery(qyInput, false, root.Name, root.Prefix, root.NodeType, /*abbrAxis:*/false);
}
else
{
result = new DescendantQuery(qyInput, root.Name, root.Prefix, root.NodeType, false, /*abbrAxis:*/false);
if ((props & Props.NonFlat) != 0)
{
result = new DocumentOrderQuery(result);
}
}
props |= Props.NonFlat;
break;
case Axis.AxisType.DescendantOrSelf:
if ((flags & Flags.SmartDesc) != 0)
{
result = new DescendantOverDescendantQuery(qyInput, true, root.Name, root.Prefix, root.NodeType, root.AbbrAxis);
}
else
{
result = new DescendantQuery(qyInput, root.Name, root.Prefix, root.NodeType, true, root.AbbrAxis);
if ((props & Props.NonFlat) != 0)
{
result = new DocumentOrderQuery(result);
}
}
props |= Props.NonFlat;
break;
case Axis.AxisType.Preceding:
result = new PrecedingQuery(qyInput, root.Name, root.Prefix, root.NodeType);
props |= Props.NonFlat;
break;
case Axis.AxisType.Following:
result = new FollowingQuery(qyInput, root.Name, root.Prefix, root.NodeType);
props |= Props.NonFlat;
break;
case Axis.AxisType.FollowingSibling:
result = new FollSiblingQuery(qyInput, root.Name, root.Prefix, root.NodeType);
if ((props & Props.NonFlat) != 0)
{
result = new DocumentOrderQuery(result);
}
break;
case Axis.AxisType.PrecedingSibling:
result = new PreSiblingQuery(qyInput, root.Name, root.Prefix, root.NodeType);
break;
case Axis.AxisType.Attribute:
result = new AttributeQuery(qyInput, root.Name, root.Prefix, root.NodeType);
break;
case Axis.AxisType.Self:
result = new XPathSelfQuery(qyInput, root.Name, root.Prefix, root.NodeType);
break;
case Axis.AxisType.Namespace:
if ((root.NodeType == XPathNodeType.All || root.NodeType == XPathNodeType.Element || root.NodeType == XPathNodeType.Attribute) && root.Prefix.Length == 0)
{
result = new NamespaceQuery(qyInput, root.Name, root.Prefix, root.NodeType);
}
else
{
result = new EmptyQuery();
}
break;
default:
throw XPathException.Create(SR.Xp_NotSupported, query);
}
return result;
}
private static bool CanBeNumber(Query q)
{
return (
q.StaticType == XPathResultType.Any ||
q.StaticType == XPathResultType.Number
);
}
private Query ProcessFilter(Filter root, Flags flags, out Props props)
{
bool first = ((flags & Flags.Filter) == 0);
Props propsCond;
Query cond = ProcessNode(root.Condition, Flags.None, out propsCond);
if (
CanBeNumber(cond) ||
(propsCond & (Props.HasPosition | Props.HasLast)) != 0
)
{
propsCond |= Props.HasPosition;
flags |= Flags.PosFilter;
}
// We don't want DescendantOverDescendant pattern to be recognized here (in case descendent::foo[expr]/descendant::bar)
// So we clean this flag here:
flags &= ~Flags.SmartDesc;
// ToDo: Instead it would be nice to wrap descendent::foo[expr] into special query that will flatten it -- i.e.
// remove all nodes that are descendant of other nodes. This is very easy because for sorted nodesets all children
// follow its parent. One step caching. This can be easily done by rightmost DescendantQuery itself.
// Interesting note! Can we guarantee that DescendantOverDescendant returns flat nodeset? This definitely true if it's input is flat.
Query qyInput = ProcessNode(root.Input, flags | Flags.Filter, out props);
if (root.Input.Type != AstNode.AstType.Filter)
{
// Props.PosFilter is for nested filters only.
// We clean it here to avoid cleaning it in all other ast nodes.
props &= ~Props.PosFilter;
}
if ((propsCond & Props.HasPosition) != 0)
{
// this condition is positional rightmost filter should be avare of this.
props |= Props.PosFilter;
}
/*merging predicates*/
{
FilterQuery qyFilter = qyInput as FilterQuery;
if (qyFilter != null && (propsCond & Props.HasPosition) == 0 && qyFilter.Condition.StaticType != XPathResultType.Any)
{
Query prevCond = qyFilter.Condition;
if (prevCond.StaticType == XPathResultType.Number)
{
prevCond = new LogicalExpr(Operator.Op.EQ, new NodeFunctions(FT.FuncPosition, null), prevCond);
}
cond = new BooleanExpr(Operator.Op.AND, prevCond, cond);
qyInput = qyFilter.qyInput;
}
}
if ((props & Props.PosFilter) != 0 && qyInput is DocumentOrderQuery)
{
qyInput = ((DocumentOrderQuery)qyInput).input;
}
if (firstInput == null)
{
firstInput = qyInput as BaseAxisQuery;
}
bool merge = (qyInput.Properties & QueryProps.Merge) != 0;
bool reverse = (qyInput.Properties & QueryProps.Reverse) != 0;
if ((propsCond & Props.HasPosition) != 0)
{
if (reverse)
{
qyInput = new ReversePositionQuery(qyInput);
}
else if ((propsCond & Props.HasLast) != 0)
{
qyInput = new ForwardPositionQuery(qyInput);
}
}
if (first && firstInput != null)
{
if (merge && (props & Props.PosFilter) != 0)
{
qyInput = new FilterQuery(qyInput, cond, /*noPosition:*/false);
Query parent = firstInput.qyInput;
if (!(parent is ContextQuery))
{ // we don't need to wrap filter with MergeFilterQuery when cardinality is parent <: ?
firstInput.qyInput = new ContextQuery();
firstInput = null;
return new MergeFilterQuery(parent, qyInput);
}
firstInput = null;
return qyInput;
}
firstInput = null;
}
return new FilterQuery(qyInput, cond, /*noPosition:*/(propsCond & Props.HasPosition) == 0);
}
private Query ProcessOperator(Operator root, out Props props)
{
Props props1, props2;
Query op1 = ProcessNode(root.Operand1, Flags.None, out props1);
Query op2 = ProcessNode(root.Operand2, Flags.None, out props2);
props = props1 | props2;
switch (root.OperatorType)
{
case Operator.Op.PLUS:
case Operator.Op.MINUS:
case Operator.Op.MUL:
case Operator.Op.MOD:
case Operator.Op.DIV:
return new NumericExpr(root.OperatorType, op1, op2);
case Operator.Op.LT:
case Operator.Op.GT:
case Operator.Op.LE:
case Operator.Op.GE:
case Operator.Op.EQ:
case Operator.Op.NE:
return new LogicalExpr(root.OperatorType, op1, op2);
case Operator.Op.OR:
case Operator.Op.AND:
return new BooleanExpr(root.OperatorType, op1, op2);
case Operator.Op.UNION:
props |= Props.NonFlat;
return new UnionExpr(op1, op2);
default: return null;
}
}
private Query ProcessVariable(Variable root)
{
needContext = true;
if (!allowVar)
{
throw XPathException.Create(SR.Xp_InvalidKeyPattern, query);
}
return new VariableQuery(root.Localname, root.Prefix);
}
private Query ProcessFunction(Function root, out Props props)
{
props = Props.None;
Query qy = null;
switch (root.TypeOfFunction)
{
case FT.FuncLast:
qy = new NodeFunctions(root.TypeOfFunction, null);
props |= Props.HasLast;
return qy;
case FT.FuncPosition:
qy = new NodeFunctions(root.TypeOfFunction, null);
props |= Props.HasPosition;
return qy;
case FT.FuncCount:
return new NodeFunctions(FT.FuncCount,
ProcessNode((AstNode)(root.ArgumentList[0]), Flags.None, out props)
);
case FT.FuncID:
qy = new IDQuery(ProcessNode((AstNode)(root.ArgumentList[0]), Flags.None, out props));
props |= Props.NonFlat;
return qy;
case FT.FuncLocalName:
case FT.FuncNameSpaceUri:
case FT.FuncName:
if (root.ArgumentList != null && root.ArgumentList.Count > 0)
{
return new NodeFunctions(root.TypeOfFunction,
ProcessNode((AstNode)(root.ArgumentList[0]), Flags.None, out props)
);
}
else
{
return new NodeFunctions(root.TypeOfFunction, null);
}
case FT.FuncString:
case FT.FuncConcat:
case FT.FuncStartsWith:
case FT.FuncContains:
case FT.FuncSubstringBefore:
case FT.FuncSubstringAfter:
case FT.FuncSubstring:
case FT.FuncStringLength:
case FT.FuncNormalize:
case FT.FuncTranslate:
return new StringFunctions(root.TypeOfFunction, ProcessArguments(root.ArgumentList, out props));
case FT.FuncNumber:
case FT.FuncSum:
case FT.FuncFloor:
case FT.FuncCeiling:
case FT.FuncRound:
if (root.ArgumentList != null && root.ArgumentList.Count > 0)
{
return new NumberFunctions(root.TypeOfFunction,
ProcessNode((AstNode)root.ArgumentList[0], Flags.None, out props)
);
}
else
{
return new NumberFunctions(Function.FunctionType.FuncNumber, null);
}
case FT.FuncTrue:
case FT.FuncFalse:
return new BooleanFunctions(root.TypeOfFunction, null);
case FT.FuncNot:
case FT.FuncLang:
case FT.FuncBoolean:
return new BooleanFunctions(root.TypeOfFunction,
ProcessNode((AstNode)root.ArgumentList[0], Flags.None, out props)
);
case FT.FuncUserDefined:
needContext = true;
if (!allowCurrent && root.Name == "current" && root.Prefix.Length == 0)
{
throw XPathException.Create(SR.Xp_CurrentNotAllowed);
}
if (!allowKey && root.Name == "key" && root.Prefix.Length == 0)
{
throw XPathException.Create(SR.Xp_InvalidKeyPattern, query);
}
qy = new FunctionQuery(root.Prefix, root.Name, ProcessArguments(root.ArgumentList, out props));
props |= Props.NonFlat;
return qy;
default:
throw XPathException.Create(SR.Xp_NotSupported, query);
}
}
List<Query> ProcessArguments(List<AstNode> args, out Props props)
{
int numArgs = args != null ? args.Count : 0;
List<Query> argList = new List<Query>(numArgs);
props = Props.None;
for (int count = 0; count < numArgs; count++)
{
Props argProps;
argList.Add(ProcessNode((AstNode)args[count], Flags.None, out argProps));
props |= argProps;
}
return argList;
}
private int parseDepth = 0;
private const int MaxParseDepth = 1024;
private Query ProcessNode(AstNode root, Flags flags, out Props props)
{
if (++parseDepth > MaxParseDepth)
{
throw XPathException.Create(SR.Xp_QueryTooComplex);
}
Debug.Assert(root != null, "root != null");
Query result = null;
props = Props.None;
switch (root.Type)
{
case AstNode.AstType.Axis:
result = ProcessAxis((Axis)root, flags, out props);
break;
case AstNode.AstType.Operator:
result = ProcessOperator((Operator)root, out props);
break;
case AstNode.AstType.Filter:
result = ProcessFilter((Filter)root, flags, out props);
break;
case AstNode.AstType.ConstantOperand:
result = new OperandQuery(((Operand)root).OperandValue);
break;
case AstNode.AstType.Variable:
result = ProcessVariable((Variable)root);
break;
case AstNode.AstType.Function:
result = ProcessFunction((Function)root, out props);
break;
case AstNode.AstType.Group:
result = new GroupQuery(ProcessNode(((Group)root).GroupNode, Flags.None, out props));
break;
case AstNode.AstType.Root:
result = new AbsoluteQuery();
break;
default:
Debug.Assert(false, "Unknown QueryType encountered!!");
break;
}
--parseDepth;
return result;
}
private Query Build(AstNode root, string query)
{
Reset();
Props props;
this.query = query;
Query result = ProcessNode(root, Flags.None, out props);
return result;
}
internal Query Build(string query, bool allowVar, bool allowKey)
{
this.allowVar = allowVar;
this.allowKey = allowKey;
this.allowCurrent = true;
return Build(XPathParser.ParseXPathExpresion(query), query);
}
internal Query Build(string query, out bool needContext)
{
Query result = Build(query, true, true);
needContext = this.needContext;
return result;
}
internal Query BuildPatternQuery(string query, bool allowVar, bool allowKey)
{
this.allowVar = allowVar;
this.allowKey = allowKey;
this.allowCurrent = false;
return Build(XPathParser.ParseXPathPattern(query), query);
}
internal Query BuildPatternQuery(string query, out bool needContext)
{
Query result = BuildPatternQuery(query, true, true);
needContext = this.needContext;
return result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using System.IO;
namespace System.Security.Cryptography
{
public abstract partial class RSA : AsymmetricAlgorithm
{
public static new RSA Create(string algName)
{
return (RSA)CryptoConfig.CreateFromName(algName);
}
public static RSA Create(int keySizeInBits)
{
RSA rsa = Create();
try
{
rsa.KeySize = keySizeInBits;
return rsa;
}
catch
{
rsa.Dispose();
throw;
}
}
public static RSA Create(RSAParameters parameters)
{
RSA rsa = Create();
try
{
rsa.ImportParameters(parameters);
return rsa;
}
catch
{
rsa.Dispose();
throw;
}
}
public abstract RSAParameters ExportParameters(bool includePrivateParameters);
public abstract void ImportParameters(RSAParameters parameters);
public virtual byte[] Encrypt(byte[] data, RSAEncryptionPadding padding) => throw DerivedClassMustOverride();
public virtual byte[] Decrypt(byte[] data, RSAEncryptionPadding padding) => throw DerivedClassMustOverride();
public virtual byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => throw DerivedClassMustOverride();
public virtual bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => throw DerivedClassMustOverride();
protected virtual byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) => throw DerivedClassMustOverride();
protected virtual byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) => throw DerivedClassMustOverride();
public virtual bool TryDecrypt(ReadOnlySpan<byte> source, Span<byte> destination, RSAEncryptionPadding padding, out int bytesWritten)
{
byte[] result = Decrypt(source.ToArray(), padding);
if (destination.Length >= result.Length)
{
new ReadOnlySpan<byte>(result).CopyTo(destination);
bytesWritten = result.Length;
return true;
}
bytesWritten = 0;
return false;
}
public virtual bool TryEncrypt(ReadOnlySpan<byte> source, Span<byte> destination, RSAEncryptionPadding padding, out int bytesWritten)
{
byte[] result = Encrypt(source.ToArray(), padding);
if (destination.Length >= result.Length)
{
new ReadOnlySpan<byte>(result).CopyTo(destination);
bytesWritten = result.Length;
return true;
}
bytesWritten = 0;
return false;
}
protected virtual bool TryHashData(ReadOnlySpan<byte> source, Span<byte> destination, HashAlgorithmName hashAlgorithm, out int bytesWritten)
{
byte[] result;
byte[] array = ArrayPool<byte>.Shared.Rent(source.Length);
try
{
source.CopyTo(array);
result = HashData(array, 0, source.Length, hashAlgorithm);
}
finally
{
Array.Clear(array, 0, source.Length);
ArrayPool<byte>.Shared.Return(array);
}
if (destination.Length >= result.Length)
{
new ReadOnlySpan<byte>(result).CopyTo(destination);
bytesWritten = result.Length;
return true;
}
bytesWritten = 0;
return false;
}
public virtual bool TrySignHash(ReadOnlySpan<byte> source, Span<byte> destination, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding, out int bytesWritten)
{
byte[] result = SignHash(source.ToArray(), hashAlgorithm, padding);
if (destination.Length >= result.Length)
{
new ReadOnlySpan<byte>(result).CopyTo(destination);
bytesWritten = result.Length;
return true;
}
bytesWritten = 0;
return false;
}
public virtual bool VerifyHash(ReadOnlySpan<byte> hash, ReadOnlySpan<byte> signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) =>
VerifyHash(hash.ToArray(), signature.ToArray(), hashAlgorithm, padding);
private static Exception DerivedClassMustOverride() =>
new NotImplementedException(SR.NotSupported_SubclassOverride);
public virtual byte[] DecryptValue(byte[] rgb) =>
throw new NotSupportedException(SR.NotSupported_Method); // Same as Desktop
public virtual byte[] EncryptValue(byte[] rgb) =>
throw new NotSupportedException(SR.NotSupported_Method); // Same as Desktop
public byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
{
if (data == null)
{
throw new ArgumentNullException(nameof(data));
}
return SignData(data, 0, data.Length, hashAlgorithm, padding);
}
public virtual byte[] SignData(
byte[] data,
int offset,
int count,
HashAlgorithmName hashAlgorithm,
RSASignaturePadding padding)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
if (offset < 0 || offset > data.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0 || count > data.Length - offset)
throw new ArgumentOutOfRangeException(nameof(count));
if (string.IsNullOrEmpty(hashAlgorithm.Name))
throw HashAlgorithmNameNullOrEmpty();
if (padding == null)
throw new ArgumentNullException(nameof(padding));
byte[] hash = HashData(data, offset, count, hashAlgorithm);
return SignHash(hash, hashAlgorithm, padding);
}
public virtual byte[] SignData(Stream data, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
if (string.IsNullOrEmpty(hashAlgorithm.Name))
throw HashAlgorithmNameNullOrEmpty();
if (padding == null)
throw new ArgumentNullException(nameof(padding));
byte[] hash = HashData(data, hashAlgorithm);
return SignHash(hash, hashAlgorithm, padding);
}
public virtual bool TrySignData(ReadOnlySpan<byte> source, Span<byte> destination, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding, out int bytesWritten)
{
if (string.IsNullOrEmpty(hashAlgorithm.Name))
{
throw HashAlgorithmNameNullOrEmpty();
}
if (padding == null)
{
throw new ArgumentNullException(nameof(padding));
}
if (TryHashData(source, destination, hashAlgorithm, out int hashLength) &&
TrySignHash(destination.Slice(0, hashLength), destination, hashAlgorithm, padding, out bytesWritten))
{
return true;
}
bytesWritten = 0;
return false;
}
public bool VerifyData(byte[] data, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
return VerifyData(data, 0, data.Length, signature, hashAlgorithm, padding);
}
public virtual bool VerifyData(
byte[] data,
int offset,
int count,
byte[] signature,
HashAlgorithmName hashAlgorithm,
RSASignaturePadding padding)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
if (offset < 0 || offset > data.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0 || count > data.Length - offset)
throw new ArgumentOutOfRangeException(nameof(count));
if (signature == null)
throw new ArgumentNullException(nameof(signature));
if (string.IsNullOrEmpty(hashAlgorithm.Name))
throw HashAlgorithmNameNullOrEmpty();
if (padding == null)
throw new ArgumentNullException(nameof(padding));
byte[] hash = HashData(data, offset, count, hashAlgorithm);
return VerifyHash(hash, signature, hashAlgorithm, padding);
}
public bool VerifyData(Stream data, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
if (signature == null)
throw new ArgumentNullException(nameof(signature));
if (string.IsNullOrEmpty(hashAlgorithm.Name))
throw HashAlgorithmNameNullOrEmpty();
if (padding == null)
throw new ArgumentNullException(nameof(padding));
byte[] hash = HashData(data, hashAlgorithm);
return VerifyHash(hash, signature, hashAlgorithm, padding);
}
public virtual bool VerifyData(ReadOnlySpan<byte> data, ReadOnlySpan<byte> signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
{
if (string.IsNullOrEmpty(hashAlgorithm.Name))
{
throw HashAlgorithmNameNullOrEmpty();
}
if (padding == null)
{
throw new ArgumentNullException(nameof(padding));
}
for (int i = 256; ; i = checked(i * 2))
{
int hashLength = 0;
byte[] hash = ArrayPool<byte>.Shared.Rent(i);
try
{
if (TryHashData(data, hash, hashAlgorithm, out hashLength))
{
return VerifyHash(new ReadOnlySpan<byte>(hash, 0, hashLength), signature, hashAlgorithm, padding);
}
}
finally
{
Array.Clear(hash, 0, hashLength);
ArrayPool<byte>.Shared.Return(hash);
}
}
}
public override string KeyExchangeAlgorithm => "RSA";
public override string SignatureAlgorithm => "RSA";
private static Exception HashAlgorithmNameNullOrEmpty() =>
new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, "hashAlgorithm");
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Symbology.dll
// Description: The core libraries for the DotSpatial project.
//
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 2/21/2008 9:28:29 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using DotSpatial.Data;
namespace DotSpatial.Symbology
{
/// <summary>
/// This can be used as a component to work as a LayerManager. This also provides the
/// very important DefaultLayerManager property, which is where the developer controls
/// what LayerManager should be used for their project.
/// </summary>
[ToolboxItem(true)]
public class LayerManager : ILayerManager
{
#region Private Variables
// If this doesn't exist, a new one is created when you "get" this data manager.
private static ILayerManager _defaultLayerManager;
private IList<ILayer> _activeProjectLayers;
private string _dialogReadFilter;
private string _dialogWriteFilter;
private string _imageReadFilter;
private string _imageWriteFilter;
private List<string> _layerProviderDirectories;
private List<ILayerProvider> _layerProviders;
private bool _loadInRam = true;
private Dictionary<string, ILayerProvider> _preferredProviders;
private IProgressHandler _progressHandler;
private string _rasterReadFilter;
private string _rasterWriteFilter;
private string _vectorReadFilter;
private string _vectorWriteFilter;
/// <summary>
/// Gets or sets the implementation of ILayerManager for the project to use when
/// accessing data. This is THE place where the LayerManager can be replaced
/// by a different data manager. If you add this data manager to your
/// project, this will automatically set itself as the DefaultLayerManager.
/// However, since each DM will do this, you may have to control this manually
/// if you add more than one LayerManager to the project in order to set the
/// one that will be chosen.
/// </summary>
public static ILayerManager DefaultLayerManager
{
get
{
if (_defaultLayerManager == null)
{
_defaultLayerManager = new LayerManager();
}
return _defaultLayerManager;
}
set
{
_defaultLayerManager = value;
}
}
/// <summary>
/// Gets or sets a temporary list of active project layers. This is designed to house
/// the layers from a map frame when the property grids are shown for layers in that
/// map frame. This list on the DefaultLayerManager is what is used to create the
/// list that populates dropdowns that can take a Layer as a parameter.
/// </summary>
public IList<ILayer> ActiveProjectLayers
{
get { return _activeProjectLayers; }
set { _activeProjectLayers = value; }
}
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of the LayerManager class. A data manager is more or less
/// just a list of data providers to use. The very important
/// LayerManager.DefaultLayerManager property controls which LayerManager will be used
/// to load data. By default, each LayerManager sets itself as the default in its
/// constructor.
/// </summary>
public LayerManager()
{
// InitializeComponent();
_defaultLayerManager = this;
_layerProviders = new List<ILayerProvider>();
// _layerProviders.Add(new ShapefileLayerProvider()); // .shp files
// _layerProviders.Add(new BinaryLayerProvider()); // .bgd files
//string path = Application.ExecutablePath;
_layerProviderDirectories = new List<string>();
_layerProviderDirectories.Add("\\Plugins");
_preferredProviders = new Dictionary<string, ILayerProvider>();
}
#endregion
#region Methods
/// <summary>
/// Checks a dialog filter and returns a list of just the extensions.
/// </summary>
/// <param name="dialogFilter">The Dialog Filter to read extensions from</param>
/// <returns>A list of extensions</returns>
public virtual List<string> GetSupportedExtensions(string dialogFilter)
{
List<string> extensions = new List<string>();
string[] formats = dialogFilter.Split('|');
char[] wild = { '*' };
// We don't care about the description strings, just the extensions.
for (int i = 1; i < formats.Length; i += 2)
{
// Multiple extension types are separated by semicolons
string[] potentialExtensions = formats[i].Split(';');
foreach (string potentialExtension in potentialExtensions)
{
string ext = potentialExtension.TrimStart(wild);
if (extensions.Contains(ext) == false)
{
extensions.Add(ext);
}
}
}
return extensions;
}
/// <summary>
/// This opens a file, but populates the dialog filter with only raster formats.
/// </summary>
/// <returns>An IRaster with the data from the file specified in an open file dialog</returns>
public virtual IRasterLayer OpenRasterLayer()
{
//OpenFileDialog ofd = new OpenFileDialog();
//ofd.Filter = RasterReadFilter;
//if (ofd.ShowDialog() != DialogResult.OK) return null;
//return OpenLayer(ofd.FileName, LoadInRam, null, ProgressHandler) as IRasterLayer;
throw new NotImplementedException();
}
/// <summary>
/// This opens a file, but populates the dialog filter with only raster formats.
/// </summary>
/// <returns>An IFeatureSet with the data from the file specified in a dialog</returns>
public virtual IFeatureLayer OpenVectorLayer()
{
//OpenFileDialog ofd = new OpenFileDialog();
//ofd.Filter = VectorReadFilter;
//if (ofd.ShowDialog() != DialogResult.OK) return null;
//return OpenLayer(ofd.FileName, LoadInRam, null, ProgressHandler) as IFeatureLayer;
throw new NotImplementedException();
}
/// <summary>
/// This attempts to open the specified raster file and returns an associated layer
/// </summary>
/// <param name="fileName">The string fileName to open</param>
/// <returns>An IRaster with the data from the file specified in an open file dialog</returns>
public virtual IRasterLayer OpenRasterLayer(string fileName)
{
return OpenLayer(fileName, LoadInRam, null, ProgressHandler) as IRasterLayer;
}
/// <summary>
/// This attempts to open the specified vector file and returns an associated layer
/// </summary>
/// <param name="fileName">the string fileName to open</param>
/// <returns>An IFeatureSet with the data from the file specified in a dialog</returns>
public virtual IFeatureLayer OpenVectorLayer(string fileName)
{
return OpenLayer(fileName, LoadInRam, null, ProgressHandler) as IFeatureLayer;
}
/// <summary>
/// Opens a new layer and automatically adds it to the specified container.
/// </summary>
/// <param name="container">The container (usually a LayerCollection) to add to</param>
/// <returns>The layer after it has been created and added to the container</returns>
public virtual ILayer OpenLayer(ICollection<ILayer> container)
{
//OpenFileDialog ofd = new OpenFileDialog();
//ofd.Filter = DialogReadFilter;
//if (ofd.ShowDialog() != DialogResult.OK) return null;
//return OpenLayer(ofd.FileName, LoadInRam, container, ProgressHandler);
throw new NotImplementedException();
}
/// <summary>
/// This launches an open file dialog and attempts to load the specified file.
/// </summary>
/// <param name="progressHandler">Specifies the progressHandler to receive progress messages. This value overrides the property on this DataManager.</param>
/// <returns>A Layer</returns>
public virtual ILayer OpenLayer(IProgressHandler progressHandler)
{
throw new NotImplementedException();
//OpenFileDialog ofd = new OpenFileDialog();
//ofd.Filter = DialogReadFilter;
//if (ofd.ShowDialog() != DialogResult.OK) return null;
//return OpenLayer(ofd.FileName, LoadInRam, null, progressHandler);
}
/// <summary>
/// This launches an open file dialog and attempts to load the specified file.
/// </summary>
/// <returns>A Layer created from the file</returns>
public virtual ILayer OpenLayer()
{
throw new NotImplementedException();
//OpenFileDialog ofd = new OpenFileDialog();
//ofd.Filter = DialogReadFilter;
//if (ofd.ShowDialog() != DialogResult.OK) return null;
//return OpenLayer(ofd.FileName, LoadInRam, null, ProgressHandler);
}
/// <summary>
/// Attempts to call the open fileName method for any ILayerProvider plugin
/// that matches the extension on the string.
/// </summary>
/// <param name="fileName">A String fileName to attempt to open.</param>
public virtual ILayer OpenLayer(string fileName)
{
return OpenLayer(fileName, LoadInRam, null, ProgressHandler);
}
/// <summary>
/// Opens a new layer and automatically adds it to the specified container.
/// </summary>
/// <param name="fileName">A String fileName to attempt to open.</param>
/// <param name="container">The container (usually a LayerCollection) to add to</param>
/// <returns>The layer after it has been created and added to the container</returns>
public virtual ILayer OpenLayer(string fileName, ICollection<ILayer> container)
{
return OpenLayer(fileName, LoadInRam, container, ProgressHandler);
}
/// <summary>
/// This launches an open file dialog and attempts to load the specified file.
/// </summary>
/// <param name="fileName">A String fileName to attempt to open.</param>
/// <param name="progressHandler">Specifies the progressHandler to receive progress messages. This value overrides the property on this DataManager.</param>
/// <returns>A Layer</returns>
public virtual ILayer OpenLayer(string fileName, IProgressHandler progressHandler)
{
return OpenLayer(fileName, LoadInRam, null, progressHandler);
}
/// <summary>
/// Attempts to call the open fileName method for any ILayerProvider plugin
/// that matches the extension on the string.
/// </summary>
/// <param name="fileName">A String fileName to attempt to open.</param>
/// <param name="inRam">A boolean value that if true will attempt to force a load of the data into memory. This value overrides the property on this LayerManager.</param>
/// <param name="container">A container to open this layer in</param>
/// <param name="progressHandler">Specifies the progressHandler to receive progress messages. This value overrides the property on this LayerManager.</param>
/// <returns>An ILayer</returns>
public virtual ILayer OpenLayer(string fileName, bool inRam, ICollection<ILayer> container, IProgressHandler progressHandler)
{
// To Do: Add Customization that allows users to specify which plugins to use in priority order.
// First check for the extension in the preferred plugins list
string ext = Path.GetExtension(fileName);
if (ext != null)
{
ILayer result;
if (_preferredProviders.ContainsKey(ext))
{
result = _preferredProviders[ext].OpenLayer(fileName, inRam, container, progressHandler);
if (result != null)
{
return result;
}
// if we get here, we found the provider, but it did not succeed in opening the file.
}
// Then check the general list of developer specified providers... but not the directory providers
foreach (ILayerProvider dp in _layerProviders)
{
if (GetSupportedExtensions(dp.DialogReadFilter).Contains(ext))
{
// attempt to open with the fileName.
result = dp.OpenLayer(fileName, inRam, container, progressHandler);
if (result != null)
{
return result;
}
}
}
}
throw new ApplicationException(SymbologyMessageStrings.LayerManager_FileTypeNotSupported);
}
/// <summary>
/// This create new method implies that this provider has the priority for creating a new file.
/// An instance of the dataset should be created and then returned. By this time, the fileName
/// will already be checked to see if it exists, and deleted if the user wants to overwrite it.
/// </summary>
/// <param name="name">The string fileName for the new instance.</param>
/// <param name="driverCode">The string short name of the driver for creating the raster.</param>
/// <param name="xSize">The number of columns in the raster.</param>
/// <param name="ySize">The number of rows in the raster.</param>
/// <param name="numBands">The number of bands to create in the raster.</param>
/// <param name="dataType">The data type to use for the raster.</param>
/// <param name="options">The options to be used.</param>
/// <returns>A new IRasterLayer.</returns>
public virtual IRasterLayer CreateRasterLayer(string name, string driverCode, int xSize, int ySize, int numBands, Type dataType, string[] options)
{
// First check for the extension in the preferred plugins list
string ext = Path.GetExtension(name);
if (ext != null)
{
IRasterLayer result;
if (_preferredProviders.ContainsKey(ext))
{
IRasterLayerProvider rp = _preferredProviders[ext] as IRasterLayerProvider;
if (rp != null)
{
result = rp.Create(name, driverCode, xSize, ySize, numBands, dataType, options);
if (result != null)
{
return result;
}
}
// if we get here, we found the provider, but it did not succeed in opening the file.
}
// Then check the general list of developer specified providers... but not the directory providers
foreach (ILayerProvider dp in _layerProviders)
{
if (GetSupportedExtensions(dp.DialogReadFilter).Contains(ext))
{
IRasterLayerProvider rp = dp as IRasterLayerProvider;
if (rp != null)
{
// attempt to open with the fileName.
result = rp.Create(name, driverCode, xSize, ySize, numBands, dataType, options);
if (result != null)
{
return result;
}
}
}
}
}
throw new ApplicationException(SymbologyMessageStrings.LayerManager_FileTypeNotSupported);
}
/// <summary>
/// This opens a file, but populates the dialog filter with only raster formats.
/// </summary>
/// <returns>for now an ILayerSet</returns>
public virtual ILayer OpenImageLayer()
{
//OpenFileDialog ofd = new OpenFileDialog();
//ofd.Filter = ImageReadFilter;
//if (ofd.ShowDialog() != DialogResult.OK) return null;
//return OpenLayer(ofd.FileName, LoadInRam, null, ProgressHandler);
throw new NotImplementedException();
}
#endregion
#region Properties
// May make this invisible if we can
/// <summary>
/// Gets or sets the dialog read filter to use for opening data files.
/// </summary>
[Category("Filters"),
Description("Gets or sets the string that should be used when using this data manager is used to open images.")]
public virtual string ImageReadFilter
{
get
{
// The developer can bypass the default behavior simply by caching something here.
if (_imageReadFilter != null) return _imageReadFilter;
return GetReadFilter<IImageDataProvider>("Images");
}
set { _imageReadFilter = value; }
}
/// <summary>
/// Gets or sets the dialog write filter to use for saving data files.
/// </summary>
[Category("Filters"),
Description("Gets or sets the string that should be used when this data manager is used to save images.")]
public virtual string ImageWriteFilter
{
get
{
// Setting this to something overrides the default
if (_imageWriteFilter != null) return _imageWriteFilter;
return GetWriteFilter<IImageDataProvider>("Images");
}
set { _imageWriteFilter = value; }
}
/// <summary>
/// Gets or sets the list of ILayerProviders that should be used in the project.
/// </summary>
[Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual List<ILayerProvider> LayerProviders
{
get { return _layerProviders; }
set
{
_layerProviders = value;
}
}
/// <summary>
/// Gets or sets the path (either as a full path or as a path relative to
/// the DotSpatial.dll) to search for plugins that implement the ILayerProvider interface.
/// </summary>
[Category("Providers"),
Description("Gets or sets the list of string path names that should be used to search for ILayerProvider interfaces.")]
public virtual List<string> LayerProviderDirectories
{
get { return _layerProviderDirectories; }
set { _layerProviderDirectories = value; }
}
/// <summary>
/// Gets or sets the dialog read filter to use for opening data files.
/// </summary>
[Category("Filters"),
Description("Gets or sets the string that should be used when using this data manager is used to open files.")]
public virtual string DialogReadFilter
{
get
{
// The developer can bypass the default behavior simply by caching something here.
if (_dialogReadFilter != null) return _dialogReadFilter;
List<string> rasterExtensions = new List<string>();
List<string> vectorExtensions = new List<string>();
List<string> imageExtensions = new List<string>();
List<string> extensions = _preferredProviders.Select(item => item.Key).ToList();
foreach (ILayerProvider dp in _layerProviders)
{
string[] formats = dp.DialogReadFilter.Split('|');
// We don't care about the description strings, just the extensions.
for (int i = 1; i < formats.Length; i += 2)
{
// Multiple extension types are separated by semicolons
string[] potentialExtensions = formats[i].Split(';');
foreach (string potentialExtension in potentialExtensions)
{
if (extensions.Contains(potentialExtension) == false)
{
extensions.Add(potentialExtension);
if (dp is IRasterProvider)
{
rasterExtensions.Add(potentialExtension);
}
if (dp is IVectorProvider)
{
vectorExtensions.Add(potentialExtension);
}
if (dp is IImageDataProvider)
{
imageExtensions.Add(potentialExtension);
}
}
}
}
}
// We now have a list of all the file extensions supported
string result = "All Supported Formats|" + String.Join(";", extensions.ToArray());
if (vectorExtensions.Count > 0)
{
result += "|Vectors|" + String.Join(";", vectorExtensions.ToArray());
}
if (rasterExtensions.Count > 0)
{
result += "|Rasters|" + String.Join(";", rasterExtensions.ToArray());
}
if (imageExtensions.Count > 0)
{
result += "|Images|" + String.Join(";", imageExtensions.ToArray());
}
foreach (KeyValuePair<string, ILayerProvider> item in _preferredProviders)
{
// we don't have to check for uniqueness here because it is enforced by the HashTable
result += "| [" + item.Key + "] - " + item.Value.Name + "| " + item.Key;
}
// Now add each of the individual lines, prepended with the provider name
foreach (ILayerProvider dp in _layerProviders)
{
string[] formats = dp.DialogReadFilter.Split('|');
string potentialFormat = null;
for (int i = 0; i < formats.Length; i++)
{
if (i % 2 == 0)
{
// For descriptions, prepend the name:
potentialFormat = "|" + dp.Name + " - " + formats[i];
}
else
{
// don't add this format if it was already added by a "preferred data provider"
if (_preferredProviders.ContainsKey(formats[i]) == false)
{
result += potentialFormat;
result += "|" + formats[i];
}
}
}
}
result += "|All Files (*.*) |*.*";
return result;
}
set { _dialogReadFilter = value; }
}
/// <summary>
/// Gets or sets the dialog write filter to use for saving data files.
/// </summary>
[Category("Filters"),
Description("Gets or sets the string that should be used when this data manager is used to save files.")]
public virtual string DialogWriteFilter
{
get
{
// Setting this to something overrides the default
if (_dialogWriteFilter != null) return _dialogWriteFilter;
List<string> extensions = new List<string>();
List<string> rasterExtensions = new List<string>();
List<string> vectorExtensions = new List<string>();
List<string> imageExtensions = new List<string>();
foreach (KeyValuePair<string, ILayerProvider> item in _preferredProviders)
{
extensions.Add(item.Key);
}
foreach (ILayerProvider dp in _layerProviders)
{
string[] formats = dp.DialogWriteFilter.Split('|');
// We don't care about the description strings, just the extensions.
for (int i = 1; i < formats.Length; i += 2)
{
// Multiple extension types are separated by semicolons
string[] potentialExtensions = formats[i].Split(';');
foreach (string potentialExtension in potentialExtensions)
{
if (extensions.Contains(potentialExtension) == false)
{
extensions.Add(potentialExtension);
if (dp is IRasterProvider)
{
rasterExtensions.Add(potentialExtension);
}
if (dp is IVectorProvider)
{
vectorExtensions.Add(potentialExtension);
}
if (dp is IImageDataProvider)
{
imageExtensions.Add(potentialExtension);
}
}
}
}
}
// We now have a list of all the file extensions supported
string result = "All Supported Formats|" + String.Join(";", extensions.ToArray());
if (vectorExtensions.Count > 0)
{
result += "|Vectors|" + String.Join(";", vectorExtensions.ToArray());
}
if (rasterExtensions.Count > 0)
{
result += "|Rasters|" + String.Join(";", rasterExtensions.ToArray());
}
if (imageExtensions.Count > 0)
{
result += "|Images|" + String.Join(";", imageExtensions.ToArray());
}
foreach (KeyValuePair<string, ILayerProvider> item in _preferredProviders)
{
// we don't have to check for uniqueness here because it is enforced by the HashTable
result += "| [" + item.Key + "] - " + item.Value.Name + "| " + item.Key;
}
// Now add each of the individual lines, prepended with the provider name
foreach (ILayerProvider dp in _layerProviders)
{
string[] formats = dp.DialogWriteFilter.Split('|');
string potentialFormat = null;
for (int i = 0; i < formats.Length; i++)
{
if (i % 2 == 0)
{
// For descriptions, prepend the name:
potentialFormat += "|" + dp.Name + " - " + formats[i];
}
else
{
if (_preferredProviders.ContainsKey(formats[i]) == false)
{
result += potentialFormat;
result += "|" + formats[i];
}
}
}
}
result += "|All Files (*.*) |*.*";
return result;
}
set { _dialogWriteFilter = value; }
}
/// <summary>
/// Gets or sets the dialog read filter to use for opening data files that are specifically raster formats.
/// </summary>
[Category("Filters"),
Description("Gets or sets the string that should be used when using this data manager is used to open rasters.")]
public virtual string RasterReadFilter
{
get
{
// The developer can bypass the default behavior simply by caching something here.
if (_rasterReadFilter != null) return _rasterReadFilter;
return GetReadFilter<IRasterProvider>("Rasters");
}
set { _rasterReadFilter = value; }
}
/// <summary>
/// Gets or sets the dialog write filter to use for saving data files.
/// </summary>
[Category("Filters"),
Description("Gets or sets the string that should be used when this data manager is used to save rasters.")]
public virtual string RasterWriteFilter
{
get
{
// Setting this to something overrides the default
if (_rasterWriteFilter != null) return _rasterWriteFilter;
return GetWriteFilter<IRasterProvider>("Rasters");
}
set { _rasterWriteFilter = value; }
}
/// <summary>
/// Gets or sets the dialog read filter to use for opening data files.
/// </summary>
[Category("Filters"),
Description("Gets or sets the string that should be used when using this data manager is used to open vectors.")]
public virtual string VectorReadFilter
{
get
{
// The developer can bypass the default behavior simply by caching something here.
if (_vectorReadFilter != null) return _vectorReadFilter;
return GetReadFilter<IVectorProvider>("Vectors");
}
set { _vectorReadFilter = value; }
}
/// <summary>
/// Gets or sets the dialog write filter to use for saving data files.
/// </summary>
[Category("Filters"),
Description("Gets or sets the string that should be used when this data manager is used to save vectors.")]
public virtual string VectorWriteFilter
{
get
{
// Setting this to something overrides the default
if (_vectorWriteFilter != null) return _vectorWriteFilter;
return GetWriteFilter<IVectorProvider>("Vectors");
}
set { _vectorWriteFilter = value; }
}
/// <summary>
/// Sets the default condition for how this data manager should try to load layers.
/// This will be overridden if the inRam property is specified as a parameter.
/// </summary>
[Category("Behavior"),
Description("Gets or sets the default condition for subsequent load operations which may be overridden by specifying inRam in the parameters.")]
public bool LoadInRam
{
get { return _loadInRam; }
set { _loadInRam = value; }
}
/// <summary>
/// Gets or sets a dictionary of ILayerProviders with corresponding extensions. The
/// standard order is to try to load the data using a PreferredProvider. If that
/// fails, then it will check the list of dataProviders, and finally, if that fails,
/// it will check the plugin Layer Providers in directories.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual Dictionary<string, ILayerProvider> PreferredProviders
{
get { return _preferredProviders; }
set { _preferredProviders = value; }
}
/// <summary>
/// Gets or sets a progress handler for any open operations that are intiated by this
/// LayerManager and don't override this value with an IProgressHandler specified in the parameters.
/// </summary>
[Category("Handlers")]
[Description("Gets or sets the object that implements the IProgressHandler interface for recieving status messages.")]
public virtual IProgressHandler ProgressHandler
{
get { return _progressHandler; }
set { _progressHandler = value; }
}
private string GetWriteFilter<T>(string description)
{
string result = null;
List<string> extensions = new List<string>();
foreach (KeyValuePair<string, ILayerProvider> item in _preferredProviders)
{
if (item.Value is T)
{
extensions.Add(item.Key);
}
}
foreach (ILayerProvider dp in _layerProviders)
{
string[] formats = dp.DialogWriteFilter.Split('|');
// We don't care about the description strings, just the extensions.
for (int i = 1; i < formats.Length; i += 2)
{
// Multiple extension types are separated by semicolons
string[] potentialExtensions = formats[i].Split(';');
foreach (string potentialExtension in potentialExtensions)
{
if (extensions.Contains(potentialExtension) == false)
{
if (dp is T)
{
extensions.Add(potentialExtension);
}
}
}
}
}
// We now have a list of all the file extensions supported
if (extensions.Count > 0)
{
result += String.Format("{0}|", description) + String.Join(";", extensions.ToArray());
}
foreach (KeyValuePair<string, ILayerProvider> item in _preferredProviders)
{
if (item.Value is T)
{
// we don't have to check for uniqueness here because it is enforced by the HashTable
result += "| [" + item.Key + "] - " + item.Value.Name + "| " + item.Key;
}
}
// Now add each of the individual lines, prepended with the provider name
foreach (ILayerProvider dp in _layerProviders)
{
string[] formats = dp.DialogWriteFilter.Split('|');
string potentialFormat = null;
for (int i = 0; i < formats.Length; i++)
{
if (i % 2 == 0)
{
// For descriptions, prepend the name:
potentialFormat += "|" + dp.Name + " - " + formats[i];
}
else
{
if (_preferredProviders.ContainsKey(formats[i]) == false)
{
if (dp is T)
{
result += potentialFormat;
result += "|" + formats[i];
}
}
}
}
}
result += "|All Files (*.*) |*.*";
return result;
}
private string GetReadFilter<T>(string description)
{
List<string> extensions = new List<string>();
foreach (KeyValuePair<string, ILayerProvider> item in _preferredProviders)
{
if (item.Value is T)
{
// we don't have to check for uniqueness here because it is enforced by the HashTable
extensions.Add(item.Key);
}
}
foreach (ILayerProvider dp in _layerProviders)
{
string[] formats = dp.DialogReadFilter.Split('|');
// We don't care about the description strings, just the extensions.
for (int i = 1; i < formats.Length; i += 2)
{
// Multiple extension types are separated by semicolons
string[] potentialExtensions = formats[i].Split(';');
foreach (string potentialExtension in potentialExtensions)
{
if (extensions.Contains(potentialExtension) == false)
{
if (dp is T)
{
extensions.Add(potentialExtension);
}
}
}
}
}
// We now have a list of all the file extensions supported
string result = String.Format("{0}|", description) + String.Join(";", extensions.ToArray());
foreach (KeyValuePair<string, ILayerProvider> item in _preferredProviders)
{
if (item.Value is T)
{
// we don't have to check for uniqueness here because it is enforced by the HashTable
result += "| [" + item.Key + "] - " + item.Value.Name + "| " + item.Key;
}
}
// Now add each of the individual lines, prepended with the provider name
foreach (ILayerProvider dp in _layerProviders)
{
string[] formats = dp.DialogReadFilter.Split('|');
string potentialFormat = null;
for (int i = 0; i < formats.Length; i++)
{
if (i % 2 == 0)
{
// For descriptions, prepend the name:
potentialFormat = "|" + dp.Name + " - " + formats[i];
}
else
{
// don't add this format if it was already added by a "preferred data provider"
if (_preferredProviders.ContainsKey(formats[i]) == false)
{
if (dp is T)
{
result += potentialFormat;
result += "|" + formats[i];
}
}
}
}
}
result += "|All Files (*.*) |*.*";
return result;
}
#endregion
#region Events
/// <summary>
/// Occurs after the directory providers have been loaded into the project.
/// </summary>
public event EventHandler<LayerProviders> DirectoryProvidersLoaded;
/// <summary>
/// Triggers the DirectoryProvidersLoaded event
/// </summary>
protected virtual void OnProvidersLoaded(List<ILayerProvider> list)
{
if (DirectoryProvidersLoaded != null)
{
DirectoryProvidersLoaded(this, new LayerProviders(list));
}
}
#endregion
#region Private Functions
/// <summary>
/// This should be called once all the permitted directories have been set in the code.
/// This will not affect the PreferredProviders or the general list of Providers.
/// These automatically have the lowest priority and will only be used if nothing
/// else works. Use the PreferredProviders to force preferential loading of
/// a plugin LayerProvider.
/// </summary>
/// <returns>A list of just the newly added LayerProviders from this method.</returns>
public virtual List<ILayerProvider> LoadProvidersFromDirectories()
{
Assembly asm;
List<ILayerProvider> result = new List<ILayerProvider>();
foreach (string directory in _layerProviderDirectories)
{
foreach (string file in Directory.GetFiles(directory, "*.dll", SearchOption.AllDirectories))
{
if (file.Contains("Interop")) continue;
if (Path.GetFileName(file) == "DotSpatial.dll") continue; // If they forget to turn "copy local" to false.
asm = Assembly.LoadFrom(file);
try
{
Type[] coClassList = asm.GetTypes();
foreach (Type coClass in coClassList)
{
Type[] infcList = coClass.GetInterfaces();
foreach (Type infc in infcList)
{
if (infc == typeof(ILayerProvider))
{
try
{
object obj = asm.CreateInstance(coClass.FullName);
ILayerProvider dp = obj as ILayerProvider;
if (dp != null)
{
_layerProviders.Add(dp);
result.Add(dp);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
// this object didn't work, but keep looking
}
}
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
// We will fail frequently.
}
}
}
OnProvidersLoaded(result);
return result;
}
/// <summary>
/// Given a string fileName for the "*.dll" file, this will attempt to load any classes that implement the
/// ILayerProvder interface.
/// </summary>
/// <param name="fileName">The string path of the assembly to load from.</param>
/// <returns>A list that contains only the providers that were just loaded. This may be a list of count 0, but shouldn't return null.</returns>
public virtual List<ILayerProvider> LoadProvidersFromAssembly(string fileName)
{
List<ILayerProvider> result = new List<ILayerProvider>();
if (Path.GetExtension(fileName) != ".dll") return result;
if (fileName.Contains("Interop")) return result;
Assembly asm = Assembly.LoadFrom(fileName);
try
{
Type[] coClassList = asm.GetTypes();
foreach (Type coClass in coClassList)
{
Type[] infcList = coClass.GetInterfaces();
foreach (Type infc in infcList)
{
if (infc != typeof(ILayerProvider)) continue;
try
{
object obj = asm.CreateInstance(coClass.FullName);
ILayerProvider dp = obj as ILayerProvider;
if (dp != null)
{
_layerProviders.Add(dp);
result.Add(dp);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
// this object didn't work, but keep looking
}
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
// We will fail frequently.
}
OnProvidersLoaded(result);
return result;
}
#endregion
}
}
| |
#pragma warning disable 1587
#region Header
///
/// JsonMapper.cs
/// JSON to .Net object and object to JSON conversions.
///
/// The authors disclaim copyright to this source code. For more details, see
/// the COPYING file included with this distribution.
///
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using Amazon.Util;
using Amazon.Util.Internal;
namespace ThirdParty.Json.LitJson
{
internal struct PropertyMetadata
{
public MemberInfo Info;
public bool IsField;
public Type Type;
}
internal struct ArrayMetadata
{
private Type element_type;
private bool is_array;
private bool is_list;
public Type ElementType {
get {
if (element_type == null)
return typeof (JsonData);
return element_type;
}
set { element_type = value; }
}
public bool IsArray {
get { return is_array; }
set { is_array = value; }
}
public bool IsList {
get { return is_list; }
set { is_list = value; }
}
}
internal struct ObjectMetadata
{
private Type element_type;
private bool is_dictionary;
private IDictionary<string, PropertyMetadata> properties;
public Type ElementType {
get {
if (element_type == null)
return typeof (JsonData);
return element_type;
}
set { element_type = value; }
}
public bool IsDictionary {
get { return is_dictionary; }
set { is_dictionary = value; }
}
public IDictionary<string, PropertyMetadata> Properties {
get { return properties; }
set { properties = value; }
}
}
internal delegate void ExporterFunc (object obj, JsonWriter writer);
internal delegate void ExporterFunc<T> (T obj, JsonWriter writer);
internal delegate object ImporterFunc (object input);
internal delegate TValue ImporterFunc<TJson, TValue> (TJson input);
internal delegate IJsonWrapper WrapperFactory ();
internal class JsonMapper
{
#region Fields
private static int max_nesting_depth;
private static IFormatProvider datetime_format;
private static IDictionary<Type, ExporterFunc> base_exporters_table;
private static IDictionary<Type, ExporterFunc> custom_exporters_table;
private static IDictionary<Type,
IDictionary<Type, ImporterFunc>> base_importers_table;
private static IDictionary<Type,
IDictionary<Type, ImporterFunc>> custom_importers_table;
private static IDictionary<Type, ArrayMetadata> array_metadata;
private static readonly object array_metadata_lock = new Object ();
private static IDictionary<Type,
IDictionary<Type, MethodInfo>> conv_ops;
private static readonly object conv_ops_lock = new Object ();
private static IDictionary<Type, ObjectMetadata> object_metadata;
private static readonly object object_metadata_lock = new Object ();
private static IDictionary<Type,
IList<PropertyMetadata>> type_properties;
private static readonly object type_properties_lock = new Object ();
private static JsonWriter static_writer;
private static readonly object static_writer_lock = new Object ();
private static readonly HashSet<string> dictionary_properties_to_ignore = new HashSet<string>(StringComparer.Ordinal)
{
"Comparer", "Count", "Keys", "Values"
};
#endregion
#region Constructors
static JsonMapper ()
{
max_nesting_depth = 100;
array_metadata = new Dictionary<Type, ArrayMetadata> ();
conv_ops = new Dictionary<Type, IDictionary<Type, MethodInfo>> ();
object_metadata = new Dictionary<Type, ObjectMetadata> ();
type_properties = new Dictionary<Type,
IList<PropertyMetadata>> ();
static_writer = new JsonWriter ();
datetime_format = DateTimeFormatInfo.InvariantInfo;
base_exporters_table = new Dictionary<Type, ExporterFunc> ();
custom_exporters_table = new Dictionary<Type, ExporterFunc> ();
base_importers_table = new Dictionary<Type,
IDictionary<Type, ImporterFunc>> ();
custom_importers_table = new Dictionary<Type,
IDictionary<Type, ImporterFunc>> ();
RegisterBaseExporters ();
RegisterBaseImporters ();
}
#endregion
#region Private Methods
private static void AddArrayMetadata (Type type)
{
if (array_metadata.ContainsKey (type))
return;
ArrayMetadata data = new ArrayMetadata ();
data.IsArray = type.IsArray;
var typeInfo = TypeFactory.GetTypeInfo(type);
if (typeInfo.GetInterface("System.Collections.IList") != null)
data.IsList = true;
foreach (PropertyInfo p_info in typeInfo.GetProperties())
{
if (p_info.Name != "Item")
continue;
ParameterInfo[] parameters = p_info.GetIndexParameters ();
if (parameters.Length != 1)
continue;
if (parameters[0].ParameterType == typeof (int))
data.ElementType = p_info.PropertyType;
}
lock (array_metadata_lock) {
try {
array_metadata.Add (type, data);
} catch (ArgumentException) {
return;
}
}
}
private static void AddObjectMetadata (Type type)
{
if (object_metadata.ContainsKey (type))
return;
ObjectMetadata data = new ObjectMetadata ();
var typeInfo = TypeFactory.GetTypeInfo(type);
if (typeInfo.GetInterface("System.Collections.IDictionary") != null)
data.IsDictionary = true;
data.Properties = new Dictionary<string, PropertyMetadata> ();
foreach (PropertyInfo p_info in typeInfo.GetProperties())
{
if (p_info.Name == "Item") {
ParameterInfo[] parameters = p_info.GetIndexParameters ();
if (parameters.Length != 1)
continue;
if (parameters[0].ParameterType == typeof (string))
data.ElementType = p_info.PropertyType;
continue;
}
if (data.IsDictionary && dictionary_properties_to_ignore.Contains(p_info.Name))
continue;
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = p_info;
p_data.Type = p_info.PropertyType;
data.Properties.Add (p_info.Name, p_data);
}
foreach (FieldInfo f_info in typeInfo.GetFields())
{
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = f_info;
p_data.IsField = true;
p_data.Type = f_info.FieldType;
data.Properties.Add (f_info.Name, p_data);
}
lock (object_metadata_lock) {
try {
object_metadata.Add (type, data);
} catch (ArgumentException) {
return;
}
}
}
private static void AddTypeProperties (Type type)
{
if (type_properties.ContainsKey (type))
return;
var typeInfo = TypeFactory.GetTypeInfo(type);
IList<PropertyMetadata> props = new List<PropertyMetadata> ();
foreach (PropertyInfo p_info in typeInfo.GetProperties())
{
if (p_info.Name == "Item")
continue;
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = p_info;
p_data.IsField = false;
props.Add (p_data);
}
foreach (FieldInfo f_info in typeInfo.GetFields())
{
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = f_info;
p_data.IsField = true;
props.Add (p_data);
}
lock (type_properties_lock) {
try {
type_properties.Add (type, props);
} catch (ArgumentException) {
return;
}
}
}
private static MethodInfo GetConvOp (Type t1, Type t2)
{
lock (conv_ops_lock) {
if (! conv_ops.ContainsKey (t1))
conv_ops.Add (t1, new Dictionary<Type, MethodInfo> ());
}
var typeInfoT1 = TypeFactory.GetTypeInfo(t1);
var typeInfoT2 = TypeFactory.GetTypeInfo(t2);
if (conv_ops[t1].ContainsKey (t2))
return conv_ops[t1][t2];
MethodInfo op = typeInfoT1.GetMethod(
"op_Implicit", new ITypeInfo[] { typeInfoT2 });
lock (conv_ops_lock) {
try {
conv_ops[t1].Add (t2, op);
} catch (ArgumentException) {
return conv_ops[t1][t2];
}
}
return op;
}
private static object ReadValue (Type inst_type, JsonReader reader)
{
reader.Read ();
var inst_typeInfo = TypeFactory.GetTypeInfo(inst_type);
if (reader.Token == JsonToken.ArrayEnd)
return null;
//support for nullable types
Type underlying_type = Nullable.GetUnderlyingType(inst_type);
Type value_type = underlying_type ?? inst_type;
if (reader.Token == JsonToken.Null) {
if (inst_typeInfo.IsClass || underlying_type != null)
{
return null;
}
throw new JsonException (String.Format (
"Can't assign null to an instance of type {0}",
inst_type));
}
if (reader.Token == JsonToken.Double ||
reader.Token == JsonToken.Int ||
reader.Token == JsonToken.UInt ||
reader.Token == JsonToken.Long ||
reader.Token == JsonToken.ULong ||
reader.Token == JsonToken.String ||
reader.Token == JsonToken.Boolean) {
Type json_type = reader.Value.GetType ();
var json_typeInfo = TypeFactory.GetTypeInfo(json_type);
if (inst_typeInfo.IsAssignableFrom(json_typeInfo))
return reader.Value;
// If there's a custom importer that fits, use it
if (custom_importers_table.ContainsKey (json_type) &&
custom_importers_table[json_type].ContainsKey (
value_type)) {
ImporterFunc importer =
custom_importers_table[json_type][value_type];
return importer (reader.Value);
}
// Maybe there's a base importer that works
if (base_importers_table.ContainsKey (json_type) &&
base_importers_table[json_type].ContainsKey (
value_type)) {
ImporterFunc importer =
base_importers_table[json_type][value_type];
return importer (reader.Value);
}
// Maybe it's an enum
if (inst_typeInfo.IsEnum)
return Enum.ToObject (value_type, reader.Value);
// Try using an implicit conversion operator
MethodInfo conv_op = GetConvOp (value_type, json_type);
if (conv_op != null)
return conv_op.Invoke (null,
new object[] { reader.Value });
// No luck
throw new JsonException (String.Format (
"Can't assign value '{0}' (type {1}) to type {2}",
reader.Value, json_type, inst_type));
}
object instance = null;
if (reader.Token == JsonToken.ArrayStart) {
AddArrayMetadata (inst_type);
ArrayMetadata t_data = array_metadata[inst_type];
if (! t_data.IsArray && ! t_data.IsList)
throw new JsonException (String.Format (
"Type {0} can't act as an array",
inst_type));
IList list;
Type elem_type;
if (! t_data.IsArray) {
list = (IList) Activator.CreateInstance (inst_type);
elem_type = t_data.ElementType;
} else {
list = new List<object> ();
elem_type = inst_type.GetElementType ();
}
while (true) {
object item = ReadValue (elem_type, reader);
if (reader.Token == JsonToken.ArrayEnd)
break;
list.Add (item);
}
if (t_data.IsArray) {
int n = list.Count;
instance = Array.CreateInstance (elem_type, n);
for (int i = 0; i < n; i++)
((Array) instance).SetValue (list[i], i);
} else
instance = list;
} else if (reader.Token == JsonToken.ObjectStart) {
AddObjectMetadata (value_type);
ObjectMetadata t_data = object_metadata[value_type];
instance = Activator.CreateInstance (value_type);
while (true) {
reader.Read ();
if (reader.Token == JsonToken.ObjectEnd)
break;
string property = (string) reader.Value;
if (t_data.Properties.ContainsKey (property)) {
PropertyMetadata prop_data =
t_data.Properties[property];
if (prop_data.IsField) {
((FieldInfo) prop_data.Info).SetValue (
instance, ReadValue (prop_data.Type, reader));
} else {
PropertyInfo p_info =
(PropertyInfo) prop_data.Info;
if (p_info.CanWrite)
p_info.SetValue (
instance,
ReadValue (prop_data.Type, reader),
null);
else
ReadValue (prop_data.Type, reader);
}
} else {
if (! t_data.IsDictionary)
throw new JsonException (String.Format (
"The type {0} doesn't have the " +
"property '{1}'", inst_type, property));
((IDictionary) instance).Add (
property, ReadValue (
t_data.ElementType, reader));
}
}
}
return instance;
}
private static IJsonWrapper ReadValue (WrapperFactory factory,
JsonReader reader)
{
reader.Read ();
if (reader.Token == JsonToken.ArrayEnd ||
reader.Token == JsonToken.Null)
return null;
IJsonWrapper instance = factory ();
if (reader.Token == JsonToken.String) {
instance.SetString ((string) reader.Value);
return instance;
}
if (reader.Token == JsonToken.Double) {
instance.SetDouble ((double) reader.Value);
return instance;
}
if (reader.Token == JsonToken.Int) {
instance.SetInt ((int) reader.Value);
return instance;
}
if (reader.Token == JsonToken.UInt) {
instance.SetUInt((uint)reader.Value);
return instance;
}
if (reader.Token == JsonToken.Long) {
instance.SetLong ((long) reader.Value);
return instance;
}
if (reader.Token == JsonToken.ULong) {
instance.SetULong((ulong)reader.Value);
return instance;
}
if (reader.Token == JsonToken.Boolean) {
instance.SetBoolean ((bool) reader.Value);
return instance;
}
if (reader.Token == JsonToken.ArrayStart) {
instance.SetJsonType (JsonType.Array);
while (true) {
IJsonWrapper item = ReadValue (factory, reader);
// nij - added check to see if the item is not null. This is to handle arrays within arrays.
// In those cases when the outer array read the inner array an item was returned back the current
// reader.Token is at the ArrayEnd for the inner array.
if (item == null && reader.Token == JsonToken.ArrayEnd)
break;
((IList) instance).Add (item);
}
}
else if (reader.Token == JsonToken.ObjectStart) {
instance.SetJsonType (JsonType.Object);
while (true) {
reader.Read ();
if (reader.Token == JsonToken.ObjectEnd)
break;
string property = (string) reader.Value;
((IDictionary) instance)[property] = ReadValue (
factory, reader);
}
}
return instance;
}
private static void RegisterBaseExporters ()
{
base_exporters_table[typeof (byte)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((byte) obj));
};
base_exporters_table[typeof (char)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToString ((char) obj));
};
base_exporters_table[typeof (DateTime)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToString ((DateTime) obj,
datetime_format));
};
base_exporters_table[typeof (decimal)] =
delegate (object obj, JsonWriter writer) {
writer.Write ((decimal) obj);
};
base_exporters_table[typeof (sbyte)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((sbyte) obj));
};
base_exporters_table[typeof (short)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((short) obj));
};
base_exporters_table[typeof (ushort)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((ushort) obj));
};
base_exporters_table[typeof (uint)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToUInt64 ((uint) obj));
};
base_exporters_table[typeof (ulong)] =
delegate (object obj, JsonWriter writer) {
writer.Write ((ulong) obj);
};
base_exporters_table[typeof(float)] =
delegate (object obj,JsonWriter writer){
writer.Write(Convert.ToDouble((float) obj));
};
base_exporters_table[typeof(Int64)] =
delegate (object obj,JsonWriter writer){
writer.Write(Convert.ToDouble((Int64) obj));
};
}
private static void RegisterBaseImporters ()
{
ImporterFunc importer;
importer = delegate (object input) {
return Convert.ToByte ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (byte), importer);
importer = delegate (object input) {
return Convert.ToUInt64 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (ulong), importer);
importer = delegate (object input) {
return Convert.ToSByte ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (sbyte), importer);
importer = delegate (object input) {
return Convert.ToInt16 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (short), importer);
importer = delegate (object input) {
return Convert.ToUInt16 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (ushort), importer);
importer = delegate (object input) {
return Convert.ToUInt32 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (uint), importer);
importer = delegate (object input) {
return Convert.ToSingle ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (float), importer);
importer = delegate (object input) {
return Convert.ToDouble ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (double), importer);
importer = delegate (object input) {
return Convert.ToDecimal ((double) input);
};
RegisterImporter (base_importers_table, typeof (double),
typeof (decimal), importer);
importer = delegate(object input)
{
return Convert.ToSingle((float)(double)input);
};
RegisterImporter(base_importers_table,typeof(double),
typeof(float),importer);
importer = delegate (object input) {
return Convert.ToUInt32 ((long) input);
};
RegisterImporter (base_importers_table, typeof (long),
typeof (uint), importer);
importer = delegate (object input) {
return Convert.ToChar ((string) input);
};
RegisterImporter (base_importers_table, typeof (string),
typeof (char), importer);
importer = delegate (object input) {
return Convert.ToDateTime ((string) input, datetime_format);
};
RegisterImporter (base_importers_table, typeof (string),
typeof (DateTime), importer);
importer = delegate(object input) {
return Convert.ToInt64 ((Int32)input);
};
RegisterImporter (base_importers_table, typeof (Int32),
typeof(Int64), importer);
}
private static void RegisterImporter (
IDictionary<Type, IDictionary<Type, ImporterFunc>> table,
Type json_type, Type value_type, ImporterFunc importer)
{
if (! table.ContainsKey (json_type))
table.Add (json_type, new Dictionary<Type, ImporterFunc> ());
table[json_type][value_type] = importer;
}
private static void WriteValue (object obj, JsonWriter writer,
bool writer_is_private,
int depth)
{
if (depth > max_nesting_depth)
throw new JsonException (
String.Format ("Max allowed object depth reached while " +
"trying to export from type {0}",
obj.GetType ()));
if (obj == null) {
writer.Write (null);
return;
}
if (obj is IJsonWrapper) {
if (writer_is_private)
writer.TextWriter.Write (((IJsonWrapper) obj).ToJson ());
else
((IJsonWrapper) obj).ToJson (writer);
return;
}
if (obj is String) {
writer.Write ((string) obj);
return;
}
if (obj is Double) {
writer.Write ((double) obj);
return;
}
if (obj is Int32) {
writer.Write ((int) obj);
return;
}
if (obj is UInt32)
{
writer.Write((uint)obj);
return;
}
if (obj is Boolean) {
writer.Write ((bool) obj);
return;
}
if (obj is Int64) {
writer.Write ((long) obj);
return;
}
if (obj is UInt64)
{
writer.Write((ulong)obj);
}
if (obj is Array) {
writer.WriteArrayStart ();
foreach (object elem in (Array) obj)
WriteValue (elem, writer, writer_is_private, depth + 1);
writer.WriteArrayEnd ();
return;
}
if (obj is IList) {
writer.WriteArrayStart ();
foreach (object elem in (IList) obj)
WriteValue (elem, writer, writer_is_private, depth + 1);
writer.WriteArrayEnd ();
return;
}
if (obj is IDictionary) {
writer.WriteObjectStart ();
foreach (DictionaryEntry entry in (IDictionary) obj) {
writer.WritePropertyName ((string) entry.Key);
WriteValue (entry.Value, writer, writer_is_private,
depth + 1);
}
writer.WriteObjectEnd ();
return;
}
Type obj_type = obj.GetType ();
// See if there's a custom exporter for the object
if (custom_exporters_table.ContainsKey (obj_type)) {
ExporterFunc exporter = custom_exporters_table[obj_type];
exporter (obj, writer);
return;
}
// If not, maybe there's a base exporter
if (base_exporters_table.ContainsKey (obj_type)) {
ExporterFunc exporter = base_exporters_table[obj_type];
exporter (obj, writer);
return;
}
// Last option, let's see if it's an enum
if (obj is Enum) {
Type e_type = Enum.GetUnderlyingType (obj_type);
if (e_type == typeof (long)
|| e_type == typeof (uint)
|| e_type == typeof (ulong))
writer.Write ((ulong) obj);
else
writer.Write ((int) obj);
return;
}
// Okay, so it looks like the input should be exported as an
// object
AddTypeProperties (obj_type);
IList<PropertyMetadata> props = type_properties[obj_type];
writer.WriteObjectStart ();
foreach (PropertyMetadata p_data in props) {
if (p_data.IsField) {
writer.WritePropertyName (p_data.Info.Name);
WriteValue (((FieldInfo) p_data.Info).GetValue (obj),
writer, writer_is_private, depth + 1);
}
else {
PropertyInfo p_info = (PropertyInfo) p_data.Info;
if (p_info.CanRead)
{
writer.WritePropertyName(p_data.Info.Name);
WriteValue(p_info.GetGetMethod().Invoke(obj, null),
writer, writer_is_private, depth + 1);
}
}
}
writer.WriteObjectEnd ();
}
#endregion
public static string ToJson (object obj)
{
lock (static_writer_lock) {
static_writer.Reset ();
WriteValue (obj, static_writer, true, 0);
return static_writer.ToString ();
}
}
public static void ToJson (object obj, JsonWriter writer)
{
WriteValue (obj, writer, false, 0);
}
public static JsonData ToObject (JsonReader reader)
{
return (JsonData) ToWrapper (
delegate { return new JsonData (); }, reader);
}
public static JsonData ToObject (TextReader reader)
{
JsonReader json_reader = new JsonReader (reader);
return (JsonData) ToWrapper (
delegate { return new JsonData (); }, json_reader);
}
public static JsonData ToObject (string json)
{
return (JsonData) ToWrapper (
delegate { return new JsonData (); }, json);
}
public static T ToObject<T> (JsonReader reader)
{
return (T) ReadValue (typeof (T), reader);
}
public static T ToObject<T> (TextReader reader)
{
JsonReader json_reader = new JsonReader (reader);
return (T) ReadValue (typeof (T), json_reader);
}
public static T ToObject<T> (string json)
{
JsonReader reader = new JsonReader (json);
return (T) ReadValue (typeof (T), reader);
}
public static IJsonWrapper ToWrapper (WrapperFactory factory,
JsonReader reader)
{
return ReadValue (factory, reader);
}
public static IJsonWrapper ToWrapper (WrapperFactory factory,
string json)
{
JsonReader reader = new JsonReader (json);
return ReadValue (factory, reader);
}
public static void RegisterExporter<T> (ExporterFunc<T> exporter)
{
ExporterFunc exporter_wrapper =
delegate (object obj, JsonWriter writer) {
exporter ((T) obj, writer);
};
custom_exporters_table[typeof (T)] = exporter_wrapper;
}
public static void RegisterImporter<TJson, TValue> (
ImporterFunc<TJson, TValue> importer)
{
ImporterFunc importer_wrapper =
delegate (object input) {
return importer ((TJson) input);
};
RegisterImporter (custom_importers_table, typeof (TJson),
typeof (TValue), importer_wrapper);
}
public static void UnregisterExporters ()
{
custom_exporters_table.Clear ();
}
public static void UnregisterImporters ()
{
custom_importers_table.Clear ();
}
}
}
| |
using System;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
#if BASELINE
using MySql.Data.MySqlClient;
#endif
using Xunit;
namespace MySqlConnector.Tests;
public class MySqlConnectionStringBuilderTests
{
[Fact]
public void Defaults()
{
var csb = new MySqlConnectionStringBuilder();
Assert.False(csb.AllowLoadLocalInfile);
Assert.False(csb.AllowPublicKeyRetrieval);
Assert.False(csb.AllowUserVariables);
Assert.False(csb.AllowZeroDateTime);
Assert.True(csb.AutoEnlist);
#if BASELINE
Assert.Null(csb.CertificateFile);
Assert.Null(csb.CertificatePassword);
Assert.Null(csb.CertificateThumbprint);
#else
Assert.Equal(2, csb.CancellationTimeout);
Assert.Equal("", csb.CertificateFile);
Assert.Equal("", csb.CertificatePassword);
Assert.Equal("", csb.CertificateThumbprint);
#endif
Assert.Equal(MySqlCertificateStoreLocation.None, csb.CertificateStoreLocation);
Assert.Equal("", csb.CharacterSet);
Assert.Equal(0u, csb.ConnectionLifeTime);
Assert.Equal(MySqlConnectionProtocol.Sockets, csb.ConnectionProtocol);
#if BASELINE
Assert.False(csb.ConnectionReset);
#else
Assert.True(csb.ConnectionReset);
#pragma warning disable 618
Assert.Equal(0u, csb.ConnectionIdlePingTime);
Assert.True(csb.DeferConnectionReset);
#pragma warning restore 618
#endif
Assert.Equal(15u, csb.ConnectionTimeout);
Assert.False(csb.ConvertZeroDateTime);
#if !BASELINE
Assert.Equal(MySqlDateTimeKind.Unspecified, csb.DateTimeKind);
#endif
Assert.Equal("", csb.Database);
Assert.Equal(30u, csb.DefaultCommandTimeout);
#if !BASELINE
Assert.Equal("", csb.ApplicationName);
Assert.Equal(180u, csb.ConnectionIdleTimeout);
Assert.False(csb.ForceSynchronous);
Assert.Equal(MySqlGuidFormat.Default, csb.GuidFormat);
Assert.False(csb.IgnoreCommandTransaction);
Assert.Equal(MySqlLoadBalance.RoundRobin, csb.LoadBalance);
Assert.False(csb.IgnorePrepare);
#endif
Assert.False(csb.InteractiveSession);
Assert.Equal(0u, csb.Keepalive);
Assert.Equal(100u, csb.MaximumPoolSize);
Assert.Equal(0u, csb.MinimumPoolSize);
Assert.Equal("", csb.Password);
Assert.Equal("MYSQL", csb.PipeName);
#if !BASELINE
Assert.False(csb.NoBackslashEscapes);
Assert.Equal(MySqlServerRedirectionMode.Disabled, csb.ServerRedirectionMode);
#endif
Assert.False(csb.OldGuids);
Assert.False(csb.PersistSecurityInfo);
#if !BASELINE
Assert.True(csb.Pipelining);
#endif
Assert.True(csb.Pooling);
Assert.Equal(3306u, csb.Port);
Assert.Equal("", csb.Server);
#if !BASELINE
Assert.Equal("", csb.ServerRsaPublicKeyFile);
Assert.Equal("", csb.ServerSPN);
Assert.Equal("", csb.SslCa);
Assert.Equal("", csb.SslCert);
Assert.Equal("", csb.SslKey);
Assert.Equal("", csb.TlsCipherSuites);
Assert.Equal("", csb.TlsVersion);
#else
Assert.Null(csb.SslCa);
Assert.Null(csb.SslCert);
Assert.Null(csb.SslKey);
Assert.Null(csb.TlsVersion);
#endif
Assert.Equal(MySqlSslMode.Preferred, csb.SslMode);
Assert.True(csb.TreatTinyAsBoolean);
Assert.False(csb.UseCompression);
Assert.Equal("", csb.UserID);
Assert.False(csb.UseAffectedRows);
#if !BASELINE
Assert.True(csb.UseXaTransactions);
#endif
}
[Fact]
public void ParseConnectionString()
{
var csb = new MySqlConnectionStringBuilder
{
ConnectionString = "Data Source=db-server;" +
"Initial Catalog=schema_name;" +
"allow load local infile=true;" +
"allowpublickeyretrieval = true;" +
"Allow User Variables=true;" +
"allow zero datetime=true;" +
"auto enlist=False;" +
"certificate file=file.pfx;" +
"certificate password=Pass1234;" +
"certificate store location=CurrentUser;" +
"certificate thumb print=thumbprint123;" +
"Character Set=latin1;" +
"Compress=true;" +
"connect timeout=30;" +
"connection lifetime=15;" +
"ConnectionReset=false;" +
"Convert Zero Datetime=true;" +
#if !BASELINE
"datetimekind=utc;" +
#endif
"default command timeout=123;" +
#if !BASELINE
"application name=My Test Application;" +
"cancellation timeout = -1;" +
"connectionidletimeout=30;" +
"defer connection reset=true;" +
"forcesynchronous=true;" +
"ignore command transaction=true;" +
"server rsa public key file=rsa.pem;" +
"load balance=random;" +
"guidformat=timeswapbinary16;" +
"nobackslashescapes=true;" +
"pipelining=false;" +
"server redirection mode=required;" +
"server spn=mariadb/[email protected];" +
"use xa transactions=false;" +
"tls cipher suites=TLS_AES_128_CCM_8_SHA256,TLS_RSA_WITH_RC4_128_MD5;" +
"ignore prepare=true;" +
#endif
"interactive=true;" +
"Keep Alive=90;" +
"minpoolsize=5;" +
"maxpoolsize=15;" +
"OldGuids=true;" +
"persistsecurityinfo=yes;" +
"Pipe=MyPipe;" +
"Pooling=no;" +
"Port=1234;" +
"protocol=pipe;" +
"pwd=Pass1234;" +
"Treat Tiny As Boolean=false;" +
"ssl-ca=ca.pem;" +
"ssl-cert=client-cert.pem;" +
"ssl-key=client-key.pem;" +
"ssl mode=verifyca;" +
"tls version=Tls12, TLS v1.3;" +
"Uid=username;" +
"useaffectedrows=true"
};
Assert.True(csb.AllowLoadLocalInfile);
Assert.True(csb.AllowPublicKeyRetrieval);
Assert.True(csb.AllowUserVariables);
Assert.True(csb.AllowZeroDateTime);
Assert.False(csb.AutoEnlist);
#if !BASELINE
Assert.Equal(-1, csb.CancellationTimeout);
// Connector/NET treats "CertificateFile" (client certificate) and "SslCa" (server CA) as aliases
Assert.Equal("file.pfx", csb.CertificateFile);
#endif
Assert.Equal("Pass1234", csb.CertificatePassword);
Assert.Equal(MySqlCertificateStoreLocation.CurrentUser, csb.CertificateStoreLocation);
Assert.Equal("thumbprint123", csb.CertificateThumbprint);
Assert.Equal("latin1", csb.CharacterSet);
Assert.Equal(15u, csb.ConnectionLifeTime);
Assert.Equal(MySqlConnectionProtocol.NamedPipe, csb.ConnectionProtocol);
Assert.False(csb.ConnectionReset);
Assert.Equal(30u, csb.ConnectionTimeout);
Assert.True(csb.ConvertZeroDateTime);
#if !BASELINE
Assert.Equal(MySqlDateTimeKind.Utc, csb.DateTimeKind);
#endif
Assert.Equal("schema_name", csb.Database);
Assert.Equal(123u, csb.DefaultCommandTimeout);
#if !BASELINE
Assert.Equal("My Test Application", csb.ApplicationName);
Assert.Equal(30u, csb.ConnectionIdleTimeout);
#pragma warning disable 618
Assert.True(csb.DeferConnectionReset);
#pragma warning restore 618
Assert.True(csb.ForceSynchronous);
Assert.True(csb.IgnoreCommandTransaction);
Assert.Equal("rsa.pem", csb.ServerRsaPublicKeyFile);
Assert.Equal(MySqlLoadBalance.Random, csb.LoadBalance);
Assert.Equal(MySqlGuidFormat.TimeSwapBinary16, csb.GuidFormat);
Assert.True(csb.NoBackslashEscapes);
Assert.False(csb.Pipelining);
Assert.Equal(MySqlServerRedirectionMode.Required, csb.ServerRedirectionMode);
Assert.Equal("mariadb/[email protected]", csb.ServerSPN);
Assert.False(csb.UseXaTransactions);
Assert.Equal("TLS_AES_128_CCM_8_SHA256,TLS_RSA_WITH_RC4_128_MD5", csb.TlsCipherSuites);
Assert.True(csb.IgnorePrepare);
#endif
Assert.True(csb.InteractiveSession);
Assert.Equal(90u, csb.Keepalive);
Assert.Equal(15u, csb.MaximumPoolSize);
Assert.Equal(5u, csb.MinimumPoolSize);
Assert.Equal("Pass1234", csb.Password);
Assert.Equal("MyPipe", csb.PipeName);
Assert.True(csb.OldGuids);
Assert.True(csb.PersistSecurityInfo);
Assert.False(csb.Pooling);
Assert.Equal(1234u, csb.Port);
Assert.Equal("db-server", csb.Server);
Assert.False(csb.TreatTinyAsBoolean);
Assert.Equal("ca.pem", csb.SslCa);
Assert.Equal("client-cert.pem", csb.SslCert);
Assert.Equal("client-key.pem", csb.SslKey);
Assert.Equal(MySqlSslMode.VerifyCA, csb.SslMode);
#if BASELINE
Assert.Equal("Tls12, Tls13", csb.TlsVersion);
#else
Assert.Equal("TLS 1.2, TLS 1.3", csb.TlsVersion);
#endif
Assert.True(csb.UseAffectedRows);
Assert.True(csb.UseCompression);
Assert.Equal("username", csb.UserID);
}
[Fact]
public void EnumInvalidOperation()
{
Assert.Throws<ArgumentException>(() => new MySqlConnectionStringBuilder("ssl mode=invalid;"));
}
#if !BASELINE
[Fact]
public void ConstructWithNull()
{
var csb = new MySqlConnectionStringBuilder(default(string));
Assert.Equal("", csb.ConnectionString);
}
#endif
[Fact]
public void ConstructWithEmptyString()
{
var csb = new MySqlConnectionStringBuilder("");
Assert.Equal("", csb.ConnectionString);
}
[Fact]
public void SetConnectionStringToNull()
{
var csb = new MySqlConnectionStringBuilder
{
ConnectionString = null,
};
Assert.Equal("", csb.ConnectionString);
}
[Fact]
public void SetConnectionStringToEmptyString()
{
var csb = new MySqlConnectionStringBuilder
{
ConnectionString = "",
};
Assert.Equal("", csb.ConnectionString);
}
[Fact]
public void SetServerToNull()
{
var csb = new MySqlConnectionStringBuilder("Server=test");
csb.Server = null;
Assert.Equal("", csb.ConnectionString);
}
[Fact]
public void SetUserIdToNull()
{
var csb = new MySqlConnectionStringBuilder("User ID=test");
csb.UserID = null;
Assert.Equal("", csb.ConnectionString);
}
[Fact]
public void SetPasswordToNull()
{
var csb = new MySqlConnectionStringBuilder("Password=test");
csb.Password = null;
Assert.Equal("", csb.ConnectionString);
}
[Fact]
public void SetDatabaseToNull()
{
var csb = new MySqlConnectionStringBuilder("Database=test");
csb.Database = null;
Assert.Equal("", csb.ConnectionString);
}
[Fact]
public void SetPipeNameToNull()
{
var csb = new MySqlConnectionStringBuilder("Pipe=test");
csb.PipeName = null;
Assert.Equal("", csb.ConnectionString);
}
[Fact]
public void SetCertificateFileToNull()
{
var csb = new MySqlConnectionStringBuilder("CertificateFile=test");
csb.CertificateFile = null;
Assert.Equal("", csb.ConnectionString);
}
[Fact]
public void SetCertificatePasswordToNull()
{
var csb = new MySqlConnectionStringBuilder("CertificatePassword=test");
csb.CertificatePassword = null;
Assert.Equal("", csb.ConnectionString);
}
[Fact]
public void SetSslCaToNull()
{
var csb = new MySqlConnectionStringBuilder("SslCa=test");
csb.SslCa = null;
Assert.Equal("", csb.ConnectionString);
}
[Fact]
public void SetSslCertToNull()
{
var csb = new MySqlConnectionStringBuilder("SslCert=test");
csb.SslCert = null;
Assert.Equal("", csb.ConnectionString);
}
[Fact]
public void SetSslKeyToNull()
{
var csb = new MySqlConnectionStringBuilder("SslKey=test");
csb.SslKey = null;
Assert.Equal("", csb.ConnectionString);
}
[Fact]
public void SetCertificateThumbprintToNull()
{
var csb = new MySqlConnectionStringBuilder("CertificateThumbprint=test");
csb.CertificateThumbprint = null;
Assert.Equal("", csb.ConnectionString);
}
[Fact]
public void SetCharacterSetToNull()
{
var csb = new MySqlConnectionStringBuilder("CharSet=test");
csb.CharacterSet = null;
Assert.Equal("", csb.ConnectionString);
}
#if !BASELINE
[Fact]
public void SetApplicationNameToNull()
{
var csb = new MySqlConnectionStringBuilder("ApplicationName=test");
csb.ApplicationName = null;
Assert.Equal("", csb.ConnectionString);
}
[Fact]
public void SetServerRsaPublicKeyFileToNull()
{
var csb = new MySqlConnectionStringBuilder("ServerRSAPublicKeyFile=test");
csb.ServerRsaPublicKeyFile = null;
Assert.Equal("", csb.ConnectionString);
}
[Fact]
public void SetServerSPNToNull()
{
var csb = new MySqlConnectionStringBuilder("ServerSPN=test");
csb.ServerSPN = null;
Assert.Equal("", csb.ConnectionString);
}
#endif
[Theory]
#if !BASELINE
[InlineData("Tls", "0")]
[InlineData("Tls1", "0")]
[InlineData("Tlsv1", "0")]
[InlineData("Tlsv1.0", "0")]
[InlineData("TLS 1.0", "0")]
[InlineData("TLS v1.0", "0")]
[InlineData("Tls11", "1")]
[InlineData("Tlsv11", "1")]
[InlineData("Tlsv1.1", "1")]
[InlineData("TLS 1.1", "1")]
[InlineData("TLS v1.1", "1")]
#endif
[InlineData("Tls12", "2")]
[InlineData("Tlsv12", "2")]
[InlineData("Tlsv1.2", "2")]
[InlineData("TLS 1.2", "2")]
[InlineData("TLS v1.2", "2")]
[InlineData("Tls13", "3")]
[InlineData("Tlsv13", "3")]
[InlineData("Tlsv1.3", "3")]
[InlineData("TLS 1.3", "3")]
[InlineData("TLS v1.3", "3")]
#if !BASELINE
[InlineData("Tls,Tls", "0")]
[InlineData("Tls1.1,Tls v1.1, TLS 1.1", "1")]
[InlineData("Tls12,Tls10", "0,2")]
[InlineData("TLS v1.3, TLS12, Tls 1.1", "1,2,3")]
#endif
[InlineData("TLS v1.3, TLS12", "2,3")]
public void ParseTlsVersion(string input, string expected)
{
var csb = new MySqlConnectionStringBuilder { TlsVersion = input };
#if !BASELINE
string[] normalizedVersions = new[] { "TLS 1.0", "TLS 1.1", "TLS 1.2", "TLS 1.3" };
#else
string[] normalizedVersions = new[] { "Tls", "Tls11", "Tls12", "Tls13" };
#endif
var expectedTlsVersion = string.Join(", ", expected.Split(',').Select(int.Parse).Select(x => normalizedVersions[x]));
Assert.Equal(expectedTlsVersion, csb.TlsVersion);
}
[Fact]
public void ParseInvalidTlsVersion()
{
var csb = new MySqlConnectionStringBuilder();
Assert.Throws<ArgumentException>(() => csb.TlsVersion = "Tls14");
Assert.Throws<ArgumentException>(() => new MySqlConnectionStringBuilder("TlsVersion=Tls14"));
}
[Theory]
#if BASELINE
[InlineData("AllowPublicKeyRetrieval", false)]
#else
[InlineData("Allow Public Key Retrieval", false)]
#endif
[InlineData("Allow User Variables", true)]
[InlineData("Allow Zero DateTime", true)]
[InlineData("Auto Enlist", true)]
[InlineData("Certificate File", "C:\\cert.pfx")]
[InlineData("Certificate Password", "password")]
[InlineData("Certificate Store Location", MySqlCertificateStoreLocation.CurrentUser)]
[InlineData("Character Set", "utf8mb4")]
[InlineData("Connection Lifetime", 30u)]
[InlineData("Connection Protocol", MySqlConnectionProtocol.NamedPipe)]
[InlineData("Connection Reset", true)]
#if BASELINE
[InlineData("Connect Timeout", 10u)]
#else
[InlineData("Connection Timeout", 10u)]
#endif
[InlineData("Convert Zero DateTime", true)]
[InlineData("Database", "test")]
[InlineData("Default Command Timeout", 15u)]
[InlineData("Interactive Session", false)]
[InlineData("Keep Alive", 5u)]
[InlineData("Minimum Pool Size", 1u)]
[InlineData("Maximum Pool Size", 5u)]
[InlineData("Old Guids", true)]
[InlineData("Password", "password")]
[InlineData("Persist Security Info", true)]
[InlineData("Pipe Name", "test")]
[InlineData("Pooling", false)]
[InlineData("Port", 3307u)]
[InlineData("Server", "localhost")]
[InlineData("SSL Mode", MySqlSslMode.Required)]
#if BASELINE
[InlineData("TLS version", "Tls12")]
#else
[InlineData("TLS Version", "TLS 1.2")]
#endif
[InlineData("Treat Tiny As Boolean", false)]
[InlineData("Use Affected Rows", false)]
[InlineData("Use Compression", true)]
[InlineData("User ID", "user")]
#if !BASELINE
// misspelled
[InlineData("Allow Load Local Infile", true)]
// property name doesn't work with a space
[InlineData("Certificate Thumbprint", "01020304")]
[InlineData("SSL CA", "C:\\ca.pem")]
[InlineData("SSL Cert", "C:\\cert.pem")]
[InlineData("SSL Key", "C:\\key.pem")]
// not supported
[InlineData("Application Name", "MyApp")]
[InlineData("Cancellation Timeout", 5)]
[InlineData("Connection Idle Timeout", 10u)]
[InlineData("DateTime Kind", MySqlDateTimeKind.Utc)]
[InlineData("Force Synchronous", true)]
[InlineData("GUID Format", MySqlGuidFormat.Binary16)]
[InlineData("Ignore Command Transaction", true)]
[InlineData("Ignore Prepare", false)]
[InlineData("Load Balance", MySqlLoadBalance.Random)]
[InlineData("No Backslash Escapes", true)]
[InlineData("Server Redirection Mode", MySqlServerRedirectionMode.Required)]
[InlineData("Server RSA Public Key File", "C:\\server.pem")]
[InlineData("Server SPN", "test")]
[InlineData("TLS Cipher Suites", "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384")]
[InlineData("Use XA Transactions", false)]
#endif
public void NamedProperty(string propertyName, object value)
{
var stringValue = Convert.ToString(value, CultureInfo.InvariantCulture);
#if BASELINE
// fix some properties that are spelt differently
propertyName = propertyName.Replace("SSL ", "Ssl ").Replace("DateTime", "Datetime");
#endif
for (var i = 0; i < 2; i++)
{
var csb = new MySqlConnectionStringBuilder();
#if !BASELINE
// Connector/NET sets all properties to default values
Assert.False(csb.ContainsKey(propertyName));
#endif
Assert.False(csb.TryGetValue(propertyName, out var setValue));
Assert.Null(setValue);
ICustomTypeDescriptor typeDescriptor = csb;
var propertyDescriptor = typeDescriptor.GetProperties().Cast<PropertyDescriptor>().SingleOrDefault(x => x.DisplayName == propertyName);
Assert.NotNull(propertyDescriptor);
if (i == 0)
csb[propertyName] = value;
else
csb.ConnectionString = propertyName + " = " + stringValue;
Assert.True(csb.ContainsKey(propertyName));
#if !BASELINE
// https://bugs.mysql.com/bug.php?id=104910
Assert.True(csb.TryGetValue(propertyName, out setValue));
Assert.Equal(stringValue, setValue);
var propertyDescriptorValue = propertyDescriptor.GetValue(csb);
Assert.Equal(stringValue, propertyDescriptorValue);
#endif
Assert.Equal(value, csb[propertyName]);
}
}
}
| |
using System;
using System.IO;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Paddings;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.Encoders;
namespace Org.BouncyCastle.Crypto.Examples
{
/**
* DesExample is a simple DES based encryptor/decryptor.
* <p>
* The program is command line driven, with the input
* and output files specified on the command line.
* <pre>
* java org.bouncycastle.crypto.examples.DesExample infile outfile [keyfile]
* </pre>
* A new key is generated for each encryption, if key is not specified,
* then the example will assume encryption is required, and as output
* create deskey.dat in the current directory. This key is a hex
* encoded byte-stream that is used for the decryption. The output
* file is Hex encoded, 60 characters wide text file.
* </p>
* <p>
* When encrypting;
* <ul>
* <li>the infile is expected to be a byte stream (text or binary)</li>
* <li>there is no keyfile specified on the input line</li>
* </ul>
* </p>
* <p>
* When decrypting;
* <li>the infile is expected to be the 60 character wide base64
* encoded file</li>
* <li>the keyfile is expected to be a base64 encoded file</li>
* </p>
* <p>
* This example shows how to use the light-weight API, DES and
* the filesystem for message encryption and decryption.
* </p>
*/
public class DesExample
{
// Encrypting or decrypting ?
private bool encrypt = true;
// To hold the initialised DESede cipher
private PaddedBufferedBlockCipher cipher = null;
// The input stream of bytes to be processed for encryption
private Stream inStr = null;
// The output stream of bytes to be procssed
private Stream outStr = null;
// The key
private byte[] key = null;
/*
* start the application
*/
public static int Main(
string[] args)
{
bool encrypt = true;
string infile = null;
string outfile = null;
string keyfile = null;
if (args.Length < 2)
{
// Console.Error.WriteLine("Usage: java " + typeof(DesExample).Name + " infile outfile [keyfile]");
Console.Error.WriteLine("Usage: " + typeof(DesExample).Name + " infile outfile [keyfile]");
return 1;
}
keyfile = "deskey.dat";
infile = args[0];
outfile = args[1];
if (args.Length > 2)
{
encrypt = false;
keyfile = args[2];
}
try
{
DesExample de = new DesExample(infile, outfile, keyfile, encrypt);
de.process();
}
catch (Exception)
{
return 1;
}
return 0;
}
// Default constructor, used for the usage message
public DesExample()
{
}
/*
* Constructor, that takes the arguments appropriate for
* processing the command line directives.
*/
public DesExample(
string infile,
string outfile,
string keyfile,
bool encrypt)
{
/*
* First, determine that infile & keyfile exist as appropriate.
*
* This will also create the BufferedInputStream as required
* for reading the input file. All input files are treated
* as if they are binary, even if they contain text, it's the
* bytes that are encrypted.
*/
this.encrypt = encrypt;
try
{
inStr = File.OpenRead(infile);
}
catch (FileNotFoundException e)
{
Console.Error.WriteLine("Input file not found ["+infile+"]");
throw e;
}
try
{
outStr = File.Create(outfile);
}
catch (IOException e)
{
Console.Error.WriteLine("Output file not created ["+outfile+"]");
throw e;
}
if (encrypt)
{
try
{
/*
* The process of creating a new key requires a
* number of steps.
*
* First, create the parameters for the key generator
* which are a secure random number generator, and
* the length of the key (in bits).
*/
SecureRandom sr = new SecureRandom();
KeyGenerationParameters kgp = new KeyGenerationParameters(
sr,
DesEdeParameters.DesEdeKeyLength * 8);
/*
* Second, initialise the key generator with the parameters
*/
DesEdeKeyGenerator kg = new DesEdeKeyGenerator();
kg.Init(kgp);
/*
* Third, and finally, generate the key
*/
key = kg.GenerateKey();
/*
* We can now output the key to the file, but first
* hex Encode the key so that we can have a look
* at it with a text editor if we so desire
*/
using (Stream keystream = File.Create(keyfile))
{
Hex.Encode(key, keystream);
}
}
catch (IOException e)
{
Console.Error.WriteLine("Could not decryption create key file "+
"["+keyfile+"]");
throw e;
}
}
else
{
try
{
// TODO This block is a bit dodgy
// read the key, and Decode from hex encoding
Stream keystream = File.OpenRead(keyfile);
// int len = keystream.available();
int len = (int) keystream.Length;
byte[] keyhex = new byte[len];
keystream.Read(keyhex, 0, len);
key = Hex.Decode(keyhex);
}
catch (IOException e)
{
Console.Error.WriteLine("Decryption key file not found, "
+ "or not valid ["+keyfile+"]");
throw e;
}
}
}
private void process()
{
/*
* Setup the DESede cipher engine, create a PaddedBufferedBlockCipher
* in CBC mode.
*/
cipher = new PaddedBufferedBlockCipher(
new CbcBlockCipher(new DesEdeEngine()));
/*
* The input and output streams are currently set up
* appropriately, and the key bytes are ready to be
* used.
*
*/
if (encrypt)
{
performEncrypt(key);
}
else
{
performDecrypt(key);
}
// after processing clean up the files
try
{
inStr.Close();
outStr.Flush();
outStr.Close();
}
catch (IOException)
{
}
}
/*
* This method performs all the encryption and writes
* the cipher text to the buffered output stream created
* previously.
*/
private void performEncrypt(byte[] key)
{
// initialise the cipher with the key bytes, for encryption
cipher.Init(true, new KeyParameter(key));
/*
* Create some temporary byte arrays for use in
* encryption, make them a reasonable size so that
* we don't spend forever reading small chunks from
* a file.
*
* There is no particular reason for using getBlockSize()
* to determine the size of the input chunk. It just
* was a convenient number for the example.
*/
// int inBlockSize = cipher.getBlockSize() * 5;
int inBlockSize = 47;
int outBlockSize = cipher.GetOutputSize(inBlockSize);
byte[] inblock = new byte[inBlockSize];
byte[] outblock = new byte[outBlockSize];
/*
* now, read the file, and output the chunks
*/
try
{
int inL;
int outL;
while ((inL = inStr.Read(inblock, 0, inBlockSize)) > 0)
{
outL = cipher.ProcessBytes(inblock, 0, inL, outblock, 0);
/*
* Before we write anything out, we need to make sure
* that we've got something to write out.
*/
if (outL > 0)
{
Hex.Encode(outblock, 0, outL, outStr);
outStr.WriteByte((byte)'\n');
}
}
try
{
/*
* Now, process the bytes that are still buffered
* within the cipher.
*/
outL = cipher.DoFinal(outblock, 0);
if (outL > 0)
{
Hex.Encode(outblock, 0, outL, outStr);
outStr.WriteByte((byte) '\n');
}
}
catch (CryptoException)
{
}
}
catch (IOException ioeread)
{
Console.Error.WriteLine(ioeread.StackTrace);
}
}
/*
* This method performs all the decryption and writes
* the plain text to the buffered output stream created
* previously.
*/
private void performDecrypt(byte[] key)
{
// initialise the cipher for decryption
cipher.Init(false, new KeyParameter(key));
/*
* As the decryption is from our preformatted file,
* and we know that it's a hex encoded format, then
* we wrap the InputStream with a BufferedReader
* so that we can read it easily.
*/
// BufferedReader br = new BufferedReader(new StreamReader(inStr));
StreamReader br = new StreamReader(inStr); // 'inStr' already buffered
/*
* now, read the file, and output the chunks
*/
try
{
int outL;
byte[] inblock = null;
byte[] outblock = null;
string rv = null;
while ((rv = br.ReadLine()) != null)
{
inblock = Hex.Decode(rv);
outblock = new byte[cipher.GetOutputSize(inblock.Length)];
outL = cipher.ProcessBytes(inblock, 0, inblock.Length, outblock, 0);
/*
* Before we write anything out, we need to make sure
* that we've got something to write out.
*/
if (outL > 0)
{
outStr.Write(outblock, 0, outL);
}
}
try
{
/*
* Now, process the bytes that are still buffered
* within the cipher.
*/
outL = cipher.DoFinal(outblock, 0);
if (outL > 0)
{
outStr.Write(outblock, 0, outL);
}
}
catch (CryptoException)
{
}
}
catch (IOException ioeread)
{
Console.Error.WriteLine(ioeread.StackTrace);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using ApiExplorerWebSite;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Testing;
using Newtonsoft.Json;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.FunctionalTests
{
public class ApiExplorerTest : IClassFixture<MvcTestFixture<ApiExplorerWebSite.Startup>>
{
public ApiExplorerTest(MvcTestFixture<ApiExplorerWebSite.Startup> fixture)
{
Client = fixture.CreateDefaultClient();
}
public HttpClient Client { get; }
[Fact]
public async Task ApiExplorer_IsVisible_EnabledWithConvention()
{
// Arrange & Act
var response = await Client.GetAsync("http://localhost/ApiExplorerVisibilityEnabledByConvention");
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
Assert.Single(result);
}
[Fact]
public async Task ApiExplorer_IsVisible_DisabledWithConvention()
{
// Arrange & Act
var response = await Client.GetAsync("http://localhost/ApiExplorerVisibilityDisabledByConvention");
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
Assert.Empty(result);
}
[Fact]
public async Task ApiExplorer_IsVisible_DisabledWithAttribute()
{
// Arrange & Act
var response = await Client.GetAsync("http://localhost/ApiExplorerVisibilitySetExplicitly/Disabled");
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
Assert.Empty(result);
}
[Fact]
public async Task ApiExplorer_IsVisible_EnabledWithAttribute()
{
// Arrange & Act
var response = await Client.GetAsync("http://localhost/ApiExplorerVisibilitySetExplicitly/Enabled");
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
Assert.Single(result);
}
[Fact]
public async Task ApiExplorer_GroupName_SetByConvention()
{
// Arrange & Act
var response = await Client.GetAsync("http://localhost/ApiExplorerNameSetByConvention");
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
Assert.Equal("ApiExplorerNameSetByConvention", description.GroupName);
}
[Fact]
public async Task ApiExplorer_GroupName_SetByAttributeOnController()
{
// Arrange & Act
var response = await Client.GetAsync("http://localhost/ApiExplorerNameSetExplicitly/SetOnController");
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
Assert.Equal("SetOnController", description.GroupName);
}
[Fact]
public async Task ApiExplorer_GroupName_SetByAttributeOnAction()
{
// Arrange & Act
var response = await Client.GetAsync("http://localhost/ApiExplorerNameSetExplicitly/SetOnAction");
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
Assert.Equal("SetOnAction", description.GroupName);
}
[Fact]
public async Task ApiExplorer_GroupName_SetByEndpointMetadataOnController()
{
// Arrange & Act
var response = await Client.GetAsync("http://localhost/ApiExplorerApiController/ActionWithIdParameter");
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
Assert.Equal("GroupNameOnController", description.GroupName);
}
[Fact]
public async Task ApiExplorer_GroupName_SetByEndpointMetadataOnAction()
{
// Arrange & Act
var response = await Client.GetAsync("http://localhost/ApiExplorerApiController/ActionWithSomeParameters");
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
Assert.Equal("GroupNameOnAction", description.GroupName);
}
[Fact]
public async Task ApiExplorer_RouteTemplate_DisplaysFixedRoute()
{
// Arrange & Act
var response = await Client.GetAsync("http://localhost/ApiExplorerRouteAndPathParametersInformation");
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
Assert.Equal("ApiExplorerRouteAndPathParametersInformation", description.RelativePath);
}
[Fact]
public async Task ApiExplorer_RouteTemplate_DisplaysRouteWithParameters()
{
// Arrange & Act
var response = await Client.GetAsync("http://localhost/ApiExplorerRouteAndPathParametersInformation/5");
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
Assert.Equal("ApiExplorerRouteAndPathParametersInformation/{id}", description.RelativePath);
var parameter = Assert.Single(description.ParameterDescriptions);
Assert.Equal("id", parameter.Name);
Assert.False(parameter.RouteInfo.IsOptional);
Assert.Equal("Path", parameter.Source);
Assert.Empty(parameter.RouteInfo.ConstraintTypes);
}
[Fact]
public async Task ApiExplorer_RouteTemplate_StripsInlineConstraintsFromThePath()
{
// Arrange
var url = "http://localhost/ApiExplorerRouteAndPathParametersInformation/Constraint/5";
// Act
var response = await Client.GetAsync(url);
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
Assert.Equal("ApiExplorerRouteAndPathParametersInformation/Constraint/{integer}", description.RelativePath);
var parameter = Assert.Single(description.ParameterDescriptions);
Assert.Equal("integer", parameter.Name);
Assert.False(parameter.RouteInfo.IsOptional);
Assert.Equal("Path", parameter.Source);
Assert.Equal("IntRouteConstraint", Assert.Single(parameter.RouteInfo.ConstraintTypes));
}
[Fact]
public async Task ApiExplorer_RouteTemplate_StripsCatchAllsFromThePath()
{
// Arrange
var url = "http://localhost/ApiExplorerRouteAndPathParametersInformation/CatchAll/5";
// Act
var response = await Client.GetAsync(url);
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
Assert.Equal("ApiExplorerRouteAndPathParametersInformation/CatchAll/{parameter}", description.RelativePath);
var parameter = Assert.Single(description.ParameterDescriptions);
Assert.Equal("parameter", parameter.Name);
Assert.False(parameter.RouteInfo.IsOptional);
Assert.Equal("Path", parameter.Source);
}
[Fact]
public async Task ApiExplorer_RouteTemplate_StripsCatchAllsWithConstraintsFromThePath()
{
// Arrange
var url = "http://localhost/ApiExplorerRouteAndPathParametersInformation/CatchAllAndConstraint/5";
// Act
var response = await Client.GetAsync(url);
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
Assert.Equal(
"ApiExplorerRouteAndPathParametersInformation/CatchAllAndConstraint/{integer}",
description.RelativePath);
var parameter = Assert.Single(description.ParameterDescriptions);
Assert.Equal("integer", parameter.Name);
Assert.False(parameter.RouteInfo.IsOptional);
Assert.Equal("Path", parameter.Source);
Assert.Equal("IntRouteConstraint", Assert.Single(parameter.RouteInfo.ConstraintTypes));
}
[Fact]
public async Task ApiExplorer_RouteTemplateStripsMultipleConstraints_OnTheSamePathSegment()
{
// Arrange
var url = "http://localhost/ApiExplorerRouteAndPathParametersInformation/"
+ "MultipleParametersInSegment/12-01-1987";
var expectedRelativePath = "ApiExplorerRouteAndPathParametersInformation/"
+ "MultipleParametersInSegment/{month}-{day}-{year}";
// Act
var response = await Client.GetAsync(url);
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
Assert.Equal(expectedRelativePath, description.RelativePath);
var month = Assert.Single(description.ParameterDescriptions, p => p.Name == "month");
Assert.False(month.RouteInfo.IsOptional);
Assert.Equal("Path", month.Source);
Assert.Equal("RangeRouteConstraint", Assert.Single(month.RouteInfo.ConstraintTypes));
var day = Assert.Single(description.ParameterDescriptions, p => p.Name == "day");
Assert.False(day.RouteInfo.IsOptional);
Assert.Equal("Path", day.Source);
Assert.Equal("IntRouteConstraint", Assert.Single(day.RouteInfo.ConstraintTypes));
var year = Assert.Single(description.ParameterDescriptions, p => p.Name == "year");
Assert.False(year.RouteInfo.IsOptional);
Assert.Equal("Path", year.Source);
Assert.Equal("IntRouteConstraint", Assert.Single(year.RouteInfo.ConstraintTypes));
}
[Fact]
public async Task ApiExplorer_RouteTemplateStripsMultipleConstraints_InMultipleSegments()
{
// Arrange
var url = "http://localhost/ApiExplorerRouteAndPathParametersInformation/"
+ "MultipleParametersInMultipleSegments/12/01/1987";
var expectedRelativePath = "ApiExplorerRouteAndPathParametersInformation/"
+ "MultipleParametersInMultipleSegments/{month}/{day}/{year}";
// Act
var response = await Client.GetAsync(url);
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
Assert.Equal(expectedRelativePath, description.RelativePath);
var month = Assert.Single(description.ParameterDescriptions, p => p.Name == "month");
Assert.False(month.RouteInfo.IsOptional);
Assert.Equal("Path", month.Source);
Assert.Equal("RangeRouteConstraint", Assert.Single(month.RouteInfo.ConstraintTypes));
var day = Assert.Single(description.ParameterDescriptions, p => p.Name == "day");
Assert.True(day.RouteInfo.IsOptional);
Assert.Equal("ModelBinding", day.Source);
Assert.Equal("IntRouteConstraint", Assert.Single(day.RouteInfo.ConstraintTypes));
var year = Assert.Single(description.ParameterDescriptions, p => p.Name == "year");
Assert.True(year.RouteInfo.IsOptional);
Assert.Equal("ModelBinding", year.Source);
Assert.Equal("IntRouteConstraint", Assert.Single(year.RouteInfo.ConstraintTypes));
}
[Fact]
public async Task ApiExplorer_DescribeParameters_FromAllSources()
{
// Arrange
var url = "http://localhost/ApiExplorerRouteAndPathParametersInformation/MultipleTypesOfParameters/1/2/3";
var expectedRelativePath = "ApiExplorerRouteAndPathParametersInformation/"
+ "MultipleTypesOfParameters/{path}/{pathAndQuery}/{pathAndFromBody}";
// Act
var response = await Client.GetAsync(url);
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
Assert.Equal(expectedRelativePath, description.RelativePath);
var path = Assert.Single(description.ParameterDescriptions, p => p.Name == "path");
Assert.Equal("Path", path.Source);
var pathAndQuery = Assert.Single(description.ParameterDescriptions, p => p.Name == "pathAndQuery");
Assert.Equal("Path", pathAndQuery.Source);
Assert.Single(description.ParameterDescriptions, p => p.Name == "pathAndFromBody" && p.Source == "Body");
Assert.Single(description.ParameterDescriptions, p => p.Name == "pathAndFromBody" && p.Source == "Path");
}
[Fact]
public async Task ApiExplorer_RouteTemplate_MakesParametersOptional()
{
// Arrange & Act
var response = await Client.GetAsync(
"http://localhost/ApiExplorerRouteAndPathParametersInformation/Optional/");
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
Assert.Equal("ApiExplorerRouteAndPathParametersInformation/Optional/{id}", description.RelativePath);
var id = Assert.Single(description.ParameterDescriptions, p => p.Name == "id");
Assert.True(id.RouteInfo.IsOptional);
Assert.Equal("ModelBinding", id.Source);
}
[Fact]
public async Task ApiExplorer_HttpMethod_All()
{
// Arrange & Act
var response = await Client.GetAsync("http://localhost/ApiExplorerHttpMethod/All");
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
Assert.Null(description.HttpMethod);
}
[Fact]
public async Task ApiExplorer_HttpMethod_Single_GET()
{
// Arrange & Act
var response = await Client.GetAsync("http://localhost/ApiExplorerHttpMethod/Get");
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
Assert.Equal("GET", description.HttpMethod);
}
// This is hitting one action with two allowed methods (using [AcceptVerbs]). This should
// return two api descriptions.
[Fact]
public async Task ApiExplorer_HttpMethod_Single_PUT()
{
// Arrange
var request = new HttpRequestMessage(
new HttpMethod("PUT"),
"http://localhost/ApiExplorerHttpMethod/Single");
// Act
var response = await Client.SendAsync(request);
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
Assert.Equal(2, result.Count);
Assert.Single(result, d => d.HttpMethod == "PUT");
Assert.Single(result, d => d.HttpMethod == "POST");
}
// This is hitting one action with two allowed methods (using [AcceptVerbs]). This should
// return two api descriptions.
[Fact]
public async Task ApiExplorer_HttpMethod_Single_POST()
{
// Arrange
var request = new HttpRequestMessage(
new HttpMethod("POST"),
"http://localhost/ApiExplorerHttpMethod/Single");
// Act
var response = await Client.SendAsync(request);
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
Assert.Equal(2, result.Count);
Assert.Single(result, d => d.HttpMethod == "PUT");
Assert.Single(result, d => d.HttpMethod == "POST");
}
[Theory]
[InlineData("GetVoidWithExplicitResponseTypeStatusCode")]
[InlineData("GetTaskWithExplicitResponseTypeStatusCode")]
public async Task ApiExplorer_ResponseType_VoidWithResponseTypeAttributeStatusCode(string action)
{
// Arrange & Act
var response = await Client.GetAsync(
"http://localhost/ApiExplorerResponseTypeWithAttribute/" + action);
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
var responseType = Assert.Single(description.SupportedResponseTypes);
Assert.Equal(typeof(void).FullName, responseType.ResponseType);
Assert.Equal(204, responseType.StatusCode);
Assert.Empty(responseType.ResponseFormats);
}
[Theory]
[InlineData("GetVoid")]
[InlineData("GetTask")]
public async Task ApiExplorer_ResponseType_VoidWithoutAttributeDefaultStatusCode(string action)
{
// Arrange & Act
var response = await Client.GetAsync(
"http://localhost/ApiExplorerResponseTypeWithoutAttribute/" + action);
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
var responseType = Assert.Single(description.SupportedResponseTypes);
Assert.Equal(typeof(void).FullName, responseType.ResponseType);
Assert.Equal(200, responseType.StatusCode);
Assert.Empty(responseType.ResponseFormats);
}
[Theory]
[InlineData("GetObject")]
[InlineData("GetIActionResult")]
[InlineData("GetDerivedActionResult")]
[InlineData("GetTaskOfObject")]
[InlineData("GetTaskOfIActionResult")]
[InlineData("GetTaskOfDerivedActionResult")]
public async Task ApiExplorer_ResponseType_UnknownWithoutAttribute(string action)
{
// Arrange & Act
var response = await Client.GetAsync(
"http://localhost/ApiExplorerResponseTypeWithoutAttribute/" + action);
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
Assert.Empty(description.SupportedResponseTypes);
}
[Theory]
[InlineData("GetProduct", "ApiExplorerWebSite.Product")]
[InlineData("GetActionResultProduct", "ApiExplorerWebSite.Product")]
[InlineData("GetInt", "System.Int32")]
[InlineData("GetTaskOfProduct", "ApiExplorerWebSite.Product")]
[InlineData("GetTaskOfInt", "System.Int32")]
public async Task ApiExplorer_ResponseType_KnownWithoutAttribute(string action, string type)
{
// Arrange & Act
var response = await Client.GetAsync(
"http://localhost/ApiExplorerResponseTypeWithoutAttribute/" + action);
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
var expectedMediaTypes = new[] { "application/json", "application/xml", "text/json", "text/xml" };
// Assert
var description = Assert.Single(result);
var responseType = Assert.Single(description.SupportedResponseTypes);
Assert.Equal(200, responseType.StatusCode);
Assert.Equal(type, responseType.ResponseType);
Assert.Equal(expectedMediaTypes, GetSortedMediaTypes(responseType));
}
[Fact]
public async Task ApiExplorer_ResponseType_KnownWithoutAttribute_ReturnVoid()
{
// Arrange
var type = "ApiExplorerWebSite.Customer";
var expectedMediaTypes = new[] { "application/json", "application/xml", "text/json", "text/xml" };
// Act
var response = await Client.GetAsync(
"http://localhost/ApiExplorerResponseTypeWithAttribute/GetVoid");
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
var responseType = Assert.Single(description.SupportedResponseTypes);
Assert.Equal(200, responseType.StatusCode);
Assert.Equal(type, responseType.ResponseType);
Assert.Equal(expectedMediaTypes, GetSortedMediaTypes(responseType));
}
[Fact]
public async Task ApiExplorer_ResponseType_DifferentOnAttributeThanReturnType()
{
// Arrange
var type = "ApiExplorerWebSite.Customer";
var expectedMediaTypes = new[] { "application/json", "application/xml", "text/json", "text/xml" };
// Act
var response = await Client.GetAsync(
"http://localhost/ApiExplorerResponseTypeWithAttribute/GetProduct");
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
var responseType = Assert.Single(description.SupportedResponseTypes);
Assert.Equal(200, responseType.StatusCode);
Assert.Equal(type, responseType.ResponseType);
Assert.Equal(expectedMediaTypes, GetSortedMediaTypes(responseType));
}
[Theory]
[InlineData("GetObject", "ApiExplorerWebSite.Product")]
[InlineData("GetIActionResult", "System.String")]
[InlineData("GetTask", "System.Int32")]
public async Task ApiExplorer_ResponseType_KnownWithAttribute(string action, string type)
{
// Arrange & Act
var response = await Client.GetAsync(
"http://localhost/ApiExplorerResponseTypeWithAttribute/" + action);
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
var responseType = Assert.Single(description.SupportedResponseTypes);
Assert.Equal(type, responseType.ResponseType);
Assert.Equal(200, responseType.StatusCode);
var responseFormat = Assert.Single(responseType.ResponseFormats);
Assert.Equal("application/json", responseFormat.MediaType);
}
[Fact]
public async Task ExplicitResponseTypeDecoration_SuppressesDefaultStatus()
{
// Arrange
var type1 = typeof(ApiExplorerWebSite.Product).FullName;
var type2 = typeof(SerializableError).FullName;
var expectedMediaTypes = new[] { "application/json", "application/xml", "text/json", "text/xml" };
// Act
var response = await Client.GetAsync(
"http://localhost/ApiExplorerResponseTypeWithAttribute/CreateProductWithDefaultResponseContentTypes");
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
Assert.Equal(2, description.SupportedResponseTypes.Count);
var responseType = description.SupportedResponseTypes[0];
Assert.Equal(type1, responseType.ResponseType);
Assert.Equal(201, responseType.StatusCode);
Assert.Equal(
expectedMediaTypes,
responseType.ResponseFormats.Select(responseFormat => responseFormat.MediaType).OrderBy(o => o).ToArray());
responseType = description.SupportedResponseTypes[1];
Assert.Equal(type2, responseType.ResponseType);
Assert.Equal(400, responseType.StatusCode);
Assert.Equal(
expectedMediaTypes,
responseType.ResponseFormats.Select(responseFormat => responseFormat.MediaType).OrderBy(o => o).ToArray());
}
[Fact]
public async Task ExplicitResponseTypeDecoration_SuppressesDefaultStatus_AlsoHonorsProducesContentTypes()
{
// Arrange
var type1 = typeof(ApiExplorerWebSite.Product).FullName;
var type2 = typeof(SerializableError).FullName;
var expectedMediaTypes = new[] { "text/xml" };
// Act
var response = await Client.GetAsync(
"http://localhost/ApiExplorerResponseTypeWithAttribute/CreateProductWithLimitedResponseContentTypes");
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
Assert.Equal(2, description.SupportedResponseTypes.Count);
var responseType = description.SupportedResponseTypes[0];
Assert.Equal(type1, responseType.ResponseType);
Assert.Equal(201, responseType.StatusCode);
Assert.Equal(
expectedMediaTypes,
responseType.ResponseFormats.Select(responseFormat => responseFormat.MediaType).ToArray());
responseType = description.SupportedResponseTypes[1];
Assert.Equal(type2, responseType.ResponseType);
Assert.Equal(400, responseType.StatusCode);
Assert.Equal(
expectedMediaTypes,
responseType.ResponseFormats.Select(responseFormat => responseFormat.MediaType).ToArray());
}
[Fact]
public async Task ExplicitResponseTypeDecoration_WithExplicitDefaultStatus()
{
// Arrange
var type1 = typeof(ApiExplorerWebSite.Product).FullName;
var type2 = typeof(SerializableError).FullName;
var expectedMediaTypes = new[] { "application/json", "application/xml", "text/json", "text/xml" };
// Act
var response = await Client.GetAsync(
"http://localhost/ApiExplorerResponseTypeWithAttribute/UpdateProductWithDefaultResponseContentTypes");
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
Assert.Equal(2, description.SupportedResponseTypes.Count);
var responseType = description.SupportedResponseTypes[0];
Assert.Equal(type1, responseType.ResponseType);
Assert.Equal(200, responseType.StatusCode);
Assert.Equal(
expectedMediaTypes,
responseType.ResponseFormats.Select(responseFormat => responseFormat.MediaType).OrderBy(o => o).ToArray());
responseType = description.SupportedResponseTypes[1];
Assert.Equal(type2, responseType.ResponseType);
Assert.Equal(400, responseType.StatusCode);
Assert.Equal(
expectedMediaTypes,
responseType.ResponseFormats.Select(responseFormat => responseFormat.MediaType).OrderBy(o => o).ToArray());
}
[Fact]
public async Task ExplicitResponseTypeDecoration_WithExplicitDefaultStatus_SpecifiedViaProducesAttribute()
{
// Arrange
var type1 = typeof(ApiExplorerWebSite.Product).FullName;
var type2 = typeof(SerializableError).FullName;
var expectedMediaTypes = new[] { "text/xml" };
// Act
var response = await Client.GetAsync(
"http://localhost/ApiExplorerResponseTypeWithAttribute/UpdateProductWithLimitedResponseContentTypes");
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
Assert.Equal(2, description.SupportedResponseTypes.Count);
var responseType = description.SupportedResponseTypes[0];
Assert.Equal(type1, responseType.ResponseType);
Assert.Equal(200, responseType.StatusCode);
Assert.Equal(
expectedMediaTypes,
responseType.ResponseFormats.Select(responseFormat => responseFormat.MediaType).ToArray());
responseType = description.SupportedResponseTypes[1];
Assert.Equal(type2, responseType.ResponseType);
Assert.Equal(400, responseType.StatusCode);
Assert.Equal(
expectedMediaTypes,
responseType.ResponseFormats.Select(responseFormat => responseFormat.MediaType).ToArray());
}
[Fact]
public async Task ApiExplorer_ResponseType_InheritingFromController()
{
// Arrange
var type = "ApiExplorerWebSite.Product";
var errorType = "ApiExplorerWebSite.ErrorInfo";
// Act
var response = await Client.GetAsync(
"http://localhost/ApiExplorerResponseTypeOverrideOnAction/Controller");
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
Assert.Collection(
description.SupportedResponseTypes.OrderBy(responseType => responseType.StatusCode),
responseType =>
{
Assert.Equal(type, responseType.ResponseType);
Assert.Equal(200, responseType.StatusCode);
var responseFormat = Assert.Single(responseType.ResponseFormats);
Assert.Equal("application/json", responseFormat.MediaType);
},
responseType =>
{
Assert.Equal(errorType, responseType.ResponseType);
Assert.Equal(500, responseType.StatusCode);
var responseFormat = Assert.Single(responseType.ResponseFormats);
Assert.Equal("application/json", responseFormat.MediaType);
});
}
[Fact]
public async Task ApiExplorer_ResponseType_OverrideOnAction()
{
// Arrange
var type = "ApiExplorerWebSite.Customer";
// type overriding the one specified on the controller
var errorType = "ApiExplorerWebSite.ErrorInfoOverride";
var expectedMediaTypes = new[] { "application/json", "application/xml", "text/json", "text/xml" };
// Act
var response = await Client.GetAsync(
"http://localhost/ApiExplorerResponseTypeOverrideOnAction/Action");
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
Assert.Collection(
description.SupportedResponseTypes.OrderBy(responseType => responseType.StatusCode),
responseType =>
{
Assert.Equal(type, responseType.ResponseType);
Assert.Equal(200, responseType.StatusCode);
Assert.Equal(expectedMediaTypes, GetSortedMediaTypes(responseType));
},
responseType =>
{
Assert.Equal(errorType, responseType.ResponseType);
Assert.Equal(500, responseType.StatusCode);
Assert.Equal(expectedMediaTypes, GetSortedMediaTypes(responseType));
});
}
[Fact]
public async Task ApiExplorer_ResponseTypeWithContentType_OverrideOnAction()
{
// This test scenario validates that a ProducesResponseType attribute will overide
// content-type given by a Produces attribute with a lower-specificity.
// Arrange
var type = "ApiExplorerWebSite.Customer";
var errorType = "ApiExplorerWebSite.ErrorInfo";
// Act
var response = await Client.GetAsync(
"http://localhost/ApiExplorerResponseTypeOverrideOnAction/Action2");
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
Assert.Collection(
description.SupportedResponseTypes.OrderBy(responseType => responseType.StatusCode),
responseType =>
{
Assert.Equal(type, responseType.ResponseType);
Assert.Equal(200, responseType.StatusCode);
Assert.Equal(new[] { "text/plain" }, GetSortedMediaTypes(responseType));
},
responseType =>
{
Assert.Equal(errorType, responseType.ResponseType);
Assert.Equal(500, responseType.StatusCode);
Assert.Equal(new[] { "application/json" }, GetSortedMediaTypes(responseType));
});
}
[ConditionalFact]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task ApiExplorer_ResponseContentType_Unset()
{
// Arrange & Act
var response = await Client.GetAsync("http://localhost/ApiExplorerResponseContentType/Unset");
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
var responseType = Assert.Single(description.SupportedResponseTypes);
Assert.Equal(4, responseType.ResponseFormats.Count);
var textXml = Assert.Single(responseType.ResponseFormats, f => f.MediaType == "text/xml");
Assert.Equal(typeof(XmlDataContractSerializerOutputFormatter).FullName, textXml.FormatterType);
var applicationXml = Assert.Single(responseType.ResponseFormats, f => f.MediaType == "application/xml");
Assert.Equal(typeof(XmlDataContractSerializerOutputFormatter).FullName, applicationXml.FormatterType);
var textJson = Assert.Single(responseType.ResponseFormats, f => f.MediaType == "text/json");
Assert.Equal(typeof(NewtonsoftJsonOutputFormatter).FullName, textJson.FormatterType);
var applicationJson = Assert.Single(responseType.ResponseFormats, f => f.MediaType == "application/json");
Assert.Equal(typeof(NewtonsoftJsonOutputFormatter).FullName, applicationJson.FormatterType);
}
[Fact]
public async Task ApiExplorer_ResponseContentType_Specific()
{
// Arrange & Act
var response = await Client.GetAsync("http://localhost/ApiExplorerResponseContentType/Specific");
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
var responseType = Assert.Single(description.SupportedResponseTypes);
Assert.Equal(2, responseType.ResponseFormats.Count);
var applicationJson = Assert.Single(
responseType.ResponseFormats,
format => format.MediaType == "application/json");
Assert.Equal(typeof(NewtonsoftJsonOutputFormatter).FullName, applicationJson.FormatterType);
var textJson = Assert.Single(responseType.ResponseFormats, f => f.MediaType == "text/json");
Assert.Equal(typeof(NewtonsoftJsonOutputFormatter).FullName, textJson.FormatterType);
}
[Fact]
public async Task ApiExplorer_ResponseContentType_WildcardMatch()
{
// Arrange & Act
var response = await Client.GetAsync("http://localhost/ApiExplorerResponseContentType/WildcardMatch");
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
var responseType = Assert.Single(description.SupportedResponseTypes);
Assert.Collection(
responseType.ResponseFormats,
responseFormat =>
{
Assert.Equal("application/hal+custom", responseFormat.MediaType);
Assert.Null(responseFormat.FormatterType);
},
responseFormat =>
{
Assert.Equal("application/hal+json", responseFormat.MediaType);
Assert.Equal(typeof(NewtonsoftJsonOutputFormatter).FullName, responseFormat.FormatterType);
});
}
[Fact]
public async Task ApiExplorer_ResponseContentType_NoMatch()
{
// Arrange
var expectedMediaTypes = new[] { "application/custom", "text/hal+bson" };
// Act
var response = await Client.GetAsync("http://localhost/ApiExplorerResponseContentType/NoMatch");
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
var responseType = Assert.Single(description.SupportedResponseTypes);
Assert.Equal(typeof(Product).FullName, responseType.ResponseType);
Assert.Equal(200, responseType.StatusCode);
Assert.Equal(expectedMediaTypes, GetSortedMediaTypes(responseType));
}
[ConditionalTheory]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
[InlineData("Controller", "text/xml", typeof(XmlDataContractSerializerOutputFormatter))]
[InlineData("Action", "application/json", typeof(NewtonsoftJsonOutputFormatter))]
public async Task ApiExplorer_ResponseContentType_OverrideOnAction(
string action,
string contentType,
Type formatterType)
{
// Arrange & Act
var response = await Client.GetAsync(
"http://localhost/ApiExplorerResponseContentTypeOverrideOnAction/" + action);
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
var responseType = Assert.Single(description.SupportedResponseTypes);
var responseFormat = Assert.Single(responseType.ResponseFormats);
Assert.Equal(contentType, responseFormat.MediaType);
Assert.Equal(formatterType.FullName, responseFormat.FormatterType);
}
[Fact]
public async Task ApiExplorer_Parameters_SimpleTypes_Default()
{
// Arrange & Act
var response = await Client.GetAsync("http://localhost/ApiExplorerParameters/SimpleParameters");
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
var parameters = description.ParameterDescriptions;
Assert.Equal(2, parameters.Count);
var i = Assert.Single(parameters, p => p.Name == "i");
Assert.Equal(BindingSource.ModelBinding.Id, i.Source);
Assert.Equal(typeof(int).FullName, i.Type);
var s = Assert.Single(parameters, p => p.Name == "s");
Assert.Equal(BindingSource.ModelBinding.Id, s.Source);
Assert.Equal(typeof(string).FullName, s.Type);
}
[Fact]
public async Task ApiExplorer_Parameters_SimpleTypes_BinderMetadataOnParameters()
{
// Arrange & Act
var response = await Client.GetAsync(
"http://localhost/ApiExplorerParameters/SimpleParametersWithBinderMetadata");
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
var parameters = description.ParameterDescriptions;
Assert.Equal(2, parameters.Count);
var i = Assert.Single(parameters, p => p.Name == "i");
Assert.Equal(BindingSource.Query.Id, i.Source);
Assert.Equal(typeof(int).FullName, i.Type);
var s = Assert.Single(parameters, p => p.Name == "s");
Assert.Equal(BindingSource.Path.Id, s.Source);
Assert.Equal(typeof(string).FullName, s.Type);
}
[Fact]
public async Task ApiExplorer_ParametersSimpleModel()
{
// Arrange & Act
var response = await Client.GetAsync("http://localhost/ApiExplorerParameters/SimpleModel");
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
var parameters = description.ParameterDescriptions;
Assert.Equal(2, parameters.Count);
var id = Assert.Single(parameters, p => p.Name == "Id");
Assert.Equal(BindingSource.ModelBinding.Id, id.Source);
Assert.Equal(typeof(int).FullName, id.Type);
var name = Assert.Single(parameters, p => p.Name == "Name");
Assert.Equal(BindingSource.ModelBinding.Id, name.Source);
Assert.Equal(typeof(string).FullName, name.Type);
}
[Fact]
public async Task ApiExplorer_Parameters_SimpleTypes_SimpleModel_FromBody()
{
// Arrange & Act
var response = await Client.GetAsync("http://localhost/ApiExplorerParameters/SimpleModelFromBody/5");
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
var parameters = description.ParameterDescriptions;
Assert.Equal(2, parameters.Count);
var id = Assert.Single(parameters, p => p.Name == "id");
Assert.Equal(BindingSource.Path.Id, id.Source);
Assert.Equal(typeof(int).FullName, id.Type);
var product = Assert.Single(parameters, p => p.Name == "product");
Assert.Equal(BindingSource.Body.Id, product.Source);
Assert.Equal(typeof(ApiExplorerWebSite.Product).FullName, product.Type);
}
[Fact]
public async Task ApiExplorer_Parameters_SimpleTypes_ComplexModel()
{
// Arrange & Act
var response = await Client.GetAsync("http://localhost/ApiExplorerParameters/ComplexModel");
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
var parameters = description.ParameterDescriptions;
Assert.Equal(7, parameters.Count);
var customerId = Assert.Single(parameters, p => p.Name == "CustomerId");
Assert.Equal(BindingSource.Query.Id, customerId.Source);
Assert.Equal(typeof(string).FullName, customerId.Type);
var referrer = Assert.Single(parameters, p => p.Name == "Referrer");
Assert.Equal(BindingSource.Header.Id, referrer.Source);
Assert.Equal(typeof(string).FullName, referrer.Type);
var quantity = Assert.Single(parameters, p => p.Name == "Details.Quantity");
Assert.Equal(BindingSource.Form.Id, quantity.Source);
Assert.Equal(typeof(int).FullName, quantity.Type);
var productId = Assert.Single(parameters, p => p.Name == "Details.Product.Id");
Assert.Equal(BindingSource.Form.Id, productId.Source);
Assert.Equal(typeof(int).FullName, productId.Type);
var productName = Assert.Single(parameters, p => p.Name == "Details.Product.Name");
Assert.Equal(BindingSource.Form.Id, productName.Source);
Assert.Equal(typeof(string).FullName, productName.Type);
var shippingInstructions = Assert.Single(parameters, p => p.Name == "Comments.ShippingInstructions");
Assert.Equal(BindingSource.Query.Id, shippingInstructions.Source);
Assert.Equal(typeof(string).FullName, shippingInstructions.Type);
var feedback = Assert.Single(parameters, p => p.Name == "Comments.Feedback");
Assert.Equal(BindingSource.Form.Id, feedback.Source);
Assert.Equal(typeof(string).FullName, feedback.Type);
}
[Fact]
public async Task ApiExplorer_Parameters_DefaultValue()
{
// Arrange & Act
var response = await Client.GetAsync("ApiExplorerParameters/DefaultValueParameters");
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
var parameters = description.ParameterDescriptions;
Assert.Collection(
parameters,
parameter =>
{
Assert.Equal("searchTerm", parameter.Name);
Assert.Null(parameter.DefaultValue);
},
parameter =>
{
Assert.Equal("top", parameter.Name);
Assert.Equal("10", parameter.DefaultValue);
},
parameter =>
{
Assert.Equal("searchDay", parameter.Name);
Assert.Equal(nameof(DayOfWeek.Wednesday), parameter.DefaultValue);
});
}
[Fact]
public async Task ApiExplorer_Parameters_IsRequired()
{
// Arrange & Act
var response = await Client.GetAsync("ApiExplorerParameters/IsRequiredParameters");
var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
var parameters = description.ParameterDescriptions;
Assert.Collection(
parameters,
parameter =>
{
Assert.Equal("requiredParam", parameter.Name);
Assert.True(parameter.IsRequired);
},
parameter =>
{
Assert.Equal("notRequiredParam", parameter.Name);
Assert.False(parameter.IsRequired);
},
parameter =>
{
Assert.Equal("Id", parameter.Name);
Assert.True(parameter.IsRequired);
},
parameter =>
{
Assert.Equal("Name", parameter.Name);
Assert.False(parameter.IsRequired);
});
}
[Fact]
public async Task ApiExplorer_Updates_WhenActionDescriptorCollectionIsUpdated()
{
// Act - 1
var body = await Client.GetStringAsync("ApiExplorerReload/Index");
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert - 1
var description = Assert.Single(result);
Assert.Empty(description.ParameterDescriptions);
Assert.Equal("ApiExplorerReload/Index", description.RelativePath);
// Act - 2
var response = await Client.GetAsync("ApiExplorerReload/Reload");
// Assert - 2
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
// Act - 3
response = await Client.GetAsync("ApiExplorerReload/Index");
// Assert - 3
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
// Act - 4
body = await Client.GetStringAsync("ApiExplorerReload/NewIndex");
result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert - 4
description = Assert.Single(result);
Assert.Empty(description.ParameterDescriptions);
Assert.Equal("ApiExplorerReload/NewIndex", description.RelativePath);
}
[Fact]
public async Task ApiExplorer_DoesNotListActionsSuppressedForPathMatching()
{
// Act
var body = await Client.GetStringAsync("ApiExplorerInboundOutbound/SuppressedForLinkGeneration");
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
Assert.Empty(description.ParameterDescriptions);
Assert.Equal("ApiExplorerInboundOutbound/SuppressedForLinkGeneration", description.RelativePath);
}
[Fact]
public async Task ApiBehavior_AddsMultipartFormDataConsumesConstraint_ForActionsWithFormFileParameters()
{
// Act
var body = await Client.GetStringAsync("ApiExplorerApiController/ActionWithFormFileCollectionParameter");
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
var requestFormat = Assert.Single(description.SupportedRequestFormats);
Assert.Equal("multipart/form-data", requestFormat.MediaType);
}
[Fact]
public async Task ApiBehavior_UsesContentTypeFromProducesAttribute_WhenNoFormatterSupportsIt()
{
// Arrange
var expectedMediaTypes = new[] { "application/pdf" };
// Act
var body = await Client.GetStringAsync("ApiExplorerApiController/ProducesWithUnsupportedContentType");
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
// Assert
var description = Assert.Single(result);
Assert.Collection(
description.SupportedResponseTypes.OrderBy(r => r.StatusCode),
responseType =>
{
Assert.Equal(typeof(Stream).FullName, responseType.ResponseType);
Assert.Equal(200, responseType.StatusCode);
Assert.Equal(expectedMediaTypes, GetSortedMediaTypes(responseType));
});
}
[Fact]
public Task ApiConvention_ForGetMethod_ReturningModel() => ApiConvention_ForGetMethod("GetProduct");
[Fact]
public Task ApiConvention_ForGetMethod_ReturningTaskOfActionResultOfModel() => ApiConvention_ForGetMethod("GetTaskOfActionResultOfProduct");
private async Task ApiConvention_ForGetMethod(string action)
{
// Arrange
var expectedMediaTypes = new[] { "application/json", "application/xml", "text/json", "text/xml" };
// Act
var response = await Client.GetStringAsync(
$"ApiExplorerResponseTypeWithApiConventionController/{action}");
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(response);
// Assert
var description = Assert.Single(result);
Assert.Collection(
description.SupportedResponseTypes.OrderBy(r => r.StatusCode),
responseType =>
{
Assert.True(responseType.IsDefaultResponse);
},
responseType =>
{
Assert.Equal(typeof(Product).FullName, responseType.ResponseType);
Assert.Equal(200, responseType.StatusCode);
Assert.Equal(expectedMediaTypes, GetSortedMediaTypes(responseType));
},
responseType =>
{
Assert.Equal(typeof(ProblemDetails).FullName, responseType.ResponseType);
Assert.Equal(404, responseType.StatusCode);
Assert.Equal(expectedMediaTypes, GetSortedMediaTypes(responseType));
});
}
[Fact]
public async Task ApiConvention_ForGetMethodThatDoesNotMatchConvention()
{
// Arrange
var expectedMediaTypes = new[] { "application/json", "application/xml", "text/json", "text/xml" };
// Act
var response = await Client.GetStringAsync(
$"ApiExplorerResponseTypeWithApiConventionController/GetProducts");
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(response);
// Assert
var description = Assert.Single(result);
Assert.Collection(
description.SupportedResponseTypes.OrderBy(r => r.StatusCode),
responseType =>
{
Assert.Equal(typeof(IEnumerable<Product>).FullName, responseType.ResponseType);
Assert.Equal(200, responseType.StatusCode);
var actualMediaTypes = responseType.ResponseFormats.Select(r => r.MediaType).OrderBy(r => r);
Assert.Equal(expectedMediaTypes, actualMediaTypes);
});
}
[Fact]
public async Task ApiConvention_ForMethodWithResponseTypeAttributes()
{
// Arrange
var expectedMediaTypes = new[] { "application/json" };
// Act
var response = await Client.PostAsync(
$"ApiExplorerResponseTypeWithApiConventionController/PostWithConventions",
new StringContent(string.Empty));
var responseBody = await response.EnsureSuccessStatusCode().Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(responseBody);
// Assert
var description = Assert.Single(result);
Assert.Collection(
description.SupportedResponseTypes.OrderBy(r => r.StatusCode),
responseType =>
{
Assert.Equal(typeof(void).FullName, responseType.ResponseType);
Assert.Equal(202, responseType.StatusCode);
Assert.Empty(responseType.ResponseFormats);
},
responseType =>
{
Assert.Equal(typeof(ProblemDetails).FullName, responseType.ResponseType);
Assert.Equal(403, responseType.StatusCode);
Assert.Equal(expectedMediaTypes, GetSortedMediaTypes(responseType));
});
}
[Fact]
public async Task ApiConvention_ForPostMethodThatMatchesConvention()
{
// Arrange
var expectedMediaTypes = new[] { "application/json", "application/xml", "text/json", "text/xml" };
// Act
var response = await Client.PostAsync(
$"ApiExplorerResponseTypeWithApiConventionController/PostTaskOfProduct",
new StringContent(string.Empty));
var responseBody = await response.EnsureSuccessStatusCode().Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(responseBody);
// Assert
var description = Assert.Single(result);
Assert.Collection(
description.SupportedResponseTypes.OrderBy(r => r.StatusCode),
responseType =>
{
Assert.True(responseType.IsDefaultResponse);
},
responseType =>
{
Assert.Equal(typeof(void).FullName, responseType.ResponseType);
Assert.Equal(201, responseType.StatusCode);
Assert.Empty(responseType.ResponseFormats);
},
responseType =>
{
Assert.Equal(typeof(ProblemDetails).FullName, responseType.ResponseType);
Assert.Equal(400, responseType.StatusCode);
Assert.Equal(expectedMediaTypes, GetSortedMediaTypes(responseType));
});
}
[Fact]
public async Task ApiConvention_ForPostActionWithProducesAttribute()
{
// Arrange
var expectedMediaTypes = new[] { "application/json", "text/json", };
// Act
var response = await Client.PostAsync(
$"ApiExplorerResponseTypeWithApiConventionController/PostWithProduces",
new StringContent(string.Empty));
var responseBody = await response.EnsureSuccessStatusCode().Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(responseBody);
// Assert
var description = Assert.Single(result);
Assert.Collection(
description.SupportedResponseTypes.OrderBy(r => r.StatusCode),
responseType =>
{
Assert.True(responseType.IsDefaultResponse);
},
responseType =>
{
Assert.Equal(typeof(void).FullName, responseType.ResponseType);
Assert.Equal(201, responseType.StatusCode);
Assert.Empty(responseType.ResponseFormats);
},
responseType =>
{
Assert.Equal(typeof(ProblemDetails).FullName, responseType.ResponseType);
Assert.Equal(400, responseType.StatusCode);
Assert.Equal(expectedMediaTypes, GetSortedMediaTypes(responseType));
});
}
[Fact]
public async Task ApiConvention_ForPutActionThatMatchesConvention()
{
// Arrange
var expectedMediaTypes = new[] { "application/json", "application/xml", "text/json", "text/xml" };
// Act
var response = await Client.PutAsync(
$"ApiExplorerResponseTypeWithApiConventionController/Put",
new StringContent(string.Empty));
var responseBody = await response.EnsureSuccessStatusCode().Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(responseBody);
// Assert
var description = Assert.Single(result);
Assert.Collection(
description.SupportedResponseTypes.OrderBy(r => r.StatusCode),
responseType =>
{
Assert.True(responseType.IsDefaultResponse);
},
responseType =>
{
Assert.Equal(typeof(void).FullName, responseType.ResponseType);
Assert.Equal(204, responseType.StatusCode);
Assert.Empty(responseType.ResponseFormats);
},
responseType =>
{
Assert.Equal(typeof(ProblemDetails).FullName, responseType.ResponseType);
Assert.Equal(400, responseType.StatusCode);
Assert.Equal(expectedMediaTypes, GetSortedMediaTypes(responseType));
},
responseType =>
{
Assert.Equal(typeof(ProblemDetails).FullName, responseType.ResponseType);
Assert.Equal(404, responseType.StatusCode);
Assert.Equal(expectedMediaTypes, GetSortedMediaTypes(responseType));
});
}
[Fact]
public async Task ApiConvention_ForDeleteActionThatMatchesConvention()
{
// Arrange
var expectedMediaTypes = new[] { "application/json", "application/xml", "text/json", "text/xml" };
// Act
var response = await Client.DeleteAsync(
$"ApiExplorerResponseTypeWithApiConventionController/DeleteProduct");
var responseBody = await response.EnsureSuccessStatusCode().Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(responseBody);
// Assert
var description = Assert.Single(result);
Assert.Collection(
description.SupportedResponseTypes.OrderBy(r => r.StatusCode),
responseType =>
{
Assert.True(responseType.IsDefaultResponse);
},
responseType =>
{
Assert.Equal(typeof(void).FullName, responseType.ResponseType);
Assert.Equal(200, responseType.StatusCode);
Assert.Empty(responseType.ResponseFormats);
},
responseType =>
{
Assert.Equal(typeof(ProblemDetails).FullName, responseType.ResponseType);
Assert.Equal(400, responseType.StatusCode);
Assert.Equal(expectedMediaTypes, GetSortedMediaTypes(responseType));
},
responseType =>
{
Assert.Equal(typeof(ProblemDetails).FullName, responseType.ResponseType);
Assert.Equal(404, responseType.StatusCode);
Assert.Equal(expectedMediaTypes, GetSortedMediaTypes(responseType));
});
}
[Fact]
public async Task ApiConvention_ForActionWithApiConventionMethod()
{
// Arrange
var expectedMediaTypes = new[] { "application/json", "application/xml", "text/json", "text/xml" };
// Act
var response = await Client.PostAsync(
"ApiExplorerResponseTypeWithApiConventionController/PostItem",
new StringContent(string.Empty));
var responseBody = await response.EnsureSuccessStatusCode().Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(responseBody);
// Assert
var description = Assert.Single(result);
Assert.Collection(
description.SupportedResponseTypes.OrderBy(r => r.StatusCode),
responseType =>
{
Assert.Equal(typeof(void).FullName, responseType.ResponseType);
Assert.Equal(302, responseType.StatusCode);
Assert.Empty(responseType.ResponseFormats);
},
responseType =>
{
Assert.Equal(typeof(ProblemDetails).FullName, responseType.ResponseType);
Assert.Equal(409, responseType.StatusCode);
Assert.Equal(expectedMediaTypes, GetSortedMediaTypes(responseType));
});
}
[Theory]
[InlineData("ActionWithNoExplicitType", typeof(ProblemDetails))]
[InlineData("ActionWithVoidType", typeof(void))]
public async Task ApiAction_ForActionWithVoidResponseType(string path, Type type)
{
// Act
var response = await Client.GetAsync($"http://localhost/ApiExplorerVoid/{path}");
var responseBody = await response.EnsureSuccessStatusCode().Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(responseBody);
// Assert
var description = Assert.Single(result);
Assert.Collection(
description.SupportedResponseTypes.OrderBy(r => r.StatusCode),
responseType =>
{
Assert.Equal(type.FullName, responseType.ResponseType);
Assert.Equal(401, responseType.StatusCode);
Assert.False(responseType.IsDefaultResponse);
});
}
private IEnumerable<string> GetSortedMediaTypes(ApiExplorerResponseType apiResponseType)
{
return apiResponseType.ResponseFormats
.OrderBy(format => format.MediaType)
.Select(format => format.MediaType);
}
// Used to serialize data between client and server
private class ApiExplorerData
{
public string GroupName { get; set; }
public string HttpMethod { get; set; }
public List<ApiExplorerParameterData> ParameterDescriptions { get; } = new List<ApiExplorerParameterData>();
public string RelativePath { get; set; }
public List<ApiExplorerResponseType> SupportedResponseTypes { get; } = new List<ApiExplorerResponseType>();
public List<ApiExplorerRequestFormat> SupportedRequestFormats { get; } = new List<ApiExplorerRequestFormat>();
}
// Used to serialize data between client and server
private class ApiExplorerParameterData
{
public string Name { get; set; }
public ApiExplorerParameterRouteInfo RouteInfo { get; set; }
public string Source { get; set; }
public string Type { get; set; }
public string DefaultValue { get; set; }
public bool IsRequired { get; set; }
}
// Used to serialize data between client and server
private class ApiExplorerParameterRouteInfo
{
public string[] ConstraintTypes { get; set; }
public object DefaultValue { get; set; }
public bool IsOptional { get; set; }
}
// Used to serialize data between client and server
private class ApiExplorerResponseType
{
public IList<ApiExplorerResponseFormat> ResponseFormats { get; }
= new List<ApiExplorerResponseFormat>();
public string ResponseType { get; set; }
public int StatusCode { get; set; }
public bool IsDefaultResponse { get; set; }
}
private class ApiExplorerResponseFormat
{
public string MediaType { get; set; }
public string FormatterType { get; set; }
}
private class ApiExplorerRequestFormat
{
public string MediaType { get; set; }
public string FormatterType { get; set; }
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using Test.Utilities;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Microsoft.NetCore.Analyzers.Runtime.InitializeStaticFieldsInlineAnalyzer,
Microsoft.NetCore.Analyzers.Runtime.InitializeStaticFieldsInlineFixer>;
using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier<
Microsoft.NetCore.Analyzers.Runtime.InitializeStaticFieldsInlineAnalyzer,
Microsoft.NetCore.Analyzers.Runtime.InitializeStaticFieldsInlineFixer>;
namespace Microsoft.NetCore.Analyzers.Runtime.UnitTests
{
public class InitializeStaticFieldsInlineTests
{
#region Unit tests for no analyzer diagnostic
[Fact]
public async Task CA1810_EmptyStaticConstructorAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class Class1
{
private readonly static int field = 1;
static Class1() // Empty
{
}
}
");
await VerifyVB.VerifyAnalyzerAsync(@"
Public Class Class1
Private Shared ReadOnly field As Integer = 1
Shared Sub New() ' Empty
End Sub
End Class
");
}
[Fact]
public async Task CA2207_EmptyStaticConstructorAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public struct Struct1
{
private readonly static int field = 1;
static Struct1() // Empty
{
}
}
");
await VerifyVB.VerifyAnalyzerAsync(@"
Public Structure Struct1
Private Shared ReadOnly field As Integer = 1
Shared Sub New() ' Empty
End Sub
End Structure
");
}
[Fact]
public async Task CA1810_NoStaticFieldInitializedInStaticConstructorAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class Class1
{
private readonly static int field = 1;
static Class1() // No static field initialization
{
Class1_Method();
var field2 = 1;
}
private static void Class1_Method() { throw new System.NotImplementedException(); }
}
");
await VerifyVB.VerifyAnalyzerAsync(@"
Public Class Class1
Private Shared ReadOnly field As Integer = 1
Shared Sub New() ' No static field initalization
Class1_Method()
Dim field2 = 1
End Sub
Private Shared Sub Class1_Method()
Throw New System.NotImplementedException()
End Sub
End Class
");
}
[Fact]
public async Task CA1810_StaticPropertyInStaticConstructorAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class Class1
{
private static int Property { get; set; }
static Class1() // Static property initalization
{
Property = 1;
}
}
");
await VerifyVB.VerifyAnalyzerAsync(@"
Public Class Class1
Private Shared Property [Property]() As Integer
Get
Return 0
End Get
Set
End Set
End Property
Shared Sub New()
' Static property initalization
[Property] = 1
End Sub
End Class
");
}
[Fact]
public async Task CA1810_InitializionInNonStaticConstructorAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class Class1
{
private static int field = 1;
public Class1() // Non static constructor
{
field = 0;
}
public static void Class1_Method() // Non constructor
{
field = 0;
}
}
");
await VerifyVB.VerifyAnalyzerAsync(@"
Public Class Class1
Private Shared field As Integer = 1
Public Sub New() ' Non static constructor
field = 0
End Sub
Public Shared Sub Class1_Method() ' Non constructor
field = 0
End Sub
End Class
");
}
[Fact, WorkItem(3138, "https://github.com/dotnet/roslyn-analyzers/issues/3138")]
public async Task CA1810_EventLambdas_NoDiagnosticAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
class C
{
private static string s;
static C()
{
Console.CancelKeyPress += (o, e) => s = string.Empty;
Console.CancelKeyPress -= (o, e) => s = string.Empty;
}
}");
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Class C
Private Shared s As String
Shared Sub New()
AddHandler Console.CancelKeyPress,
Sub(o, e)
s = string.Empty
End Sub
RemoveHandler Console.CancelKeyPress,
Sub(o, e)
s = string.Empty
End Sub
End Sub
End Class");
}
[Fact, WorkItem(3138, "https://github.com/dotnet/roslyn-analyzers/issues/3138")]
public async Task CA1810_EventDelegate_NoDiagnosticAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
class C
{
private static string s;
static C()
{
Console.CancelKeyPress += delegate { s = string.Empty; };
}
}");
}
[Fact, WorkItem(3138, "https://github.com/dotnet/roslyn-analyzers/issues/3138")]
public async Task CA1810_TaskRunActionAndFunc_NoDiagnosticAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System.Threading.Tasks;
class C
{
private static int s;
static C()
{
Task.Run(() => s = 3);
Task.Run(() =>
{
s = 3;
return 42;
});
}
}");
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Threading.Tasks
Class C
Private Shared s As Integer
Shared Sub New()
Task.Run(Sub()
s = 3
End Sub)
Task.Run(Function()
s = 3
Return 42
End Function)
End Sub
End Class");
}
[Fact, WorkItem(3138, "https://github.com/dotnet/roslyn-analyzers/issues/3138")]
public async Task CA1810_EnumerableWhere_NoDiagnosticAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System.Collections.Generic;
using System.Linq;
class C
{
private static int s;
static C()
{
var result = new List<int>().Where(x =>
{
if (x > 10)
{
s = x;
return true;
}
return false;
});
}
}");
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Collections.Generic
Imports System.Linq
Class C
Private Shared s As Integer
Shared Sub New()
Dim list = New List(Of Integer)
Dim result = list.Where(Function(x)
If x > 10 Then
s = x
Return True
End if
Return False
End Function)
End Sub
End Class");
}
[Fact, WorkItem(3138, "https://github.com/dotnet/roslyn-analyzers/issues/3138")]
public async Task CA1810_MixedFieldInitialization_NoDiagnosticAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
class C
{
private static string s1;
private static string s2;
static C()
{
Console.CancelKeyPress += (o, e) => s1 = string.Empty;
s2 = string.Empty;
}
}");
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Class C
Private Shared s1 As String
Private Shared s2 As String
Shared Sub New()
AddHandler Console.CancelKeyPress,
Sub(o, e)
s1 = string.Empty
End Sub
s2 = string.Empty
End Sub
End Class");
}
[Fact, WorkItem(3852, "https://github.com/dotnet/roslyn-analyzers/issues/3852")]
public async Task CA1810_EventSubscriptionInStaticCtorPreventsDiagnosticAsync()
{
await new VerifyCS.Test
{
ReferenceAssemblies = AdditionalMetadataReferences.DefaultWithWinForms,
TestCode = @"
using System;
using System.Windows.Forms;
public class C1
{
private static readonly int field;
static C1()
{
Application.ThreadExit += new EventHandler(OnThreadExit);
field = 42;
}
private static void OnThreadExit(object sender, EventArgs e) {}
}
public class C2
{
private static readonly int field;
static C2()
{
Application.ThreadExit -= new EventHandler(OnThreadExit);
field = 42;
}
private static void OnThreadExit(object sender, EventArgs e) {}
}
",
}.RunAsync();
}
#endregion
#region Unit tests for analyzer diagnostic(s)
[Fact]
public async Task CA1810_InitializationInStaticConstructorAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class Class1
{
private readonly static int field;
static Class1() // Non static constructor
{
field = 0;
}
}
",
GetCA1810CSharpDefaultResultAt(5, 12, "Class1"));
await VerifyVB.VerifyAnalyzerAsync(@"
Public Class Class1
Private Shared ReadOnly field As Integer
Shared Sub New()
' Non static constructor
field = 0
End Sub
End Class
",
GetCA1810BasicDefaultResultAt(4, 13, "Class1"));
}
[Fact]
public async Task CA2207_InitializationInStaticConstructorAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public struct Struct1
{
private readonly static int field;
static Struct1() // Non static constructor
{
field = 0;
}
}
",
GetCA2207CSharpDefaultResultAt(5, 12, "Struct1"));
await VerifyVB.VerifyAnalyzerAsync(@"
Public Structure Struct1
Private Shared ReadOnly field As Integer
Shared Sub New()
' Non static constructor
field = 0
End Sub
End Structure
",
GetCA2207BasicDefaultResultAt(4, 13, "Struct1"));
}
[Fact]
public async Task CA1810_NoDuplicateDiagnosticsAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class Class1
{
private readonly static int field, field2;
static Class1() // Non static constructor
{
field = 0;
field2 = 0;
}
}
",
GetCA1810CSharpDefaultResultAt(5, 12, "Class1"));
await VerifyVB.VerifyAnalyzerAsync(@"
Public Class Class1
Private Shared ReadOnly field As Integer, field2 As Integer
Shared Sub New()
' Non static constructor
field = 0
field2 = 0
End Sub
End Class",
GetCA1810BasicDefaultResultAt(4, 13, "Class1"));
}
[Fact]
public async Task CA2207_NoDuplicateDiagnosticsAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public struct Struct1
{
private readonly static int field, field2;
static Struct1() // Non static constructor
{
field = 0;
field2 = 0;
}
}
",
GetCA2207CSharpDefaultResultAt(5, 12, "Struct1"));
await VerifyVB.VerifyAnalyzerAsync(@"
Public Structure Struct1
Private Shared ReadOnly field As Integer, field2 As Integer
Shared Sub New()
' Non static constructor
field = 0
field2 = 0
End Sub
End Structure",
GetCA2207BasicDefaultResultAt(4, 13, "Struct1"));
}
[Fact, WorkItem(3138, "https://github.com/dotnet/roslyn-analyzers/issues/3138")]
public async Task CA1810_LocalFunc_DiagnosticAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System.Collections.Generic;
using System.Linq;
class C
{
private static int s;
static C()
{
void LocalFunc()
{
s = 1;
}
}
}",
GetCA1810CSharpDefaultResultAt(9, 12, "C"));
}
[Fact, WorkItem(3138, "https://github.com/dotnet/roslyn-analyzers/issues/3138")]
public async Task CA1810_StaticLocalFunc_DiagnosticAsync()
{
await new VerifyCS.Test
{
LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp8,
TestCode = @"
using System.Collections.Generic;
using System.Linq;
class C
{
private static int s;
static C()
{
static void StaticLocalFunc()
{
s = 2;
}
}
}",
ExpectedDiagnostics =
{
GetCA1810CSharpDefaultResultAt(9, 12, "C")
},
}
.RunAsync();
}
#endregion
#region Helpers
private static DiagnosticResult GetCA1810CSharpDefaultResultAt(int line, int column, string typeName) =>
#pragma warning disable RS0030 // Do not used banned APIs
VerifyCS.Diagnostic(InitializeStaticFieldsInlineAnalyzer.CA1810Rule)
.WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
.WithArguments(typeName);
private static DiagnosticResult GetCA1810BasicDefaultResultAt(int line, int column, string typeName) =>
#pragma warning disable RS0030 // Do not used banned APIs
VerifyVB.Diagnostic(InitializeStaticFieldsInlineAnalyzer.CA1810Rule)
.WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
.WithArguments(typeName);
private static DiagnosticResult GetCA2207CSharpDefaultResultAt(int line, int column, string typeName) =>
#pragma warning disable RS0030 // Do not used banned APIs
VerifyCS.Diagnostic(InitializeStaticFieldsInlineAnalyzer.CA2207Rule)
.WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
.WithArguments(typeName);
private static DiagnosticResult GetCA2207BasicDefaultResultAt(int line, int column, string typeName) =>
#pragma warning disable RS0030 // Do not used banned APIs
VerifyVB.Diagnostic(InitializeStaticFieldsInlineAnalyzer.CA2207Rule)
.WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
.WithArguments(typeName);
#endregion
}
}
| |
using UnityEngine;
using System.Collections;
namespace Pathfinding.Util {
/** Simple implementation of a GUID */
public struct Guid {
//private byte b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15;
const string hex = "0123456789ABCDEF";
public static readonly Guid zero = new Guid(new byte[16]);
public static readonly string zeroString = new Guid(new byte[16]).ToString();
private ulong _a, _b;
public Guid (byte[] bytes) {
_a =((ulong)bytes[0] << 8*0) |
((ulong)bytes[1] << 8*1) |
((ulong)bytes[2] << 8*2) |
((ulong)bytes[3] << 8*3) |
((ulong)bytes[4] << 8*4) |
((ulong)bytes[5] << 8*5) |
((ulong)bytes[6] << 8*6) |
((ulong)bytes[7] << 8*7);
_b =((ulong)bytes[8] << 8*0) |
((ulong)bytes[9] << 8*1) |
((ulong)bytes[10] << 8*2) |
((ulong)bytes[11] << 8*3) |
((ulong)bytes[12] << 8*4) |
((ulong)bytes[13] << 8*5) |
((ulong)bytes[14] << 8*6) |
((ulong)bytes[15] << 8*7);
/*b1 = bytes[1];
b2 = bytes[2];
b3 = bytes[3];
b4 = bytes[4];
b5 = bytes[5];
b6 = bytes[6];
b7 = bytes[7];
b8 = bytes[8];
b9 = bytes[9];
b10 = bytes[10];
b11 = bytes[11];
b12 = bytes[12];
b13 = bytes[13];
b14 = bytes[14];
b15 = bytes[15];*/
}
public Guid (string str) {
/*b0 = 0;
b1 = 0;
b2 = 0;
b3 = 0;
b4 = 0;
b5 = 0;
b6 = 0;
b7 = 0;
b8 = 0;
b9 = 0;
b10 = 0;
b11 = 0;
b12 = 0;
b13 = 0;
b14 = 0;
b15 = 0;*/
_a = 0;
_b = 0;
if (str.Length < 32)
throw new System.FormatException ("Invalid Guid format");
int counter = 0;
int i = 0;
int offset = 15*4;
for (;counter < 16;i++) {
if (i >= str.Length)
throw new System.FormatException ("Invalid Guid format. String too short");
char c = str[i];
if (c == '-') continue;
//Neat trick, perhaps a bit slow, but one will probably not use Guid parsing that much
int value = hex.IndexOf(char.ToUpperInvariant(c));
if (value == -1)
throw new System.FormatException ("Invalid Guid format : "+c+" is not a hexadecimal character");
_a |= (ulong)value << offset;
//SetByte (counter,(byte)value);
offset -= 4;
counter++;
}
offset = 15*4;
for (;counter < 32;i++) {
if (i >= str.Length)
throw new System.FormatException ("Invalid Guid format. String too short");
char c = str[i];
if (c == '-') continue;
//Neat trick, perhaps a bit slow, but one will probably not use Guid parsing that much
int value = hex.IndexOf(char.ToUpperInvariant(c));
if (value == -1)
throw new System.FormatException ("Invalid Guid format : "+c+" is not a hexadecimal character");
_b |= (ulong)value << offset;
//SetByte (counter,(byte)value);
offset -= 4;
counter++;
}
}
public static Guid Parse (string input) {
return new Guid(input);
}
public byte[] ToByteArray () {
byte[] bytes = new byte[16];
byte[] ba = System.BitConverter.GetBytes(_a);
byte[] bb = System.BitConverter.GetBytes(_b);
for (int i=0;i<8;i++) {
bytes[i] = ba[i];
bytes[i+8] = bb[i];
}
return bytes;
}
private static System.Random random = new System.Random();
public static Guid NewGuid () {
byte[] bytes = new byte[16];
random.NextBytes(bytes);
return new Guid(bytes);
}
/*private void SetByte (int i, byte value) {
switch (i) {
case 0: b0 = value; break;
case 1: b1 = value; break;
case 2: b2 = value; break;
case 3: b3 = value; break;
case 4: b4 = value; break;
case 5: b5 = value; break;
case 6: b6 = value; break;
case 7: b7 = value; break;
case 8: b8 = value; break;
case 9: b9 = value; break;
case 10: b10 = value; break;
case 11: b11 = value; break;
case 12: b12 = value; break;
case 13: b13 = value; break;
case 14: b14 = value; break;
case 15: b15 = value; break;
default: throw new System.IndexOutOfRangeException ("Cannot set byte value "+i+", only 0...15 permitted");
}
}*/
public static bool operator == (Guid lhs, Guid rhs) {
return lhs._a == rhs._a && lhs._b == rhs._b;
}
public static bool operator != (Guid lhs, Guid rhs) {
return lhs._a != rhs._a || lhs._b != rhs._b;
}
public override bool Equals (System.Object _rhs) {
if (!(_rhs is Guid)) return false;
Guid rhs = (Guid)_rhs;
return this._a == rhs._a && this._b == rhs._b;
}
public override int GetHashCode () {
ulong ab = _a ^ _b;
return (int)(ab >> 32) ^ (int)ab;
}
/*public static bool operator == (Guid lhs, Guid rhs) {
return
lhs.b0 == rhs.b0 &&
lhs.b1 == rhs.b1 &&
lhs.b2 == rhs.b2 &&
lhs.b3 == rhs.b3 &&
lhs.b4 == rhs.b4 &&
lhs.b5 == rhs.b5 &&
lhs.b6 == rhs.b6 &&
lhs.b7 == rhs.b7 &&
lhs.b8 == rhs.b8 &&
lhs.b9 == rhs.b9 &&
lhs.b10 == rhs.b10 &&
lhs.b11 == rhs.b11 &&
lhs.b12 == rhs.b12 &&
lhs.b13 == rhs.b13 &&
lhs.b14 == rhs.b14 &&
lhs.b15 == rhs.b15;
}
public static bool operator != (Guid lhs, Guid rhs) {
return
lhs.b0 != rhs.b0 ||
lhs.b1 != rhs.b1 ||
lhs.b2 != rhs.b2 ||
lhs.b3 != rhs.b3 ||
lhs.b4 != rhs.b4 ||
lhs.b5 != rhs.b5 ||
lhs.b6 != rhs.b6 ||
lhs.b7 != rhs.b7 ||
lhs.b8 != rhs.b8 ||
lhs.b9 != rhs.b9 ||
lhs.b10 != rhs.b10 ||
lhs.b11 != rhs.b11 ||
lhs.b12 != rhs.b12 ||
lhs.b13 != rhs.b13 ||
lhs.b14 != rhs.b14 ||
lhs.b15 != rhs.b15;
}*/
private static System.Text.StringBuilder text;
public override string ToString () {
if (text == null) {
text = new System.Text.StringBuilder();
}
lock (text) {
text.Length = 0;
text.Append (_a.ToString("x16")).Append('-').Append(_b.ToString("x16"));
return text.ToString();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using CppSharp.AST;
using CppSharp.Generators;
using CppSharp.Parser;
using CppSharp.Passes;
using CppAbi = CppSharp.Parser.AST.CppAbi;
namespace CppSharp
{
/// <summary>
/// Generates C# and C++/CLI bindings for the CppSharp.CppParser project.
/// </summary>
class ParserGen : ILibrary
{
internal readonly GeneratorKind Kind;
internal readonly string Triple;
internal readonly CppAbi Abi;
internal readonly bool IsGnuCpp11Abi;
public ParserGen(GeneratorKind kind, string triple, CppAbi abi,
bool isGnuCpp11Abi = false)
{
Kind = kind;
Triple = triple;
Abi = abi;
IsGnuCpp11Abi = isGnuCpp11Abi;
}
static string GetSourceDirectory(string dir)
{
var directory = new DirectoryInfo(Directory.GetCurrentDirectory());
while (directory != null)
{
var path = Path.Combine(directory.FullName, dir);
if (Directory.Exists(path) &&
Directory.Exists(Path.Combine(directory.FullName, "deps")))
return path;
directory = directory.Parent;
}
throw new Exception("Could not find build directory: " + dir);
}
public void Setup(Driver driver)
{
var parserOptions = driver.ParserOptions;
parserOptions.TargetTriple = Triple;
parserOptions.Abi = Abi;
var options = driver.Options;
options.LibraryName = "CppSharp.CppParser";
options.GeneratorKind = Kind;
options.Headers.AddRange(new[]
{
"AST.h",
"Sources.h",
"CppParser.h"
});
options.Libraries.Add("CppSharp.CppParser.lib");
if (Abi == CppAbi.Microsoft)
parserOptions.MicrosoftMode = true;
if (Triple.Contains("apple"))
SetupMacOptions(parserOptions);
if (Triple.Contains("linux"))
SetupLinuxOptions(parserOptions);
var basePath = Path.Combine(GetSourceDirectory("src"), "CppParser");
parserOptions.AddIncludeDirs(basePath);
parserOptions.AddLibraryDirs(".");
options.OutputDir = Path.Combine(GetSourceDirectory("src"), "CppParser",
"Bindings", Kind.ToString());
var extraTriple = IsGnuCpp11Abi ? "-cxx11abi" : string.Empty;
if (Kind == GeneratorKind.CSharp)
options.OutputDir = Path.Combine(options.OutputDir, parserOptions.TargetTriple + extraTriple);
options.OutputNamespace = string.Empty;
options.CheckSymbols = false;
//options.Verbose = true;
options.UnityBuild = true;
}
private void SetupLinuxOptions(ParserOptions options)
{
options.MicrosoftMode = false;
options.NoBuiltinIncludes = true;
var headersPath = Platform.IsLinux ? string.Empty :
Path.Combine(GetSourceDirectory("build"), "headers", "x86_64-linux-gnu");
// Search for the available GCC versions on the provided headers.
var versions = Directory.EnumerateDirectories(Path.Combine(headersPath,
"usr/include/c++"));
if (versions.Count() == 0)
throw new Exception("No valid GCC version found on system include paths");
string gccVersionPath = versions.First();
string gccVersion = gccVersionPath.Substring(
gccVersionPath.LastIndexOf(Path.DirectorySeparatorChar) + 1);
string[] systemIncludeDirs = {
Path.Combine("usr", "include", "c++", gccVersion),
Path.Combine("usr", "include", "x86_64-linux-gnu", "c++", gccVersion),
Path.Combine("usr", "include", "c++", gccVersion, "backward"),
Path.Combine("usr", "lib", "gcc", "x86_64-linux-gnu", gccVersion, "include"),
Path.Combine("usr", "include", "x86_64-linux-gnu"),
Path.Combine("usr", "include")
};
foreach (var dir in systemIncludeDirs)
options.AddSystemIncludeDirs(Path.Combine(headersPath, dir));
options.AddDefines("_GLIBCXX_USE_CXX11_ABI=" + (IsGnuCpp11Abi ? "1" : "0"));
}
private static void SetupMacOptions(ParserOptions options)
{
options.MicrosoftMode = false;
options.NoBuiltinIncludes = true;
if (Platform.IsMacOS)
{
var headersPaths = new List<string> {
Path.Combine(GetSourceDirectory("deps"), "llvm/tools/clang/lib/Headers"),
Path.Combine(GetSourceDirectory("deps"), "libcxx", "include"),
"/usr/include",
};
foreach (var header in headersPaths)
Console.WriteLine(header);
foreach (var header in headersPaths)
options.AddSystemIncludeDirs(header);
}
var headersPath = Path.Combine(GetSourceDirectory("build"), "headers",
"osx");
options.AddSystemIncludeDirs(Path.Combine(headersPath, "include"));
options.AddSystemIncludeDirs(Path.Combine(headersPath, "clang", "4.2", "include"));
options.AddSystemIncludeDirs(Path.Combine(headersPath, "libcxx", "include"));
options.AddArguments("-stdlib=libc++");
}
public void SetupPasses(Driver driver)
{
driver.AddTranslationUnitPass(new IgnoreStdFieldsPass());
}
public void Preprocess(Driver driver, ASTContext ctx)
{
ctx.RenameNamespace("CppSharp::CppParser", "Parser");
if (driver.Options.IsCSharpGenerator)
{
driver.Generator.OnUnitGenerated += o =>
{
Block firstBlock = o.Outputs[0].RootBlock.Blocks[1];
if (o.TranslationUnit.Module == driver.Options.SystemModule)
{
firstBlock.NewLine();
firstBlock.WriteLine("[assembly:InternalsVisibleTo(\"CppSharp.Parser.CSharp\")]");
}
else
{
firstBlock.WriteLine("using System.Runtime.CompilerServices;");
firstBlock.NewLine();
firstBlock.WriteLine("[assembly:InternalsVisibleTo(\"CppSharp.Parser\")]");
}
};
}
}
public void Postprocess(Driver driver, ASTContext ctx)
{
}
public static void Main(string[] args)
{
if (Platform.IsWindows)
{
Console.WriteLine("Generating the C++/CLI parser bindings for Windows...");
ConsoleDriver.Run(new ParserGen(GeneratorKind.CLI, "i686-pc-win32-msvc",
CppAbi.Microsoft));
Console.WriteLine();
Console.WriteLine("Generating the C# parser bindings for Windows...");
ConsoleDriver.Run(new ParserGen(GeneratorKind.CSharp, "i686-pc-win32-msvc",
CppAbi.Microsoft));
Console.WriteLine();
Console.WriteLine("Generating the C# 64-bit parser bindings for Windows...");
ConsoleDriver.Run(new ParserGen(GeneratorKind.CSharp, "x86_64-pc-win32-msvc",
CppAbi.Microsoft));
Console.WriteLine();
}
var osxHeadersPath = Path.Combine(GetSourceDirectory("build"), @"headers\osx");
if (Directory.Exists(osxHeadersPath) || Platform.IsMacOS)
{
Console.WriteLine("Generating the C# parser bindings for OSX...");
ConsoleDriver.Run(new ParserGen(GeneratorKind.CSharp, "i686-apple-darwin12.4.0",
CppAbi.Itanium));
Console.WriteLine();
Console.WriteLine("Generating the C# parser bindings for OSX...");
ConsoleDriver.Run(new ParserGen(GeneratorKind.CSharp, "x86_64-apple-darwin12.4.0",
CppAbi.Itanium));
Console.WriteLine();
}
var linuxHeadersPath = Path.Combine(GetSourceDirectory("build"), @"headers\x86_64-linux-gnu");
if (Directory.Exists(linuxHeadersPath) || Platform.IsLinux)
{
Console.WriteLine("Generating the C# parser bindings for Linux...");
ConsoleDriver.Run(new ParserGen(GeneratorKind.CSharp, "x86_64-linux-gnu",
CppAbi.Itanium));
Console.WriteLine();
Console.WriteLine("Generating the C# parser bindings for Linux (GCC C++11 ABI)...");
ConsoleDriver.Run(new ParserGen(GeneratorKind.CSharp, "x86_64-linux-gnu",
CppAbi.Itanium, isGnuCpp11Abi: true));
Console.WriteLine();
}
}
}
public class IgnoreStdFieldsPass : TranslationUnitPass
{
public override bool VisitFieldDecl(Field field)
{
if (!field.IsGenerated)
return false;
if (!IsStdType(field.QualifiedType)) return false;
field.ExplicitlyIgnore();
return true;
}
public override bool VisitFunctionDecl(Function function)
{
if (function.GenerationKind == GenerationKind.None)
return false;
if (function.Parameters.Any(param => IsStdType(param.QualifiedType)))
{
function.ExplicitlyIgnore();
return false;
}
return true;
}
private bool IsStdType(QualifiedType type)
{
var typePrinter = new CppTypePrinter();
var typeName = type.Visit(typePrinter);
return typeName.Contains("std::");
}
}
}
| |
/*
* 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 Apache.NMS.Stomp.Commands;
using Apache.NMS.Stomp.Transport;
using Apache.NMS.Util;
using System;
using System.IO;
using System.Text;
using System.Globalization;
namespace Apache.NMS.Stomp.Protocol
{
/// <summary>
/// Implements the <a href="http://stomp.codehaus.org/">STOMP</a> protocol.
/// </summary>
public class StompWireFormat : IWireFormat
{
private Encoding encoder = new UTF8Encoding();
private IPrimitiveMapMarshaler mapMarshaler = new XmlPrimitiveMapMarshaler();
private ITransport transport;
private WireFormatInfo remoteWireFormatInfo;
private int connectedResponseId = -1;
private bool encodeHeaders = false;
private int maxInactivityDuration = 30000;
private int maxInactivityDurationInitialDelay = 0;
public StompWireFormat()
{
}
public ITransport Transport
{
get { return transport; }
set { transport = value; }
}
public int Version
{
get { return 1; }
}
public Encoding Encoder
{
get { return this.encoder; }
set { this.encoder = value; }
}
public IPrimitiveMapMarshaler MapMarshaler
{
get { return this.mapMarshaler; }
set { this.mapMarshaler = value; }
}
public int MaxInactivityDuration
{
get { return this.maxInactivityDuration; }
set { this.maxInactivityDuration = value; }
}
public int MaxInactivityDurationInitialDelay
{
get { return this.maxInactivityDurationInitialDelay; }
set { this.maxInactivityDurationInitialDelay = value; }
}
public long ReadCheckInterval
{
get { return this.MaxInactivityDuration; }
}
public long WriteCheckInterval
{
get { return maxInactivityDuration > 3 ? maxInactivityDuration / 3 : maxInactivityDuration; }
}
public void Marshal(Object o, BinaryWriter dataOut)
{
Tracer.Debug("StompWireFormat - Marshaling: " + o);
if(o is ConnectionInfo)
{
WriteConnectionInfo((ConnectionInfo) o, dataOut);
}
else if(o is Message)
{
WriteMessage((Message) o, dataOut);
}
else if(o is ConsumerInfo)
{
WriteConsumerInfo((ConsumerInfo) o, dataOut);
}
else if(o is MessageAck)
{
WriteMessageAck((MessageAck) o, dataOut);
}
else if(o is TransactionInfo)
{
WriteTransactionInfo((TransactionInfo) o, dataOut);
}
else if(o is ShutdownInfo)
{
WriteShutdownInfo((ShutdownInfo) o, dataOut);
}
else if(o is RemoveInfo)
{
WriteRemoveInfo((RemoveInfo) o, dataOut);
}
else if(o is KeepAliveInfo)
{
WriteKeepAliveInfo((KeepAliveInfo) o, dataOut);
}
else if(o is Command)
{
Command command = o as Command;
if(command.ResponseRequired)
{
Response response = new Response();
response.CorrelationId = command.CommandId;
SendCommand(response);
Tracer.Debug("StompWireFormat - Autorespond to command: " + o.GetType());
}
}
else
{
Tracer.Debug("StompWireFormat - Ignored command: " + o.GetType());
}
}
public Object Unmarshal(BinaryReader dataIn)
{
StompFrame frame = new StompFrame(this.encodeHeaders);
frame.FromStream(dataIn);
if (Tracer.IsDebugEnabled)
{
Tracer.Debug("Unmarshalled frame: " + frame);
}
Object answer = CreateCommand(frame);
return answer;
}
protected virtual Object CreateCommand(StompFrame frame)
{
string command = frame.Command;
if (Tracer.IsDebugEnabled)
{
Tracer.Debug("StompWireFormat - Received " + frame.ToString());
}
if(command == "RECEIPT")
{
string text = frame.RemoveProperty("receipt-id");
if(text != null)
{
Response answer = new Response();
if(text.StartsWith("ignore:"))
{
text = text.Substring("ignore:".Length);
}
answer.CorrelationId = Int32.Parse(text);
return answer;
}
}
else if(command == "CONNECTED")
{
return ReadConnected(frame);
}
else if(command == "ERROR")
{
string text = frame.RemoveProperty("receipt-id");
if(text != null && text.StartsWith("ignore:"))
{
Response answer = new Response();
answer.CorrelationId = Int32.Parse(text.Substring("ignore:".Length));
return answer;
}
else
{
ExceptionResponse answer = new ExceptionResponse();
if(text != null)
{
answer.CorrelationId = Int32.Parse(text);
}
BrokerError error = new BrokerError();
error.Message = frame.RemoveProperty("message");
answer.Exception = error;
return answer;
}
}
else if(command == "KEEPALIVE")
{
return new KeepAliveInfo();
}
else if(command == "MESSAGE")
{
return ReadMessage(frame);
}
Tracer.Error("Unknown command: " + frame.Command + " headers: " + frame.Properties);
return null;
}
protected virtual Command ReadConnected(StompFrame frame)
{
this.remoteWireFormatInfo = new WireFormatInfo();
if(frame.HasProperty("version"))
{
remoteWireFormatInfo.Version = Single.Parse(frame.RemoveProperty("version"),
CultureInfo.InvariantCulture);
if(remoteWireFormatInfo.Version > 1.0f)
{
this.encodeHeaders = true;
}
if(frame.HasProperty("session"))
{
remoteWireFormatInfo.Session = frame.RemoveProperty("session");
}
if(frame.HasProperty("heart-beat"))
{
string[] hearBeats = frame.RemoveProperty("heart-beat").Split(",".ToCharArray());
if(hearBeats.Length != 2)
{
throw new IOException("Malformed heartbeat property in Connected Frame.");
}
remoteWireFormatInfo.WriteCheckInterval = Int32.Parse(hearBeats[0].Trim());
remoteWireFormatInfo.ReadCheckInterval = Int32.Parse(hearBeats[1].Trim());
}
}
else
{
remoteWireFormatInfo.ReadCheckInterval = 0;
remoteWireFormatInfo.WriteCheckInterval = 0;
remoteWireFormatInfo.Version = 1.0f;
}
if(this.connectedResponseId != -1)
{
Response answer = new Response();
answer.CorrelationId = this.connectedResponseId;
SendCommand(answer);
this.connectedResponseId = -1;
}
else
{
throw new IOException("Received Connected Frame without a set Response Id for it.");
}
return remoteWireFormatInfo;
}
protected virtual Command ReadMessage(StompFrame frame)
{
Message message = null;
string transformation = frame.RemoveProperty("transformation");
if(frame.HasProperty("content-length"))
{
message = new BytesMessage();
message.Content = frame.Content;
}
else if(transformation == "jms-map-xml")
{
message = new MapMessage(this.mapMarshaler.Unmarshal(frame.Content) as PrimitiveMap);
}
else
{
message = new TextMessage(encoder.GetString(frame.Content, 0, frame.Content.Length));
}
// Remove any receipt header we might have attached if the outbound command was
// sent with response required set to true
frame.RemoveProperty("receipt");
// Clear any attached content length headers as they aren't needed anymore and can
// clutter the Message Properties.
frame.RemoveProperty("content-length");
message.Type = frame.RemoveProperty("type");
message.Destination = Destination.ConvertToDestination(frame.RemoveProperty("destination"));
message.ReplyTo = Destination.ConvertToDestination(frame.RemoveProperty("reply-to"));
message.TargetConsumerId = new ConsumerId(frame.RemoveProperty("subscription"));
message.CorrelationId = frame.RemoveProperty("correlation-id");
message.MessageId = new MessageId(frame.RemoveProperty("message-id"));
message.Persistent = StompHelper.ToBool(frame.RemoveProperty("persistent"), false);
// If it came from NMS.Stomp we added this header to ensure its reported on the
// receiver side.
if(frame.HasProperty("NMSXDeliveryMode"))
{
message.Persistent = StompHelper.ToBool(frame.RemoveProperty("NMSXDeliveryMode"), false);
}
if(frame.HasProperty("priority"))
{
message.Priority = Byte.Parse(frame.RemoveProperty("priority"));
}
if(frame.HasProperty("timestamp"))
{
message.Timestamp = Int64.Parse(frame.RemoveProperty("timestamp"));
}
if(frame.HasProperty("expires"))
{
message.Expiration = Int64.Parse(frame.RemoveProperty("expires"));
}
if(frame.RemoveProperty("redelivered") != null)
{
// We aren't told how many times that the message was redelivered so if it
// is tagged as redelivered we always set the counter to one.
message.RedeliveryCounter = 1;
}
// now lets add the generic headers
foreach(string key in frame.Properties.Keys)
{
Object value = frame.Properties[key];
if(value != null)
{
// lets coerce some standard header extensions
if(key == "JMSXGroupSeq" || key == "NMSXGroupSeq")
{
value = Int32.Parse(value.ToString());
message.Properties["NMSXGroupSeq"] = value;
continue;
}
else if(key == "JMSXGroupID" || key == "NMSXGroupID")
{
message.Properties["NMSXGroupID"] = value;
continue;
}
}
message.Properties[key] = value;
}
MessageDispatch dispatch = new MessageDispatch();
dispatch.Message = message;
dispatch.ConsumerId = message.TargetConsumerId;
dispatch.Destination = message.Destination;
dispatch.RedeliveryCounter = message.RedeliveryCounter;
return dispatch;
}
protected virtual void WriteMessage(Message command, BinaryWriter dataOut)
{
StompFrame frame = new StompFrame("SEND", encodeHeaders);
if(command.ResponseRequired)
{
frame.SetProperty("receipt", command.CommandId);
}
frame.SetProperty("destination", Destination.ConvertToStompString(command.Destination));
if(command.ReplyTo != null)
{
frame.SetProperty("reply-to", Destination.ConvertToStompString(command.ReplyTo));
}
if(command.CorrelationId != null )
{
frame.SetProperty("correlation-id", command.CorrelationId);
}
if(command.Expiration != 0)
{
frame.SetProperty("expires", command.Expiration);
}
if(command.Timestamp != 0)
{
frame.SetProperty("timestamp", command.Timestamp);
}
if(command.Priority != 4)
{
frame.SetProperty("priority", command.Priority);
}
if(command.Type != null)
{
frame.SetProperty("type", command.Type);
}
if(command.TransactionId!=null)
{
frame.SetProperty("transaction", command.TransactionId.ToString());
}
frame.SetProperty("persistent", command.Persistent.ToString().ToLower());
frame.SetProperty("NMSXDeliveryMode", command.Persistent.ToString().ToLower());
if(command.NMSXGroupID != null)
{
frame.SetProperty("JMSXGroupID", command.NMSXGroupID);
frame.SetProperty("NMSXGroupID", command.NMSXGroupID);
frame.SetProperty("JMSXGroupSeq", command.NMSXGroupSeq);
frame.SetProperty("NMSXGroupSeq", command.NMSXGroupSeq);
}
// Perform any Content Marshaling.
command.BeforeMarshall(this);
// Store the Marshaled Content.
frame.Content = command.Content;
if(command is BytesMessage)
{
if(command.Content != null && command.Content.Length > 0)
{
frame.SetProperty("content-length", command.Content.Length);
}
frame.SetProperty("transformation", "jms-byte");
}
else if(command is MapMessage)
{
frame.SetProperty("transformation", this.mapMarshaler.Name);
}
// Marshal all properties to the Frame.
IPrimitiveMap map = command.Properties;
foreach(string key in map.Keys)
{
frame.SetProperty(key, map[key]);
}
if(Tracer.IsDebugEnabled)
{
Tracer.Debug("StompWireFormat - Writing " + frame.ToString());
}
frame.ToStream(dataOut);
}
protected virtual void WriteMessageAck(MessageAck command, BinaryWriter dataOut)
{
StompFrame frame = new StompFrame("ACK", encodeHeaders);
if(command.ResponseRequired)
{
frame.SetProperty("receipt", "ignore:" + command.CommandId);
}
frame.SetProperty("message-id", command.LastMessageId.ToString());
frame.SetProperty("subscription", command.ConsumerId.ToString());
if(command.TransactionId != null)
{
frame.SetProperty("transaction", command.TransactionId.ToString());
}
if(Tracer.IsDebugEnabled)
{
Tracer.Debug("StompWireFormat - Writing " + frame.ToString());
}
frame.ToStream(dataOut);
}
protected virtual void WriteConnectionInfo(ConnectionInfo command, BinaryWriter dataOut)
{
// lets force a receipt for the Connect Frame.
StompFrame frame = new StompFrame("CONNECT", encodeHeaders);
frame.SetProperty("client-id", command.ClientId);
if(!String.IsNullOrEmpty(command.UserName))
{
frame.SetProperty("login", command.UserName);
}
if(!String.IsNullOrEmpty(command.Password))
{
frame.SetProperty("passcode", command.Password);
}
frame.SetProperty("host", command.Host);
frame.SetProperty("accept-version", "1.0,1.1");
if(MaxInactivityDuration != 0)
{
frame.SetProperty("heart-beat", WriteCheckInterval + "," + ReadCheckInterval);
}
if(Tracer.IsDebugEnabled)
{
Tracer.Debug("StompWireFormat - Writing " + frame.ToString());
}
this.connectedResponseId = command.CommandId;
frame.ToStream(dataOut);
}
protected virtual void WriteShutdownInfo(ShutdownInfo command, BinaryWriter dataOut)
{
System.Diagnostics.Debug.Assert(!command.ResponseRequired);
StompFrame frame = new StompFrame("DISCONNECT", encodeHeaders);
if(Tracer.IsDebugEnabled)
{
Tracer.Debug("StompWireFormat - Writing " + frame.ToString());
}
frame.ToStream(dataOut);
}
protected virtual void WriteConsumerInfo(ConsumerInfo command, BinaryWriter dataOut)
{
StompFrame frame = new StompFrame("SUBSCRIBE", encodeHeaders);
if(command.ResponseRequired)
{
frame.SetProperty("receipt", command.CommandId);
}
frame.SetProperty("destination", Destination.ConvertToStompString(command.Destination));
frame.SetProperty("id", command.ConsumerId.ToString());
frame.SetProperty("durable-subscriber-name", command.SubscriptionName);
frame.SetProperty("selector", command.Selector);
frame.SetProperty("ack", StompHelper.ToStomp(command.AckMode));
if(command.NoLocal)
{
frame.SetProperty("no-local", command.NoLocal.ToString());
}
// ActiveMQ extensions to STOMP
if(command.Transformation != null)
{
frame.SetProperty("transformation", command.Transformation);
}
else
{
frame.SetProperty("transformation", "jms-xml");
}
frame.SetProperty("activemq.dispatchAsync", command.DispatchAsync);
if(command.Exclusive)
{
frame.SetProperty("activemq.exclusive", command.Exclusive);
}
if(command.SubscriptionName != null)
{
frame.SetProperty("activemq.subscriptionName", command.SubscriptionName);
// For an older 4.0 broker we need to set this header so they get the
// subscription as well..
frame.SetProperty("activemq.subcriptionName", command.SubscriptionName);
}
frame.SetProperty("activemq.maximumPendingMessageLimit", command.MaximumPendingMessageLimit);
frame.SetProperty("activemq.prefetchSize", command.PrefetchSize);
frame.SetProperty("activemq.priority", command.Priority);
if(command.Retroactive)
{
frame.SetProperty("activemq.retroactive", command.Retroactive);
}
if(Tracer.IsDebugEnabled)
{
Tracer.Debug("StompWireFormat - Writing " + frame.ToString());
}
frame.ToStream(dataOut);
}
protected virtual void WriteKeepAliveInfo(KeepAliveInfo command, BinaryWriter dataOut)
{
StompFrame frame = new StompFrame(StompFrame.KEEPALIVE, encodeHeaders);
if(Tracer.IsDebugEnabled)
{
Tracer.Debug("StompWireFormat - Writing " + frame.ToString());
}
frame.ToStream(dataOut);
}
protected virtual void WriteRemoveInfo(RemoveInfo command, BinaryWriter dataOut)
{
StompFrame frame = new StompFrame("UNSUBSCRIBE", encodeHeaders);
object id = command.ObjectId;
if(id is ConsumerId)
{
ConsumerId consumerId = id as ConsumerId;
if(command.ResponseRequired)
{
frame.SetProperty("receipt", command.CommandId);
}
frame.SetProperty("id", consumerId.ToString() );
if(Tracer.IsDebugEnabled)
{
Tracer.Debug("StompWireFormat - Writing " + frame.ToString());
}
frame.ToStream(dataOut);
}
}
protected virtual void WriteTransactionInfo(TransactionInfo command, BinaryWriter dataOut)
{
string type = "BEGIN";
TransactionType transactionType = (TransactionType) command.Type;
switch(transactionType)
{
case TransactionType.Commit:
command.ResponseRequired = true;
type = "COMMIT";
break;
case TransactionType.Rollback:
command.ResponseRequired = true;
type = "ABORT";
break;
}
Tracer.Debug("StompWireFormat - For transaction type: " + transactionType +
" we are using command type: " + type);
StompFrame frame = new StompFrame(type, encodeHeaders);
if(command.ResponseRequired)
{
frame.SetProperty("receipt", command.CommandId);
}
frame.SetProperty("transaction", command.TransactionId.ToString());
if(Tracer.IsDebugEnabled)
{
Tracer.Debug("StompWireFormat - Writing " + frame.ToString());
}
frame.ToStream(dataOut);
}
protected virtual void SendCommand(Command command)
{
if(transport == null)
{
Tracer.Fatal("No transport configured so cannot return command: " + command);
}
else
{
transport.Command(transport, command);
}
}
protected virtual string ToString(object value)
{
if(value != null)
{
return value.ToString();
}
else
{
return null;
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.