context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* [email protected]. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Designer.Interfaces;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using ErrorHandler = Microsoft.VisualStudio.ErrorHandler;
using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
using VSConstants = Microsoft.VisualStudio.VSConstants;
namespace Microsoft.VisualStudioTools.Project {
/// <summary>
/// Common factory for creating our editor
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")]
public abstract class CommonEditorFactory : IVsEditorFactory {
private Package _package;
private ServiceProvider _serviceProvider;
private readonly bool _promptEncodingOnLoad;
public CommonEditorFactory(Package package) {
_package = package;
}
public CommonEditorFactory(Package package, bool promptEncodingOnLoad) {
_package = package;
_promptEncodingOnLoad = promptEncodingOnLoad;
}
#region IVsEditorFactory Members
public virtual int SetSite(Microsoft.VisualStudio.OLE.Interop.IServiceProvider psp) {
_serviceProvider = new ServiceProvider(psp);
return VSConstants.S_OK;
}
public virtual object GetService(Type serviceType) {
return _serviceProvider.GetService(serviceType);
}
// This method is called by the Environment (inside IVsUIShellOpenDocument::
// OpenStandardEditor and OpenSpecificEditor) to map a LOGICAL view to a
// PHYSICAL view. A LOGICAL view identifies the purpose of the view that is
// desired (e.g. a view appropriate for Debugging [LOGVIEWID_Debugging], or a
// view appropriate for text view manipulation as by navigating to a find
// result [LOGVIEWID_TextView]). A PHYSICAL view identifies an actual type
// of view implementation that an IVsEditorFactory can create.
//
// NOTE: Physical views are identified by a string of your choice with the
// one constraint that the default/primary physical view for an editor
// *MUST* use a NULL string as its physical view name (*pbstrPhysicalView = NULL).
//
// NOTE: It is essential that the implementation of MapLogicalView properly
// validates that the LogicalView desired is actually supported by the editor.
// If an unsupported LogicalView is requested then E_NOTIMPL must be returned.
//
// NOTE: The special Logical Views supported by an Editor Factory must also
// be registered in the local registry hive. LOGVIEWID_Primary is implicitly
// supported by all editor types and does not need to be registered.
// For example, an editor that supports a ViewCode/ViewDesigner scenario
// might register something like the following:
// HKLM\Software\Microsoft\VisualStudio\9.0\Editors\
// {...guidEditor...}\
// LogicalViews\
// {...LOGVIEWID_TextView...} = s ''
// {...LOGVIEWID_Code...} = s ''
// {...LOGVIEWID_Debugging...} = s ''
// {...LOGVIEWID_Designer...} = s 'Form'
//
public virtual int MapLogicalView(ref Guid logicalView, out string physicalView) {
// initialize out parameter
physicalView = null;
bool isSupportedView = false;
// Determine the physical view
if (VSConstants.LOGVIEWID_Primary == logicalView ||
VSConstants.LOGVIEWID_Debugging == logicalView ||
VSConstants.LOGVIEWID_Code == logicalView ||
VSConstants.LOGVIEWID_TextView == logicalView) {
// primary view uses NULL as pbstrPhysicalView
isSupportedView = true;
} else if (VSConstants.LOGVIEWID_Designer == logicalView) {
physicalView = "Design";
isSupportedView = true;
}
if (isSupportedView)
return VSConstants.S_OK;
else {
// E_NOTIMPL must be returned for any unrecognized rguidLogicalView values
return VSConstants.E_NOTIMPL;
}
}
public virtual int Close() {
return VSConstants.S_OK;
}
/// <summary>
///
/// </summary>
/// <param name="grfCreateDoc"></param>
/// <param name="pszMkDocument"></param>
/// <param name="pszPhysicalView"></param>
/// <param name="pvHier"></param>
/// <param name="itemid"></param>
/// <param name="punkDocDataExisting"></param>
/// <param name="ppunkDocView"></param>
/// <param name="ppunkDocData"></param>
/// <param name="pbstrEditorCaption"></param>
/// <param name="pguidCmdUI"></param>
/// <param name="pgrfCDW"></param>
/// <returns></returns>
public virtual int CreateEditorInstance(
uint createEditorFlags,
string documentMoniker,
string physicalView,
IVsHierarchy hierarchy,
uint itemid,
System.IntPtr docDataExisting,
out System.IntPtr docView,
out System.IntPtr docData,
out string editorCaption,
out Guid commandUIGuid,
out int createDocumentWindowFlags) {
// Initialize output parameters
docView = IntPtr.Zero;
docData = IntPtr.Zero;
commandUIGuid = Guid.Empty;
createDocumentWindowFlags = 0;
editorCaption = null;
// Validate inputs
if ((createEditorFlags & (VSConstants.CEF_OPENFILE | VSConstants.CEF_SILENT)) == 0) {
return VSConstants.E_INVALIDARG;
}
if (_promptEncodingOnLoad && docDataExisting != IntPtr.Zero) {
return VSConstants.VS_E_INCOMPATIBLEDOCDATA;
}
// Get a text buffer
IVsTextLines textLines = GetTextBuffer(docDataExisting);
// Assign docData IntPtr to either existing docData or the new text buffer
if (docDataExisting != IntPtr.Zero) {
docData = docDataExisting;
Marshal.AddRef(docData);
} else {
docData = Marshal.GetIUnknownForObject(textLines);
}
try {
docView = CreateDocumentView(documentMoniker, physicalView, hierarchy, itemid, textLines, out editorCaption, out commandUIGuid);
} finally {
if (docView == IntPtr.Zero) {
if (docDataExisting != docData && docData != IntPtr.Zero) {
// Cleanup the instance of the docData that we have addref'ed
Marshal.Release(docData);
docData = IntPtr.Zero;
}
}
}
return VSConstants.S_OK;
}
#endregion
#region Helper methods
private IVsTextLines GetTextBuffer(System.IntPtr docDataExisting) {
IVsTextLines textLines;
if (docDataExisting == IntPtr.Zero) {
// Create a new IVsTextLines buffer.
Type textLinesType = typeof(IVsTextLines);
Guid riid = textLinesType.GUID;
Guid clsid = typeof(VsTextBufferClass).GUID;
textLines = _package.CreateInstance(ref clsid, ref riid, textLinesType) as IVsTextLines;
// set the buffer's site
((IObjectWithSite)textLines).SetSite(_serviceProvider.GetService(typeof(IOleServiceProvider)));
} else {
// Use the existing text buffer
Object dataObject = Marshal.GetObjectForIUnknown(docDataExisting);
textLines = dataObject as IVsTextLines;
if (textLines == null) {
// Try get the text buffer from textbuffer provider
IVsTextBufferProvider textBufferProvider = dataObject as IVsTextBufferProvider;
if (textBufferProvider != null) {
textBufferProvider.GetTextBuffer(out textLines);
}
}
if (textLines == null) {
// Unknown docData type then, so we have to force VS to close the other editor.
ErrorHandler.ThrowOnFailure((int)VSConstants.VS_E_INCOMPATIBLEDOCDATA);
}
}
return textLines;
}
private IntPtr CreateDocumentView(string documentMoniker, string physicalView, IVsHierarchy hierarchy, uint itemid, IVsTextLines textLines, out string editorCaption, out Guid cmdUI) {
//Init out params
editorCaption = string.Empty;
cmdUI = Guid.Empty;
if (string.IsNullOrEmpty(physicalView)) {
// create code window as default physical view
return CreateCodeView(documentMoniker, textLines, ref editorCaption, ref cmdUI);
} else if (string.Compare(physicalView, "design", true, CultureInfo.InvariantCulture) == 0) {
// Create Form view
return CreateFormView(hierarchy, itemid, textLines, ref editorCaption, ref cmdUI);
}
// We couldn't create the view
// Return special error code so VS can try another editor factory.
ErrorHandler.ThrowOnFailure((int)VSConstants.VS_E_UNSUPPORTEDFORMAT);
return IntPtr.Zero;
}
private IntPtr CreateFormView(IVsHierarchy hierarchy, uint itemid, IVsTextLines textLines, ref string editorCaption, ref Guid cmdUI) {
// Request the Designer Service
IVSMDDesignerService designerService = (IVSMDDesignerService)GetService(typeof(IVSMDDesignerService));
// Create loader for the designer
IVSMDDesignerLoader designerLoader = (IVSMDDesignerLoader)designerService.CreateDesignerLoader("Microsoft.VisualStudio.Designer.Serialization.VSDesignerLoader");
bool loaderInitalized = false;
try {
IOleServiceProvider provider = _serviceProvider.GetService(typeof(IOleServiceProvider)) as IOleServiceProvider;
// Initialize designer loader
designerLoader.Initialize(provider, hierarchy, (int)itemid, textLines);
loaderInitalized = true;
// Create the designer
IVSMDDesigner designer = designerService.CreateDesigner(provider, designerLoader);
// Get editor caption
editorCaption = designerLoader.GetEditorCaption((int)READONLYSTATUS.ROSTATUS_Unknown);
// Get view from designer
object docView = designer.View;
// Get command guid from designer
cmdUI = designer.CommandGuid;
return Marshal.GetIUnknownForObject(docView);
} catch {
// The designer loader may have created a reference to the shell or the text buffer.
// In case we fail to create the designer we should manually dispose the loader
// in order to release the references to the shell and the textbuffer
if (loaderInitalized) {
designerLoader.Dispose();
}
throw;
}
}
private IntPtr CreateCodeView(string documentMoniker, IVsTextLines textLines, ref string editorCaption, ref Guid cmdUI) {
Type codeWindowType = typeof(IVsCodeWindow);
Guid riid = codeWindowType.GUID;
Guid clsid = typeof(VsCodeWindowClass).GUID;
IVsCodeWindow window = (IVsCodeWindow)_package.CreateInstance(ref clsid, ref riid, codeWindowType);
ErrorHandler.ThrowOnFailure(window.SetBuffer(textLines));
ErrorHandler.ThrowOnFailure(window.SetBaseEditorCaption(null));
ErrorHandler.ThrowOnFailure(window.GetEditorCaption(READONLYSTATUS.ROSTATUS_Unknown, out editorCaption));
IVsUserData userData = textLines as IVsUserData;
if (userData != null) {
if (_promptEncodingOnLoad) {
var guid = VSConstants.VsTextBufferUserDataGuid.VsBufferEncodingPromptOnLoad_guid;
userData.SetData(ref guid, (uint)1);
}
}
InitializeLanguageService(textLines);
cmdUI = VSConstants.GUID_TextEditorFactory;
return Marshal.GetIUnknownForObject(window);
}
/// <summary>
/// Initializes the language service for the given file. This allows files with different
/// extensions to be opened by the editor type and get correct highlighting and intellisense
/// controllers.
///
/// New in 1.1
/// </summary>
protected virtual void InitializeLanguageService(IVsTextLines textLines) {
}
#endregion
protected void InitializeLanguageService(IVsTextLines textLines, Guid langSid) {
IVsUserData userData = textLines as IVsUserData;
if (userData != null) {
if (langSid != Guid.Empty) {
Guid vsCoreSid = new Guid("{8239bec4-ee87-11d0-8c98-00c04fc2ab22}");
Guid currentSid;
ErrorHandler.ThrowOnFailure(textLines.GetLanguageServiceID(out currentSid));
// If the language service is set to the default SID, then
// set it to our language
if (currentSid == vsCoreSid) {
ErrorHandler.ThrowOnFailure(textLines.SetLanguageServiceID(ref langSid));
} else if (currentSid != langSid) {
// Some other language service has it, so return VS_E_INCOMPATIBLEDOCDATA
throw new COMException("Incompatible doc data", VSConstants.VS_E_INCOMPATIBLEDOCDATA);
}
Guid bufferDetectLang = VSConstants.VsTextBufferUserDataGuid.VsBufferDetectLangSID_guid;
ErrorHandler.ThrowOnFailure(userData.SetData(ref bufferDetectLang, false));
}
}
}
}
}
| |
namespace GrantApp
{
partial class AddGrantor
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.txtName = new System.Windows.Forms.TextBox();
this.lblName = new System.Windows.Forms.Label();
this.txtAddress = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.txtPhone = new System.Windows.Forms.TextBox();
this.txtCity = new System.Windows.Forms.TextBox();
this.txtZip = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.txtEmail = new System.Windows.Forms.TextBox();
this.label7 = new System.Windows.Forms.Label();
this.txtFax = new System.Windows.Forms.TextBox();
this.txtContactName = new System.Windows.Forms.TextBox();
this.label8 = new System.Windows.Forms.Label();
this.label9 = new System.Windows.Forms.Label();
this.txtContactTitle = new System.Windows.Forms.TextBox();
this.btnOkay = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.label10 = new System.Windows.Forms.Label();
this.label11 = new System.Windows.Forms.Label();
this.txtAvgGift = new System.Windows.Forms.TextBox();
this.label12 = new System.Windows.Forms.Label();
this.label13 = new System.Windows.Forms.Label();
this.label14 = new System.Windows.Forms.Label();
this.txtTypeOfSupport = new GrantApp.TextBoxWithExpandButton();
this.txtGivingHistory = new GrantApp.TextBoxWithExpandButton();
this.txtBuzzwords = new GrantApp.TextBoxWithExpandButton();
this.txtNotes = new GrantApp.TextBoxWithExpandButton();
this.txtError = new System.Windows.Forms.Label();
this.dropState = new GrantApp.BetterComboBox();
this.SuspendLayout();
//
// txtName
//
this.txtName.Location = new System.Drawing.Point(66, 12);
this.txtName.MaxLength = 50;
this.txtName.Name = "txtName";
this.txtName.Size = new System.Drawing.Size(242, 20);
this.txtName.TabIndex = 0;
//
// lblName
//
this.lblName.AutoSize = true;
this.lblName.Location = new System.Drawing.Point(12, 15);
this.lblName.Name = "lblName";
this.lblName.Size = new System.Drawing.Size(38, 13);
this.lblName.TabIndex = 5;
this.lblName.Text = "Name:";
//
// txtAddress
//
this.txtAddress.Location = new System.Drawing.Point(66, 39);
this.txtAddress.MaxLength = 100;
this.txtAddress.Name = "txtAddress";
this.txtAddress.Size = new System.Drawing.Size(242, 20);
this.txtAddress.TabIndex = 1;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 42);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(48, 13);
this.label1.TabIndex = 7;
this.label1.Text = "Address:";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(12, 99);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(35, 13);
this.label2.TabIndex = 8;
this.label2.Text = "State:";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(12, 71);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(27, 13);
this.label3.TabIndex = 9;
this.label3.Text = "City:";
//
// txtPhone
//
this.txtPhone.Location = new System.Drawing.Point(66, 185);
this.txtPhone.MaxLength = 50;
this.txtPhone.Name = "txtPhone";
this.txtPhone.Size = new System.Drawing.Size(242, 20);
this.txtPhone.TabIndex = 6;
//
// txtCity
//
this.txtCity.Location = new System.Drawing.Point(66, 71);
this.txtCity.MaxLength = 50;
this.txtCity.Name = "txtCity";
this.txtCity.Size = new System.Drawing.Size(242, 20);
this.txtCity.TabIndex = 2;
//
// txtZip
//
this.txtZip.Location = new System.Drawing.Point(66, 133);
this.txtZip.MaxLength = 15;
this.txtZip.Name = "txtZip";
this.txtZip.Size = new System.Drawing.Size(242, 20);
this.txtZip.TabIndex = 4;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(12, 133);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(25, 13);
this.label4.TabIndex = 15;
this.label4.Text = "Zip:";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(12, 192);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(41, 13);
this.label5.TabIndex = 16;
this.label5.Text = "Phone:";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(12, 166);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(35, 13);
this.label6.TabIndex = 17;
this.label6.Text = "Email:";
//
// txtEmail
//
this.txtEmail.Location = new System.Drawing.Point(66, 159);
this.txtEmail.MaxLength = 50;
this.txtEmail.Name = "txtEmail";
this.txtEmail.Size = new System.Drawing.Size(242, 20);
this.txtEmail.TabIndex = 5;
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(12, 220);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(27, 13);
this.label7.TabIndex = 20;
this.label7.Text = "Fax:";
//
// txtFax
//
this.txtFax.Location = new System.Drawing.Point(66, 213);
this.txtFax.MaxLength = 20;
this.txtFax.Name = "txtFax";
this.txtFax.Size = new System.Drawing.Size(242, 20);
this.txtFax.TabIndex = 7;
//
// txtContactName
//
this.txtContactName.Location = new System.Drawing.Point(98, 254);
this.txtContactName.MaxLength = 50;
this.txtContactName.Name = "txtContactName";
this.txtContactName.Size = new System.Drawing.Size(210, 20);
this.txtContactName.TabIndex = 8;
//
// label8
//
this.label8.AutoSize = true;
this.label8.Cursor = System.Windows.Forms.Cursors.Default;
this.label8.Location = new System.Drawing.Point(12, 254);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(78, 13);
this.label8.TabIndex = 22;
this.label8.Text = "Contact Name:";
//
// label9
//
this.label9.AutoSize = true;
this.label9.Cursor = System.Windows.Forms.Cursors.Default;
this.label9.Location = new System.Drawing.Point(12, 288);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(70, 13);
this.label9.TabIndex = 24;
this.label9.Text = "Contact Title:";
//
// txtContactTitle
//
this.txtContactTitle.Location = new System.Drawing.Point(98, 285);
this.txtContactTitle.MaxLength = 50;
this.txtContactTitle.Name = "txtContactTitle";
this.txtContactTitle.Size = new System.Drawing.Size(210, 20);
this.txtContactTitle.TabIndex = 9;
//
// btnOkay
//
this.btnOkay.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnOkay.DialogResult = System.Windows.Forms.DialogResult.OK;
this.btnOkay.Location = new System.Drawing.Point(482, 409);
this.btnOkay.Name = "btnOkay";
this.btnOkay.Size = new System.Drawing.Size(75, 23);
this.btnOkay.TabIndex = 15;
this.btnOkay.Text = "OK";
this.btnOkay.UseVisualStyleBackColor = true;
//
// btnCancel
//
this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnCancel.CausesValidation = false;
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.Location = new System.Drawing.Point(563, 409);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(75, 23);
this.btnCancel.TabIndex = 16;
this.btnCancel.Text = "Cancel";
this.btnCancel.UseVisualStyleBackColor = true;
//
// label10
//
this.label10.AutoSize = true;
this.label10.Location = new System.Drawing.Point(314, 15);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(66, 13);
this.label10.TabIndex = 25;
this.label10.Text = "Average Gift";
//
// label11
//
this.label11.AutoSize = true;
this.label11.Location = new System.Drawing.Point(12, 316);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(86, 13);
this.label11.TabIndex = 26;
this.label11.Text = "Type of Support:";
//
// txtAvgGift
//
this.txtAvgGift.Location = new System.Drawing.Point(392, 12);
this.txtAvgGift.Name = "txtAvgGift";
this.txtAvgGift.Size = new System.Drawing.Size(165, 20);
this.txtAvgGift.TabIndex = 11;
//
// label12
//
this.label12.AutoSize = true;
this.label12.Location = new System.Drawing.Point(314, 162);
this.label12.Name = "label12";
this.label12.Size = new System.Drawing.Size(58, 13);
this.label12.TabIndex = 30;
this.label12.Text = "Buzzwords";
//
// label13
//
this.label13.AutoSize = true;
this.label13.Location = new System.Drawing.Point(314, 285);
this.label13.Name = "label13";
this.label13.Size = new System.Drawing.Size(35, 13);
this.label13.TabIndex = 32;
this.label13.Text = "Notes";
//
// label14
//
this.label14.AutoSize = true;
this.label14.Location = new System.Drawing.Point(314, 42);
this.label14.Name = "label14";
this.label14.Size = new System.Drawing.Size(72, 13);
this.label14.TabIndex = 34;
this.label14.Text = "Giving History";
//
// txtTypeOfSupport
//
this.txtTypeOfSupport.AcceptsReturn = true;
this.txtTypeOfSupport.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.txtTypeOfSupport.Location = new System.Drawing.Point(98, 316);
this.txtTypeOfSupport.Multiline = true;
this.txtTypeOfSupport.Name = "txtTypeOfSupport";
this.txtTypeOfSupport.ReadOnly = false;
this.txtTypeOfSupport.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtTypeOfSupport.Size = new System.Drawing.Size(210, 116);
this.txtTypeOfSupport.TabIndex = 10;
//
// txtGivingHistory
//
this.txtGivingHistory.AcceptsReturn = true;
this.txtGivingHistory.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtGivingHistory.Location = new System.Drawing.Point(392, 42);
this.txtGivingHistory.Multiline = true;
this.txtGivingHistory.Name = "txtGivingHistory";
this.txtGivingHistory.ReadOnly = false;
this.txtGivingHistory.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtGivingHistory.Size = new System.Drawing.Size(246, 114);
this.txtGivingHistory.TabIndex = 12;
//
// txtBuzzwords
//
this.txtBuzzwords.AcceptsReturn = true;
this.txtBuzzwords.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtBuzzwords.Location = new System.Drawing.Point(392, 162);
this.txtBuzzwords.Multiline = true;
this.txtBuzzwords.Name = "txtBuzzwords";
this.txtBuzzwords.ReadOnly = false;
this.txtBuzzwords.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtBuzzwords.Size = new System.Drawing.Size(246, 112);
this.txtBuzzwords.TabIndex = 13;
//
// txtNotes
//
this.txtNotes.AcceptsReturn = true;
this.txtNotes.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtNotes.Location = new System.Drawing.Point(392, 285);
this.txtNotes.Multiline = true;
this.txtNotes.Name = "txtNotes";
this.txtNotes.ReadOnly = false;
this.txtNotes.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtNotes.Size = new System.Drawing.Size(246, 118);
this.txtNotes.TabIndex = 14;
//
// txtError
//
this.txtError.AutoSize = true;
this.txtError.ForeColor = System.Drawing.Color.DarkRed;
this.txtError.Location = new System.Drawing.Point(100, 9);
this.txtError.Name = "txtError";
this.txtError.Size = new System.Drawing.Size(0, 13);
this.txtError.TabIndex = 35;
//
// dropState
//
this.dropState.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend;
this.dropState.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems;
this.dropState.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.dropState.FormattingEnabled = true;
this.dropState.Location = new System.Drawing.Point(66, 99);
this.dropState.Name = "dropState";
this.dropState.Size = new System.Drawing.Size(242, 21);
this.dropState.TabIndex = 3;
//
// AddGrantor
//
this.AcceptButton = this.btnOkay;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoValidate = System.Windows.Forms.AutoValidate.EnableAllowFocusChange;
this.CancelButton = this.btnCancel;
this.ClientSize = new System.Drawing.Size(650, 444);
this.Controls.Add(this.txtError);
this.Controls.Add(this.txtNotes);
this.Controls.Add(this.txtBuzzwords);
this.Controls.Add(this.txtGivingHistory);
this.Controls.Add(this.txtTypeOfSupport);
this.Controls.Add(this.label14);
this.Controls.Add(this.label13);
this.Controls.Add(this.label12);
this.Controls.Add(this.txtAvgGift);
this.Controls.Add(this.label11);
this.Controls.Add(this.label10);
this.Controls.Add(this.btnOkay);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.label9);
this.Controls.Add(this.txtContactTitle);
this.Controls.Add(this.label8);
this.Controls.Add(this.txtContactName);
this.Controls.Add(this.label7);
this.Controls.Add(this.txtFax);
this.Controls.Add(this.txtEmail);
this.Controls.Add(this.label6);
this.Controls.Add(this.label5);
this.Controls.Add(this.label4);
this.Controls.Add(this.txtZip);
this.Controls.Add(this.txtCity);
this.Controls.Add(this.dropState);
this.Controls.Add(this.txtPhone);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.txtAddress);
this.Controls.Add(this.lblName);
this.Controls.Add(this.txtName);
this.Name = "AddGrantor";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Grantor Editor";
this.Load += new System.EventHandler(this.AddGrantor_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox txtName;
private System.Windows.Forms.Label lblName;
private System.Windows.Forms.TextBox txtAddress;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox txtPhone;
private System.Windows.Forms.TextBox txtCity;
private System.Windows.Forms.TextBox txtZip;
protected System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.TextBox txtEmail;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.TextBox txtFax;
private System.Windows.Forms.TextBox txtContactName;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.TextBox txtContactTitle;
private System.Windows.Forms.Button btnOkay;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.TextBox txtAvgGift;
private System.Windows.Forms.Label label12;
private System.Windows.Forms.Label label13;
private System.Windows.Forms.Label label14;
private GrantApp.TextBoxWithExpandButton txtTypeOfSupport;
private GrantApp.TextBoxWithExpandButton txtGivingHistory;
private GrantApp.TextBoxWithExpandButton txtBuzzwords;
private GrantApp.TextBoxWithExpandButton txtNotes;
private System.Windows.Forms.Label txtError;
private BetterComboBox dropState;
//private Database1DataSet database1DataSet;
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using Lucene.Net.Documents;
using Lucene.Net.Support;
namespace Lucene.Net.Index
{
using Lucene.Net.Randomized.Generators;
using NUnit.Framework;
using IBits = Lucene.Net.Util.IBits;
using BytesRef = Lucene.Net.Util.BytesRef;
using Directory = Lucene.Net.Store.Directory;
using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator;
using Document = Documents.Document;
using Field = Field;
using FieldType = FieldType;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
/*
* 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 MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using TestUtil = Lucene.Net.Util.TestUtil;
using TextField = TextField;
[TestFixture]
public class TestDocsAndPositions : LuceneTestCase
{
private string FieldName;
[SetUp]
public override void SetUp()
{
base.SetUp();
FieldName = "field" + Random().Next();
}
/// <summary>
/// Simple testcase for <seealso cref="DocsAndPositionsEnum"/>
/// </summary>
[Test]
public virtual void TestPositionsSimple()
{
Directory directory = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random(), directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
for (int i = 0; i < 39; i++)
{
Document doc = new Document();
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.OmitNorms = true;
doc.Add(NewField(FieldName, "1 2 3 4 5 6 7 8 9 10 " + "1 2 3 4 5 6 7 8 9 10 " + "1 2 3 4 5 6 7 8 9 10 " + "1 2 3 4 5 6 7 8 9 10", customType));
writer.AddDocument(doc);
}
IndexReader reader = writer.Reader;
writer.Dispose();
int num = AtLeast(13);
for (int i = 0; i < num; i++)
{
BytesRef bytes = new BytesRef("1");
IndexReaderContext topReaderContext = reader.Context;
foreach (AtomicReaderContext atomicReaderContext in topReaderContext.Leaves)
{
DocsAndPositionsEnum docsAndPosEnum = GetDocsAndPositions((AtomicReader)atomicReaderContext.Reader, bytes, null);
Assert.IsNotNull(docsAndPosEnum);
if (atomicReaderContext.Reader.MaxDoc == 0)
{
continue;
}
int advance = docsAndPosEnum.Advance(Random().Next(atomicReaderContext.Reader.MaxDoc));
do
{
string msg = "Advanced to: " + advance + " current doc: " + docsAndPosEnum.DocID; // TODO: + " usePayloads: " + usePayload;
Assert.AreEqual(4, docsAndPosEnum.Freq, msg);
Assert.AreEqual(0, docsAndPosEnum.NextPosition(), msg);
Assert.AreEqual(4, docsAndPosEnum.Freq, msg);
Assert.AreEqual(10, docsAndPosEnum.NextPosition(), msg);
Assert.AreEqual(4, docsAndPosEnum.Freq, msg);
Assert.AreEqual(20, docsAndPosEnum.NextPosition(), msg);
Assert.AreEqual(4, docsAndPosEnum.Freq, msg);
Assert.AreEqual(30, docsAndPosEnum.NextPosition(), msg);
} while (docsAndPosEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
}
}
reader.Dispose();
directory.Dispose();
}
public virtual DocsAndPositionsEnum GetDocsAndPositions(AtomicReader reader, BytesRef bytes, IBits liveDocs)
{
Terms terms = reader.GetTerms(FieldName);
if (terms != null)
{
TermsEnum te = terms.GetIterator(null);
if (te.SeekExact(bytes))
{
return te.DocsAndPositions(liveDocs, null);
}
}
return null;
}
/// <summary>
/// this test indexes random numbers within a range into a field and checks
/// their occurrences by searching for a number from that range selected at
/// random. All positions for that number are saved up front and compared to
/// the enums positions.
/// </summary>
[Test]
public virtual void TestRandomPositions()
{
Directory dir = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMergePolicy(NewLogMergePolicy()));
int numDocs = AtLeast(47);
int max = 1051;
int term = Random().Next(max);
int?[][] positionsInDoc = new int?[numDocs][];
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.OmitNorms = true;
for (int i = 0; i < numDocs; i++)
{
Document doc = new Document();
List<int?> positions = new List<int?>();
StringBuilder builder = new StringBuilder();
int num = AtLeast(131);
for (int j = 0; j < num; j++)
{
int nextInt = Random().Next(max);
builder.Append(nextInt).Append(" ");
if (nextInt == term)
{
positions.Add(Convert.ToInt32(j));
}
}
if (positions.Count == 0)
{
builder.Append(term);
positions.Add(num);
}
doc.Add(NewField(FieldName, builder.ToString(), customType));
positionsInDoc[i] = positions.ToArray();
writer.AddDocument(doc);
}
IndexReader reader = writer.Reader;
writer.Dispose();
int num_ = AtLeast(13);
for (int i = 0; i < num_; i++)
{
BytesRef bytes = new BytesRef("" + term);
IndexReaderContext topReaderContext = reader.Context;
foreach (AtomicReaderContext atomicReaderContext in topReaderContext.Leaves)
{
DocsAndPositionsEnum docsAndPosEnum = GetDocsAndPositions((AtomicReader)atomicReaderContext.Reader, bytes, null);
Assert.IsNotNull(docsAndPosEnum);
int initDoc = 0;
int maxDoc = atomicReaderContext.Reader.MaxDoc;
// initially advance or do next doc
if (Random().NextBoolean())
{
initDoc = docsAndPosEnum.NextDoc();
}
else
{
initDoc = docsAndPosEnum.Advance(Random().Next(maxDoc));
}
// now run through the scorer and check if all positions are there...
do
{
int docID = docsAndPosEnum.DocID;
if (docID == DocIdSetIterator.NO_MORE_DOCS)
{
break;
}
int?[] pos = positionsInDoc[atomicReaderContext.DocBase + docID];
Assert.AreEqual(pos.Length, docsAndPosEnum.Freq);
// number of positions read should be random - don't read all of them
// allways
int howMany = Random().Next(20) == 0 ? pos.Length - Random().Next(pos.Length) : pos.Length;
for (int j = 0; j < howMany; j++)
{
Assert.AreEqual(pos[j], docsAndPosEnum.NextPosition(), "iteration: " + i + " initDoc: " + initDoc + " doc: " + docID + " base: " + atomicReaderContext.DocBase + " positions: " + pos); /* TODO: + " usePayloads: "
+ usePayload*/
}
if (Random().Next(10) == 0) // once is a while advance
{
if (docsAndPosEnum.Advance(docID + 1 + Random().Next((maxDoc - docID))) == DocIdSetIterator.NO_MORE_DOCS)
{
break;
}
}
} while (docsAndPosEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
}
}
reader.Dispose();
dir.Dispose();
}
[Test]
public virtual void TestRandomDocs()
{
Directory dir = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMergePolicy(NewLogMergePolicy()));
int numDocs = AtLeast(49);
int max = 15678;
int term = Random().Next(max);
int[] freqInDoc = new int[numDocs];
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.OmitNorms = true;
for (int i = 0; i < numDocs; i++)
{
Document doc = new Document();
StringBuilder builder = new StringBuilder();
for (int j = 0; j < 199; j++)
{
int nextInt = Random().Next(max);
builder.Append(nextInt).Append(' ');
if (nextInt == term)
{
freqInDoc[i]++;
}
}
doc.Add(NewField(FieldName, builder.ToString(), customType));
writer.AddDocument(doc);
}
IndexReader reader = writer.Reader;
writer.Dispose();
int num = AtLeast(13);
for (int i = 0; i < num; i++)
{
BytesRef bytes = new BytesRef("" + term);
IndexReaderContext topReaderContext = reader.Context;
foreach (AtomicReaderContext context in topReaderContext.Leaves)
{
int maxDoc = context.AtomicReader.MaxDoc;
DocsEnum docsEnum = TestUtil.Docs(Random(), context.Reader, FieldName, bytes, null, null, DocsFlags.FREQS);
if (FindNext(freqInDoc, context.DocBase, context.DocBase + maxDoc) == int.MaxValue)
{
Assert.IsNull(docsEnum);
continue;
}
Assert.IsNotNull(docsEnum);
docsEnum.NextDoc();
for (int j = 0; j < maxDoc; j++)
{
if (freqInDoc[context.DocBase + j] != 0)
{
Assert.AreEqual(j, docsEnum.DocID);
Assert.AreEqual(docsEnum.Freq, freqInDoc[context.DocBase + j]);
if (i % 2 == 0 && Random().Next(10) == 0)
{
int next = FindNext(freqInDoc, context.DocBase + j + 1, context.DocBase + maxDoc) - context.DocBase;
int advancedTo = docsEnum.Advance(next);
if (next >= maxDoc)
{
Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, advancedTo);
}
else
{
Assert.IsTrue(next >= advancedTo, "advanced to: " + advancedTo + " but should be <= " + next);
}
}
else
{
docsEnum.NextDoc();
}
}
}
Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, docsEnum.DocID, "DocBase: " + context.DocBase + " maxDoc: " + maxDoc + " " + docsEnum.GetType());
}
}
reader.Dispose();
dir.Dispose();
}
private static int FindNext(int[] docs, int pos, int max)
{
for (int i = pos; i < max; i++)
{
if (docs[i] != 0)
{
return i;
}
}
return int.MaxValue;
}
/// <summary>
/// tests retrieval of positions for terms that have a large number of
/// occurrences to force test of buffer refill during positions iteration.
/// </summary>
[Test]
public virtual void TestLargeNumberOfPositions()
{
Directory dir = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
int howMany = 1000;
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.OmitNorms = true;
for (int i = 0; i < 39; i++)
{
Document doc = new Document();
StringBuilder builder = new StringBuilder();
for (int j = 0; j < howMany; j++)
{
if (j % 2 == 0)
{
builder.Append("even ");
}
else
{
builder.Append("odd ");
}
}
doc.Add(NewField(FieldName, builder.ToString(), customType));
writer.AddDocument(doc);
}
// now do searches
IndexReader reader = writer.Reader;
writer.Dispose();
int num = AtLeast(13);
for (int i = 0; i < num; i++)
{
BytesRef bytes = new BytesRef("even");
IndexReaderContext topReaderContext = reader.Context;
foreach (AtomicReaderContext atomicReaderContext in topReaderContext.Leaves)
{
DocsAndPositionsEnum docsAndPosEnum = GetDocsAndPositions((AtomicReader)atomicReaderContext.Reader, bytes, null);
Assert.IsNotNull(docsAndPosEnum);
int initDoc = 0;
int maxDoc = atomicReaderContext.Reader.MaxDoc;
// initially advance or do next doc
if (Random().NextBoolean())
{
initDoc = docsAndPosEnum.NextDoc();
}
else
{
initDoc = docsAndPosEnum.Advance(Random().Next(maxDoc));
}
string msg = "Iteration: " + i + " initDoc: " + initDoc; // TODO: + " payloads: " + usePayload;
Assert.AreEqual(howMany / 2, docsAndPosEnum.Freq);
for (int j = 0; j < howMany; j += 2)
{
Assert.AreEqual(j, docsAndPosEnum.NextPosition(), "position missmatch index: " + j + " with freq: " + docsAndPosEnum.Freq + " -- " + msg);
}
}
}
reader.Dispose();
dir.Dispose();
}
[Test]
public virtual void TestDocsEnumStart()
{
Directory dir = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, Similarity, TimeZone);
Document doc = new Document();
doc.Add(NewStringField("foo", "bar", Field.Store.NO));
writer.AddDocument(doc);
DirectoryReader reader = writer.Reader;
AtomicReader r = GetOnlySegmentReader(reader);
DocsEnum disi = TestUtil.Docs(Random(), r, "foo", new BytesRef("bar"), null, null, DocsFlags.NONE);
int docid = disi.DocID;
Assert.AreEqual(-1, docid);
Assert.IsTrue(disi.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
// now reuse and check again
TermsEnum te = r.GetTerms("foo").GetIterator(null);
Assert.IsTrue(te.SeekExact(new BytesRef("bar")));
disi = TestUtil.Docs(Random(), te, null, disi, DocsFlags.NONE);
docid = disi.DocID;
Assert.AreEqual(-1, docid);
Assert.IsTrue(disi.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
writer.Dispose();
r.Dispose();
dir.Dispose();
}
[Test]
public virtual void TestDocsAndPositionsEnumStart()
{
Directory dir = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, Similarity, TimeZone);
Document doc = new Document();
doc.Add(NewTextField("foo", "bar", Field.Store.NO));
writer.AddDocument(doc);
DirectoryReader reader = writer.Reader;
AtomicReader r = GetOnlySegmentReader(reader);
DocsAndPositionsEnum disi = r.GetTermPositionsEnum(new Term("foo", "bar"));
int docid = disi.DocID;
Assert.AreEqual(-1, docid);
Assert.IsTrue(disi.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
// now reuse and check again
TermsEnum te = r.GetTerms("foo").GetIterator(null);
Assert.IsTrue(te.SeekExact(new BytesRef("bar")));
disi = te.DocsAndPositions(null, disi);
docid = disi.DocID;
Assert.AreEqual(-1, docid);
Assert.IsTrue(disi.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
writer.Dispose();
r.Dispose();
dir.Dispose();
}
}
}
| |
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using OrchardCore.ContentManagement.Metadata;
using OrchardCore.Modules;
namespace OrchardCore.ContentManagement.Handlers
{
/// <summary>
/// This component coordinates how parts are affecting content items.
/// </summary>
public class ContentPartHandlerCoordinator : ContentHandlerBase
{
private readonly IContentPartHandlerResolver _contentPartHandlerResolver;
private readonly ITypeActivatorFactory<ContentPart> _contentPartFactory;
private readonly IContentDefinitionManager _contentDefinitionManager;
private readonly ITypeActivatorFactory<ContentField> _contentFieldFactory;
private readonly ILogger _logger;
public ContentPartHandlerCoordinator(
IContentPartHandlerResolver contentPartHandlerResolver,
ITypeActivatorFactory<ContentPart> contentPartFactory,
ITypeActivatorFactory<ContentField> contentFieldFactory,
IContentDefinitionManager contentDefinitionManager,
ILogger<ContentPartHandlerCoordinator> logger)
{
_contentPartHandlerResolver = contentPartHandlerResolver;
_contentPartFactory = contentPartFactory;
_contentFieldFactory = contentFieldFactory;
_contentDefinitionManager = contentDefinitionManager;
_logger = logger;
}
public override async Task ActivatingAsync(ActivatingContentContext context)
{
// This method is called on New()
// Adds all the parts to a content item based on the content type definition.
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
// We create the part from it's known type or from a generic one
var part = _contentPartFactory.GetTypeActivator(partName).CreateInstance();
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.ActivatingAsync(context, part), context, part, _logger);
context.ContentItem.Weld(typePartDefinition.Name, part);
foreach (var partFieldDefinition in typePartDefinition.PartDefinition.Fields)
{
var fieldName = partFieldDefinition.Name;
if (!part.Has(fieldName))
{
var fieldActivator = _contentFieldFactory.GetTypeActivator(partFieldDefinition.FieldDefinition.Name);
part.Weld(fieldName, fieldActivator.CreateInstance());
}
}
}
}
public override async Task ActivatedAsync(ActivatedContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, partName) as ContentPart;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.ActivatedAsync(context, part), context, part, _logger);
}
}
}
public override async Task CreatingAsync(CreateContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.CreatingAsync(context, part), context, part, _logger);
}
}
}
public override async Task CreatedAsync(CreateContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.CreatedAsync(context, part), context, part, _logger);
}
}
}
public override async Task ImportingAsync(ImportContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.ImportingAsync(context, part), context, part, _logger);
}
}
}
public override async Task ImportedAsync(ImportContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.ImportedAsync(context, part), context, part, _logger);
}
}
}
public override async Task InitializingAsync(InitializingContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.InitializingAsync(context, part), context, part, _logger);
}
}
}
public override async Task InitializedAsync(InitializingContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.InitializedAsync(context, part), context, part, _logger);
}
}
}
public override async Task LoadingAsync(LoadContentContext context)
{
// This method is called on Get()
// Adds all the missing parts to a content item based on the content type definition.
// A part is missing if the content type is changed and an old content item is loaded,
// like edited.
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
{
return;
}
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart;
// If no existing part was not found in the content item, create a new one
if (part == null)
{
part = activator.CreateInstance();
context.ContentItem.Weld(typePartDefinition.Name, part);
}
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.LoadingAsync(context, part), context, part, _logger);
foreach (var partFieldDefinition in typePartDefinition.PartDefinition.Fields)
{
var fieldName = partFieldDefinition.Name;
if (!part.Has(fieldName))
{
var fieldActivator = _contentFieldFactory.GetTypeActivator(partFieldDefinition.FieldDefinition.Name);
part.Weld(fieldName, fieldActivator.CreateInstance());
}
}
}
}
public override async Task LoadedAsync(LoadContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.LoadedAsync(context, part), context, part, _logger);
}
}
}
public override async Task ValidatingAsync(ValidateContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.ValidatingAsync(context, part), context, part, _logger);
}
}
}
public override async Task ValidatedAsync(ValidateContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.ValidatedAsync(context, part), context, part, _logger);
}
}
}
public override async Task DraftSavingAsync(SaveDraftContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart; ;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.DraftSavingAsync(context, part), context, part, _logger);
}
}
}
public override async Task DraftSavedAsync(SaveDraftContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart; ;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.DraftSavedAsync(context, part), context, part, _logger);
}
}
}
public override async Task PublishingAsync(PublishContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart; ;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.PublishingAsync(context, part), context, part, _logger);
}
}
}
public override async Task PublishedAsync(PublishContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart; ;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.PublishedAsync(context, part), context, part, _logger);
}
}
}
public override async Task RemovingAsync(RemoveContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart; ;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.RemovingAsync(context, part), context, part, _logger);
}
}
}
public override async Task RemovedAsync(RemoveContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart; ;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.RemovedAsync(context, part), context, part, _logger);
}
}
}
public override async Task UnpublishingAsync(PublishContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart; ;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.UnpublishingAsync(context, part), context, part, _logger);
}
}
}
public override async Task UnpublishedAsync(PublishContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart; ;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.UnpublishedAsync(context, part), context, part, _logger);
}
}
}
public override async Task UpdatingAsync(UpdateContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart; ;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.UpdatingAsync(context, part), context, part, _logger);
}
}
}
public override async Task UpdatedAsync(UpdateContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart; ;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.UpdatedAsync(context, part), context, part, _logger);
}
}
}
public override async Task VersioningAsync(VersionContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var buildingPart = context.BuildingContentItem.Get(activator.Type, partName) as ContentPart;
var existingPart = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart;
if (buildingPart != null && existingPart != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, existingPart, buildingPart) => handler.VersioningAsync(context, existingPart, buildingPart), context, existingPart, buildingPart, _logger);
}
}
}
public override async Task VersionedAsync(VersionContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var buildingPart = (ContentPart)context.BuildingContentItem.Get(activator.Type, partName);
var existingPart = (ContentPart)context.ContentItem.Get(activator.Type, typePartDefinition.Name);
if (buildingPart != null && existingPart != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, existingPart, buildingPart) => handler.VersionedAsync(context, existingPart, buildingPart), context, existingPart, buildingPart, _logger);
}
}
}
public override async Task GetContentItemAspectAsync(ContentItemAspectContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.GetContentItemAspectAsync(context, part), context, part, _logger);
}
}
}
public override async Task ClonedAsync(CloneContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.ClonedAsync(context, part), context, part, _logger);
}
}
}
public override async Task CloningAsync(CloneContentContext context)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
return;
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart;
if (part != null)
{
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.CloningAsync(context, part), context, part, _logger);
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Cysharp.Threading.Tasks;
using Cytoid.Storyboard;
using Lean.Touch;
using UnityEngine;
public class GlobalCalibrator
{
private readonly List<double> offsets = new List<double>();
private readonly Game game;
private readonly BeatPulseVisualizer beatPulseVisualizer;
private readonly CircleProgressIndicator progressIndicator;
private readonly GameMessageText messageText;
private bool disposed;
private bool needRetry;
private int retries;
private bool calibratedFourMeasures;
private bool calibrationCompleted;
private readonly CancellationTokenSource cancelSource = new CancellationTokenSource();
private readonly CancellationTokenSource canExitSource = new CancellationTokenSource();
public GlobalCalibrator(Game game)
{
this.game = game;
beatPulseVisualizer = GameObjectProvider.Instance.beatPulseVisualizer;
progressIndicator = GameObjectProvider.Instance.circleProgressIndicator;
messageText = GameObjectProvider.Instance.messageText;
// Reset offset
Context.Player.Settings.BaseNoteOffset = 0;
Context.Player.SaveSettings();
game.Level.Record.RelativeNoteOffset = 0;
game.Level.SaveRecord();
// Hide overlay UI
StoryboardRendererProvider.Instance.UiCanvasGroup.alpha = 0;
game.onGameStarted.AddListener(_ =>
{
game.Config.GlobalNoteOpacityMultiplier = 0;
Flow();
DetectCanSkipCalibration();
});
game.BeforeExitTasks.Add(UniTask.Never(canExitSource.Token)); // Game never switches scenes by itself
}
public void Restart()
{
game.Retry();
}
private async void Flow()
{
try
{
messageText.Enqueue("OFFSET_SETUP_WIZARD_1".Get());
await UniTask.Delay(4000);
messageText.Enqueue("OFFSET_SETUP_WIZARD_2".Get());
LeanTouch.OnFingerDown = OnFingerDown;
await UniTask.WaitUntil(() => needRetry || calibratedFourMeasures,
cancellationToken: cancelSource.Token);
reset:
if (needRetry)
{
needRetry = false;
messageText.Enqueue("OFFSET_SETUP_WIZARD_3".Get());
await UniTask.WaitUntil(() => needRetry || calibratedFourMeasures, cancellationToken: cancelSource.Token);
if (needRetry)
{
calibratedFourMeasures = false;
goto reset;
}
}
messageText.Enqueue("OFFSET_SETUP_WIZARD_4".Get());
await UniTask.WaitUntil(() => needRetry || calibrationCompleted, cancellationToken: cancelSource.Token);
if (needRetry)
{
calibratedFourMeasures = false;
goto reset;
}
}
catch (OperationCanceledException)
{
}
}
private async void DetectCanSkipCalibration()
{
try
{
await UniTask.WhenAny(
UniTask.WaitUntil(() => retries >= 10),
UniTask.Delay(TimeSpan.FromSeconds(120), cancellationToken: cancelSource.Token)
);
if (game == null || game.gameObject == null) return;
AskSkipCalibration();
}
catch (OperationCanceledException)
{
}
}
private void OnFingerDown(LeanFinger finger)
{
var lastNote = game.Chart.Model.note_list.FindLast(it => it.start_time - 0.5f < game.Time);
var error = game.Time - lastNote.start_time;
game.effectController.PlayRippleEffect(finger.GetWorldPosition(0, game.camera));
beatPulseVisualizer.StartPulsing();
Debug.Log($"{calibratedFourMeasures} - Offset: {error}s");
offsets.Add(error);
if (offsets.Count > 1 && Math.Abs(offsets.Last() - offsets.GetRange(0, offsets.Count - 1).Average()) > 0.080)
{
retries++;
needRetry = true;
calibratedFourMeasures = false;
offsets.Clear();
progressIndicator.Progress = 0;
progressIndicator.Text = "";
return;
}
var progress = calibratedFourMeasures ? 4 + offsets.Count : offsets.Count;
progressIndicator.Progress = progress * 1f / 8f;
progressIndicator.Text = $"{progress} / 8";
if (offsets.Count == 4)
{
if (calibratedFourMeasures)
{
LeanTouch.OnFingerDown = _ => { };
PromptComplete();
}
else
{
calibratedFourMeasures = true;
offsets.Clear();
}
}
}
private void AskSkipCalibration()
{
if (calibrationCompleted) return;
LeanTouch.OnFingerDown = _ => { };
game.Complete(true);
Dialog.Prompt("OFFSET_SETUP_WIZARD_DIALOG_ASK_SKIP".Get(), Skip, Restart);
}
private void Skip()
{
if (calibrationCompleted) return;
LeanTouch.OnFingerDown = _ => { };
offsets.Clear();
Complete();
}
private void PromptComplete()
{
if (calibrationCompleted) return;
LeanTouch.OnFingerDown = _ => { };
calibrationCompleted = true;
game.Complete(true);
Dialog.PromptAlert("OFFSET_SETUP_WIZARD_DIALOG_COMPLETE".Get($"{offsets.Average():F3}"),
Complete
);
}
private async void Complete()
{
LeanTouch.OnFingerDown = _ => { };
calibrationCompleted = true;
messageText.Enqueue(string.Empty, true);
progressIndicator.Progress = 0;
progressIndicator.Text = string.Empty;
if (offsets.Count > 0)
{
Context.Player.Settings.BaseNoteOffset = (float) Math.Round((decimal) offsets.Average(), 3, MidpointRounding.AwayFromZero);
Context.Player.SaveSettings();
}
canExitSource.Cancel();
game.Complete(true);
}
public void Dispose()
{
if (disposed) return;
LeanTouch.OnFingerDown = _ => { };
disposed = true;
cancelSource.Cancel();
}
}
| |
/* *********************************************************************************
* TNValidate Fluent Validation Library
* https://tnvalidate.codeplex.com/
* Copyright (C) TN Datakonsult AB 2009
* http://www.tn-data.se/
*
* 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.Text;
using System.Text.RegularExpressions;
namespace BigfootDNN.Model.Validation
{
/// ********************************************************************
/// <summary>
/// String validation handler.
/// </summary>
public class StringValidator : ValidatorBase<StringValidator, string>
{
/// ********************************************************************
/// <summary>
/// Initializes a new instance of the <see cref="StringValidator"/> class.
/// </summary>
/// <param name="value"></param>
/// <param name="fieldName"></param>
/// <param name="validatorObj"></param>
public StringValidator(string value, string fieldName, Validator validatorObj) : base(value, fieldName, validatorObj)
{
}
/// ********************************************************************
/// <summary>
/// Checks if the string is empty.
/// </summary>
/// <param name="ErrorMessage"></param>
/// <returns>My instance to allow me to chain multiple validations together</returns>
public StringValidator IsEmpty(string ErrorMessage)
{
SetResult((Value ?? string.Empty).Length != 0, string.Format(ErrorMessage, FieldName), ValidationErrorCode.StringIsEmpty);
return this;
}
/// <summary>
/// Checks if the string is empty.
/// </summary>
/// <returns>My instance to allow me to chain multiple validations together</returns>
public StringValidator IsEmpty()
{
IsEmpty(ValidatorObj.LookupLanguageString("string_IsEmpty", NegateNextValidationResult));
return this;
}
/// <summary>
/// Checks if the string is not empty.
/// </summary>
/// <returns>My instance to allow me to chain multiple validations together</returns>
public StringValidator IsNotEmpty()
{
var ErrorMessage = ValidatorObj.LookupLanguageString("string_IsEmpty", true);
SetResult((Value ?? string.Empty).Length == 0, string.Format(ErrorMessage, FieldName), ValidationErrorCode.StringIsEmpty);
return this;
}
/// <summary>
/// Checks if the string is not empty.
/// </summary>
/// <returns>My instance to allow me to chain multiple validations together</returns>
public StringValidator IsNotEmpty(string ErrorMessage)
{
SetResult((Value ?? string.Empty).Length == 0, string.Format(ErrorMessage, FieldName), ValidationErrorCode.StringIsEmpty);
return this;
}
/// ********************************************************************
/// <summary>
/// Checks if the string has the correct length
/// </summary>
/// <param name="RequiredLength">The required length.</param>
/// <param name="ErrorMessage"></param>
/// <returns>My instance to allow me to chain multiple validations together</returns>
public StringValidator IsLength(int RequiredLength, string ErrorMessage)
{
SetResult(Value.Length != RequiredLength, string.Format(ErrorMessage, FieldName, RequiredLength.ToString()), ValidationErrorCode.StringIsLength);
return this;
}
/// <summary>
/// Checks if the string has the correct length
/// </summary>
/// <param name="RequiredLength">The required length.</param>
/// <returns>
/// My instance to allow me to chain multiple validations together
/// </returns>
public StringValidator IsLength(int RequiredLength)
{
IsLength(RequiredLength, ValidatorObj.LookupLanguageString("string_IsLength", NegateNextValidationResult));
return this;
}
/// ********************************************************************
/// <summary>
/// Checks if the string has more characters than the specified minimum.
/// </summary>
/// <param name="MinLength">The minimum length.</param>
/// <param name="ErrorMessage"></param>
/// <returns>My instance to allow me to chain multiple validations together</returns>
public StringValidator IsLongerThan(int MinLength, string ErrorMessage)
{
SetResult(Value.Length <= MinLength, string.Format(ErrorMessage, FieldName, MinLength.ToString()), ValidationErrorCode.StringIsLongerThan);
return this;
}
/// <summary>
/// Checks if the string has more characters than the specified minimum.
/// </summary>
/// <param name="MinLength">The minimum length.</param>
/// <returns>
/// My instance to allow me to chain multiple validations together
/// </returns>
public StringValidator IsLongerThan(int MinLength)
{
IsLongerThan(MinLength, ValidatorObj.LookupLanguageString("string_IsLongerThan", NegateNextValidationResult));
return this;
}
/// ********************************************************************
/// <summary>
/// Checks that the string has less characters than the provided maximum.
/// </summary>
/// <param name="MaxLength">The maximum length.</param>
/// <param name="ErrorMessage"></param>
/// <returns>My instance to allow me to chain multiple validations together </returns>
public StringValidator IsShorterThan(int MaxLength, string ErrorMessage)
{
SetResult(Value.Length >= MaxLength, string.Format(ErrorMessage, FieldName, MaxLength.ToString()), ValidationErrorCode.StringIsShorterThan);
return this;
}
/// <summary>
/// Checks that the string has less characters than the provided maximum.
/// </summary>
/// <param name="MaxLength">The maximum length.</param>
/// <returns>
/// My instance to allow me to chain multiple validations together
/// </returns>
public StringValidator IsShorterThan(int MaxLength)
{
IsShorterThan(MaxLength, ValidatorObj.LookupLanguageString("string_IsShorterThan", NegateNextValidationResult));
return this;
}
/// ********************************************************************
/// <summary>
/// Checks that the string matches the supplied regular expression.
/// </summary>
/// <param name="RegularExpression">The regular expression to check against.</param>
/// <param name="ErrorMessage">The Error Message.</param>
/// <returns>My instance to allow me to chain multiple validations together </returns>
public StringValidator MatchRegex(string RegularExpression, string ErrorMessage)
{
Regex Reg = new Regex(RegularExpression);
SetResult(!Reg.IsMatch(Value), ErrorMessage, ValidationErrorCode.StringMatchRegex);
return this;
}
/// ********************************************************************
/// <summary>
/// Checks that the string matches the supplied regular expression.
/// </summary>
/// <param name="RegularExpression">The regular expression to check against.</param>
/// <param name="regexOptions">Any options for the regular expression.</param>
/// <param name="ErrorMessage">The Error Message.</param>
/// <returns>My instance to allow me to chain multiple validations together </returns>
public StringValidator MatchRegex(string RegularExpression, RegexOptions regexOptions, string ErrorMessage)
{
Regex Reg = new Regex(RegularExpression, regexOptions);
SetResult(!Reg.IsMatch(Value), ErrorMessage, ValidationErrorCode.StringMatchRegex);
return this;
}
/// ********************************************************************
/// <summary>
/// Checks that the string is an email address.
/// </summary>
/// <param name="ErrorMessage"></param>
/// <returns>
/// My instance to allow me to chain multiple validations together
/// </returns>
public StringValidator IsEmail(string ErrorMessage)
{
Regex Reg = new Regex(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+$", RegexOptions.IgnoreCase);
SetResult(!Reg.IsMatch(Value), string.Format(ErrorMessage, FieldName, Value.ToString()), ValidationErrorCode.StringIsEmail);
return this;
}
/// <summary>
/// Checks that the string is an email address.
/// </summary>
/// <returns>
/// My instance to allow me to chain multiple validations together
/// </returns>
public StringValidator IsEmail()
{
IsEmail(ValidatorObj.LookupLanguageString("string_IsEmail", NegateNextValidationResult));
return this;
}
/// ********************************************************************
/// <summary>
/// Checks that the string is a URL.
/// </summary>
/// <param name="ErrorMessage"></param>
/// <returns>
/// My instance to allow me to chain multiple validations together
/// </returns>
public StringValidator IsURL(string ErrorMessage)
{
Regex Reg = new Regex(@"^\w+://(?:[\w-]+(?:\:[\w-]+)?\@)?(?:[\w-]+\.)+[\w-]+(?:\:\d+)?[\w- ./?%&=\+]*$", RegexOptions.IgnoreCase);
SetResult(!Reg.IsMatch(Value), string.Format(ErrorMessage, FieldName, Value.ToString()), ValidationErrorCode.StringIsURL);
return this;
}
/// <summary>
/// Checks that the string is a URL.
/// </summary>
/// <returns>
/// My instance to allow me to chain multiple validations together
/// </returns>
public StringValidator IsURL()
{
IsURL(ValidatorObj.LookupLanguageString("string_IsURL", NegateNextValidationResult));
return this;
}
/// ********************************************************************
/// <summary>
/// Checks if the string can be parsed as a date under the current locale.
/// </summary>
/// <param name="ErrorMessage"></param>
/// <returns>
/// My instance to allow me to chain multiple validations together
/// </returns>
public StringValidator IsDate(string ErrorMessage)
{
DateTime Date;
SetResult(!DateTime.TryParse(Value, out Date), string.Format(ErrorMessage, FieldName, Value.ToString()), ValidationErrorCode.StringIsDate);
return this;
}
/// <summary>
/// Checks if the string can be parsed as a date under the current locale.
/// </summary>
/// <returns>
/// My instance to allow me to chain multiple validations together
/// </returns>
public StringValidator IsDate()
{
IsDate(ValidatorObj.LookupLanguageString("string_IsDate", NegateNextValidationResult));
return this;
}
/// ********************************************************************
/// <summary>
/// Checks if the string can be parsed as an integer.
/// </summary>
/// <param name="ErrorMessage"></param>
/// <returns>
/// My instance to allow me to chain multiple validations together
/// </returns>
public StringValidator IsInteger(string ErrorMessage)
{
int tmp;
SetResult(!int.TryParse(Value, out tmp), string.Format(ErrorMessage, FieldName, Value.ToString()), ValidationErrorCode.StringIsInteger);
return this;
}
/// <summary>
/// Checks if the string can be parsed as an integer.
/// </summary>
/// <returns>
/// My instance to allow me to chain multiple validations together
/// </returns>
public StringValidator IsInteger()
{
IsInteger(ValidatorObj.LookupLanguageString("string_IsInteger", NegateNextValidationResult));
return this;
}
/// ********************************************************************
/// <summary>
/// Checks if the string can be parsed as a deciaml under the current locale.
/// </summary>
/// <param name="ErrorMessage"></param>
/// <returns>
/// My instance to allow me to chain multiple validations together
/// </returns>
public StringValidator IsDecimal(string ErrorMessage)
{
decimal tmp;
SetResult(!decimal.TryParse(Value, out tmp), string.Format(ErrorMessage, FieldName, Value.ToString()), ValidationErrorCode.StringIsDecimal);
return this;
}
/// <summary>
/// Checks if the string can be parsed as a deciaml under the current locale.
/// </summary>
/// <returns>
/// My instance to allow me to chain multiple validations together
/// </returns>
public StringValidator IsDecimal()
{
IsDecimal(ValidatorObj.LookupLanguageString("string_IsDecimal", NegateNextValidationResult));
return this;
}
/// ********************************************************************
/// <summary>
/// Checks that the length of the string is within the provided minimum
/// and maximum length limits.
/// </summary>
/// <param name="MinLength"></param>
/// <param name="MaxLength"></param>
/// <param name="ErrorMessage"></param>
/// <returns>
/// My instance to allow me to chain multiple validations together
/// </returns>
public StringValidator HasALengthBetween(int MinLength, int MaxLength, string ErrorMessage)
{
SetResult(Value.Length < MinLength || Value.Length > MaxLength, string.Format(ErrorMessage, FieldName, MinLength, MaxLength), ValidationErrorCode.StringHasALengthBetween);
return this;
}
/// <summary>
/// Checks that the length of the string is within the provided minimum
/// and maximum length limits.
/// </summary>
/// <param name="MinLength"></param>
/// <param name="MaxLength"></param>
/// <returns>
/// My instance to allow me to chain multiple validations together
/// </returns>
public StringValidator HasALengthBetween(int MinLength, int MaxLength)
{
HasALengthBetween(MinLength, MaxLength, ValidatorObj.LookupLanguageString("string_HasALengthBetween", NegateNextValidationResult));
return this;
}
/// ********************************************************************
/// <summary>
/// Checks that the string starts with StartValue.
/// </summary>
/// <param name="StartValue"></param>
/// <param name="ErrorMessage"></param>
/// <returns>
/// My instance to allow me to chain multiple validations together
/// </returns>
public StringValidator StartsWith(string StartValue, string ErrorMessage)
{
SetResult(!Value.StartsWith(StartValue), string.Format(ErrorMessage, FieldName, StartValue), ValidationErrorCode.StringStartsWith);
return this;
}
/// <summary>
/// Checks that the string starts with StartValue.
/// </summary>
/// <param name="StartValue"></param>
/// <returns>
/// My instance to allow me to chain multiple validations together
/// </returns>
public StringValidator StartsWith(string StartValue)
{
StartsWith(StartValue, ValidatorObj.LookupLanguageString("string_StartsWith", NegateNextValidationResult));
return this;
}
/// ********************************************************************
/// <summary>
/// Checks that the string ends with EndValue.
/// </summary>
/// <param name="EndValue"></param>
/// <param name="ErrorMessage"></param>
/// <returns>
/// My instance to allow me to chain multiple validations together
/// </returns>
public StringValidator EndsWith(string EndValue, string ErrorMessage)
{
SetResult(!Value.EndsWith(EndValue), string.Format(ErrorMessage, FieldName, EndValue), ValidationErrorCode.StringEndsWith);
return this;
}
/// <summary>
/// Checks that the string ends with EndValue.
/// </summary>
/// <param name="EndValue"></param>
/// <returns>
/// My instance to allow me to chain multiple validations together
/// </returns>
public StringValidator EndsWith(string EndValue)
{
EndsWith(EndValue, ValidatorObj.LookupLanguageString("string_EndsWith", NegateNextValidationResult));
return this;
}
/// ********************************************************************
/// <summary>
/// Checks that the string contains the specified CompareValue.
/// </summary>
/// <param name="CompareValue"></param>
/// <param name="ErrorMessage"></param>
/// <returns>
/// My instance to allow me to chain multiple validations together
/// </returns>
public StringValidator Contains(string CompareValue, string ErrorMessage)
{
SetResult(!Value.Contains(CompareValue), string.Format(ErrorMessage, FieldName, CompareValue), ValidationErrorCode.StringContains);
return this;
}
/// <summary>
/// Checks that the string contains the specified CompareValue.
/// </summary>
/// <param name="CompareValue"></param>
/// <returns>
/// My instance to allow me to chain multiple validations together
/// </returns>
public StringValidator Contains(string CompareValue)
{
Contains(CompareValue, ValidatorObj.LookupLanguageString("string_Contains", NegateNextValidationResult));
return this;
}
/// <summary>
/// Checks if the string is a valid credit card.
/// </summary>
/// <returns>My instance to allow me to chain multiple validations together</returns>
public StringValidator IsCreditCard()
{
IsCreditCard(ValidatorObj.LookupLanguageString("string_IsCreditCard", NegateNextValidationResult));
return this;
}
/// ********************************************************************
/// <summary>
/// Checks if the string is a valid credit card.
/// </summary>
/// <param name="ErrorMessage"></param>
/// <returns>My instance to allow me to chain multiple validations together</returns>
public StringValidator IsCreditCard(string ErrorMessage)
{
// Allow only digits
const string allowed = "0123456789";
int i;
// Clean the input
StringBuilder cleanNumber = new StringBuilder();
for (i = 0; i < Value.Length; i++)
{
if (allowed.IndexOf(Value.Substring(i, 1)) >= 0)
cleanNumber.Append(Value.Substring(i, 1));
}
// Credit card length must be greater than 13 and smaller than 16
if (cleanNumber.Length < 13 || cleanNumber.Length > 16)
{
SetResult(true, string.Format(ErrorMessage, FieldName), ValidationErrorCode.StringIsCreditCard);
return this;
}
for (i = cleanNumber.Length + 1; i <= 16; i++)
cleanNumber.Insert(0, "0");
int multiplier, digit, sum, total = 0;
string number = cleanNumber.ToString();
for (i = 1; i <= 16; i++)
{
multiplier = 1 + (i % 2);
digit = int.Parse(number.Substring(i - 1, 1));
sum = digit * multiplier;
if (sum > 9)
sum -= 9;
total += sum;
}
/*SET RESULT*/
SetResult(!(total % 10 == 0), string.Format(ErrorMessage, FieldName), ValidationErrorCode.StringIsCreditCard);
return this;
}
}
}
| |
namespace GitVersion
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using JetBrains.Annotations;
using LibGit2Sharp;
static class LibGitExtensions
{
public static DateTimeOffset When(this Commit commit)
{
return commit.Committer.When;
}
public static IEnumerable<SemanticVersion> GetVersionTagsOnBranch(this Branch branch, IRepository repository, string tagPrefixRegex)
{
var tags = repository.Tags.Select(t => t).ToList();
return repository.Commits.QueryBy(new CommitFilter
{
IncludeReachableFrom = branch.Tip
})
.SelectMany(c => tags.Where(t => c.Sha == t.Target.Sha).SelectMany(t =>
{
SemanticVersion semver;
if (SemanticVersion.TryParse(t.FriendlyName, tagPrefixRegex, out semver))
return new [] { semver };
return new SemanticVersion[0];
}));
}
public static Commit FindCommitBranchWasBranchedFrom([NotNull] this Branch branch, IRepository repository, params Branch[] excludedBranches)
{
const string missingTipFormat = "{0} has no tip. Please see http://example.com/docs for information on how to fix this.";
if (branch == null)
{
throw new ArgumentNullException("branch");
}
using (Logger.IndentLog("Finding branch source"))
{
if (branch.Tip == null)
{
Logger.WriteWarning(string.Format(missingTipFormat, branch.FriendlyName));
return null;
}
var otherBranches = repository.Branches
.Except(excludedBranches)
.Where(b => IsSameBranch(branch, b))
.ToList();
var mergeBases = otherBranches.Select(otherBranch =>
{
if (otherBranch.Tip == null)
{
Logger.WriteWarning(string.Format(missingTipFormat, otherBranch.FriendlyName));
return null;
}
var findMergeBase = FindMergeBase(branch, otherBranch, repository);
return new
{
mergeBaseCommit = findMergeBase,
branch = otherBranch
};
}).Where(b => b.mergeBaseCommit != null).OrderByDescending(b => b.mergeBaseCommit.Committer.When).ToList();
var firstOrDefault = mergeBases.FirstOrDefault();
if (firstOrDefault != null)
{
return firstOrDefault.mergeBaseCommit;
}
return null;
}
}
public static Commit FindMergeBase(this Branch branch, Branch otherBranch, IRepository repository)
{
using (Logger.IndentLog(string.Format("Finding merge base between '{0}' and {1}.", branch.FriendlyName, otherBranch.FriendlyName)))
{
// Otherbranch tip is a forward merge
var commitToFindCommonBase = otherBranch.Tip;
var commit = branch.Tip;
if (otherBranch.Tip.Parents.Contains(commit))
{
commitToFindCommonBase = otherBranch.Tip.Parents.First();
}
var findMergeBase = repository.ObjectDatabase.FindMergeBase(commit, commitToFindCommonBase);
if (findMergeBase != null)
{
Logger.WriteInfo(string.Format("Found merge base of {0}", findMergeBase.Sha));
// We do not want to include merge base commits which got forward merged into the other branch
bool mergeBaseWasFowardMerge;
do
{
// Now make sure that the merge base is not a forward merge
mergeBaseWasFowardMerge = otherBranch.Commits
.SkipWhile(c => c != commitToFindCommonBase)
.TakeWhile(c => c != findMergeBase)
.Any(c => c.Parents.Contains(findMergeBase));
if (mergeBaseWasFowardMerge)
{
var second = commitToFindCommonBase.Parents.First();
var mergeBase = repository.ObjectDatabase.FindMergeBase(commit, second);
if (mergeBase == findMergeBase)
{
break;
}
findMergeBase = mergeBase;
Logger.WriteInfo(string.Format("Merge base was due to a forward merge, next merge base is {0}", findMergeBase));
}
} while (mergeBaseWasFowardMerge);
}
return findMergeBase;
}
}
static bool IsSameBranch(Branch branch, Branch b)
{
return (b.IsRemote ?
b.FriendlyName.Substring(b.FriendlyName.IndexOf("/", StringComparison.Ordinal) + 1) :
b.FriendlyName) != branch.FriendlyName;
}
public static IEnumerable<Branch> GetBranchesContainingCommit([NotNull] this Commit commit, IRepository repository, IList<Branch> branches, bool onlyTrackedBranches)
{
if (commit == null)
{
throw new ArgumentNullException("commit");
}
using (Logger.IndentLog(string.Format("Getting branches containing the commit '{0}'.", commit.Id)))
{
var directBranchHasBeenFound = false;
Logger.WriteInfo("Trying to find direct branches.");
// TODO: It looks wasteful looping through the branches twice. Can't these loops be merged somehow? @asbjornu
foreach (var branch in branches)
{
if (branch.Tip != null && branch.Tip.Sha != commit.Sha || (onlyTrackedBranches && !branch.IsTracking))
{
continue;
}
directBranchHasBeenFound = true;
Logger.WriteInfo(string.Format("Direct branch found: '{0}'.", branch.FriendlyName));
yield return branch;
}
if (directBranchHasBeenFound)
{
yield break;
}
Logger.WriteInfo(string.Format("No direct branches found, searching through {0} branches.", onlyTrackedBranches ? "tracked" : "all"));
foreach (var branch in branches.Where(b => onlyTrackedBranches && !b.IsTracking))
{
Logger.WriteInfo(string.Format("Searching for commits reachable from '{0}'.", branch.FriendlyName));
var commits = repository.Commits.QueryBy(new CommitFilter
{
IncludeReachableFrom = branch
}).Where(c => c.Sha == commit.Sha);
if (!commits.Any())
{
Logger.WriteInfo(string.Format("The branch '{0}' has no matching commits.", branch.FriendlyName));
continue;
}
Logger.WriteInfo(string.Format("The branch '{0}' has a matching commit.", branch.FriendlyName));
yield return branch;
}
}
}
private static Dictionary<string, GitObject> _cachedPeeledTarget = new Dictionary<string, GitObject>();
public static GitObject PeeledTarget(this Tag tag)
{
GitObject cachedTarget;
if(_cachedPeeledTarget.TryGetValue(tag.Target.Sha, out cachedTarget))
{
return cachedTarget;
}
var target = tag.Target;
while (target is TagAnnotation)
{
target = ((TagAnnotation)(target)).Target;
}
_cachedPeeledTarget.Add(tag.Target.Sha, target);
return target;
}
public static IEnumerable<Commit> CommitsPriorToThan(this Branch branch, DateTimeOffset olderThan)
{
return branch.Commits.SkipWhile(c => c.When() > olderThan);
}
public static bool IsDetachedHead(this Branch branch)
{
return branch.CanonicalName.Equals("(no branch)", StringComparison.OrdinalIgnoreCase);
}
public static string GetRepositoryDirectory(this IRepository repository, bool omitGitPostFix = true)
{
var gitDirectory = repository.Info.Path;
gitDirectory = gitDirectory.TrimEnd(Path.DirectorySeparatorChar);
if (omitGitPostFix && gitDirectory.EndsWith(".git"))
{
gitDirectory = gitDirectory.Substring(0, gitDirectory.Length - ".git".Length);
gitDirectory = gitDirectory.TrimEnd(Path.DirectorySeparatorChar);
}
return gitDirectory;
}
public static void CheckoutFilesIfExist(this IRepository repository, params string[] fileNames)
{
if (fileNames == null || fileNames.Length == 0)
{
return;
}
Logger.WriteInfo("Checking out files that might be needed later in dynamic repository");
foreach (var fileName in fileNames)
{
try
{
Logger.WriteInfo(string.Format(" Trying to check out '{0}'", fileName));
var headBranch = repository.Head;
var tip = headBranch.Tip;
var treeEntry = tip[fileName];
if (treeEntry == null)
{
continue;
}
var fullPath = Path.Combine(repository.GetRepositoryDirectory(), fileName);
using (var stream = ((Blob) treeEntry.Target).GetContentStream())
{
using (var streamReader = new BinaryReader(stream))
{
File.WriteAllBytes(fullPath, streamReader.ReadBytes((int)stream.Length));
}
}
}
catch (Exception ex)
{
Logger.WriteWarning(string.Format(" An error occurred while checking out '{0}': '{1}'", fileName, ex.Message));
}
}
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.Linq;
public class tk2dSpriteAnimationEditorPopup : EditorWindow
{
tk2dSpriteAnimation anim;
tk2dEditor.SpriteAnimationEditor.ClipEditor clipEditor = null;
tk2dEditor.SpriteAnimationEditor.AnimOperator[] animOps = new tk2dEditor.SpriteAnimationEditor.AnimOperator[0];
// "Create" menu
GUIContent[] menuItems = new GUIContent[0];
tk2dEditor.SpriteAnimationEditor.AnimOperator[] menuTargets = new tk2dEditor.SpriteAnimationEditor.AnimOperator[0];
void OnEnable()
{
// Detect animOps
List<tk2dEditor.SpriteAnimationEditor.AnimOperator> animOpList = new List<tk2dEditor.SpriteAnimationEditor.AnimOperator>();
foreach (var assembly in System.AppDomain.CurrentDomain.GetAssemblies())
{
try
{
System.Type[] types = assembly.GetTypes();
foreach (var type in types)
{
if (type.BaseType == typeof(tk2dEditor.SpriteAnimationEditor.AnimOperator))
{
tk2dEditor.SpriteAnimationEditor.AnimOperator inst = (tk2dEditor.SpriteAnimationEditor.AnimOperator)System.Activator.CreateInstance(type);
if (inst != null)
animOpList.Add(inst);
}
}
}
catch { }
}
animOpList.Sort((a, b) => a.SortId.CompareTo(b.SortId));
animOps = animOpList.ToArray();
// Create menu items
List<GUIContent> menuItems = new List<GUIContent>();
List<tk2dEditor.SpriteAnimationEditor.AnimOperator> menuTargets = new List<tk2dEditor.SpriteAnimationEditor.AnimOperator>();
menuItems.Add(new GUIContent("Clip")); menuTargets.Add(null);
foreach (tk2dEditor.SpriteAnimationEditor.AnimOperator animOp in animOps)
{
for (int i = 0; i < animOp.AnimToolsMenu.Length; ++i)
{
menuItems.Add(new GUIContent(animOp.AnimToolsMenu[i]));
menuTargets.Add(animOp);
}
}
this.menuItems = menuItems.ToArray();
this.menuTargets = menuTargets.ToArray();
// Create clip editor
if (clipEditor == null)
{
clipEditor = new tk2dEditor.SpriteAnimationEditor.ClipEditor();
clipEditor.clipNameChangedEvent += ClipNameChanged;
clipEditor.clipDeletedEvent += ClipDeleted;
clipEditor.clipSelectionChangedEvent += ClipSelectionChanged;
clipEditor.hostEditorWindow = this;
}
clipEditor.animOps = animOps;
FilterClips();
if (selectedClipId != -1 && selectedClipId < allClips.Count)
{
selectedClip = allClips[selectedClipId];
}
else
{
selectedClip = null;
}
}
void OnDisable()
{
OnDestroy();
}
void OnDestroy()
{
if (clipEditor != null)
clipEditor.Destroy();
tk2dEditorSkin.Done();
}
public void ClipNameChanged(tk2dSpriteAnimationClip clip, int param)
{
FilterClips();
Repaint();
}
public void ClipDeleted(tk2dSpriteAnimationClip clip, int param)
{
clip.Clear();
selectedClip = null;
FilterClips();
Repaint();
}
public void ClipSelectionChanged(tk2dSpriteAnimationClip clip, int direction)
{
int selectedId = -1;
for (int i = 0; i < filteredClips.Count; ++i)
{
if (filteredClips[i] == clip)
{
selectedId = i;
break;
}
}
if (selectedId != -1)
{
int newSelectedId = selectedId + direction;
if (newSelectedId >= 0 && newSelectedId < filteredClips.Count)
{
selectedClip = filteredClips[newSelectedId];
}
}
Repaint();
}
public void SetSpriteAnimation(tk2dSpriteAnimation anim)
{
if (anim != this.anim)
{
searchFilter = "";
this.anim = anim;
this.name = anim.name;
}
selectedClip = null;
MirrorClips();
FilterClips();
Repaint();
}
void MirrorClips()
{
if (anim == null) return;
allClips.Clear();
if (anim.clips != null)
{
foreach (tk2dSpriteAnimationClip clip in anim.clips)
{
tk2dSpriteAnimationClip c = new tk2dSpriteAnimationClip();
c.CopyFrom(clip);
allClips.Add(c);
}
}
}
int minLeftBarWidth = 150;
int leftBarWidth { get { return tk2dPreferences.inst.animListWidth; } set { tk2dPreferences.inst.animListWidth = Mathf.Max(value, minLeftBarWidth); } }
string searchFilter = "";
List<tk2dSpriteAnimationClip> allClips = new List<tk2dSpriteAnimationClip>();
List<tk2dSpriteAnimationClip> filteredClips = new List<tk2dSpriteAnimationClip>();
tk2dSpriteAnimationClip _selectedClip;
int selectedClipId = -1;
tk2dSpriteAnimationClip selectedClip
{
get { return _selectedClip; }
set
{
selectedClipId = -1;
if (value != null)
{
for (int i = 0; i < allClips.Count; ++i)
{
if (allClips[i] == value)
{
_selectedClip = value;
selectedClipId = i;
break;
}
}
}
if (selectedClipId == -1)
{
if (value != null) Debug.LogError("Unable to find clip");
_selectedClip = null;
}
}
}
public static bool Contains(string s, string text) { return s.ToLower().IndexOf(text.ToLower()) != -1; }
void FilterClips()
{
filteredClips = new List<tk2dSpriteAnimationClip>(allClips.Count);
if (searchFilter.Length == 0) {
filteredClips = (from clip in allClips where !clip.Empty select clip)
.OrderBy( a => a.name, new tk2dEditor.Shared.NaturalComparer() )
.ToList();
}
else {
filteredClips = (from clip in allClips where !clip.Empty && Contains(clip.name, searchFilter) select clip)
.OrderBy( a => a.name, new tk2dEditor.Shared.NaturalComparer() )
.ToList();
}
}
void Commit()
{
if (anim == null) return;
// Handle duplicate names
string dupNameString = "";
HashSet<string> duplicateNames = new HashSet<string>();
HashSet<string> names = new HashSet<string>();
foreach (tk2dSpriteAnimationClip clip in allClips)
{
if (clip.Empty) continue;
if (names.Contains(clip.name)) { duplicateNames.Add(clip.name); dupNameString += clip.name + " "; continue; }
names.Add(clip.name);
}
if (duplicateNames.Count > 0)
{
int res = EditorUtility.DisplayDialogComplex("Commit",
"Duplicate names found in animation library. You won't be able to select duplicates in the interface.\n" +
"Duplicates: " + dupNameString,
"Auto-rename",
"Cancel",
"Force commit");
if (res == 1) return; // cancel
if (res == 0)
{
// auto rename
HashSet<string> firstOccurances = new HashSet<string>();
foreach (tk2dSpriteAnimationClip clip in allClips)
{
if (clip.Empty) continue;
string name = clip.name;
if (duplicateNames.Contains(name))
{
if (!firstOccurances.Contains(name))
{
firstOccurances.Add(name);
}
else
{
// find suitable name
int i = 1;
string n = "";
do
{
n = string.Format("{0} {1}", name, i++);
} while (names.Contains(n));
name = n;
names.Add(name);
clip.name = name;
}
}
}
FilterClips();
Repaint();
}
}
anim.clips = new tk2dSpriteAnimationClip[allClips.Count];
for (int i = 0; i < allClips.Count; ++i)
{
anim.clips[i] = new tk2dSpriteAnimationClip();
anim.clips[i].CopyFrom(allClips[i]);
}
EditorUtility.SetDirty(anim);
AssetDatabase.SaveAssets();
}
void Revert()
{
MirrorClips();
searchFilter = "";
FilterClips();
selectedClip = null;
}
Vector2 listScroll = Vector2.zero;
void DrawList()
{
listScroll = GUILayout.BeginScrollView(listScroll, GUILayout.Width(leftBarWidth));
GUILayout.BeginVertical(tk2dEditorSkin.SC_ListBoxBG, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true));
foreach (tk2dSpriteAnimationClip clip in filteredClips)
{
// 0 length name signifies inactive clip
if (clip.name.Length == 0) continue;
bool selected = selectedClip == clip;
bool newSelected = GUILayout.Toggle(selected, clip.name, tk2dEditorSkin.SC_ListBoxItem, GUILayout.ExpandWidth(true));
if (newSelected != selected && newSelected == true)
{
selectedClip = clip;
GUIUtility.keyboardControl = 0;
Repaint();
}
}
GUILayout.EndVertical();
GUILayout.EndScrollView();
Rect viewRect = GUILayoutUtility.GetLastRect();
leftBarWidth = (int)tk2dGuiUtility.DragableHandle(4819283,
viewRect, leftBarWidth,
tk2dGuiUtility.DragDirection.Horizontal);
}
void TrimClips()
{
if (allClips.Count < 1)
return;
int validCount = allClips.Count;
while (validCount > 0 && !allClips[validCount - 1].Empty)
--validCount;
allClips.RemoveRange(validCount, allClips.Count - validCount);
if (allClips.Count == 0)
{
allClips.Add(CreateNewClip());
FilterClips();
}
}
tk2dSpriteAnimationClip FindValidClip()
{
if (selectedClip != null && !selectedClip.Empty)
return selectedClip;
foreach (tk2dSpriteAnimationClip c in allClips)
if (!c.Empty) return c;
return null;
}
tk2dSpriteAnimationClip CreateNewClip()
{
// Find a unique name
string uniqueName = tk2dEditor.SpriteAnimationEditor.AnimOperatorUtil.UniqueClipName(allClips, "New Clip");
tk2dSpriteAnimationClip clip = new tk2dSpriteAnimationClip();
clip.name = uniqueName;
tk2dSpriteAnimationClip source = FindValidClip();
clip.frames = new tk2dSpriteAnimationFrame[1];
clip.frames[0] = new tk2dSpriteAnimationFrame();
if (source != null)
{
clip.frames[0].CopyFrom(source.frames[0]);
}
else
{
clip.frames[0].spriteCollection = tk2dSpriteGuiUtility.GetDefaultSpriteCollection();
clip.frames[0].spriteId = clip.frames[0].spriteCollection.FirstValidDefinitionIndex;
}
bool inserted = false;
for (int i = 0; i < allClips.Count; ++i)
{
if (allClips[i].Empty)
{
allClips[i] = clip;
inserted = true;
break;
}
}
if (!inserted)
allClips.Add(clip);
searchFilter = "";
FilterClips();
return clip;
}
void DrawToolbar()
{
GUILayout.BeginHorizontal(EditorStyles.toolbar, GUILayout.ExpandWidth(true));
// LHS
GUILayout.BeginHorizontal(GUILayout.Width(leftBarWidth - 6));
// Create Button
GUIContent createButton = new GUIContent("Create");
Rect createButtonRect = GUILayoutUtility.GetRect(createButton, EditorStyles.toolbarDropDown, GUILayout.ExpandWidth(false));
if (GUI.Button(createButtonRect, createButton, EditorStyles.toolbarDropDown) && anim != null)
{
GUIUtility.hotControl = 0;
EditorUtility.DisplayCustomMenu(createButtonRect, menuItems, -1,
delegate(object userData, string[] options, int selected) {
if (selected == 0)
{
selectedClip = CreateNewClip();
clipEditor.Clip = selectedClip;
clipEditor.InitForNewClip();
Repaint();
}
else if (menuTargets[selected] != null)
{
tk2dEditor.SpriteAnimationEditor.AnimOperator animOp = menuTargets[selected];
tk2dSpriteAnimationClip newSelectedClip = animOp.OnAnimMenu(options[selected], allClips, selectedClip);
if (selectedClip != newSelectedClip)
{
selectedClip = newSelectedClip;
clipEditor.Clip = selectedClip;
}
if ((animOp.AnimEditOperations & tk2dEditor.SpriteAnimationEditor.AnimEditOperations.AllClipsChanged) != tk2dEditor.SpriteAnimationEditor.AnimEditOperations.None)
{
FilterClips();
Repaint();
}
if ((animOp.AnimEditOperations & tk2dEditor.SpriteAnimationEditor.AnimEditOperations.NewClipCreated) != tk2dEditor.SpriteAnimationEditor.AnimEditOperations.None)
{
clipEditor.InitForNewClip();
Repaint();
}
}
}
, null);
}
// Filter box
if (anim != null)
{
GUILayout.Space(8);
string newSearchFilter = GUILayout.TextField(searchFilter, tk2dEditorSkin.ToolbarSearch, GUILayout.ExpandWidth(true));
if (newSearchFilter != searchFilter)
{
searchFilter = newSearchFilter;
FilterClips();
}
if (searchFilter.Length > 0)
{
if (GUILayout.Button("", tk2dEditorSkin.ToolbarSearchClear, GUILayout.ExpandWidth(false)))
{
searchFilter = "";
FilterClips();
}
}
else
{
GUILayout.Label("", tk2dEditorSkin.ToolbarSearchRightCap);
}
}
GUILayout.EndHorizontal();
// Label
if (anim != null)
{
if (GUILayout.Button(anim.name, EditorStyles.label))
EditorGUIUtility.PingObject(anim);
}
// RHS
GUILayout.FlexibleSpace();
if (anim != null && GUILayout.Button("Revert", EditorStyles.toolbarButton))
Revert();
if (anim != null && GUILayout.Button("Commit", EditorStyles.toolbarButton))
Commit();
GUILayout.EndHorizontal();
}
void OnGUI()
{
DrawToolbar();
if (anim != null)
{
GUILayout.BeginHorizontal();
DrawList();
clipEditor.Clip = selectedClip;
clipEditor.Draw(Screen.width - leftBarWidth - 2);
GUILayout.EndHorizontal();
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Xml;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation
{
internal class DscResourceHelpProvider : HelpProviderWithCache
{
/// <summary>
/// Constructor for DscResourceHelpProvider.
/// </summary>
internal DscResourceHelpProvider(HelpSystem helpSystem)
: base(helpSystem)
{
_context = helpSystem.ExecutionContext;
}
/// <summary>
/// Execution context of the HelpSystem.
/// </summary>
private readonly ExecutionContext _context;
/// <summary>
/// This is a hashtable to track which help files are loaded already.
///
/// This will avoid one help file getting loaded again and again.
/// </summary>
private readonly Hashtable _helpFiles = new Hashtable();
[TraceSource("DscResourceHelpProvider", "DscResourceHelpProvider")]
private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("DscResourceHelpProvider", "DscResourceHelpProvider");
#region common properties
/// <summary>
/// Name of the Help Provider.
/// </summary>
internal override string Name
{
get { return "Dsc Resource Help Provider"; }
}
/// <summary>
/// Supported Help Categories.
/// </summary>
internal override HelpCategory HelpCategory
{
get { return Automation.HelpCategory.DscResource; }
}
#endregion
/// <summary>
/// Override SearchHelp to find a dsc resource help matching a pattern.
/// </summary>
/// <param name="helpRequest">Help request.</param>
/// <param name="searchOnlyContent">Not used.</param>
/// <returns></returns>
internal override IEnumerable<HelpInfo> SearchHelp(HelpRequest helpRequest, bool searchOnlyContent)
{
Debug.Assert(helpRequest != null, "helpRequest cannot be null.");
string target = helpRequest.Target;
Collection<string> patternList = new Collection<string>();
bool decoratedSearch = !WildcardPattern.ContainsWildcardCharacters(helpRequest.Target);
if (decoratedSearch)
{
patternList.Add("*" + target + "*");
}
else
patternList.Add(target);
foreach (string pattern in patternList)
{
DscResourceSearcher searcher = new DscResourceSearcher(pattern, _context);
foreach (var helpInfo in GetHelpInfo(searcher))
{
if (helpInfo != null)
yield return helpInfo;
}
}
}
/// <summary>
/// Override ExactMatchHelp to find the matching DscResource matching help request.
/// </summary>
/// <param name="helpRequest">Help Request for the search.</param>
/// <returns>Enumerable of HelpInfo objects.</returns>
internal override IEnumerable<HelpInfo> ExactMatchHelp(HelpRequest helpRequest)
{
Debug.Assert(helpRequest != null, "helpRequest cannot be null.");
if ((helpRequest.HelpCategory & Automation.HelpCategory.DscResource) == 0)
{
yield return null;
}
string target = helpRequest.Target;
DscResourceSearcher searcher = new DscResourceSearcher(target, _context);
foreach (var helpInfo in GetHelpInfo(searcher))
{
if (helpInfo != null)
{
yield return helpInfo;
}
}
}
/// <summary>
/// Get the help in for the DscResource Info. ///
/// </summary>
/// <param name="searcher">Searcher for DscResources.</param>
/// <returns>Next HelpInfo object.</returns>
private IEnumerable<HelpInfo> GetHelpInfo(DscResourceSearcher searcher)
{
while (searcher.MoveNext())
{
DscResourceInfo current = ((IEnumerator<DscResourceInfo>)searcher).Current;
string moduleName = null;
string moduleDir = current.ParentPath;
// for binary modules, current.Module is empty.
// in such cases use the leaf folder of ParentPath as filename.
if (current.Module != null)
{
moduleName = current.Module.Name;
}
else if (!string.IsNullOrEmpty(moduleDir))
{
string[] splitPath = moduleDir.Split(Utils.Separators.Backslash);
moduleName = splitPath[splitPath.Length - 1];
}
if (!string.IsNullOrEmpty(moduleName) && !string.IsNullOrEmpty(moduleDir))
{
string helpFileToFind = moduleName + "-Help.xml";
string helpFileName = null;
Collection<string> searchPaths = new Collection<string>();
searchPaths.Add(moduleDir);
HelpInfo helpInfo = GetHelpInfoFromHelpFile(current, helpFileToFind, searchPaths, true, out helpFileName);
if (helpInfo != null)
{
yield return helpInfo;
}
}
}
}
/// <summary>
/// Check whether a HelpItems node indicates that the help content is
/// authored using maml schema.
///
/// This covers two cases:
/// a. If the help file has an extension .maml.
/// b. If HelpItems node (which should be the top node of any command help file)
/// has an attribute "schema" with value "maml", its content is in maml
/// schema.
/// </summary>
/// <param name="helpFile">File name.</param>
/// <param name="helpItemsNode">Nodes to check.</param>
/// <returns></returns>
internal static bool IsMamlHelp(string helpFile, XmlNode helpItemsNode)
{
Debug.Assert(!string.IsNullOrEmpty(helpFile), "helpFile cannot be null.");
if (helpFile.EndsWith(".maml", StringComparison.OrdinalIgnoreCase))
return true;
if (helpItemsNode.Attributes == null)
return false;
foreach (XmlNode attribute in helpItemsNode.Attributes)
{
if (attribute.Name.Equals("schema", StringComparison.OrdinalIgnoreCase)
&& attribute.Value.Equals("maml", StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
#region private methods
private HelpInfo GetHelpInfoFromHelpFile(DscResourceInfo resourceInfo, string helpFileToFind, Collection<string> searchPaths, bool reportErrors, out string helpFile)
{
Dbg.Assert(resourceInfo != null, "Caller should verify that resourceInfo != null");
Dbg.Assert(helpFileToFind != null, "Caller should verify that helpFileToFind != null");
helpFile = MUIFileSearcher.LocateFile(helpFileToFind, searchPaths);
if (!File.Exists(helpFile))
return null;
if (!string.IsNullOrEmpty(helpFile))
{
// Load the help file only once. Then use it from the cache.
if (!_helpFiles.Contains(helpFile))
{
LoadHelpFile(helpFile, helpFile, resourceInfo.Name, reportErrors);
}
return GetFromResourceHelpCache(helpFile, Automation.HelpCategory.DscResource);
}
return null;
}
/// <summary>
/// Gets the HelpInfo object corresponding to the command.
/// </summary>
/// <param name="helpFileIdentifier">Help file identifier (either name of PSSnapIn or simply full path to help file).</param>
/// <param name="helpCategory">Help Category for search.</param>
/// <returns>HelpInfo object.</returns>
private HelpInfo GetFromResourceHelpCache(string helpFileIdentifier, HelpCategory helpCategory)
{
Debug.Assert(!string.IsNullOrEmpty(helpFileIdentifier), "helpFileIdentifier should not be null or empty.");
HelpInfo result = GetCache(helpFileIdentifier);
if (result != null)
{
MamlCommandHelpInfo original = (MamlCommandHelpInfo)result;
result = original.Copy(helpCategory);
}
return result;
}
private void LoadHelpFile(string helpFile, string helpFileIdentifier, string commandName, bool reportErrors)
{
Exception e = null;
try
{
LoadHelpFile(helpFile, helpFileIdentifier);
}
catch (IOException ioException)
{
e = ioException;
}
catch (System.Security.SecurityException securityException)
{
e = securityException;
}
catch (XmlException xmlException)
{
e = xmlException;
}
catch (NotSupportedException notSupportedException)
{
e = notSupportedException;
}
catch (UnauthorizedAccessException unauthorizedAccessException)
{
e = unauthorizedAccessException;
}
catch (InvalidOperationException invalidOperationException)
{
e = invalidOperationException;
}
if (e != null)
s_tracer.WriteLine("Error occurred in DscResourceHelpProvider {0}", e.Message);
if (reportErrors && (e != null))
{
ReportHelpFileError(e, commandName, helpFile);
}
}
/// <summary>
/// Load help file for HelpInfo objects. The HelpInfo objects will be
/// put into help cache.
/// </summary>
/// <remarks>
/// 1. Needs to pay special attention about error handling in this function.
/// Common errors include: file not found and invalid xml. None of these error
/// should cause help search to stop.
/// 2. a helpfile cache is used to avoid same file got loaded again and again.
/// </remarks>
private void LoadHelpFile(string helpFile, string helpFileIdentifier)
{
Dbg.Assert(!string.IsNullOrEmpty(helpFile), "HelpFile cannot be null or empty.");
Dbg.Assert(!string.IsNullOrEmpty(helpFileIdentifier), "helpFileIdentifier cannot be null or empty.");
XmlDocument doc = InternalDeserializer.LoadUnsafeXmlDocument(
new FileInfo(helpFile),
false, /* ignore whitespace, comments, etc. */
null); /* default maxCharactersInDocument */
// Add this file into _helpFiles hashtable to prevent it to be loaded again.
_helpFiles[helpFile] = 0;
XmlNode helpItemsNode = null;
if (doc.HasChildNodes)
{
for (int i = 0; i < doc.ChildNodes.Count; i++)
{
XmlNode node = doc.ChildNodes[i];
if (node.NodeType == XmlNodeType.Element && string.Equals(node.LocalName, "helpItems", StringComparison.OrdinalIgnoreCase))
{
helpItemsNode = node;
break;
}
}
}
if (helpItemsNode == null)
{
s_tracer.WriteLine("Unable to find 'helpItems' element in file {0}", helpFile);
return;
}
bool isMaml = IsMamlHelp(helpFile, helpItemsNode);
using (this.HelpSystem.Trace(helpFile))
{
if (helpItemsNode.HasChildNodes)
{
for (int i = 0; i < helpItemsNode.ChildNodes.Count; i++)
{
XmlNode node = helpItemsNode.ChildNodes[i];
string nodeLocalName = node.LocalName;
bool isDscResource = (string.Equals(nodeLocalName, "dscResource", StringComparison.OrdinalIgnoreCase));
if (node.NodeType == XmlNodeType.Element && isDscResource)
{
MamlCommandHelpInfo helpInfo = null;
if (isMaml)
{
if (isDscResource)
helpInfo = MamlCommandHelpInfo.Load(node, HelpCategory.DscResource);
}
if (helpInfo != null)
{
this.HelpSystem.TraceErrors(helpInfo.Errors);
AddCache(helpFileIdentifier, helpInfo);
}
}
}
}
}
}
#endregion
}
}
| |
//---------------------------------------------------------------------
// <copyright file="LiteralFormatter.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------
#if ASTORIA_CLIENT
namespace Microsoft.OData.Client
#else
#if ASTORIA_SERVER
namespace Microsoft.OData.Service
#else
namespace Microsoft.OData.Core.Evaluation
#endif
#endif
{
#if ASTORIA_SERVER
using System.Data.Linq;
#endif
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using System.Linq;
using System.Xml;
#if ODATALIB
using Microsoft.OData.Core.UriParser;
using Microsoft.OData.Edm.Library;
using Microsoft.Spatial;
#else
using System.Xml.Linq;
using Microsoft.OData.Core;
using Microsoft.OData.Edm.Library;
using Microsoft.Spatial;
using ExpressionConstants = XmlConstants;
#endif
/// <summary>
/// Component for formatting literals for use in URIs, ETags, and skip-tokens.
/// </summary>
internal abstract class LiteralFormatter
{
/// <summary>Default singleton instance for parenthetical keys, etags, or skiptokens.</summary>
private static readonly LiteralFormatter DefaultInstance = new DefaultLiteralFormatter();
#if ODATALIB
/// <summary>Default singleton instance which does not URL-encode the resulting string.</summary>
private static readonly LiteralFormatter DefaultInstanceWithoutEncoding = new DefaultLiteralFormatter(/*disableUrlEncoding*/ true);
#endif
/// <summary>Default singleton instance for keys formatted as segments.</summary>
private static readonly LiteralFormatter KeyAsSegmentInstance = new KeysAsSegmentsLiteralFormatter();
#if ASTORIA_SERVER
/// <summary>
/// Gets the literal formatter for ETags.
/// </summary>
internal static LiteralFormatter ForETag
{
get { return DefaultInstance; }
}
/// <summary>
/// Gets the literal formatter for skip-tokens.
/// </summary>
internal static LiteralFormatter ForSkipToken
{
get { return DefaultInstance; }
}
#else
/// <summary>
/// Gets the literal formatter for URL constants.
/// </summary>
internal static LiteralFormatter ForConstants
{
get
{
return DefaultInstance;
}
}
#endif
#if ODATALIB
/// <summary>
/// Gets the literal formatter for URL constants which does not URL-encode the string.
/// </summary>
internal static LiteralFormatter ForConstantsWithoutEncoding
{
get
{
return DefaultInstanceWithoutEncoding;
}
}
#endif
/// <summary>
/// Gets the literal formatter for keys.
/// </summary>
/// <param name="keysAsSegment">if set to <c>true</c> then the key is going to be written as a segment, rather than in parentheses.</param>
/// <returns>The literal formatter for keys.</returns>
internal static LiteralFormatter ForKeys(bool keysAsSegment)
{
return keysAsSegment ? KeyAsSegmentInstance : DefaultInstance;
}
/// <summary>Converts the specified value to an encoded, serializable string for URI key.</summary>
/// <param name="value">Non-null value to convert.</param>
/// <returns>value converted to a serializable string for URI key.</returns>
internal abstract string Format(object value);
/// <summary>
/// Escapes the result accoridng to URI escaping rules.
/// </summary>
/// <param name="result">The result to escape.</param>
/// <returns>The escaped string.</returns>
[SuppressMessage("DataWeb.Usage", "AC0018:SystemUriEscapeDataStringRule", Justification = "Values are correctly being escaped before the literal delimiters are added.")]
protected virtual string EscapeResultForUri(string result)
{
// required for strings as data, DateTime for ':', numbers for '+'
// we specifically do not want to encode leading and trailing "'" wrapping strings/datetime/guid
return Uri.EscapeDataString(result);
}
/// <summary>Converts the given byte[] into string.</summary>
/// <param name="byteArray">byte[] that needs to be converted.</param>
/// <returns>String containing hex values representing the byte[].</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("DataWeb.Usage", "AC0018:SystemUriEscapeDataStringRule", Justification = "Usage is in Debug.Assert only")]
private static string ConvertByteArrayToKeyString(byte[] byteArray)
{
Debug.Assert(byteArray != null, "byteArray != null");
return Convert.ToBase64String(byteArray, 0, byteArray.Length);
}
/// <summary>
/// Formats the literal without a type prefix, quotes, or escaping.
/// </summary>
/// <param name="value">The non-null value to format.</param>
/// <returns>The formatted literal, without type marker or quotes.</returns>
private static string FormatRawLiteral(object value)
{
Debug.Assert(value != null, "value != null");
string stringValue = value as string;
if (stringValue != null)
{
return stringValue;
}
if (value is bool)
{
return XmlConvert.ToString((bool)value);
}
if (value is byte)
{
return XmlConvert.ToString((byte)value);
}
#if ASTORIA_SERVER
if (value is DateTime)
{
// Since the server/client supports DateTime values, convert the DateTime value
// to DateTimeOffset and use XmlCOnvert to convert to String.
DateTimeOffset dto = WebUtil.ConvertDateTimeToDateTimeOffset((DateTime)value);
return XmlConvert.ToString(dto);
}
#endif
if (value is decimal)
{
return XmlConvert.ToString((decimal)value);
}
if (value is double)
{
string formattedDouble = XmlConvert.ToString((double)value);
formattedDouble = SharedUtils.AppendDecimalMarkerToDouble(formattedDouble);
return formattedDouble;
}
if (value is Guid)
{
return value.ToString();
}
if (value is short)
{
return XmlConvert.ToString((Int16)value);
}
if (value is int)
{
return XmlConvert.ToString((Int32)value);
}
if (value is long)
{
return XmlConvert.ToString((Int64)value);
}
if (value is sbyte)
{
return XmlConvert.ToString((SByte)value);
}
if (value is float)
{
return XmlConvert.ToString((Single)value);
}
byte[] array = value as byte[];
if (array != null)
{
return ConvertByteArrayToKeyString(array);
}
if (value is Date)
{
return value.ToString();
}
if (value is DateTimeOffset)
{
return XmlConvert.ToString((DateTimeOffset)value);
}
if (value is TimeOfDay)
{
return value.ToString();
}
if (value is TimeSpan)
{
return EdmValueWriter.DurationAsXml((TimeSpan)value);
}
Geography geography = value as Geography;
if (geography != null)
{
return WellKnownTextSqlFormatter.Create(true).Write(geography);
}
Geometry geometry = value as Geometry;
if (geometry != null)
{
return WellKnownTextSqlFormatter.Create(true).Write(geometry);
}
throw SharedUtils.CreateExceptionForUnconvertableType(value);
}
/// <summary>
/// Formats the literal without a type prefix or quotes, but does escape it.
/// </summary>
/// <param name="value">The non-null value to format.</param>
/// <returns>The formatted literal, without type marker or quotes.</returns>
private string FormatAndEscapeLiteral(object value)
{
Debug.Assert(value != null, "value != null");
string result = FormatRawLiteral(value);
Debug.Assert(result != null, "result != null");
if (value is string)
{
result = result.Replace("'", "''");
}
return this.EscapeResultForUri(result);
}
/// <summary>
/// Helper utilities that capture any deltas between ODL, the WCF DS Client, and the WCF DS Server.
/// </summary>
private static class SharedUtils
{
/// <summary>
/// Creates a new exception instance to be thrown if the value is not a type that can be formatted as a literal.
/// DEVNOTE: Will return a different exception depending on whether this is ODataLib, the WCF DS Server, or the WCF DS client.
/// </summary>
/// <param name="value">The literal value that could not be converted.</param>
/// <returns>The exception that should be thrown.</returns>
internal static InvalidOperationException CreateExceptionForUnconvertableType(object value)
{
#if ASTORIA_SERVER
return new InvalidOperationException(Microsoft.OData.Service.Strings.Serializer_CannotConvertValue(value));
#endif
#if ASTORIA_CLIENT
return Error.InvalidOperation(Client.Strings.Context_CannotConvertKey(value));
#endif
#if ODATALIB
return new ODataException(OData.Core.Strings.ODataUriUtils_ConvertToUriLiteralUnsupportedType(value.GetType().ToString()));
#endif
}
/// <summary>
/// Tries to convert the given value to one of the standard recognized types. Used specifically for handling XML and binary types.
/// </summary>
/// <param name="value">The original value.</param>
/// <param name="converted">The value converted to one of the standard types.</param>
/// <returns>Whether or not the value was converted.</returns>
internal static bool TryConvertToStandardType(object value, out object converted)
{
byte[] array;
if (TryGetByteArrayFromBinary(value, out array))
{
converted = array;
return true;
}
#if !ODATALIB
XElement xml = value as XElement;
if (xml != null)
{
converted = xml.ToString();
return true;
}
#endif
converted = null;
return false;
}
/// <summary>
/// Appends the decimal marker to string form of double value if necessary.
/// DEVNOTE: Only used by the client and ODL, for legacy/back-compat reasons.
/// </summary>
/// <param name="input">Input string.</param>
/// <returns>String with decimal marker optionally added.</returns>
internal static string AppendDecimalMarkerToDouble(string input)
{
// DEVNOTE: for some reason, the client adds .0 to doubles where the server does not.
// Unfortunately, it would be a breaking change to alter this behavior now.
#if ASTORIA_CLIENT || ODATALIB
IEnumerable<char> characters = input.ToCharArray();
#if ODATALIB
// negative numbers can also be 'whole', but the client did not take that into account.
if (input[0] == '-')
{
characters = characters.Skip(1);
}
#endif
// a whole number should be all digits.
if (characters.All(char.IsDigit))
{
return input + ".0";
}
#endif
// the server never appended anything, so it will fall through to here.
return input;
}
/// <summary>
/// Tries to convert an instance of System.Data.Linq.Binary to a byte array.
/// </summary>
/// <param name="value">The original value which might be an instance of System.Data.Linq.Binary.</param>
/// <param name="array">The converted byte array, if it was converted.</param>
/// <returns>Whether or not the value was converted.</returns>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "value", Justification = "Method is compiled into 3 assemblies, and the parameter is used in 2 of them.")]
private static bool TryGetByteArrayFromBinary(object value, out byte[] array)
{
// DEVNOTE: the client does not have a reference to System.Data.Linq, but the server does.
// So we need to interact with Binary differently.
#if ASTORIA_SERVER
Binary binary = value as Binary;
if (binary != null)
{
array = binary.ToArray();
return true;
}
#endif
#if ASTORIA_CLIENT
return ClientConvert.TryConvertBinaryToByteArray(value, out array);
#else
array = null;
return false;
#endif
}
}
/// <summary>
/// Default literal formatter implementation.
/// </summary>
private sealed class DefaultLiteralFormatter : LiteralFormatter
{
/// <summary>If true, literals will not be URL encoded.</summary>
private readonly bool disableUrlEncoding;
/// <summary>
/// Creates a new instance of <see cref="DefaultLiteralFormatter"/>.
/// </summary>
internal DefaultLiteralFormatter()
: this(false /*disableUrlEncoding*/)
{
}
#if ODATALIB
/// <summary>
/// Creates a new instance of <see cref="DefaultLiteralFormatter"/>.
/// </summary>
/// <param name="disableUrlEncoding">If true, literals will not be URL encoded.</param>
internal DefaultLiteralFormatter(bool disableUrlEncoding)
#else
/// <summary>
/// Creates a new instance of <see cref="DefaultLiteralFormatter"/>.
/// </summary>
/// <param name="disableUrlEncoding">If true, literals will not be URL encoded.</param>
private DefaultLiteralFormatter(bool disableUrlEncoding)
#endif
{
this.disableUrlEncoding = disableUrlEncoding;
}
/// <summary>Converts the specified value to an encoded, serializable string for URI key.</summary>
/// <param name="value">Non-null value to convert.</param>
/// <returns>value converted to a serializable string for URI key.</returns>
internal override string Format(object value)
{
object converted;
if (SharedUtils.TryConvertToStandardType(value, out converted))
{
value = converted;
}
return this.FormatLiteralWithTypePrefix(value);
}
/// <summary>
/// Escapes the result accoridng to URI escaping rules.
/// </summary>
/// <param name="result">The result to escape.</param>
/// <returns>The escaped string.</returns>
protected override string EscapeResultForUri(string result)
{
#if !ODATALIB
Debug.Assert(!this.disableUrlEncoding, "Only supported for ODataLib for backwards compatibility reasons.");
#endif
if (!this.disableUrlEncoding)
{
result = base.EscapeResultForUri(result);
}
return result;
}
/// <summary>
/// Formats the literal with a type prefix and quotes (if the type requires it).
/// </summary>
/// <param name="value">The value to format.</param>
/// <returns>The formatted literal, with type marker if needed.</returns>
private string FormatLiteralWithTypePrefix(object value)
{
Debug.Assert(value != null, "value != null. Null values need to be handled differently in some cases.");
string result = this.FormatAndEscapeLiteral(value);
if (value is byte[])
{
return ExpressionConstants.LiteralPrefixBinary + "'" + result + "'";
}
if (value is Geography)
{
return ExpressionConstants.LiteralPrefixGeography + "'" + result + "'";
}
if (value is Geometry)
{
return ExpressionConstants.LiteralPrefixGeometry + "'" + result + "'";
}
if (value is TimeSpan)
{
return ExpressionConstants.LiteralPrefixDuration + "'" + result + "'";
}
if (value is string)
{
return "'" + result + "'";
}
// for int32,int64,float,double, decimal, Infinity/NaN, just output them without prefix or suffix such as L/M/D/F.
return result;
}
}
/// <summary>
/// Literal formatter for keys which are written as URI segments.
/// Very similar to the default, but it never puts the type markers or single quotes around the value.
/// </summary>
private sealed class KeysAsSegmentsLiteralFormatter : LiteralFormatter
{
/// <summary>
/// Creates a new instance of <see cref="KeysAsSegmentsLiteralFormatter"/>.
/// </summary>
internal KeysAsSegmentsLiteralFormatter()
{
}
/// <summary>Converts the specified value to an encoded, serializable string for URI key.</summary>
/// <param name="value">Non-null value to convert.</param>
/// <returns>value converted to a serializable string for URI key.</returns>
internal override string Format(object value)
{
Debug.Assert(value != null, "value != null");
object converted;
if (SharedUtils.TryConvertToStandardType(value, out converted))
{
value = converted;
}
string stringValue = value as string;
if (stringValue != null)
{
value = EscapeLeadingDollarSign(stringValue);
}
return FormatAndEscapeLiteral(value);
}
/// <summary>
/// If the string starts with a '$', prepends another '$' to escape it.
/// </summary>
/// <param name="stringValue">The string value.</param>
/// <returns>The string value with a leading '$' escaped, if one was present.</returns>
private static string EscapeLeadingDollarSign(string stringValue)
{
if (stringValue.Length > 0 && stringValue[0] == '$')
{
stringValue = '$' + stringValue;
}
return stringValue;
}
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2014 Charlie Poole, Rob Prouse
//
// 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.
// ***********************************************************************
#if PARALLEL
using System.Threading;
using NUnit.TestUtilities;
namespace NUnit.Framework.Internal.Execution
{
public class WorkItemQueueTests
{
private WorkItemQueue _queue;
[SetUp]
public void CreateQueue()
{
_queue = new WorkItemQueue("TestQ", true, ApartmentState.MTA);
}
[Test]
public void InitialState()
{
Assert.That(_queue.Name, Is.EqualTo("TestQ"));
Assert.That(_queue.IsEmpty, "Queue is not empty");
Assert.That(_queue.State, Is.EqualTo(WorkItemQueueState.Paused));
}
[Test]
public void StartQueue()
{
_queue.Start();
Assert.That(_queue.State, Is.EqualTo(WorkItemQueueState.Running));
}
[Test]
public void StopQueue_NoWorkers()
{
_queue.Start();
_queue.Stop();
Assert.That(_queue.State, Is.EqualTo(WorkItemQueueState.Stopped));
}
[Test]
public void StopQueue_WithWorkers()
{
var workers = new TestWorker[]
{
new TestWorker(_queue, "1"),
new TestWorker(_queue, "2"),
new TestWorker(_queue, "3")
};
foreach (var worker in workers)
{
worker.Start();
Assert.That(worker.IsAlive, "Worker thread {0} did not start", worker.Name);
}
_queue.Start();
_queue.Stop();
Assert.That(_queue.State, Is.EqualTo(WorkItemQueueState.Stopped));
int iters = 10;
int alive = workers.Length;
while (iters-- > 0 && alive > 0)
{
Thread.Sleep(60); // Allow time for workers to stop
alive = 0;
foreach (var worker in workers)
if (worker.IsAlive)
alive++;
}
if (alive > 0)
foreach (var worker in workers)
Assert.False(worker.IsAlive, "Worker thread {0} did not stop", worker.Name);
}
[Test]
public void PauseQueue()
{
_queue.Start();
_queue.Pause();
Assert.That(_queue.State, Is.EqualTo(WorkItemQueueState.Paused));
}
[Test]
public void EnqueueBeforeDequeue()
{
string[] names = new[] { "Test1", "Test2", "Test3" };
EnqueueWorkItems(names);
_queue.Start();
VerifyQueueContents(names);
}
[Test]
public void DequeueBeforeEnqueue()
{
_queue.Start();
var names = new string[] { "Test1", "Test2", "Test3" };
new Thread(new ThreadStart(() =>
{
Thread.Sleep(10);
EnqueueWorkItems(names);
})).Start();
VerifyQueueContents(names);
}
[Test]
public void EnqueueAndDequeueWhilePaused()
{
string[] names = new[] { "Test1", "Test2", "Test3" };
EnqueueWorkItems(names);
new Thread(new ThreadStart(() =>
{
Thread.Sleep(10);
_queue.Start();
})).Start();
VerifyQueueContents(names);
}
const int HIGH_PRIORITY = 0;
const int NORMAL_PRIORITY = 1;
[Test]
public void PriorityIsHonored()
{
EnqueueWorkItem("Test1", NORMAL_PRIORITY);
EnqueueWorkItem("Test2", HIGH_PRIORITY);
EnqueueWorkItem("Test3", NORMAL_PRIORITY);
_queue.Start();
VerifyQueueContents("Test2", "Test1", "Test3");
}
[Test]
public void OneTimeTearDownGetsPriority()
{
var testFixture = new TestFixture(new TypeWrapper(typeof(MyFixture)));
var fixtureItem = WorkItemBuilder.CreateWorkItem(testFixture, TestFilter.Empty) as CompositeWorkItem;
var tearDown = new CompositeWorkItem.OneTimeTearDownWorkItem(fixtureItem);
EnqueueWorkItem("Test1");
_queue.Enqueue(tearDown);
EnqueueWorkItem("Test2");
_queue.Start();
VerifyQueueContents("WorkItemQueueTests+MyFixture", "Test1", "Test2");
}
private void EnqueueWorkItems(params string[] names)
{
foreach (string name in names)
EnqueueWorkItem(name);
}
private void EnqueueWorkItem(string name)
{
_queue.Enqueue(Fakes.GetWorkItem(this, name));
}
private void EnqueueWorkItem(string name, int priority)
{
_queue.Enqueue(Fakes.GetWorkItem(this, name), priority);
}
private void VerifyQueueContents(params string[] names)
{
foreach (string name in names)
Assert.That(_queue.Dequeue().Test.Name, Is.EqualTo(name));
}
private void Test1()
{
}
private void Test2()
{
}
private void Test3()
{
}
private class MyFixture
{
}
}
}
#endif
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class DefaultKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AtRoot_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterClass_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterGlobalStatement_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterGlobalVariableDeclaration_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInUsingAlias()
{
VerifyAbsence(
@"using Foo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInPreprocessor1()
{
VerifyAbsence(
@"class C {
#$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInPreprocessor2()
{
VerifyAbsence(
@"class C {
#if $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterHash()
{
VerifyKeyword(
@"#line $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterHashAndSpace()
{
VerifyKeyword(
@"# line $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InEmptyStatement()
{
VerifyKeyword(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InExpression()
{
VerifyKeyword(AddInsideMethod(
@"var q = $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterSwitch()
{
VerifyKeyword(AddInsideMethod(
@"switch (expr) {
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterCase()
{
VerifyKeyword(AddInsideMethod(
@"switch (expr) {
case 0:
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterDefault()
{
VerifyKeyword(AddInsideMethod(
@"switch (expr) {
default:
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterOneStatement()
{
VerifyKeyword(AddInsideMethod(
@"switch (expr) {
default:
Console.WriteLine();
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterTwoStatements()
{
VerifyKeyword(AddInsideMethod(
@"switch (expr) {
default:
Console.WriteLine();
Console.WriteLine();
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterBlock()
{
VerifyKeyword(AddInsideMethod(
@"switch (expr) {
default: {
}
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterIfElse()
{
VerifyKeyword(AddInsideMethod(
@"switch (expr) {
default:
if (foo) {
} else {
}
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterIncompleteStatement()
{
VerifyKeyword(AddInsideMethod(
@"switch (expr) {
default:
Console.WriteLine(
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InsideBlock()
{
VerifyKeyword(AddInsideMethod(
@"switch (expr) {
default: {
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterCompleteIf()
{
VerifyKeyword(AddInsideMethod(
@"switch (expr) {
default:
if (foo)
Console.WriteLine();
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterIncompleteIf()
{
VerifyKeyword(AddInsideMethod(
@"switch (expr) {
default:
if (foo)
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterWhile()
{
VerifyKeyword(AddInsideMethod(
@"switch (expr) {
default:
while (true) {
}
$$"));
}
[WorkItem(552717)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterGotoInSwitch()
{
VerifyAbsence(AddInsideMethod(
@"switch (expr) {
default:
goto $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterGotoOutsideSwitch()
{
VerifyAbsence(AddInsideMethod(
@"goto $$"));
}
[WorkItem(538804)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInTypeOf()
{
VerifyAbsence(AddInsideMethod(
@"typeof($$"));
}
[WorkItem(538804)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInDefault()
{
VerifyAbsence(AddInsideMethod(
@"default($$"));
}
[WorkItem(538804)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInSizeOf()
{
VerifyAbsence(AddInsideMethod(
@"sizeof($$"));
}
[WorkItem(544219)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInObjectInitializerMemberContext()
{
VerifyAbsence(@"
class C
{
public int x, y;
void M()
{
var c = new C { x = 2, y = 3, $$");
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Research.AbstractDomains;
using Microsoft.Research.AbstractDomains.Numerical;
using System.Diagnostics.Contracts;
namespace Microsoft.Research.CodeAnalysis
{
[ContractVerification(false)]
public class BoxedExpressionFactory<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Var>
: IFactory<BoxedExpression>
{
#region Object invariant
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(this.True != null);
Contract.Invariant(this.False != null);
Contract.Invariant(this.One != null);
Contract.Invariant(this.medataDecoder != null);
}
#endregion
#region State
readonly private BoxedExpression True;
readonly private BoxedExpression False;
readonly private BoxedExpression One;
readonly private IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> medataDecoder;
readonly private BoxedExpression name;
readonly private BoxedExpression boundVariable;
readonly private Func<Var, BoxedExpression> VariableConverter;
readonly private Func<Var, BoxedExpression> ArrayLength;
#endregion
public BoxedExpressionFactory(IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> metadataDecoder, Func<Var, BoxedExpression> ArrayLength = null)
: this(null, null, null, metadataDecoder, ArrayLength)
{
Contract.Requires(metadataDecoder != null);
}
public BoxedExpressionFactory(
BoxedExpression boundVar,
IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> metadataDecoder, Func<Var, BoxedExpression> ArrayLength = null)
: this(boundVar, null, null, metadataDecoder, ArrayLength)
{
Contract.Requires(metadataDecoder != null);
}
public BoxedExpressionFactory(
BoxedExpression boundVar, BoxedExpression name,
Func<Var, BoxedExpression> VariableConverter,
IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> metadataDecoder,
Func<Var, BoxedExpression> ArrayLength)
{
Contract.Requires(metadataDecoder != null);
this.boundVariable = boundVar;
this.name = name;
this.VariableConverter = VariableConverter;
this.medataDecoder = metadataDecoder;
this.ArrayLength = ArrayLength;
this.True = BoxedExpression.Const(true, medataDecoder.System_Boolean, metadataDecoder);
this.False = BoxedExpression.Const(false, metadataDecoder.System_Boolean, metadataDecoder);
this.One = BoxedExpression.Const(1, metadataDecoder.System_Int32, metadataDecoder);
}
#region IFactory<BoxedExpression> Members
public IFactory<BoxedExpression> FactoryWithName(BoxedExpression name)
{
return new BoxedExpressionFactory<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Var>(name, this.name, this.VariableConverter, this.medataDecoder, this.ArrayLength);
}
public BoxedExpression Constant(int constant)
{
if (constant == 1)
return this.IdentityForMul;
else
return BoxedExpression.Const(constant, medataDecoder.System_Int32, this.medataDecoder);
}
public BoxedExpression Constant(long constant)
{
if (constant == 1)
return this.IdentityForMul;
else
return BoxedExpression.Const(constant, medataDecoder.System_Int64, this.medataDecoder);
}
public BoxedExpression Constant(Rational constant)
{
return constant.To(this);
}
public BoxedExpression Constant(bool constant)
{
if (constant)
return this.True;
else
return this.False;
}
public BoxedExpression Constant(double constant)
{
return BoxedExpression.Const(constant, this.medataDecoder.System_Double, this.medataDecoder);
}
public BoxedExpression Variable(object variable)
{
var variableAsBoxedExp = variable as BoxedExpression;
if (variableAsBoxedExp != null)
{
return variableAsBoxedExp;
}
if (VariableConverter != null)
{
var variableAsBoxedVar = variable as BoxedVariable<Var>;
if (variableAsBoxedVar != null)
{
Var v;
if (variableAsBoxedVar.TryUnpackVariable(out v))
{
return VariableConverter(v);
}
}
else if (variable is Var)
{
return VariableConverter((Var)variable);
}
}
return BoxedExpression.Var(variable);
}
public BoxedExpression Add(BoxedExpression left, BoxedExpression right)
{
if (left == this.IdentityForAdd)
return right;
if (right == this.IdentityForAdd)
return left;
return BoxedExpression.Binary(BinaryOperator.Add, left, right);
}
public BoxedExpression Sub(BoxedExpression left, BoxedExpression right)
{
return BoxedExpression.Binary(BinaryOperator.Sub, left, right);
}
public BoxedExpression Mul(BoxedExpression left, BoxedExpression right)
{
if (left == this.One)
return right;
if (right == this.One)
return left;
return BoxedExpression.Binary(BinaryOperator.Mul, left, right);
}
public BoxedExpression Div(BoxedExpression left, BoxedExpression right)
{
return BoxedExpression.Binary(BinaryOperator.Div, left, right);
}
public BoxedExpression EqualTo(BoxedExpression left, BoxedExpression right)
{
return BoxedExpression.Binary(BinaryOperator.Ceq, left, right);
}
public BoxedExpression NotEqualTo(BoxedExpression left, BoxedExpression right)
{
return BoxedExpression.Binary(BinaryOperator.Cne_Un, left, right);
}
public BoxedExpression LessThan(BoxedExpression left, BoxedExpression right)
{
if (left.Equals(right))
return False;
else
return BoxedExpression.Binary(BinaryOperator.Clt, left, right);
}
public BoxedExpression LessEqualThan(BoxedExpression left, BoxedExpression right)
{
if (left.Equals(right))
return True;
else
return BoxedExpression.Binary(BinaryOperator.Cle, left, right);
}
public BoxedExpression And(BoxedExpression left, BoxedExpression right)
{
if (left == this.IdentityForAnd)
return right;
if (right == this.IdentityForAnd)
return left;
else
return BoxedExpression.Binary(BinaryOperator.LogicalAnd, left, right);
}
public BoxedExpression Or(BoxedExpression left, BoxedExpression right)
{
if (left == this.IdentityForOr)
return right;
if (right == this.IdentityForOr)
return left;
else
return BoxedExpression.Binary(BinaryOperator.LogicalOr, left, right);
}
public BoxedExpression IdentityForMul
{
get
{
return this.One;
}
}
public BoxedExpression Null
{
get { return BoxedExpression.Const(null, this.medataDecoder.System_Object, this.medataDecoder); }
}
public BoxedExpression IdentityForAnd
{
get { return this.True; }
}
public BoxedExpression IdentityForOr
{
get { return this.False; }
}
public BoxedExpression IdentityForAdd
{
get { return null; }
}
public BoxedExpression ForAll(BoxedExpression inf, BoxedExpression sup, BoxedExpression body)
{
return new ForAllIndexedExpression(null, this.boundVariable, inf, sup, body);
}
public BoxedExpression Exists(BoxedExpression inf, BoxedExpression sup, BoxedExpression body)
{
return new ExistsIndexedExpression(null, this.boundVariable, inf, sup, body);
}
public bool TryGetName(out BoxedExpression name)
{
name = this.name;
return name != null;
}
public bool TryGetBoundVariable(out BoxedExpression boundVar)
{
boundVar = this.boundVariable;
return boundVar != null;
}
public BoxedExpression ArrayIndex(BoxedExpression array, BoxedExpression index)
{
return new BoxedExpression.ArrayIndexExpression<Type>(array, index, this.medataDecoder.System_Object);
}
public bool TryArrayLengthName(BoxedExpression array, out BoxedExpression name)
{
Var v;
if (ArrayLength != null && array.TryGetFrameworkVariable(out v))
{
name = ArrayLength(v);
}
else
{
name = null;
}
return name != null;
}
public List<BoxedExpression> SplitAnd(BoxedExpression t)
{
var result = new List<BoxedExpression>();
Recurse(t, result);
return result;
}
private void Recurse(BoxedExpression be, List<BoxedExpression> result)
{
BinaryOperator bop;
BoxedExpression left, right;
if (be.IsBinaryExpression(out bop, out left, out right) && bop == BinaryOperator.LogicalAnd)
{
Recurse(left, result);
Recurse(right, result);
}
else
{
result.Add(be);
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace App.Web.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and mediaType
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ActionDescriptor.ReturnType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using Lucene.Net.Support;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
namespace Lucene.Net.Index
{
/*
* 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 BytesRef = Lucene.Net.Util.BytesRef;
using IndexInput = Lucene.Net.Store.IndexInput;
using RAMFile = Lucene.Net.Store.RAMFile;
using RAMInputStream = Lucene.Net.Store.RAMInputStream;
using RAMOutputStream = Lucene.Net.Store.RAMOutputStream;
/// <summary>
/// Prefix codes term instances (prefixes are shared)
/// <para/>
/// @lucene.experimental
/// </summary>
internal class PrefixCodedTerms : IEnumerable<Term>
{
internal readonly RAMFile buffer;
private PrefixCodedTerms(RAMFile buffer)
{
this.buffer = buffer;
}
/// <returns> size in bytes </returns>
public virtual long GetSizeInBytes()
{
return buffer.GetSizeInBytes();
}
/// <returns> iterator over the bytes </returns>
public virtual IEnumerator<Term> GetEnumerator()
{
return new PrefixCodedTermsIterator(buffer);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
internal class PrefixCodedTermsIterator : IEnumerator<Term>
{
private readonly IndexInput input;
private string field = "";
private BytesRef bytes = new BytesRef();
private Term term;
internal PrefixCodedTermsIterator(RAMFile buffer)
{
term = new Term(field, bytes);
try
{
input = new RAMInputStream("PrefixCodedTermsIterator", buffer);
}
catch (System.IO.IOException e)
{
throw new Exception(e.ToString(), e);
}
}
public virtual Term Current
{
get { return term; }
}
public virtual void Dispose()
{
}
object IEnumerator.Current
{
get { return Current; }
}
public virtual bool MoveNext()
{
if (input.GetFilePointer() < input.Length)
{
try
{
int code = input.ReadVInt32();
if ((code & 1) != 0)
{
field = input.ReadString();
}
int prefix = Number.URShift(code, 1);
int suffix = input.ReadVInt32();
bytes.Grow(prefix + suffix);
input.ReadBytes(bytes.Bytes, prefix, suffix);
bytes.Length = prefix + suffix;
term.Set(field, bytes);
}
catch (IOException e)
{
throw new Exception(e.ToString(), e);
}
return true;
}
return false;
}
public virtual void Reset()
{
throw new NotSupportedException();
}
}
/// <summary>
/// Builds a <see cref="PrefixCodedTerms"/>: call add repeatedly, then finish. </summary>
public class Builder
{
public Builder()
{
InitializeInstanceFields();
}
internal virtual void InitializeInstanceFields()
{
output = new RAMOutputStream(buffer);
}
private RAMFile buffer = new RAMFile();
private RAMOutputStream output;
private Term lastTerm = new Term("");
/// <summary>
/// add a term </summary>
public virtual void Add(Term term)
{
Debug.Assert(lastTerm.Equals(new Term("")) || term.CompareTo(lastTerm) > 0);
try
{
int prefix = SharedPrefix(lastTerm.Bytes, term.Bytes);
int suffix = term.Bytes.Length - prefix;
if (term.Field.Equals(lastTerm.Field, StringComparison.Ordinal))
{
output.WriteVInt32(prefix << 1);
}
else
{
output.WriteVInt32(prefix << 1 | 1);
output.WriteString(term.Field);
}
output.WriteVInt32(suffix);
output.WriteBytes(term.Bytes.Bytes, term.Bytes.Offset + prefix, suffix);
lastTerm.Bytes.CopyBytes(term.Bytes);
lastTerm.Field = term.Field;
}
catch (IOException e)
{
throw new Exception(e.ToString(), e);
}
}
/// <returns>
/// finalized form </returns>
public virtual PrefixCodedTerms Finish()
{
try
{
output.Dispose();
return new PrefixCodedTerms(buffer);
}
catch (IOException e)
{
throw new Exception(e.ToString(), e);
}
}
private int SharedPrefix(BytesRef term1, BytesRef term2)
{
int pos1 = 0;
int pos1End = pos1 + Math.Min(term1.Length, term2.Length);
int pos2 = 0;
while (pos1 < pos1End)
{
if (term1.Bytes[term1.Offset + pos1] != term2.Bytes[term2.Offset + pos2])
{
return pos1;
}
pos1++;
pos2++;
}
return pos1;
}
}
}
}
| |
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using Moq;
using NFluent;
using WireMock.Admin.Mappings;
using WireMock.Handlers;
using WireMock.Matchers.Request;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using WireMock.Server;
using WireMock.Settings;
using WireMock.Util;
using Xunit;
namespace WireMock.Net.Tests
{
public class WireMockServerProxyTests
{
[Fact(Skip = "Fails in Linux CI")]
public async Task WireMockServer_ProxySSL_Should_log_proxied_requests()
{
// Assign
var settings = new WireMockServerSettings
{
UseSSL = true,
ProxyAndRecordSettings = new ProxyAndRecordSettings
{
Url = "https://www.google.com",
SaveMapping = true,
SaveMappingToFile = false
}
};
var server = WireMockServer.Start(settings);
// Act
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri(server.Urls[0])
};
var httpClientHandler = new HttpClientHandler { AllowAutoRedirect = false };
await new HttpClient(httpClientHandler).SendAsync(requestMessage).ConfigureAwait(false);
// Assert
Check.That(server.Mappings).HasSize(2);
Check.That(server.LogEntries).HasSize(1);
}
[Fact]
public async Task WireMockServer_Proxy_With_SaveMapping_Is_True_And_SaveMappingToFile_Is_False_Should_AddInternalMappingOnly()
{
// Assign
var settings = new WireMockServerSettings
{
ProxyAndRecordSettings = new ProxyAndRecordSettings
{
Url = "http://www.google.com",
SaveMapping = true,
SaveMappingToFile = false
}
};
var server = WireMockServer.Start(settings);
// Act
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri(server.Urls[0])
};
var httpClientHandler = new HttpClientHandler { AllowAutoRedirect = false };
await new HttpClient(httpClientHandler).SendAsync(requestMessage).ConfigureAwait(false);
// Assert
server.Mappings.Should().HaveCount(2);
}
[Fact]
public async Task WireMockServer_Proxy_With_SaveMapping_Is_False_And_SaveMappingToFile_Is_True_ShouldSaveMappingToFile()
{
// Assign
var fileSystemHandlerMock = new Mock<IFileSystemHandler>();
fileSystemHandlerMock.Setup(f => f.GetMappingFolder()).Returns("m");
var settings = new WireMockServerSettings
{
ProxyAndRecordSettings = new ProxyAndRecordSettings
{
Url = "http://www.google.com",
SaveMapping = false,
SaveMappingToFile = true
},
FileSystemHandler = fileSystemHandlerMock.Object
};
var server = WireMockServer.Start(settings);
// Act
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri(server.Urls[0])
};
var httpClientHandler = new HttpClientHandler { AllowAutoRedirect = false };
await new HttpClient(httpClientHandler).SendAsync(requestMessage).ConfigureAwait(false);
// Assert
server.Mappings.Should().HaveCount(1);
// Verify
fileSystemHandlerMock.Verify(f => f.WriteMappingFile(It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Fact]
public async Task WireMockServer_Proxy_With_SaveMappingForStatusCodePattern_Is_False_Should_Not_SaveMapping()
{
// Assign
var fileSystemHandlerMock = new Mock<IFileSystemHandler>();
fileSystemHandlerMock.Setup(f => f.GetMappingFolder()).Returns("m");
var settings = new WireMockServerSettings
{
ProxyAndRecordSettings = new ProxyAndRecordSettings
{
Url = "http://www.google.com",
SaveMapping = true,
SaveMappingToFile = true,
SaveMappingForStatusCodePattern = "999" // Just make sure that we don't want this mapping
},
FileSystemHandler = fileSystemHandlerMock.Object
};
var server = WireMockServer.Start(settings);
// Act
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri(server.Urls[0])
};
var httpClientHandler = new HttpClientHandler { AllowAutoRedirect = false };
await new HttpClient(httpClientHandler).SendAsync(requestMessage).ConfigureAwait(false);
// Assert
server.Mappings.Should().HaveCount(1);
// Verify
fileSystemHandlerMock.Verify(f => f.WriteMappingFile(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Fact]
public async Task WireMockServer_Proxy_Should_log_proxied_requests()
{
// Assign
var settings = new WireMockServerSettings
{
ProxyAndRecordSettings = new ProxyAndRecordSettings
{
Url = "http://www.google.com",
SaveMapping = true,
SaveMappingToFile = false
}
};
var server = WireMockServer.Start(settings);
// Act
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri(server.Urls[0])
};
var httpClientHandler = new HttpClientHandler { AllowAutoRedirect = false };
await new HttpClient(httpClientHandler).SendAsync(requestMessage).ConfigureAwait(false);
// Assert
server.Mappings.Should().HaveCount(2);
server.LogEntries.Should().HaveCount(1);
}
[Fact]
public async Task WireMockServer_Proxy_Should_proxy_responses()
{
// Assign
string path = $"/prx_{Guid.NewGuid()}";
var server = WireMockServer.Start();
server
.Given(Request.Create().WithPath(path))
.RespondWith(Response.Create().WithProxy("http://www.google.com"));
// Act
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri($"{server.Urls[0]}{path}")
};
var httpClientHandler = new HttpClientHandler { AllowAutoRedirect = false };
var response = await new HttpClient(httpClientHandler).SendAsync(requestMessage).ConfigureAwait(false);
string content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
// Assert
Check.That(server.Mappings).HasSize(1);
Check.That(server.LogEntries).HasSize(1);
Check.That(content).Contains("google");
server.Stop();
}
[Fact]
public async Task WireMockServer_Proxy_Should_preserve_content_header_in_proxied_request()
{
// Assign
string path = $"/prx_{Guid.NewGuid()}";
var serverForProxyForwarding = WireMockServer.Start();
serverForProxyForwarding
.Given(Request.Create().WithPath(path))
.RespondWith(Response.Create());
var settings = new WireMockServerSettings
{
ProxyAndRecordSettings = new ProxyAndRecordSettings
{
Url = serverForProxyForwarding.Urls[0],
SaveMapping = true,
SaveMappingToFile = false
}
};
var server = WireMockServer.Start(settings);
// Act
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri($"{server.Urls[0]}{path}"),
Content = new StringContent("stringContent", Encoding.ASCII)
};
requestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
requestMessage.Content.Headers.Add("bbb", "test");
await new HttpClient().SendAsync(requestMessage).ConfigureAwait(false);
// Assert
var receivedRequest = serverForProxyForwarding.LogEntries.First().RequestMessage;
Check.That(receivedRequest.BodyData.BodyAsString).IsEqualTo("stringContent");
Check.That(receivedRequest.Headers).ContainsKey("Content-Type");
Check.That(receivedRequest.Headers["Content-Type"].First()).Contains("text/plain");
Check.That(receivedRequest.Headers).ContainsKey("bbb");
// check that new proxied mapping is added
Check.That(server.Mappings).HasSize(2);
}
[Fact]
public async Task WireMockServer_Proxy_Should_preserve_Authorization_header_in_proxied_request()
{
// Assign
string path = $"/prx_{Guid.NewGuid()}";
var serverForProxyForwarding = WireMockServer.Start();
serverForProxyForwarding
.Given(Request.Create().WithPath(path))
.RespondWith(Response.Create().WithCallback(x => new ResponseMessage
{
BodyData = new BodyData
{
BodyAsString = x.Headers["Authorization"].ToString(),
DetectedBodyType = Types.BodyType.String
}
}));
var settings = new WireMockServerSettings
{
ProxyAndRecordSettings = new ProxyAndRecordSettings
{
Url = serverForProxyForwarding.Urls[0],
SaveMapping = true,
SaveMappingToFile = false
}
};
var server = WireMockServer.Start(settings);
// Act
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri($"{server.Urls[0]}{path}"),
Content = new StringContent("stringContent", Encoding.ASCII)
};
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("BASIC", "test-A");
var result = await new HttpClient().SendAsync(requestMessage).ConfigureAwait(false);
// Assert
(await result.Content.ReadAsStringAsync().ConfigureAwait(false)).Should().Be("BASIC test-A");
var receivedRequest = serverForProxyForwarding.LogEntries.First().RequestMessage;
var authorizationHeader = receivedRequest.Headers["Authorization"].ToString().Should().Be("BASIC test-A");
server.Mappings.Should().HaveCount(2);
var authorizationRequestMessageHeaderMatcher = ((Request)server.Mappings.Single(m => !m.IsAdminInterface).RequestMatcher)
.GetRequestMessageMatcher<RequestMessageHeaderMatcher>(x => x.Matchers.Any(m => m.GetPatterns().Contains("BASIC test-A")));
authorizationRequestMessageHeaderMatcher.Should().NotBeNull();
}
[Fact]
public async Task WireMockServer_Proxy_Should_exclude_ExcludedHeaders_in_mapping()
{
// Assign
string path = $"/prx_{Guid.NewGuid()}";
var serverForProxyForwarding = WireMockServer.Start();
serverForProxyForwarding
.Given(Request.Create().WithPath(path))
.RespondWith(Response.Create());
var settings = new WireMockServerSettings
{
ProxyAndRecordSettings = new ProxyAndRecordSettings
{
Url = serverForProxyForwarding.Urls[0],
SaveMapping = true,
SaveMappingToFile = false,
ExcludedHeaders = new[] { "excluded-header-X" }
}
};
var server = WireMockServer.Start(settings);
var defaultMapping = server.Mappings.First();
// Act
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri($"{server.Urls[0]}{path}"),
Content = new StringContent("stringContent")
};
requestMessage.Headers.Add("foobar", "exact_match");
requestMessage.Headers.Add("ok", "ok-value");
await new HttpClient().SendAsync(requestMessage).ConfigureAwait(false);
// Assert
var mapping = server.Mappings.FirstOrDefault(m => m.Guid != defaultMapping.Guid);
Check.That(mapping).IsNotNull();
var matchers = ((Request)mapping.RequestMatcher).GetRequestMessageMatchers<RequestMessageHeaderMatcher>().Select(m => m.Name).ToList();
Check.That(matchers).Not.Contains("excluded-header-X");
Check.That(matchers).Contains("ok");
}
[Fact]
public async Task WireMockServer_Proxy_Should_exclude_ExcludedCookies_in_mapping()
{
// Assign
string path = $"/prx_{Guid.NewGuid()}";
var serverForProxyForwarding = WireMockServer.Start();
serverForProxyForwarding
.Given(Request.Create().WithPath(path))
.RespondWith(Response.Create());
var settings = new WireMockServerSettings
{
ProxyAndRecordSettings = new ProxyAndRecordSettings
{
Url = serverForProxyForwarding.Urls[0],
SaveMapping = true,
SaveMappingToFile = false,
ExcludedCookies = new[] { "ASP.NET_SessionId" }
}
};
var server = WireMockServer.Start(settings);
var defaultMapping = server.Mappings.First();
// Act
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri($"{server.Urls[0]}{path}"),
Content = new StringContent("stringContent")
};
var cookieContainer = new CookieContainer(3);
cookieContainer.Add(new Uri("http://localhost"), new Cookie("ASP.NET_SessionId", "exact_match"));
cookieContainer.Add(new Uri("http://localhost"), new Cookie("AsP.NeT_SessIonID", "case_mismatch"));
cookieContainer.Add(new Uri("http://localhost"), new Cookie("GoodCookie", "I_should_pass"));
var handler = new HttpClientHandler { CookieContainer = cookieContainer };
await new HttpClient(handler).SendAsync(requestMessage).ConfigureAwait(false);
// Assert
var mapping = server.Mappings.FirstOrDefault(m => m.Guid != defaultMapping.Guid);
Check.That(mapping).IsNotNull();
var matchers = ((Request)mapping.RequestMatcher).GetRequestMessageMatchers<RequestMessageCookieMatcher>().Select(m => m.Name).ToList();
Check.That(matchers).Not.Contains("ASP.NET_SessionId");
Check.That(matchers).Not.Contains("AsP.NeT_SessIonID");
Check.That(matchers).Contains("GoodCookie");
}
[Fact]
public async Task WireMockServer_Proxy_Should_preserve_content_header_in_proxied_request_with_empty_content()
{
// Assign
string path = $"/prx_{Guid.NewGuid()}";
var serverForProxyForwarding = WireMockServer.Start();
serverForProxyForwarding
.Given(Request.Create().WithPath(path))
.RespondWith(Response.Create());
var server = WireMockServer.Start();
server
.Given(Request.Create().WithPath("/*"))
.RespondWith(Response.Create().WithProxy(serverForProxyForwarding.Urls[0]));
// Act
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri($"{server.Urls[0]}{path}"),
Content = new StringContent("")
};
requestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
await new HttpClient().SendAsync(requestMessage).ConfigureAwait(false);
// Assert
var receivedRequest = serverForProxyForwarding.LogEntries.First().RequestMessage;
Check.That(receivedRequest.BodyData.BodyAsString).IsEqualTo("");
Check.That(receivedRequest.Headers).ContainsKey("Content-Type");
Check.That(receivedRequest.Headers["Content-Type"].First()).Contains("text/plain");
}
[Fact]
public async Task WireMockServer_Proxy_Should_preserve_content_header_in_proxied_response()
{
// Assign
string path = $"/prx_{Guid.NewGuid()}";
var serverForProxyForwarding = WireMockServer.Start();
serverForProxyForwarding
.Given(Request.Create().WithPath(path))
.RespondWith(Response.Create()
.WithBody("body")
.WithHeader("Content-Type", "text/plain"));
var server = WireMockServer.Start();
server
.Given(Request.Create().WithPath(path))
.RespondWith(Response.Create().WithProxy(serverForProxyForwarding.Urls[0]));
// Act
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri($"{server.Urls[0]}{path}")
};
var response = await new HttpClient().SendAsync(requestMessage).ConfigureAwait(false);
// Assert
Check.That(await response.Content.ReadAsStringAsync().ConfigureAwait(false)).IsEqualTo("body");
Check.That(response.Content.Headers.Contains("Content-Type")).IsTrue();
Check.That(response.Content.Headers.GetValues("Content-Type")).ContainsExactly("text/plain");
}
[Fact]
public async Task WireMockServer_Proxy_Should_change_absolute_location_header_in_proxied_response()
{
// Assign
string path = $"/prx_{Guid.NewGuid()}";
var settings = new WireMockServerSettings { AllowPartialMapping = false };
var serverForProxyForwarding = WireMockServer.Start(settings);
serverForProxyForwarding
.Given(Request.Create().WithPath(path))
.RespondWith(Response.Create()
.WithStatusCode(HttpStatusCode.Redirect)
.WithHeader("Location", "/testpath"));
var server = WireMockServer.Start(settings);
server
.Given(Request.Create().WithPath(path).UsingAnyMethod())
.RespondWith(Response.Create().WithProxy(serverForProxyForwarding.Urls[0]));
// Act
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri($"{server.Urls[0]}{path}")
};
var httpClientHandler = new HttpClientHandler { AllowAutoRedirect = false };
var response = await new HttpClient(httpClientHandler).SendAsync(requestMessage).ConfigureAwait(false);
// Assert
Check.That(response.Headers.Contains("Location")).IsTrue();
Check.That(response.Headers.GetValues("Location")).ContainsExactly("/testpath");
}
[Fact]
public async Task WireMockServer_Proxy_Should_preserve_cookie_header_in_proxied_request()
{
// Assign
string path = $"/prx_{Guid.NewGuid()}";
var serverForProxyForwarding = WireMockServer.Start();
serverForProxyForwarding
.Given(Request.Create().WithPath(path))
.RespondWith(Response.Create());
var server = WireMockServer.Start();
server
.Given(Request.Create().WithPath(path))
.RespondWith(Response.Create().WithProxy(serverForProxyForwarding.Urls[0]));
// Act
var requestUri = new Uri($"{server.Urls[0]}{path}");
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = requestUri
};
var clientHandler = new HttpClientHandler();
clientHandler.CookieContainer.Add(requestUri, new Cookie("name", "value"));
await new HttpClient(clientHandler).SendAsync(requestMessage).ConfigureAwait(false);
// then
var receivedRequest = serverForProxyForwarding.LogEntries.First().RequestMessage;
Check.That(receivedRequest.Cookies).IsNotNull();
Check.That(receivedRequest.Cookies).ContainsPair("name", "value");
}
/// <summary>
/// Send some binary content in a request through the proxy and check that the same content
/// arrived at the target. As example a JPEG/JIFF header is used, which is not representable
/// in UTF8 and breaks if it is not treated as binary content.
/// </summary>
[Fact]
public async Task WireMockServer_Proxy_Should_preserve_binary_request_content()
{
// arrange
var jpegHeader = new byte[] { 0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00 };
var brokenJpegHeader = new byte[]
{0xEF, 0xBF, 0xBD, 0xEF, 0xBF, 0xBD, 0xEF, 0xBF, 0xBD, 0xEF, 0xBF, 0xBD, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00};
bool HasCorrectHeader(byte[] bytes) => bytes.SequenceEqual(jpegHeader);
bool HasBrokenHeader(byte[] bytes) => bytes.SequenceEqual(brokenJpegHeader);
var serverForProxyForwarding = WireMockServer.Start();
serverForProxyForwarding
.Given(Request.Create().WithBody(HasCorrectHeader))
.RespondWith(Response.Create().WithSuccess());
serverForProxyForwarding
.Given(Request.Create().WithBody(HasBrokenHeader))
.RespondWith(Response.Create().WithStatusCode(HttpStatusCode.InternalServerError));
var server = WireMockServer.Start();
server
.Given(Request.Create())
.RespondWith(Response.Create().WithProxy(serverForProxyForwarding.Urls[0]));
// act
var response = await new HttpClient().PostAsync(server.Urls[0], new ByteArrayContent(jpegHeader)).ConfigureAwait(false);
// assert
Check.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
}
[Fact]
public async Task WireMockServer_Proxy_Should_set_BodyAsJson_in_proxied_response()
{
// Assign
string path = $"/prx_{Guid.NewGuid()}";
var serverForProxyForwarding = WireMockServer.Start();
serverForProxyForwarding
.Given(Request.Create().WithPath(path))
.RespondWith(Response.Create()
.WithBodyAsJson(new { i = 42 })
.WithHeader("Content-Type", "application/json; charset=utf-8"));
var server = WireMockServer.Start();
server
.Given(Request.Create().WithPath(path))
.RespondWith(Response.Create().WithProxy(serverForProxyForwarding.Urls[0]));
// Act
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri($"{server.Urls[0]}{path}")
};
var response = await new HttpClient().SendAsync(requestMessage).ConfigureAwait(false);
// Assert
string content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
Check.That(content).IsEqualTo("{\"i\":42}");
Check.That(response.Content.Headers.GetValues("Content-Type")).ContainsExactly("application/json; charset=utf-8");
}
[Fact]
public async Task WireMockServer_Proxy_Should_set_Body_in_multipart_proxied_response()
{
// Assign
string path = $"/prx_{Guid.NewGuid()}";
var serverForProxyForwarding = WireMockServer.Start();
serverForProxyForwarding
.Given(Request.Create().WithPath(path))
.RespondWith(Response.Create()
.WithBodyAsJson(new { i = 42 })
);
var server = WireMockServer.Start();
server
.Given(Request.Create().WithPath(path))
.RespondWith(Response.Create().WithProxy(serverForProxyForwarding.Urls[0]));
// Act
var uri = new Uri($"{server.Urls[0]}{path}");
var form = new MultipartFormDataContent
{
{ new StringContent("data"), "test", "test.txt" }
};
var response = await new HttpClient().PostAsync(uri, form).ConfigureAwait(false);
// Assert
string content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
Check.That(content).IsEqualTo("{\"i\":42}");
}
[Fact]
public async Task WireMockServer_Proxy_Should_Not_overrule_AdminMappings()
{
// Assign
string path = $"/prx_{Guid.NewGuid()}";
var serverForProxyForwarding = WireMockServer.Start();
serverForProxyForwarding
.Given(Request.Create().WithPath(path))
.RespondWith(Response.Create().WithBody("ok"));
var server = WireMockServer.Start(new WireMockServerSettings
{
StartAdminInterface = true,
ReadStaticMappings = false,
ProxyAndRecordSettings = new ProxyAndRecordSettings
{
Url = serverForProxyForwarding.Urls[0],
SaveMapping = false,
SaveMappingToFile = false
}
});
// Act 1
var requestMessage1 = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri($"{server.Urls[0]}{path}")
};
var response1 = await new HttpClient().SendAsync(requestMessage1).ConfigureAwait(false);
// Assert 1
string content1 = await response1.Content.ReadAsStringAsync().ConfigureAwait(false);
Check.That(content1).IsEqualTo("ok");
// Act 2
var requestMessage2 = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri($"{server.Urls[0]}/__admin/mappings")
};
var response2 = await new HttpClient().SendAsync(requestMessage2).ConfigureAwait(false);
// Assert 2
string content2 = await response2.Content.ReadAsStringAsync().ConfigureAwait(false);
Check.That(content2).IsEqualTo("[]");
}
// On Ubuntu latest it's : "Resource temporarily unavailable"
// On Windows-2019 it's : "No such host is known."
[Fact]
public async Task WireMockServer_Proxy_WhenTargetIsNotAvailable_Should_Return_CorrectResponse()
{
// Assign
var settings = new WireMockServerSettings
{
ProxyAndRecordSettings = new ProxyAndRecordSettings
{
Url = $"http://error{Guid.NewGuid()}:12345"
}
};
var server = WireMockServer.Start(settings);
// Act
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri(server.Urls[0])
};
var httpClientHandler = new HttpClientHandler { AllowAutoRedirect = false };
var result = await new HttpClient(httpClientHandler).SendAsync(requestMessage).ConfigureAwait(false);
// Assert
result.StatusCode.Should().Be(HttpStatusCode.InternalServerError);
var content = await result.Content.ReadAsStringAsync().ConfigureAwait(false);
content.Should().NotBeEmpty();
server.LogEntries.Should().HaveCount(1);
var status = ((StatusModel)server.LogEntries.First().ResponseMessage.BodyData.BodyAsJson).Status;
server.Stop();
}
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.NetworkAnalyst;
using ESRI.ArcGIS.Geodatabase;
// This is the main form of the application.
namespace NAEngine
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class frmMain : System.Windows.Forms.Form
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private System.Windows.Forms.Splitter splitter1;
// Context menu objects for NAWindow's context menu
private System.Windows.Forms.ContextMenu contextMenu1;
private System.Windows.Forms.MenuItem miLoadLocations;
private System.Windows.Forms.MenuItem miClearLocations;
private System.Windows.Forms.MenuItem miAddItem;
// ArcGIS Controls on the form
private ESRI.ArcGIS.Controls.AxMapControl axMapControl1;
private ESRI.ArcGIS.Controls.AxLicenseControl axLicenseControl1;
private ESRI.ArcGIS.Controls.AxToolbarControl axToolbarControl1;
private ESRI.ArcGIS.Controls.AxTOCControl axTOCControl1;
// Listen for context menu on NAWindow
private IEngineNAWindowEventsEx_OnContextMenuEventHandler m_onContextMenu;
private IEngineNetworkAnalystEnvironmentEvents_OnNetworkLayersChangedEventHandler m_OnNetworkLayersChanged;
private IEngineNetworkAnalystEnvironmentEvents_OnCurrentNetworkLayerChangedEventHandler m_OnCurrentNetworkLayerChanged;
// Reference to ArcGIS Network Analyst extension Environment
private IEngineNetworkAnalystEnvironment m_naEnv;
// Reference to NAWindow. Need to hold on to reference for events to work.
private IEngineNAWindow m_naWindow;
// Menu for our commands on the TOC context menu
private IToolbarMenu m_menuLayer;
// incrementor for auto generated names
private static int autogenInt = 0;
public frmMain()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
ESRI.ArcGIS.ADF.COMSupport.AOUninitialize.Shutdown();
if (disposing)
{
if (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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmMain));
this.axMapControl1 = new ESRI.ArcGIS.Controls.AxMapControl();
this.axLicenseControl1 = new ESRI.ArcGIS.Controls.AxLicenseControl();
this.axToolbarControl1 = new ESRI.ArcGIS.Controls.AxToolbarControl();
this.splitter1 = new System.Windows.Forms.Splitter();
this.axTOCControl1 = new ESRI.ArcGIS.Controls.AxTOCControl();
this.contextMenu1 = new System.Windows.Forms.ContextMenu();
this.miLoadLocations = new System.Windows.Forms.MenuItem();
this.miClearLocations = new System.Windows.Forms.MenuItem();
this.miAddItem = new System.Windows.Forms.MenuItem();
((System.ComponentModel.ISupportInitialize)(this.axMapControl1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.axLicenseControl1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.axToolbarControl1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.axTOCControl1)).BeginInit();
this.SuspendLayout();
//
// axMapControl1
//
this.axMapControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.axMapControl1.Location = new System.Drawing.Point(227, 28);
this.axMapControl1.Name = "axMapControl1";
this.axMapControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axMapControl1.OcxState")));
this.axMapControl1.Size = new System.Drawing.Size(645, 472);
this.axMapControl1.TabIndex = 2;
//
// axLicenseControl1
//
this.axLicenseControl1.Enabled = true;
this.axLicenseControl1.Location = new System.Drawing.Point(664, 0);
this.axLicenseControl1.Name = "axLicenseControl1";
this.axLicenseControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axLicenseControl1.OcxState")));
this.axLicenseControl1.Size = new System.Drawing.Size(32, 32);
this.axLicenseControl1.TabIndex = 1;
//
// axToolbarControl1
//
this.axToolbarControl1.Dock = System.Windows.Forms.DockStyle.Top;
this.axToolbarControl1.Location = new System.Drawing.Point(0, 0);
this.axToolbarControl1.Name = "axToolbarControl1";
this.axToolbarControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axToolbarControl1.OcxState")));
this.axToolbarControl1.Size = new System.Drawing.Size(872, 28);
this.axToolbarControl1.TabIndex = 0;
//
// splitter1
//
this.splitter1.Location = new System.Drawing.Point(224, 28);
this.splitter1.Name = "splitter1";
this.splitter1.Size = new System.Drawing.Size(3, 472);
this.splitter1.TabIndex = 4;
this.splitter1.TabStop = false;
//
// axTOCControl1
//
this.axTOCControl1.Dock = System.Windows.Forms.DockStyle.Left;
this.axTOCControl1.Location = new System.Drawing.Point(0, 28);
this.axTOCControl1.Name = "axTOCControl1";
this.axTOCControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axTOCControl1.OcxState")));
this.axTOCControl1.Size = new System.Drawing.Size(224, 472);
this.axTOCControl1.TabIndex = 1;
this.axTOCControl1.OnMouseDown += new ESRI.ArcGIS.Controls.ITOCControlEvents_Ax_OnMouseDownEventHandler(this.axTOCControl1_OnMouseDown);
//
// contextMenu1
//
this.contextMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.miLoadLocations,
this.miClearLocations});
//
// miLoadLocations
//
this.miLoadLocations.Index = 0;
this.miLoadLocations.Text = "Load Locations...";
this.miLoadLocations.Click += new System.EventHandler(this.miLoadLocations_Click);
//
// miClearLocations
//
this.miClearLocations.Index = 1;
this.miClearLocations.Text = "Clear Locations";
this.miClearLocations.Click += new System.EventHandler(this.miClearLocations_Click);
//
// miAddItem
//
this.miAddItem.Index = -1;
this.miAddItem.Text = "Add Item";
this.miAddItem.Click += new System.EventHandler(this.miAddItem_Click);
//
// frmMain
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(872, 500);
this.Controls.Add(this.axLicenseControl1);
this.Controls.Add(this.axMapControl1);
this.Controls.Add(this.splitter1);
this.Controls.Add(this.axTOCControl1);
this.Controls.Add(this.axToolbarControl1);
this.Name = "frmMain";
this.Text = "Network Analyst Engine Application";
this.Load += new System.EventHandler(this.frmMain_Load);
((System.ComponentModel.ISupportInitialize)(this.axMapControl1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.axLicenseControl1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.axToolbarControl1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.axTOCControl1)).EndInit();
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
bool succeeded = ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.EngineOrDesktop);
if (succeeded)
{
ESRI.ArcGIS.RuntimeInfo activeRunTimeInfo = ESRI.ArcGIS.RuntimeManager.ActiveRuntime;
System.Diagnostics.Debug.Print(activeRunTimeInfo.Product.ToString());
Application.Run(new frmMain());
}
else
System.Windows.Forms.MessageBox.Show("Failed to bind to an active ArcGIS runtime");
}
private void frmMain_Load(object sender, System.EventArgs e)
{
// Add commands to the NALayer context menu
m_menuLayer = new ToolbarMenuClass();
int nItem = -1;
m_menuLayer.AddItem(new cmdLoadLocations(), -1, ++nItem, false, esriCommandStyles.esriCommandStyleTextOnly);
m_menuLayer.AddItem(new cmdRemoveLayer(), -1, ++nItem, false, esriCommandStyles.esriCommandStyleTextOnly);
m_menuLayer.AddItem(new cmdClearAnalysisLayer(), -1, ++nItem, true, esriCommandStyles.esriCommandStyleTextOnly);
m_menuLayer.AddItem(new cmdNALayerProperties(), -1, ++nItem, true, esriCommandStyles.esriCommandStyleTextOnly);
// Since this ToolbarMenu is a standalone popup menu use the SetHook method to
// specify the object that will be sent as a "hook" to the menu commands in their OnCreate methods.
m_menuLayer.SetHook(axMapControl1);
// Add command for ArcGIS Network Analyst extension env properties to end of "Network Analyst" dropdown menu
nItem = -1;
for (int i = 0; i < axToolbarControl1.Count; ++i)
{
IToolbarItem item = axToolbarControl1.GetItem(i);
IToolbarMenu mnu = item.Menu;
if (mnu == null) continue;
IMenuDef mnudef = mnu.GetMenuDef();
string name = mnudef.Name;
// Find the ArcGIS Network Analyst extension solver menu drop down and note the index
if (name == "ControlToolsNetworkAnalyst_SolverMenu")
{
nItem = i;
//break;
}
}
if (nItem >= 0)
{
// Using the index found above, get the solver menu drop down and add the Properties command to the end of it.
IToolbarItem item = axToolbarControl1.GetItem(nItem);
IToolbarMenu mnu = item.Menu;
if (mnu != null)
mnu.AddItem(new cmdNAProperties(), -1, mnu.Count, true, esriCommandStyles.esriCommandStyleTextOnly);
// Since this ToolbarMenu is an item on the ToolbarControl the Hook is shared and initialized by the ToolbarControl.
// Therefore, SetHook is not called here, like it is for the menu above.
}
// Initialize naEnv variables
m_naEnv = CommonFunctions.GetTheEngineNetworkAnalystEnvironment();
if (m_naEnv == null)
{
MessageBox.Show("Error: EngineNetworkAnalystEnvironment is not properly configured");
return;
}
m_naEnv.ZoomToResultAfterSolve = false;
m_naEnv.ShowAnalysisMessagesAfterSolve = (int)(esriEngineNAMessageType.esriEngineNAMessageTypeInformative |
esriEngineNAMessageType.esriEngineNAMessageTypeWarning);
// Set up the buddy control and initialize the NA extension, so we can get to NAWindow to listen to window events.
// This is necessary, as the various controls are not yet set up. They need to be in order to get the NAWindow's events.
axToolbarControl1.SetBuddyControl(axMapControl1);
IExtension ext = m_naEnv as IExtension;
object obj = axToolbarControl1.Object;
ext.Startup(ref obj);
// m_naWindow is set after Startup of the Network Analyst extension
m_naWindow = m_naEnv.NAWindow;
if (m_naWindow == null)
{
MessageBox.Show("Error: Unexpected null NAWindow");
return;
}
m_onContextMenu = new IEngineNAWindowEventsEx_OnContextMenuEventHandler(OnContextMenu);
((IEngineNAWindowEventsEx_Event)m_naWindow).OnContextMenu += m_onContextMenu;
m_OnNetworkLayersChanged = new IEngineNetworkAnalystEnvironmentEvents_OnNetworkLayersChangedEventHandler(OnNetworkLayersChanged);
((IEngineNetworkAnalystEnvironmentEvents_Event)m_naEnv).OnNetworkLayersChanged += m_OnNetworkLayersChanged;
m_OnCurrentNetworkLayerChanged = new IEngineNetworkAnalystEnvironmentEvents_OnCurrentNetworkLayerChangedEventHandler(OnCurrentNetworkLayerChanged);
((IEngineNetworkAnalystEnvironmentEvents_Event)m_naEnv).OnCurrentNetworkLayerChanged += m_OnCurrentNetworkLayerChanged;
}
// Show the TOC context menu when an NALayer is right-clicked on
private void axTOCControl1_OnMouseDown(object sender, ESRI.ArcGIS.Controls.ITOCControlEvents_OnMouseDownEvent e)
{
if (e.button != 2) return;
esriTOCControlItem item = esriTOCControlItem.esriTOCControlItemNone;
IBasicMap map = null;
ILayer layer = null;
object other = null;
object index = null;
//Determine what kind of item has been clicked on
axTOCControl1.HitTest(e.x, e.y, ref item, ref map, ref layer, ref other, ref index);
// Only implemented a context menu for NALayers. Exit if the layer is anything else.
if ((layer as INALayer) == null)
return;
axTOCControl1.SelectItem(layer);
// Set the layer into the CustomProperty.
// This is used by the other commands to know what layer was right-clicked on
// in the table of contents.
axMapControl1.CustomProperty = layer;
//Popup the correct context menu and update the TOC when it's done.
if (item == esriTOCControlItem.esriTOCControlItemLayer)
{
m_menuLayer.PopupMenu(e.x, e.y, axTOCControl1.hWnd);
ITOCControl toc = axTOCControl1.Object as ITOCControl;
toc.Update();
}
}
public void OnNetworkLayersChanged()
{
// The OnNetworkLayersChanged event is fired when a new INetworkLayer object is
// added, removed, or renamed within a map.
// If the INetworkLayer is renamed interactively through the user interface
// OnNetworkLayersChanged is fired. If the INetworkLayer is renamed programmatically
// using the ILayer::Name property OnNetworkLayersChanged is not fired.
}
public void OnCurrentNetworkLayerChanged()
{
// The OnCurrentNetworkLayerChanged event is fired when the user interactively
// changes the NetworkDataset or the IEngineNetworkAnalystEnvironment::CurrentNetworkLayer
// is set programatically.
}
//The OnContextMenu event is fired when a user right clicks within the
// IEngineNetworkAnalystEnvironment::NAWindow and can be used to supply a context menu.
public bool OnContextMenu(int x, int y)
{
System.Drawing.Point pt = this.PointToClient(System.Windows.Forms.Cursor.Position);
// Get the active category
var activeCategory = m_naWindow.ActiveCategory as IEngineNAWindowCategory2;
if (activeCategory == null)
return false;
MenuItem separator = new MenuItem("-");
miLoadLocations.Enabled = false;
miClearLocations.Enabled = false;
// in order for the AddItem choice to appear in the context menu, the class
// should be an input class, and it should not be editable
INAClassDefinition pNAClassDefinition = activeCategory.NAClass.ClassDefinition;
if (pNAClassDefinition.IsInput)
{
miLoadLocations.Enabled = true;
miClearLocations.Enabled = true;
// canEditShape should be false for AddItem to Apply (default is false)
// if it's a StandaloneTable canEditShape is implicitly false (there's no shape to edit)
bool canEditShape = false;
IFields pFields = pNAClassDefinition.Fields;
int nField = -1;
nField = pFields.FindField("Shape");
if (nField >= 0)
{
int naFieldType = 0;
naFieldType = pNAClassDefinition.get_FieldType("Shape");
// determining whether or not the shape field can be edited consists of running a bitwise comparison
// on the FieldType of the shape field. See the online help for a list of the possible field types.
// For our case, we want to verify that the shape field is an input field. If it is an input field,
// then we do NOT want to display the Add Item menu option.
canEditShape = ((naFieldType & (int)esriNAFieldType.esriNAFieldTypeInput) == (int)esriNAFieldType.esriNAFieldTypeInput) ? true : false;
}
if (!canEditShape)
{
contextMenu1.MenuItems.Add(separator);
contextMenu1.MenuItems.Add(miAddItem);
}
}
contextMenu1.Show(this, pt);
// even if the miAddItem menu item has not been added, Remove() won't crash.
contextMenu1.MenuItems.Remove(separator);
contextMenu1.MenuItems.Remove(miAddItem);
return true;
}
private void miLoadLocations_Click(object sender, System.EventArgs e)
{
var mapControl = axMapControl1.Object as IMapControl3;
// Show the Property Page form for ArcGIS Network Analyst extension
var loadLocations = new frmLoadLocations();
if (loadLocations.ShowModal(mapControl, m_naEnv))
{
// notify that the context has changed because we have added locations to a NAClass within it
var contextEdit = m_naEnv.NAWindow.ActiveAnalysis.Context as INAContextEdit;
contextEdit.ContextChanged();
// If loaded locations, refresh the NAWindow and the Screen
INALayer naLayer = m_naWindow.ActiveAnalysis;
mapControl.Refresh(esriViewDrawPhase.esriViewGeography, naLayer, mapControl.Extent);
m_naWindow.UpdateContent(m_naWindow.ActiveCategory);
}
}
private void miClearLocations_Click(object sender, System.EventArgs e)
{
var mapControl = axMapControl1.Object as IMapControl3;
var naHelper = m_naEnv as IEngineNetworkAnalystHelper;
IEngineNAWindow naWindow = m_naWindow;
INALayer naLayer = naWindow.ActiveAnalysis;
// we do not have to run ContextChanged() as with adding an item and loading locations,
// because that is done by the DeleteAllNetworkLocations method.
naHelper.DeleteAllNetworkLocations();
mapControl.Refresh(esriViewDrawPhase.esriViewGeography, naLayer, mapControl.Extent);
}
private void miAddItem_Click(object sender, System.EventArgs e)
{
// Developers Note:
// Once an item has been added, the user can double click on the item to edit the properties
// of the item. For the purposes of this sample, only the default values from the InitDefaultValues method
// and an auto generated Name value are populated initially for the new item.
var mapControl = axMapControl1.Object as IMapControl3;
var activeCategory = m_naWindow.ActiveCategory as IEngineNAWindowCategory2;
IDataLayer pDataLayer = activeCategory.DataLayer;
// In order to add an item, we need to create a new row in the class and populate it
// with the initial default values for that class.
var table = pDataLayer as ITable;
IRow row = table.CreateRow();
var rowSubtypes = row as IRowSubtypes;
rowSubtypes.InitDefaultValues();
// we need to auto generate a display name for the newly added item.
// In some cases (depending on how the schema is set up) InitDefaultValues may result in a nonempty name string
// in these cases do not override the preexisting non-empty name string with our auto generated one.
var ipFeatureLayer = activeCategory.Layer as IFeatureLayer;
var ipStandaloneTable = pDataLayer as IStandaloneTable;
string name = "";
if (ipFeatureLayer != null)
name = ipFeatureLayer.DisplayField;
else if (ipStandaloneTable != null)
name = ipStandaloneTable.DisplayField;
//If the display field is an empty string or does not represent an actual field on the NAClass just skip the auto generation.
// (Some custom solvers may not have set the DisplayField for example).
// Note: The name we are auto generating does not have any spaces in it. This is to ensure that any classes
// that are space sensitive will be able to handle the name (ex Specialties).
string currentName = "";
int fieldIndex = row.Fields.FindField(name);
if (fieldIndex >= 0)
{
currentName = row.get_Value(fieldIndex) as string;
if (currentName.Length <= 0)
row.set_Value(fieldIndex, "Item" + ++autogenInt);
}
// A special case is OrderPairs NAClass because that effectively has a combined 2 field display field.
// You will have to hard code to look for that NAClassName and create a default name for
// both first order and second order field names so the name will display correctly
// (look for the NAClass Name and NOT the layer name).
INAClassDefinition naClassDef = activeCategory.NAClass.ClassDefinition;
if (naClassDef.Name == "OrderPairs")
{
fieldIndex = row.Fields.FindField("SecondOrderName");
if (fieldIndex >= 0)
{
string secondName = row.get_Value(fieldIndex) as string;
if (secondName.Length <= 0)
row.set_Value(fieldIndex, "Item" + ++autogenInt);
}
}
row.Store();
// notify that the context has changed because we have added an item to a NAClass within it
var contextEdit = m_naEnv.NAWindow.ActiveAnalysis.Context as INAContextEdit;
contextEdit.ContextChanged();
// refresh the NAWindow and the Screen
INALayer naLayer = m_naWindow.ActiveAnalysis;
mapControl.Refresh(esriViewDrawPhase.esriViewGeography, naLayer, mapControl.Extent);
m_naWindow.UpdateContent(m_naWindow.ActiveCategory);
}
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
namespace NLog.Targets
{
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Security;
using Internal.Fakeables;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
using NLog.Layouts;
/// <summary>
/// Writes log message to the Event Log.
/// </summary>
/// <seealso href="https://github.com/nlog/nlog/wiki/EventLog-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/EventLog/NLog.config" />
/// <p>
/// This assumes just one target and a single rule. More configuration
/// options are described <a href="config.html">here</a>.
/// </p>
/// <p>
/// To set up the log target programmatically use code like this:
/// </p>
/// <code lang="C#" source="examples/targets/Configuration API/EventLog/Simple/Example.cs" />
/// </example>
[Target("EventLog")]
public class EventLogTarget : TargetWithLayout, IInstallable
{
private EventLog eventLogInstance;
/// <summary>
/// Initializes a new instance of the <see cref="EventLogTarget"/> class.
/// </summary>
public EventLogTarget()
: this(AppDomainWrapper.CurrentDomain)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="EventLogTarget"/> class.
/// </summary>
public EventLogTarget(IAppDomain appDomain)
{
this.Source = appDomain.FriendlyName;
this.Log = "Application";
this.MachineName = ".";
this.MaxMessageLength = 16384;
}
/// <summary>
/// Initializes a new instance of the <see cref="EventLogTarget"/> class.
/// </summary>
/// <param name="name">Name of the target.</param>
public EventLogTarget(string name) : this(AppDomainWrapper.CurrentDomain)
{
this.Name = name;
}
/// <summary>
/// Gets or sets the name of the machine on which Event Log service is running.
/// </summary>
/// <docgen category='Event Log Options' order='10' />
[DefaultValue(".")]
public string MachineName { get; set; }
/// <summary>
/// Gets or sets the layout that renders event ID.
/// </summary>
/// <docgen category='Event Log Options' order='10' />
public Layout EventId { get; set; }
/// <summary>
/// Gets or sets the layout that renders event Category.
/// </summary>
/// <docgen category='Event Log Options' order='10' />
public Layout Category { get; set; }
/// <summary>
/// Optional entrytype. When not set, or when not convertable to <see cref="LogLevel"/> then determined by <see cref="NLog.LogLevel"/>
/// </summary>
public Layout EntryType { get; set; }
/// <summary>
/// Gets or sets the value to be used as the event Source.
/// </summary>
/// <remarks>
/// By default this is the friendly name of the current AppDomain.
/// </remarks>
/// <docgen category='Event Log Options' order='10' />
public Layout Source { get; set; }
/// <summary>
/// Gets or sets the name of the Event Log to write to. This can be System, Application or
/// any user-defined name.
/// </summary>
/// <docgen category='Event Log Options' order='10' />
[DefaultValue("Application")]
public string Log { get; set; }
private int maxMessageLength;
/// <summary>
/// Gets or sets the message length limit to write to the Event Log.
/// </summary>
/// <remarks><value>MaxMessageLength</value> cannot be zero or negative</remarks>
[DefaultValue(16384)]
public int MaxMessageLength
{
get { return this.maxMessageLength; }
set
{
if (value <= 0)
throw new ArgumentException("MaxMessageLength cannot be zero or negative.");
this.maxMessageLength = value;
}
}
/// <summary>
/// Gets or sets the action to take if the message is larger than the <see cref="MaxMessageLength"/> option.
/// </summary>
/// <docgen category='Event Log Overflow Action' order='10' />
[DefaultValue(EventLogTargetOverflowAction.Truncate)]
public EventLogTargetOverflowAction OnOverflow { get; set; }
/// <summary>
/// Performs installation which requires administrative permissions.
/// </summary>
/// <param name="installationContext">The installation context.</param>
public void Install(InstallationContext installationContext)
{
var fixedSource = GetFixedSource();
//always throw error to keep backwardscomp behavior.
CreateEventSourceIfNeeded(fixedSource, true);
}
/// <summary>
/// Performs uninstallation which requires administrative permissions.
/// </summary>
/// <param name="installationContext">The installation context.</param>
public void Uninstall(InstallationContext installationContext)
{
var fixedSource = GetFixedSource();
if (string.IsNullOrEmpty(fixedSource))
{
InternalLogger.Debug("Skipping removing of event source because it contains layout renderers");
}
else
{
EventLog.DeleteEventSource(fixedSource, this.MachineName);
}
}
/// <summary>
/// Determines whether the item is installed.
/// </summary>
/// <param name="installationContext">The installation context.</param>
/// <returns>
/// Value indicating whether the item is installed or null if it is not possible to determine.
/// </returns>
public bool? IsInstalled(InstallationContext installationContext)
{
var fixedSource = GetFixedSource();
if (!string.IsNullOrEmpty(fixedSource))
{
return EventLog.SourceExists(fixedSource, this.MachineName);
}
InternalLogger.Debug("Unclear if event source exists because it contains layout renderers");
return null; //unclear!
}
/// <summary>
/// Initializes the target.
/// </summary>
protected override void InitializeTarget()
{
base.InitializeTarget();
var fixedSource = GetFixedSource();
if (string.IsNullOrEmpty(fixedSource))
{
InternalLogger.Debug("Skipping creation of event source because it contains layout renderers");
}
else
{
var currentSourceName = EventLog.LogNameFromSourceName(fixedSource, this.MachineName);
if (!currentSourceName.Equals(this.Log, StringComparison.CurrentCultureIgnoreCase))
{
this.CreateEventSourceIfNeeded(fixedSource, false);
}
}
}
/// <summary>
/// Writes the specified logging event to the event log.
/// </summary>
/// <param name="logEvent">The logging event.</param>
protected override void Write(LogEventInfo logEvent)
{
string message = this.Layout.Render(logEvent);
EventLogEntryType entryType = GetEntryType(logEvent);
int eventId = 0;
if (this.EventId != null)
{
eventId = Convert.ToInt32(this.EventId.Render(logEvent), CultureInfo.InvariantCulture);
}
short category = 0;
if (this.Category != null)
{
category = Convert.ToInt16(this.Category.Render(logEvent), CultureInfo.InvariantCulture);
}
EventLog eventLog = GetEventLog(logEvent);
// limitation of EventLog API
if (message.Length > this.MaxMessageLength)
{
if (OnOverflow == EventLogTargetOverflowAction.Truncate)
{
message = message.Substring(0, this.MaxMessageLength);
eventLog.WriteEntry(message, entryType, eventId, category);
}
else if (OnOverflow == EventLogTargetOverflowAction.Split)
{
for (int offset = 0; offset < message.Length; offset += this.MaxMessageLength)
{
string chunk = message.Substring(offset, Math.Min(this.MaxMessageLength, (message.Length - offset)));
eventLog.WriteEntry(chunk, entryType, eventId, category);
}
}
else if (OnOverflow == EventLogTargetOverflowAction.Discard)
{
//message will not be written
return;
}
}
else
{
eventLog.WriteEntry(message, entryType, eventId, category);
}
}
/// <summary>
/// Get the entry type for logging the message.
/// </summary>
/// <param name="logEvent">The logging event - for rendering the <see cref="EntryType"/></param>
/// <returns></returns>
private EventLogEntryType GetEntryType(LogEventInfo logEvent)
{
if (this.EntryType != null)
{
//try parse, if fail, determine auto
var value = this.EntryType.Render(logEvent);
EventLogEntryType eventLogEntryType;
if (EnumHelpers.TryParse(value, true, out eventLogEntryType))
{
return eventLogEntryType;
}
}
// determine auto
if (logEvent.Level >= LogLevel.Error)
{
return EventLogEntryType.Error;
}
if (logEvent.Level >= LogLevel.Warn)
{
return EventLogEntryType.Warning;
}
return EventLogEntryType.Information;
}
/// <summary>
/// Get the source, if and only if the source is fixed.
/// </summary>
/// <returns><c>null</c> when not <see cref="SimpleLayout.IsFixedText"/></returns>
/// <remarks>Internal for unit tests</remarks>
internal string GetFixedSource()
{
if (this.Source == null)
{
return null;
}
var simpleLayout = Source as SimpleLayout;
if (simpleLayout != null && simpleLayout.IsFixedText)
{
return simpleLayout.FixedText;
}
return null;
}
/// <summary>
/// Get the eventlog to write to.
/// </summary>
/// <param name="logEvent">Event if the source needs to be rendered.</param>
/// <returns></returns>
private EventLog GetEventLog(LogEventInfo logEvent)
{
return eventLogInstance ?? (eventLogInstance = new EventLog(this.Log, this.MachineName, this.Source.Render(logEvent)));
}
/// <summary>
/// (re-)create a event source, if it isn't there. Works only with fixed sourcenames.
/// </summary>
/// <param name="fixedSource">sourcenaam. If source is not fixed (see <see cref="SimpleLayout.IsFixedText"/>, then pass <c>null</c> or emptystring.</param>
/// <param name="alwaysThrowError">always throw an Exception when there is an error</param>
private void CreateEventSourceIfNeeded(string fixedSource, bool alwaysThrowError)
{
if (string.IsNullOrEmpty(fixedSource))
{
InternalLogger.Debug("Skipping creation of event source because it contains layout renderers");
//we can only create event sources if the source is fixed (no layout)
return;
}
// if we throw anywhere, we remain non-operational
try
{
if (EventLog.SourceExists(fixedSource, this.MachineName))
{
string currentLogName = EventLog.LogNameFromSourceName(fixedSource, this.MachineName);
if (!currentLogName.Equals(this.Log, StringComparison.CurrentCultureIgnoreCase))
{
// re-create the association between Log and Source
EventLog.DeleteEventSource(fixedSource, this.MachineName);
var eventSourceCreationData = new EventSourceCreationData(fixedSource, this.Log)
{
MachineName = this.MachineName
};
EventLog.CreateEventSource(eventSourceCreationData);
}
}
else
{
var eventSourceCreationData = new EventSourceCreationData(fixedSource, this.Log)
{
MachineName = this.MachineName
};
EventLog.CreateEventSource(eventSourceCreationData);
}
}
catch (Exception exception)
{
InternalLogger.Error(exception, "Error when connecting to EventLog.");
if (alwaysThrowError || exception.MustBeRethrown())
{
throw;
}
}
}
}
}
#endif
| |
/*
*
* 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;
using Lucene.Net.Util;
namespace Lucene.Net.Support
{
/// <summary>
/// This class provides supporting methods of java.util.BitSet
/// that are not present in System.Collections.BitArray.
/// </summary>
public static class BitSetSupport
{
/// <summary>
/// Returns the next set bit at or after index, or -1 if no such bit exists.
/// </summary>
/// <param name="bitArray"></param>
/// <param name="index">the index of bit array at which to start checking</param>
/// <returns>the next set bit or -1</returns>
public static int NextSetBit(this BitArray bitArray, int index)
{
while (index < bitArray.Length)
{
// if index bit is set, return it
// otherwise check next index bit
if (bitArray.Get(index))
return index;
else
index++;
}
// if no bits are set at or after index, return -1
return -1;
}
public static int PrevSetBit(this BitArray bitArray, int index)
{
while (index >= 0 && index < bitArray.Length)
{
// if index bit is set, return it
// otherwise check previous index bit
if (bitArray.SafeGet(index))
return index;
index--;
}
// if no bits are set at or before index, return -1
return -1;
}
// Produces a bitwise-and of the two BitArrays without requiring they be the same length
public static BitArray And_UnequalLengths(this BitArray bitsA, BitArray bitsB)
{
//Cycle only through fewest bits neccessary without requiring size equality
var maxIdx = Math.Min(bitsA.Length, bitsB.Length);//exclusive
var bits = new BitArray(maxIdx);
for (int i = 0; i < maxIdx; i++)
{
bits[i] = bitsA[i] & bitsB[i];
}
return bits;
}
// Produces a bitwise-or of the two BitArrays without requiring they be the same length
public static BitArray Or_UnequalLengths(this BitArray bitsA, BitArray bitsB)
{
var shorter = bitsA.Length < bitsB.Length ? bitsA : bitsB;
var longer = bitsA.Length >= bitsB.Length ? bitsA : bitsB;
var bits = new BitArray(longer.Length);
for (int i = 0; i < longer.Length; i++)
{
if (i >= shorter.Length)
{
bits[i] = longer[i];
}
else
{
bits[i] = shorter[i] | longer[i];
}
}
return bits;
}
// Produces a bitwise-xor of the two BitArrays without requiring they be the same length
public static BitArray Xor_UnequalLengths(this BitArray bitsA, BitArray bitsB)
{
var shorter = bitsA.Length < bitsB.Length ? bitsA : bitsB;
var longer = bitsA.Length >= bitsB.Length ? bitsA : bitsB;
var bits = new BitArray(longer.Length);
for (int i = 0; i < longer.Length; i++)
{
if (i >= shorter.Length)
{
bits[i] = longer[i];
}
else
{
bits[i] = shorter[i] ^ longer[i];
}
}
return bits;
}
/// <summary>
/// Returns the next un-set bit at or after index, or -1 if no such bit exists.
/// </summary>
/// <param name="bitArray"></param>
/// <param name="index">the index of bit array at which to start checking</param>
/// <returns>the next set bit or -1</returns>
public static int NextClearBit(this BitArray bitArray, int index)
{
while (index < bitArray.Length)
{
// if index bit is not set, return it
// otherwise check next index bit
if (!bitArray.Get(index))
return index;
else
index++;
}
// if no bits are set at or after index, return -1
return -1;
}
/// <summary>
/// Returns the number of bits set to true in this BitSet.
/// </summary>
/// <param name="bits">The BitArray object.</param>
/// <returns>The number of bits set to true in this BitSet.</returns>
public static int Cardinality(this BitArray bits)
{
int count = 0;
for (int i = 0; i < bits.Count; i++)
{
if (bits[i])
count++;
}
return count;
}
/// <summary>
/// Sets the bit at the given <paramref name="index"/> to true.
/// </summary>
/// <param name="bits">The BitArray object.</param>
/// <param name="index">The position to set to true.</param>
public static void Set(this BitArray bits, int index)
{
bits.SafeSet(index, true);
}
/// <summary>
/// Sets the bit at the given <paramref name="index"/> to true.
/// </summary>
/// <param name="bits">The BitArray object.</param>
/// <param name="fromIndex">The start of the range to set(inclusive)</param>
/// <param name="toIndex">The end of the range to set(exclusive)</param>
/// <param name="value">the value to set to the range</param>
public static void Set(this BitArray bits, int fromIndex, int toIndex, bool value)
{
for (int i = fromIndex; i < toIndex; ++i)
{
bits.SafeSet(i, value);
}
}
/// <summary>
/// Sets the bit at the given <paramref name="index"/> to false.
/// </summary>
/// <param name="bits">The BitArray object.</param>
/// <param name="index">The position to set to false.</param>
public static void Clear(this BitArray bits, int index)
{
bits.SafeSet(index, false);
}
/// <summary>
/// Sets all bits to false
/// </summary>
/// <param name="bits">The BitArray object.</param>
public static void Clear(this BitArray bits)
{
bits.SetAll(false);
}
//Flip all bits in the desired range, startIdx inclusive to endIdx exclusive
public static void Flip(this BitArray bits, int startIdx, int endIdx)
{
for (int i = startIdx; i < endIdx; i++)
{
bits[i] = !bits[i];
}
}
// Sets all bits in the range to false [startIdx, endIdx)
public static void Clear(this BitArray bits, int startIdx, int endIdx)
{
for (int i = startIdx; i < endIdx; i++)
{
bits[i] = false;
}
}
// Sets all bits in the range to true [startIdx, endIdx)
public static void Set(this BitArray bits, int startIdx, int endIdx)
{
for (int i = startIdx; i < endIdx; i++)
{
bits[i] = true;
}
}
// Emulates the Java BitSet.Get() method.
// Prevents exceptions from being thrown when the index is too high.
public static bool SafeGet(this BitArray a, int loc)
{
return loc < a.Count && a.Get(loc);
}
//Emulates the Java BitSet.Set() method. Required to reconcile differences between Java BitSet and C# BitArray
public static void SafeSet(this BitArray a, int loc, bool value)
{
if (loc >= a.Length)
a.Length = loc + 1;
a.Set(loc, value);
}
// Clears all bits in this BitArray that correspond to a set bit in the parameter BitArray
public static void AndNot(this BitArray bitsA, BitArray bitsB)
{
//Debug.Assert(bitsA.Length == bitsB.Length, "BitArray lengths are not the same");
for (int i = 0; i < bitsA.Length; i++)
{
//bitsA was longer than bitsB
if (i >= bitsB.Length)
{
return;
}
if (bitsA[i] && bitsB[i])
{
bitsA[i] = false;
}
}
}
//Does a deep comparison of two BitArrays
public static bool BitWiseEquals(this BitArray bitsA, BitArray bitsB)
{
if (bitsA == bitsB)
return true;
if (bitsA.Count != bitsB.Count)
return false;
for (int i = 0; i < bitsA.Count; i++)
{
if (bitsA[i] != bitsB[i])
return false;
}
return true;
}
//Compares a BitArray with an OpenBitSet
public static bool Equal(this BitArray a, OpenBitSet b)
{
var bitArrayCardinality = a.Cardinality();
if (bitArrayCardinality != b.Cardinality())
return false;
for (int i = 0; i < bitArrayCardinality; i++)
{
if (a.SafeGet(i) != b.Get(i))
return false;
}
return true;
}
}
}
| |
//
// MimeUtils.cs
//
// Author: Jeffrey Stedfast <[email protected]>
//
// Copyright (c) 2013-2016 Xamarin Inc. (www.xamarin.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;
using System.Text;
using System.Collections.Generic;
#if !PORTABLE
using System.Net.NetworkInformation;
using System.Security.Cryptography;
#endif
namespace MimeKit.Utils {
/// <summary>
/// MIME utility methods.
/// </summary>
/// <remarks>
/// Various utility methods that don't belong anywhere else.
/// </remarks>
public static class MimeUtils
{
#if PORTABLE || COREFX
static readonly Random random = new Random ((int) DateTime.Now.Ticks);
#endif
const string base36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
/// <summary>
/// A string comparer that performs a case-insensitive ordinal string comparison.
/// </summary>
/// <remarks>
/// A string comparer that performs a case-insensitive ordinal string comparison.
/// </remarks>
public static readonly IEqualityComparer<string> OrdinalIgnoreCase = new OptimizedOrdinalIgnoreCaseComparer ();
internal static void GetRandomBytes (byte[] buffer)
{
#if NET_3_5
var random = new RNGCryptoServiceProvider ();
random.GetBytes (buffer);
#elif !PORTABLE && !COREFX
using (var random = new RNGCryptoServiceProvider ())
random.GetBytes (buffer);
#else
lock (random) {
random.NextBytes (buffer);
}
#endif
}
/// <summary>
/// Generates a Message-Id.
/// </summary>
/// <remarks>
/// Generates a new Message-Id using the supplied domain.
/// </remarks>
/// <returns>The message identifier.</returns>
/// <param name="domain">A domain to use.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="domain"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentException">
/// <paramref name="domain"/> is invalid.
/// </exception>
public static string GenerateMessageId (string domain)
{
if (domain == null)
throw new ArgumentNullException ("domain");
if (domain.Length == 0)
throw new ArgumentException ("The domain is invalid.", "domain");
ulong value = (ulong) DateTime.Now.Ticks;
var id = new StringBuilder ();
var block = new byte[8];
GetRandomBytes (block);
do {
id.Append (base36[(int) (value % 36)]);
value /= 36;
} while (value != 0);
id.Append ('.');
value = 0;
for (int i = 0; i < 8; i++)
value = (value << 8) | (ulong) block[i];
do {
id.Append (base36[(int) (value % 36)]);
value /= 36;
} while (value != 0);
id.Append ('@').Append (domain);
return id.ToString ();
}
/// <summary>
/// Generates a Message-Id.
/// </summary>
/// <remarks>
/// Generates a new Message-Id using the local machine's domain.
/// </remarks>
/// <returns>The message identifier.</returns>
public static string GenerateMessageId ()
{
#if PORTABLE || COREFX
return GenerateMessageId ("localhost.localdomain");
#else
var properties = IPGlobalProperties.GetIPGlobalProperties ();
return GenerateMessageId (properties.HostName);
#endif
}
/// <summary>
/// Enumerates the message-id references such as those that can be found in
/// the In-Reply-To or References header.
/// </summary>
/// <remarks>
/// Incrementally parses Message-Ids (such as those from a References header
/// in a MIME message) from the supplied buffer starting at the given index
/// and spanning across the specified number of bytes.
/// </remarks>
/// <returns>The references.</returns>
/// <param name="buffer">The raw byte buffer to parse.</param>
/// <param name="startIndex">The index into the buffer to start parsing.</param>
/// <param name="length">The length of the buffer to parse.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the byte array.
/// </exception>
public static IEnumerable<string> EnumerateReferences (byte[] buffer, int startIndex, int length)
{
ParseUtils.ValidateArguments (buffer, startIndex, length);
byte[] sentinels = { (byte) '>' };
int endIndex = startIndex + length;
int index = startIndex;
string msgid;
do {
if (!ParseUtils.SkipCommentsAndWhiteSpace (buffer, ref index, endIndex, false))
break;
if (index >= endIndex)
break;
if (buffer[index] == '<') {
// skip over the '<'
index++;
if (index >= endIndex)
break;
string localpart;
if (!InternetAddress.TryParseLocalPart (buffer, ref index, endIndex, false, out localpart))
continue;
if (index >= endIndex)
break;
if (buffer[index] == (byte) '>') {
// The msgid token did not contain an @domain. Technically this is illegal, but for the
// sake of maximum compatibility, I guess we have no choice but to accept it...
index++;
yield return localpart;
continue;
}
if (buffer[index] != (byte) '@') {
// who the hell knows what we have here... ignore it and continue on?
continue;
}
// skip over the '@'
index++;
if (!ParseUtils.SkipCommentsAndWhiteSpace (buffer, ref index, endIndex, false))
break;
if (index >= endIndex)
break;
if (buffer[index] == (byte) '>') {
// The msgid token was in the form "<local-part@>". Technically this is illegal, but for
// the sake of maximum compatibility, I guess we have no choice but to accept it...
// https://github.com/jstedfast/MimeKit/issues/102
index++;
yield return localpart + "@";
continue;
}
string domain;
if (!ParseUtils.TryParseDomain (buffer, ref index, endIndex, sentinels, false, out domain))
continue;
msgid = localpart + "@" + domain;
// Note: some Message-Id's are broken and in the form "<local-part@domain@domain>"
// https://github.com/jstedfast/MailKit/issues/138
while (index < endIndex && buffer[index] == (byte) '@') {
int saved = index;
index++;
if (!ParseUtils.TryParseDomain (buffer, ref index, endIndex, sentinels, false, out domain)) {
index = saved;
break;
}
msgid += "@" + domain;
}
yield return msgid;
} else if (!ParseUtils.SkipWord (buffer, ref index, endIndex, false)) {
index++;
}
} while (index < endIndex);
yield break;
}
/// <summary>
/// Enumerates the message-id references such as those that can be found in
/// the In-Reply-To or References header.
/// </summary>
/// <remarks>
/// Incrementally parses Message-Ids (such as those from a References header
/// in a MIME message) from the specified text.
/// </remarks>
/// <returns>The references.</returns>
/// <param name="text">The text to parse.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="text"/> is <c>null</c>.
/// </exception>
public static IEnumerable<string> EnumerateReferences (string text)
{
if (text == null)
throw new ArgumentNullException ("text");
var buffer = Encoding.UTF8.GetBytes (text);
return EnumerateReferences (buffer, 0, buffer.Length);
}
/// <summary>
/// Parses a Message-Id header value.
/// </summary>
/// <remarks>
/// Parses the Message-Id value, returning the addr-spec portion of the msg-id token.
/// </remarks>
/// <returns>The addr-spec portion of the msg-id token.</returns>
/// <param name="buffer">The raw byte buffer to parse.</param>
/// <param name="startIndex">The index into the buffer to start parsing.</param>
/// <param name="length">The length of the buffer to parse.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the byte array.
/// </exception>
public static string ParseMessageId (byte[] buffer, int startIndex, int length)
{
ParseUtils.ValidateArguments (buffer, startIndex, length);
byte[] sentinels = { (byte) '>' };
int endIndex = startIndex + length;
int index = startIndex;
string msgid;
if (!ParseUtils.SkipCommentsAndWhiteSpace (buffer, ref index, endIndex, false))
return null;
if (index >= endIndex)
return null;
if (buffer[index] == '<') {
// skip over the '<'
index++;
if (index >= endIndex)
return null;
}
string localpart;
if (!InternetAddress.TryParseLocalPart (buffer, ref index, endIndex, false, out localpart))
return null;
if (index >= endIndex)
return null;
if (buffer[index] == (byte) '>') {
// The msgid token did not contain an @domain. Technically this is illegal, but for the
// sake of maximum compatibility, I guess we have no choice but to accept it...
return localpart;
}
if (buffer[index] != (byte) '@') {
// who the hell knows what we have here...
return null;
}
// skip over the '@'
index++;
if (!ParseUtils.SkipCommentsAndWhiteSpace (buffer, ref index, endIndex, false))
return null;
if (index >= endIndex)
return null;
if (buffer[index] == (byte) '>') {
// The msgid token was in the form "<local-part@>". Technically this is illegal, but for
// the sake of maximum compatibility, I guess we have no choice but to accept it...
// https://github.com/jstedfast/MimeKit/issues/102
return localpart + "@";
}
string domain;
if (!ParseUtils.TryParseDomain (buffer, ref index, endIndex, sentinels, false, out domain))
return null;
msgid = localpart + "@" + domain;
// Note: some Message-Id's are broken and in the form "<local-part@domain@domain>"
// https://github.com/jstedfast/MailKit/issues/138
while (index < endIndex && buffer[index] == (byte) '@') {
index++;
if (!ParseUtils.TryParseDomain (buffer, ref index, endIndex, sentinels, false, out domain))
break;
msgid += "@" + domain;
}
return msgid;
}
/// <summary>
/// Parses a Message-Id header value.
/// </summary>
/// <remarks>
/// Parses the Message-Id value, returning the addr-spec portion of the msg-id token.
/// </remarks>
/// <returns>The addr-spec portion of the msg-id token.</returns>
/// <param name="text">The text to parse.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="text"/> is <c>null</c>.
/// </exception>
public static string ParseMessageId (string text)
{
if (text == null)
throw new ArgumentNullException ("text");
var buffer = Encoding.UTF8.GetBytes (text);
return ParseMessageId (buffer, 0, buffer.Length);
}
/// <summary>
/// Tries to parse a version from a header such as Mime-Version.
/// </summary>
/// <remarks>
/// Parses a MIME version string from the supplied buffer starting at the given index
/// and spanning across the specified number of bytes.
/// </remarks>
/// <returns><c>true</c>, if the version was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="buffer">The raw byte buffer to parse.</param>
/// <param name="startIndex">The index into the buffer to start parsing.</param>
/// <param name="length">The length of the buffer to parse.</param>
/// <param name="version">The parsed version.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the byte array.
/// </exception>
public static bool TryParse (byte[] buffer, int startIndex, int length, out Version version)
{
ParseUtils.ValidateArguments (buffer, startIndex, length);
var values = new List<int> ();
int endIndex = startIndex + length;
int index = startIndex;
int value;
version = null;
do {
if (!ParseUtils.SkipCommentsAndWhiteSpace (buffer, ref index, endIndex, false) || index >= endIndex)
return false;
if (!ParseUtils.TryParseInt32 (buffer, ref index, endIndex, out value))
return false;
values.Add (value);
if (!ParseUtils.SkipCommentsAndWhiteSpace (buffer, ref index, endIndex, false))
return false;
if (index >= endIndex)
break;
if (buffer[index++] != (byte) '.')
return false;
} while (index < endIndex);
switch (values.Count) {
case 4: version = new Version (values[0], values[1], values[2], values[3]); break;
case 3: version = new Version (values[0], values[1], values[2]); break;
case 2: version = new Version (values[0], values[1]); break;
default: return false;
}
return true;
}
/// <summary>
/// Tries to parse a version from a header such as Mime-Version.
/// </summary>
/// <remarks>
/// Parses a MIME version string from the specified text.
/// </remarks>
/// <returns><c>true</c>, if the version was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="text">The text to parse.</param>
/// <param name="version">The parsed version.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="text"/> is <c>null</c>.
/// </exception>
public static bool TryParse (string text, out Version version)
{
if (text == null)
throw new ArgumentNullException ("text");
var buffer = Encoding.UTF8.GetBytes (text);
return TryParse (buffer, 0, buffer.Length, out version);
}
/// <summary>
/// Tries to parse a version from a header such as Mime-Version.
/// </summary>
/// <remarks>
/// Parses a MIME version string from the supplied buffer starting at the given index
/// and spanning across the specified number of bytes.
/// </remarks>
/// <returns><c>true</c>, if the version was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="buffer">The raw byte buffer to parse.</param>
/// <param name="startIndex">The index into the buffer to start parsing.</param>
/// <param name="length">The length of the buffer to parse.</param>
/// <param name="version">The parsed version.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the byte array.
/// </exception>
[Obsolete ("Use TryParse (byte[] buffer, int startIndex, int length, out Version version) instead.")]
public static bool TryParseVersion (byte[] buffer, int startIndex, int length, out Version version)
{
return TryParse (buffer, startIndex, length, out version);
}
/// <summary>
/// Tries to parse a version from a header such as Mime-Version.
/// </summary>
/// <remarks>
/// Parses a MIME version string from the specified text.
/// </remarks>
/// <returns><c>true</c>, if the version was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="text">The text to parse.</param>
/// <param name="version">The parsed version.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="text"/> is <c>null</c>.
/// </exception>
[Obsolete ("Use TryParse (string text, out Version version) instead.")]
public static bool TryParseVersion (string text, out Version version)
{
return TryParse (text, out version);
}
/// <summary>
/// Tries to parse the value of a Content-Transfer-Encoding header.
/// </summary>
/// <remarks>
/// Parses a Content-Transfer-Encoding header value.
/// </remarks>
/// <returns><c>true</c>, if the encoding was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="text">The text to parse.</param>
/// <param name="encoding">The parsed encoding.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="text"/> is <c>null</c>.
/// </exception>
public static bool TryParse (string text, out ContentEncoding encoding)
{
if (text == null)
throw new ArgumentNullException ("text");
var value = new char[text.Length];
int i = 0, n = 0;
string name;
// trim leading whitespace
while (i < text.Length && char.IsWhiteSpace (text[i]))
i++;
// copy the encoding name
// Note: Google Docs tacks a ';' on the end... *sigh*
// See https://github.com/jstedfast/MimeKit/issues/106 for an example.
while (i < text.Length && text[i] != ';' && !char.IsWhiteSpace (text[i]))
value[n++] = char.ToLowerInvariant (text[i++]);
name = new string (value, 0, n);
switch (name) {
case "7bit": encoding = ContentEncoding.SevenBit; break;
case "8bit": encoding = ContentEncoding.EightBit; break;
case "binary": encoding = ContentEncoding.Binary; break;
case "base64": encoding = ContentEncoding.Base64; break;
case "quoted-printable": encoding = ContentEncoding.QuotedPrintable; break;
case "x-uuencode": encoding = ContentEncoding.UUEncode; break;
case "uuencode": encoding = ContentEncoding.UUEncode; break;
default: encoding = ContentEncoding.Default; break;
}
return encoding != ContentEncoding.Default;
}
/// <summary>
/// Quotes the specified text.
/// </summary>
/// <remarks>
/// Quotes the specified text, enclosing it in double-quotes and escaping
/// any backslashes and double-quotes within.
/// </remarks>
/// <returns>The quoted text.</returns>
/// <param name="text">The text to quote.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="text"/> is <c>null</c>.
/// </exception>
public static string Quote (string text)
{
if (text == null)
throw new ArgumentNullException ("text");
var quoted = new StringBuilder (text.Length + 2, (text.Length * 2) + 2);
quoted.Append ("\"");
for (int i = 0; i < text.Length; i++) {
if (text[i] == '\\' || text[i] == '"')
quoted.Append ('\\');
quoted.Append (text[i]);
}
quoted.Append ("\"");
return quoted.ToString ();
}
/// <summary>
/// Unquotes the specified text.
/// </summary>
/// <remarks>
/// Unquotes the specified text, removing any escaped backslashes within.
/// </remarks>
/// <returns>The unquoted text.</returns>
/// <param name="text">The text to unquote.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="text"/> is <c>null</c>.
/// </exception>
public static string Unquote (string text)
{
if (text == null)
throw new ArgumentNullException ("text");
int index = text.IndexOfAny (new [] { '\r', '\n', '\t', '\\', '"' });
if (index == -1)
return text;
var builder = new StringBuilder ();
bool escaped = false;
bool quoted = false;
for (int i = 0; i < text.Length; i++) {
switch (text[i]) {
case '\r':
case '\n':
escaped = false;
break;
case '\t':
builder.Append (' ');
escaped = false;
break;
case '\\':
if (escaped)
builder.Append ('\\');
escaped = !escaped;
break;
case '"':
if (escaped) {
builder.Append ('"');
escaped = false;
} else {
quoted = !quoted;
}
break;
default:
builder.Append (text[i]);
escaped = false;
break;
}
}
return builder.ToString ();
}
}
}
| |
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
namespace SillyWidgets.Gizmos
{
public enum TokenType { Invalid, BeginDoc, Doctype, EndDoc, MarkupDecl, OpenTag, EndTag, TagName, CloseTag, SelfCloseTag, Code, BeginComment, EndComment,
EndCode, Text, AttributeName, AttributeValue };
public delegate void TokenAvailable(Token token);
public class Token
{
public TokenType Type { get; set; }
public string Value { get; set; }
public Token(TokenType type = TokenType.Invalid, string value = "")
{
Type = type;
Value = value;
}
}
public class HtmlLexerGizmo
{
public TokenAvailable Collect { get; set; }
private TextReader Stream = null;
private static HashSet<char> LetterSet = new HashSet<char>()
{
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
};
private static HashSet<char> NameSet = new HashSet<char>(LetterSet)
{
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', '.', '-', '_'
};
public HtmlLexerGizmo(TokenAvailable tokenCallback)
{
Collect = tokenCallback;
}
public void Deposit(Token artifact)
{
if (Collect != null)
{
Collect(artifact);
}
}
public void Gimme(TextReader stream)
{
if (stream == null)
{
return;
}
Stream = stream;
Deposit(new Token(TokenType.BeginDoc));
char current;
StringBuilder content = new StringBuilder();
bool isContent = false;
while(GetNext(out current))
{
if (isContent)
{
if (current != '<')
{
content.Append(current);
continue;
}
char next;
GetNext(out next, true);
if (char.IsWhiteSpace(next))
{
content.Append(current);
continue;
}
string text = content.ToString();
if (text.Length > 0)
{
Deposit(new Token(TokenType.Text, text));
content.Clear();
}
isContent = false;
}
if (char.IsWhiteSpace(current))
{
continue;
}
if (current == '<')
{
GetNext(out current);
if (current == '!')
{
MarkupDeclaration();
continue;
}
bool isScript;
if (LetterSet.Contains(current))
{
Deposit(new Token(TokenType.OpenTag));
char tagEnd = TagName(current, out isScript);
if (TagEnd(tagEnd, isScript))
{
isContent = true;
continue;
}
Attributes(tagEnd);
if (isScript)
{
Code();
}
isContent = true;
continue;
}
if (current == '/')
{
Deposit(new Token(TokenType.CloseTag));
GetNext(out current);
char tagEnd = TagName(current, out isScript);
if (tagEnd == '>')
{
Deposit(new Token(TokenType.EndTag));
isContent = true;
}
}
}
}
Deposit(new Token(TokenType.EndDoc));
}
private void Attributes(char current)
{
if (!NameSet.Contains(current))
{
return;
}
char next = BuildName(current, TokenType.AttributeName);
while (!TagEnd(next, false))
{
if (next == '=')
{
next = AttributeValue(next);
continue;
}
next = BuildName(next, TokenType.AttributeName);
}
}
private char AttributeValue(char current)
{
char next = ChewWhitespace();
StringBuilder value = new StringBuilder();
if (next == '"' || next == '\'')
{
char delimiter = next;
char previous = next;
while (GetNext(out next))
{
if (next == delimiter &&
previous != '\\')
{
break;
}
value.Append(next);
previous = next;
}
Deposit(new Token(TokenType.AttributeValue, value.ToString()));
return(ChewWhitespace());
}
if (NameSet.Contains(next))
{
next = BuildName(next, TokenType.AttributeValue);
}
return(next);
}
private char ChewWhitespace()
{
char next;
while(GetNext(out next))
{
if (!char.IsWhiteSpace(next))
{
break;
}
}
return(next);
}
private char BuildName(char current, TokenType type)
{
StringBuilder name = new StringBuilder();
name.Append(current);
char next;
while(GetNext(out next))
{
if (!NameSet.Contains(next))
{
break;
}
name.Append(next);
}
Deposit(new Token(type, name.ToString()));
if (char.IsWhiteSpace(next))
{
next = ChewWhitespace();
}
return(next);
}
private bool TagEnd(char end, bool isScript)
{
if (end == '>')
{
Deposit(new Token(TokenType.EndTag));
if (isScript)
{
Code();
}
return(true);
}
if (end == '/')
{
char next;
GetNext(out next);
if (next == '>')
{
Deposit(new Token(TokenType.SelfCloseTag));
return(true);
}
}
return(false);
}
private void Code()
{
StringBuilder buffer = new StringBuilder();
StringBuilder notSureBuffer = new StringBuilder();
char next;
char expecting = '<';
bool isClosing = false;
while(GetNext(out next))
{
if (isClosing)
{
notSureBuffer.Append(next);
if (next == '>')
{
Deposit(new Token(TokenType.Code, buffer.ToString()));
Deposit(new Token(TokenType.EndCode));
return;
}
if (!char.IsWhiteSpace(next))
{
isClosing = false;
expecting = '<';
}
else
{
continue;
}
}
if (next == expecting)
{
notSureBuffer.Append(next);
switch(next)
{
case '<':
expecting = '/';
break;
case '/':
expecting = 's';
break;
case 's':
expecting = 'c';
break;
case 'c':
expecting = 'r';
break;
case 'r':
expecting = 'i';
break;
case 'i':
expecting = 'p';
break;
case 'p':
expecting = 't';
break;
case 't':
expecting = '>';
isClosing = true;
break;
default:
break;
}
continue;
}
expecting = '<';
isClosing = false;
if (notSureBuffer.Length > 0)
{
buffer.Append(notSureBuffer.ToString());
notSureBuffer.Clear();
}
buffer.Append(next);
}
}
private char TagName(char firstChar, out bool isScript)
{
StringBuilder buffer = new StringBuilder();
char next;
bool tagDone = false;
isScript = false;
buffer.Append(firstChar);
while (GetNext(out next))
{
if (!tagDone)
{
if (NameSet.Contains(next))
{
buffer.Append(next);
continue;
}
string tagName = buffer.ToString().Trim();
Deposit(new Token(TokenType.TagName, tagName));
if (String.Compare(tagName, "script", true) == 0)
{
isScript = true;
}
}
tagDone = true;
if (char.IsWhiteSpace(next))
{
continue;
}
return(next);
}
return(next);
}
private void MarkupDeclaration()
{
Deposit(new Token(TokenType.MarkupDecl));
char next, afterNext;
if (GetNext(out next) && GetNext(out afterNext))
{
if (next == '-' && afterNext == '-')
{
Comment();
}
else
{
Doctype();
}
}
}
private void Doctype()
{
char current;
StringBuilder buffer = new StringBuilder();
buffer.Append('d');
buffer.Append('o');
while(GetNext(out current))
{
if (current == '>')
{
Deposit(new Token(TokenType.Doctype, buffer.ToString()));
Deposit(new Token(TokenType.EndTag));
return;
}
buffer.Append(current);
}
}
private bool GetNext(out char next, bool peek = false)
{
next = '\0';
if (Stream == null)
{
return(false);
}
int value = -1;
if (peek)
{
value = Stream.Peek();
}
else
{
value = Stream.Read();
}
if (value < 0)
{
return(false);
}
next = (char)value;
return(true);
}
private void Comment()
{
Deposit(new Token(TokenType.BeginComment));
StringBuilder buffer = new StringBuilder();
char current;
int dashCount = 0;
while(GetNext(out current))
{
if (current == '-')
{
++dashCount;
if (dashCount >= 2)
{
char peek;
if (GetNext(out peek, true))
{
if (peek == '>')
{
Deposit(new Token(TokenType.EndComment, buffer.ToString()));
GetNext(out current);
return;
}
}
}
}
else
{
dashCount = 0;
}
buffer.Append(current);
}
Deposit(new Token(TokenType.EndComment, buffer.ToString()));
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using FileHelpers.Engines;
using FileHelpers.Events;
using FileHelpers.Options;
namespace FileHelpers.MasterDetail
{
/// <summary>
/// Read a master detail file, eg Orders followed by detail records
/// </summary>
public sealed class MasterDetailEngine
: MasterDetailEngine<object, object>
{
#region " Constructor "
/// <include file='MasterDetailEngine.docs.xml' path='doc/MasterDetailEngineCtr/*'/>
public MasterDetailEngine(Type masterType, Type detailType)
: this(masterType, detailType, null) { }
/// <include file='MasterDetailEngine.docs.xml' path='doc/MasterDetailEngineCtr/*'/>
/// <param name="masterType">The master record class.</param>
/// <param name="detailType">The detail record class.</param>
/// <param name="recordSelector">The <see cref="MasterDetailSelector" /> to get the <see cref="RecordAction" /> (only for read operations)</param>
public MasterDetailEngine(Type masterType, Type detailType, MasterDetailSelector recordSelector)
: base(masterType, detailType, recordSelector) { }
/// <include file='MasterDetailEngine.docs.xml' path='doc/MasterDetailEngineCtr/*'/>
/// <param name="masterType">The master record class.</param>
/// <param name="detailType">The detail record class.</param>
/// <param name="action">The <see cref="CommonSelector" /> used by the engine (only for read operations)</param>
/// <param name="selector">The string passed as the selector.</param>
public MasterDetailEngine(Type masterType, Type detailType, CommonSelector action, string selector)
: base(masterType, detailType, action, selector) { }
#endregion
}
/// <include file='MasterDetailEngine.docs.xml' path='doc/MasterDetailEngine/*'/>
/// <include file='Examples.xml' path='doc/examples/MasterDetailEngine/*'/>
/// <typeparam name="TMaster">The Master Record Type</typeparam>
/// <typeparam name="TDetail">The Detail Record Type</typeparam>
public class MasterDetailEngine<TMaster, TDetail>
: EngineBase
where TMaster : class
where TDetail : class
{
#region " Constructor "
/// <include file='MasterDetailEngine.docs.xml' path='doc/MasterDetailEngineCtr1/*'/>
public MasterDetailEngine()
: this(null) { }
/// <include file='MasterDetailEngine.docs.xml' path='doc/MasterDetailEngineCtr1/*'/>
public MasterDetailEngine(MasterDetailSelector recordSelector)
: this(typeof(TMaster), typeof(TDetail), recordSelector) { }
/// <include file='MasterDetailEngine.docs.xml' path='doc/MasterDetailEngineCtr1/*'/>
internal MasterDetailEngine(Type masterType, Type detailType, MasterDetailSelector recordSelector)
: base(detailType)
{
mMasterType = masterType;
mMasterInfo = FileHelpers.RecordInfo.Resolve(mMasterType);
MasterOptions = CreateRecordOptionsCore(mMasterInfo);
mRecordSelector = recordSelector;
}
/// <include file='MasterDetailEngine.docs.xml' path='doc/MasterDetailEngineCtr2/*'/>
public MasterDetailEngine(CommonSelector action, string selector)
: this(typeof(TMaster), typeof(TDetail), action, selector) { }
/// <include file='MasterDetailEngine.docs.xml' path='doc/MasterDetailEngineCtr2/*'/>
internal MasterDetailEngine(Type masterType, Type detailType, CommonSelector action, string selector)
: base(detailType)
{
mMasterType = masterType;
mMasterInfo = FileHelpers.RecordInfo.Resolve(mMasterType);
MasterOptions = CreateRecordOptionsCore(mMasterInfo);
var sel = new MasterDetailEngine<object, object>.CommonSelectorInternal(action,
selector,
mMasterInfo.IgnoreEmptyLines || RecordInfo.IgnoreEmptyLines);
mRecordSelector = new MasterDetailSelector(sel.CommonSelectorMethod);
}
#endregion
/// <summary>
/// Allows you to change some record layout options at runtime
/// </summary>
public RecordOptions MasterOptions { get; private set; }
#region CommonSelectorInternal
internal class CommonSelectorInternal
{
private readonly CommonSelector mAction;
private readonly string mSelector;
private readonly bool mIgnoreEmpty = false;
internal CommonSelectorInternal(CommonSelector action, string selector, bool ignoreEmpty)
{
mAction = action;
mSelector = selector;
mIgnoreEmpty = ignoreEmpty;
}
internal RecordAction CommonSelectorMethod(string recordString)
{
if (mIgnoreEmpty && recordString == string.Empty)
return RecordAction.Skip;
switch (mAction)
{
case CommonSelector.DetailIfContains:
if (recordString.IndexOf(mSelector) >= 0)
return RecordAction.Detail;
else
return RecordAction.Master;
case CommonSelector.MasterIfContains:
if (recordString.IndexOf(mSelector) >= 0)
return RecordAction.Master;
else
return RecordAction.Detail;
case CommonSelector.DetailIfBegins:
if (recordString.StartsWith(mSelector))
return RecordAction.Detail;
else
return RecordAction.Master;
case CommonSelector.MasterIfBegins:
if (recordString.StartsWith(mSelector))
return RecordAction.Master;
else
return RecordAction.Detail;
case CommonSelector.DetailIfEnds:
if (recordString.EndsWith(mSelector))
return RecordAction.Detail;
else
return RecordAction.Master;
case CommonSelector.MasterIfEnds:
if (recordString.EndsWith(mSelector))
return RecordAction.Master;
else
return RecordAction.Detail;
case CommonSelector.DetailIfEnclosed:
if (recordString.StartsWith(mSelector) &&
recordString.EndsWith(mSelector))
return RecordAction.Detail;
else
return RecordAction.Master;
case CommonSelector.MasterIfEnclosed:
if (recordString.StartsWith(mSelector) &&
recordString.EndsWith(mSelector))
return RecordAction.Master;
else
return RecordAction.Detail;
}
return RecordAction.Skip;
}
}
#endregion
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly IRecordInfo mMasterInfo;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private MasterDetailSelector mRecordSelector;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly Type mMasterType;
/// <summary>
/// the type of the master records handled by this engine.
/// </summary>
public Type MasterType
{
get { return mMasterType; }
}
/// <summary>
/// The <see cref="MasterDetailSelector" /> to get the <see cref="RecordAction" /> (only for read operations)
/// </summary>
public MasterDetailSelector RecordSelector
{
get { return mRecordSelector; }
set { mRecordSelector = value; }
}
#region " ReadFile "
/// <include file='MasterDetailEngine.docs.xml' path='doc/ReadFile/*'/>
public MasterDetails<TMaster, TDetail>[] ReadFile(string fileName)
{
using (var fs = new StreamReader(fileName, mEncoding, true, DefaultReadBufferSize))
{
MasterDetails<TMaster, TDetail>[] tempRes;
tempRes = ReadStream(fs);
fs.Close();
return tempRes;
}
}
#endregion
#region " ReadStream "
/// <include file='MasterDetailEngine.docs.xml' path='doc/ReadStream/*'/>
public MasterDetails<TMaster, TDetail>[] ReadStream(TextReader reader)
{
if (reader == null)
throw new ArgumentNullException(nameof(reader), "The reader of the Stream can't be null");
if (RecordSelector == null)
throw new BadUsageException("The RecordSelector can't be null on read operations.");
var recordReader = new NewLineDelimitedRecordReader(reader);
ResetFields();
HeaderText = string.Empty;
mFooterText = string.Empty;
var resArray = new ArrayList();
using (var freader = new ForwardReader(recordReader, mMasterInfo.IgnoreLast))
{
freader.DiscardForward = true;
mLineNumber = 1;
var completeLine = freader.ReadNextLine();
var currentLine = completeLine;
if (MustNotifyProgress) // Avoid object creation
OnProgress(new ProgressEventArgs(0, -1));
int currentRecord = 0;
if (mMasterInfo.IgnoreFirst > 0)
{
for (int i = 0; i < mMasterInfo.IgnoreFirst && currentLine != null; i++)
{
HeaderText += currentLine + Environment.NewLine;
currentLine = freader.ReadNextLine();
mLineNumber++;
}
}
bool byPass = false;
MasterDetails<TMaster, TDetail> record = null;
var tmpDetails = new ArrayList();
var line = new LineInfo(currentLine)
{
mReader = freader
};
var valuesMaster = new object[mMasterInfo.FieldCount];
var valuesDetail = new object[RecordInfo.FieldCount];
while (currentLine != null)
{
try
{
currentRecord++;
line.ReLoad(currentLine);
if (MustNotifyProgress) // Avoid object creation
OnProgress(new ProgressEventArgs(currentRecord, -1));
var action = RecordAction.Skip;
try
{
action = RecordSelector(currentLine);
}
catch (Exception ex)
{
throw new Exception("Supplied Record selector failed to process record", ex);
}
switch (action)
{
case RecordAction.Master:
if (record != null)
{
record.Details = (TDetail[])tmpDetails.ToArray(typeof(TDetail));
resArray.Add(record);
}
mTotalRecords++;
record = new MasterDetails<TMaster, TDetail>();
tmpDetails.Clear();
var lastMaster = (TMaster)mMasterInfo.Operations.StringToRecord(line, valuesMaster);
if (lastMaster != null)
record.Master = lastMaster;
break;
case RecordAction.Detail:
var lastChild = (TDetail)RecordInfo.Operations.StringToRecord(line, valuesDetail);
if (lastChild != null)
tmpDetails.Add(lastChild);
break;
default:
break;
}
}
catch (Exception ex)
{
switch (mErrorManager.ErrorMode)
{
case ErrorMode.ThrowException:
byPass = true;
throw;
case ErrorMode.IgnoreAndContinue:
break;
case ErrorMode.SaveAndContinue:
var err = new ErrorInfo
{
mLineNumber = mLineNumber,
mExceptionInfo = ex,
mRecordString = completeLine,
mRecordTypeName = RecordInfo.RecordType.Name
};
mErrorManager.AddError(err);
break;
}
}
finally
{
if (byPass == false)
{
currentLine = freader.ReadNextLine();
completeLine = currentLine;
mLineNumber = freader.LineNumber;
}
}
}
if (record != null)
{
record.Details = (TDetail[])tmpDetails.ToArray(typeof(TDetail));
resArray.Add(record);
}
if (mMasterInfo.IgnoreLast > 0)
mFooterText = freader.RemainingText;
}
return (MasterDetails<TMaster, TDetail>[])resArray.ToArray(typeof(MasterDetails<TMaster, TDetail>));
}
#endregion
#region " ReadString "
/// <include file='MasterDetailEngine.docs.xml' path='doc/ReadString/*'/>
public MasterDetails<TMaster, TDetail>[] ReadString(string source)
{
var reader = new StringReader(source);
MasterDetails<TMaster, TDetail>[] res = ReadStream(reader);
reader.Close();
return res;
}
#endregion
#region " WriteFile "
/// <include file='MasterDetailEngine.docs.xml' path='doc/WriteFile/*'/>
public void WriteFile(string fileName, IEnumerable<MasterDetails<TMaster, TDetail>> records)
{
WriteFile(fileName, records, -1);
}
/// <include file='MasterDetailEngine.docs.xml' path='doc/WriteFile2/*'/>
public void WriteFile(string fileName, IEnumerable<MasterDetails<TMaster, TDetail>> records, int maxRecords)
{
using (var fs = new StreamWriter(fileName, false, mEncoding, DefaultWriteBufferSize))
{
WriteStream(fs, records, maxRecords);
fs.Close();
}
}
#endregion
#region " WriteStream "
/// <include file='MasterDetailEngine.docs.xml' path='doc/WriteStream/*'/>
public void WriteStream(TextWriter writer, IEnumerable<MasterDetails<TMaster, TDetail>> records)
{
WriteStream(writer, records, -1);
}
/// <include file='MasterDetailEngine.docs.xml' path='doc/WriteStream2/*'/>
public void WriteStream(TextWriter writer, IEnumerable<MasterDetails<TMaster, TDetail>> records, int maxRecords)
{
if (writer == null)
throw new ArgumentNullException(nameof(writer), "The writer of the Stream can be null");
if (records == null)
throw new ArgumentNullException(nameof(records), "The records can be null. Try with an empty array.");
ResetFields();
writer.NewLine = NewLineForWrite;
WriteHeader(writer);
string currentLine = null;
int max = maxRecords;
if (records is IList)
{
max = Math.Min(max < 0
? int.MaxValue
: max,
((IList)records).Count);
}
if (MustNotifyProgress) // Avoid object creation
OnProgress(new ProgressEventArgs(0, max));
int recIndex = 0;
foreach (var rec in records)
{
if (recIndex == maxRecords)
break;
try
{
if (rec == null)
throw new BadUsageException("The record at index " + recIndex.ToString() + " is null.");
if (MustNotifyProgress) // Avoid object creation
OnProgress(new ProgressEventArgs(recIndex + 1, max));
currentLine = mMasterInfo.Operations.RecordToString(rec.Master);
writer.WriteLine(currentLine);
if (rec.Details != null)
{
for (int d = 0; d < rec.Details.Length; d++)
{
currentLine = RecordInfo.Operations.RecordToString(rec.Details[d]);
writer.WriteLine(currentLine);
}
}
}
catch (Exception ex)
{
switch (mErrorManager.ErrorMode)
{
case ErrorMode.ThrowException:
throw;
case ErrorMode.IgnoreAndContinue:
break;
case ErrorMode.SaveAndContinue:
var err = new ErrorInfo
{
mLineNumber = mLineNumber,
mExceptionInfo = ex,
mRecordString = currentLine,
mRecordTypeName = RecordInfo.RecordType.Name
};
mErrorManager.AddError(err);
break;
}
}
}
mTotalRecords = recIndex;
WriteFooter(writer);
}
#endregion
#region " WriteString "
/// <include file='MasterDetailEngine.docs.xml' path='doc/WriteString/*'/>
public string WriteString(IEnumerable<MasterDetails<TMaster, TDetail>> records)
{
return WriteString(records, -1);
}
/// <include file='MasterDetailEngine.docs.xml' path='doc/WriteString2/*'/>
public string WriteString(IEnumerable<MasterDetails<TMaster, TDetail>> records, int maxRecords)
{
var sb = new StringBuilder();
var writer = new StringWriter(sb);
WriteStream(writer, records, maxRecords);
string res = writer.ToString();
writer.Close();
return res;
}
#endregion
#region " AppendToFile "
/// <include file='MasterDetailEngine.docs.xml' path='doc/AppendToFile1/*'/>
public void AppendToFile(string fileName, MasterDetails<TMaster, TDetail> record)
{
AppendToFile(fileName, new MasterDetails<TMaster, TDetail>[] { record });
}
/// <include file='MasterDetailEngine.docs.xml' path='doc/AppendToFile2/*'/>
public void AppendToFile(string fileName, IEnumerable<MasterDetails<TMaster, TDetail>> records)
{
using (
TextWriter writer = StreamHelper.CreateFileAppender(fileName,
mEncoding,
true,
false,
DefaultWriteBufferSize))
{
HeaderText = string.Empty;
mFooterText = string.Empty;
WriteStream(writer, records);
writer.Close();
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
namespace Orleans.Messaging
{
/// <summary>
/// The GatewayManager class holds the list of known gateways, as well as maintaining the list of "dead" gateways.
///
/// The known list can come from one of two places: the full list may appear in the client configuration object, or
/// the config object may contain an IGatewayListProvider delegate. If both appear, then the delegate takes priority.
/// </summary>
internal class GatewayManager : IGatewayListListener
{
internal readonly IGatewayListProvider ListProvider;
private SafeTimer gatewayRefreshTimer;
private readonly Dictionary<Uri, DateTime> knownDead;
private IList<Uri> cachedLiveGateways;
private DateTime lastRefreshTime;
private int roundRobinCounter;
private readonly SafeRandom rand;
private readonly TraceLogger logger;
private readonly object lockable;
private readonly ClientConfiguration config;
private bool gatewayRefreshCallInitiated;
public GatewayManager(ClientConfiguration cfg, IGatewayListProvider gatewayListProvider)
{
config = cfg;
knownDead = new Dictionary<Uri, DateTime>();
rand = new SafeRandom();
logger = TraceLogger.GetLogger("Messaging.GatewayManager", TraceLogger.LoggerType.Runtime);
lockable = new object();
gatewayRefreshCallInitiated = false;
ListProvider = gatewayListProvider;
var knownGateways = ListProvider.GetGateways().GetResult();
if (knownGateways.Count == 0)
{
string gatewayProviderType = gatewayListProvider.GetType().FullName;
string err = String.Format("Could not find any gateway in {0}. Orleans client cannot initialize.", gatewayProviderType);
logger.Error(ErrorCode.GatewayManager_NoGateways, err);
throw new OrleansException(err);
}
logger.Info(ErrorCode.GatewayManager_FoundKnownGateways, "Found {0} knownGateways from Gateway listProvider {1}", knownGateways.Count, Utils.EnumerableToString(knownGateways));
if (ListProvider is IGatewayListObservable)
{
((IGatewayListObservable)ListProvider).SubscribeToGatewayNotificationEvents(this);
}
roundRobinCounter = cfg.PreferedGatewayIndex >= 0 ? cfg.PreferedGatewayIndex : rand.Next(knownGateways.Count);
cachedLiveGateways = knownGateways;
lastRefreshTime = DateTime.UtcNow;
if (ListProvider.IsUpdatable)
{
gatewayRefreshTimer = new SafeTimer(RefreshSnapshotLiveGateways_TimerCallback, null, config.GatewayListRefreshPeriod, config.GatewayListRefreshPeriod);
}
}
public void Stop()
{
if (gatewayRefreshTimer != null)
{
Utils.SafeExecute(gatewayRefreshTimer.Dispose, logger);
}
gatewayRefreshTimer = null;
if (ListProvider != null && ListProvider is IGatewayListObservable)
{
Utils.SafeExecute(
() => ((IGatewayListObservable)ListProvider).UnSubscribeFromGatewayNotificationEvents(this),
logger);
}
}
public void MarkAsDead(Uri gateway)
{
lock (lockable)
{
knownDead[gateway] = DateTime.UtcNow;
var copy = cachedLiveGateways.ToList();
copy.Remove(gateway);
// swap the reference, don't mutate cachedLiveGateways, so we can access cachedLiveGateways without the lock.
cachedLiveGateways = copy;
}
}
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("GatewayManager: ");
lock (lockable)
{
if (cachedLiveGateways != null)
{
sb.Append(cachedLiveGateways.Count);
sb.Append(" cachedLiveGateways, ");
}
if (knownDead != null)
{
sb.Append(knownDead.Count);
sb.Append(" known dead gateways.");
}
}
return sb.ToString();
}
/// <summary>
/// Selects a gateway to use for a new bucket.
///
/// Note that if a list provider delegate was given, the delegate is invoked every time this method is called.
/// This method performs caching to avoid hammering the ultimate data source.
///
/// This implementation does a simple round robin selection. It assumes that the gateway list from the provider
/// is in the same order every time.
/// </summary>
/// <returns></returns>
public Uri GetLiveGateway()
{
IList<Uri> live = GetLiveGateways();
int count = live.Count;
if (count > 0)
{
lock (lockable)
{
// Round-robin through the known gateways and take the next live one, starting from where we last left off
roundRobinCounter = (roundRobinCounter + 1) % count;
return live[roundRobinCounter];
}
}
// If we drop through, then all of the known gateways are presumed dead
return null;
}
public IList<Uri> GetLiveGateways()
{
// Never takes a lock and returns the cachedLiveGateways list quickly without any operation.
// Asynchronously starts gateway refresh only when it is empty.
if (cachedLiveGateways.Count == 0)
{
ExpediteUpdateLiveGatewaysSnapshot();
}
return cachedLiveGateways;
}
internal void ExpediteUpdateLiveGatewaysSnapshot()
{
// If there is already an expedited refresh call in place, don't call again, until the previous one is finished.
// We don't want to issue too many Gateway refresh calls.
if (ListProvider == null || !ListProvider.IsUpdatable || gatewayRefreshCallInitiated) return;
// Initiate gateway list refresh asynchronously. The Refresh timer will keep ticking regardless.
// We don't want to block the client with synchronously Refresh call.
// Client's call will fail with "No Gateways found" but we will try to refresh the list quickly.
gatewayRefreshCallInitiated = true;
var task = Task.Factory.StartNew(() =>
{
RefreshSnapshotLiveGateways_TimerCallback(null);
gatewayRefreshCallInitiated = false;
});
task.Ignore();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public void GatewayListNotification(IEnumerable<Uri> gateways)
{
try
{
UpdateLiveGatewaysSnapshot(gateways, ListProvider.MaxStaleness);
}
catch (Exception exc)
{
logger.Error(ErrorCode.ProxyClient_GetGateways, "Exception occurred during GatewayListNotification -> UpdateLiveGatewaysSnapshot", exc);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
internal void RefreshSnapshotLiveGateways_TimerCallback(object context)
{
try
{
if (ListProvider == null || !ListProvider.IsUpdatable) return;
// the listProvider.GetGateways() is not under lock.
var currentKnownGateways = ListProvider.GetGateways().GetResult();
if (logger.IsVerbose)
{
logger.Verbose("Found {0} knownGateways from Gateway listProvider {1}", currentKnownGateways.Count, Utils.EnumerableToString(currentKnownGateways));
}
// the next one will grab the lock.
UpdateLiveGatewaysSnapshot(currentKnownGateways, ListProvider.MaxStaleness);
}
catch (Exception exc)
{
logger.Error(ErrorCode.ProxyClient_GetGateways, "Exception occurred during RefreshSnapshotLiveGateways_TimerCallback -> listProvider.GetGateways()", exc);
}
}
// This function is called asynchronously from gateway refresh timer.
private void UpdateLiveGatewaysSnapshot(IEnumerable<Uri> currentKnownGateways, TimeSpan maxStaleness)
{
// this is a short lock, protecting the access to knownDead and cachedLiveGateways.
lock (lockable)
{
// now take whatever listProvider gave us and exclude those we think are dead.
var live = new List<Uri>();
var knownGateways = currentKnownGateways as IList<Uri> ?? currentKnownGateways.ToList();
foreach (Uri trial in knownGateways)
{
DateTime diedAt;
// We consider a node to be dead if we recorded it is dead due to socket error
// and it was recorded (diedAt) not too long ago (less than maxStaleness ago).
// The latter is to cover the case when the Gateway provider returns an outdated list that does not yet reflect the actually recently died Gateway.
// If it has passed more than maxStaleness - we assume maxStaleness is the upper bound on Gateway provider freshness.
bool isDead = knownDead.TryGetValue(trial, out diedAt) && DateTime.UtcNow.Subtract(diedAt) < maxStaleness;
if (!isDead)
{
live.Add(trial);
}
}
// swap cachedLiveGateways pointer in one atomic operation
cachedLiveGateways = live;
DateTime prevRefresh = lastRefreshTime;
lastRefreshTime = DateTime.UtcNow;
if (logger.IsInfo)
{
logger.Info(ErrorCode.GatewayManager_FoundKnownGateways,
"Refreshed the live GateWay list. Found {0} gateways from Gateway listProvider: {1}. Picked only known live out of them. Now has {2} live Gateways: {3}. Previous refresh time was = {4}",
knownGateways.Count(),
Utils.EnumerableToString(knownGateways),
cachedLiveGateways.Count,
Utils.EnumerableToString(cachedLiveGateways),
prevRefresh);
}
}
}
}
}
| |
using Microsoft.CSharp;
using Mono.Cecil;
using Mono.Cecil.Rocks;
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using ICustomAttributeProvider = Mono.Cecil.ICustomAttributeProvider;
using TypeAttributes = System.Reflection.TypeAttributes;
// ReSharper disable BitwiseOperatorOnEnumWithoutFlags
namespace PublicApiGenerator
{
public static class ApiGenerator
{
/// <summary>
/// Generates a public API from the specified assembly.
/// </summary>
/// <param name="assembly">The assembly to generate an API from.</param>
/// <param name="options">The options to control the API output.</param>
/// <returns>The API output.</returns>
public static string GeneratePublicApi(this Assembly assembly, ApiGeneratorOptions? options = null)
{
options ??= new ApiGeneratorOptions();
var attributeFilter = new AttributeFilter(options.ExcludeAttributes);
using (var assemblyResolver = new DefaultAssemblyResolver())
{
var assemblyPath = assembly.Location;
assemblyResolver.AddSearchDirectory(Path.GetDirectoryName(assemblyPath));
assemblyResolver.AddSearchDirectory(AppDomain.CurrentDomain.BaseDirectory);
var readSymbols = File.Exists(Path.ChangeExtension(assemblyPath, ".pdb"));
using (var asm = AssemblyDefinition.ReadAssembly(assemblyPath, new ReaderParameters(ReadingMode.Deferred)
{
ReadSymbols = readSymbols,
AssemblyResolver = assemblyResolver
}))
{
return CreatePublicApiForAssembly(
asm,
typeDefinition => !typeDefinition.IsNested &&
ShouldIncludeType(typeDefinition) &&
(options.IncludeTypes == null || options.IncludeTypes.Any(type => type.FullName == typeDefinition.FullName && type.Assembly.FullName == typeDefinition.Module.Assembly.FullName)),
options.IncludeAssemblyAttributes,
options.WhitelistedNamespacePrefixes,
attributeFilter);
}
}
}
/// <summary>
/// Generates a public API from the specified types.
/// </summary>
/// <param name="types">The types to generate an API from.</param>
/// <param name="options">The options to control the API output.</param>
/// <remarks>This method assumes all the types belong to the same assembly. The assembly of the first type <code>types[0].Assembly</code> is used.</remarks>
/// <returns>The API output.</returns>
public static string GeneratePublicApi(this Type[] types, ApiGeneratorOptions? options = null)
{
if (types.Length == 0)
{
return string.Empty;
}
(options ??= new ApiGeneratorOptions()).IncludeTypes = types;
return types[0].Assembly.GeneratePublicApi(options);
}
/// <summary>
/// Generates a public API from the specified type.
/// </summary>
/// <param name="type">The type to generate an API from.</param>
/// <param name="options">The options to control the API output.</param>
/// <returns>The API output.</returns>
public static string GeneratePublicApi(this Type type, ApiGeneratorOptions? options = null)
{
(options ??= new ApiGeneratorOptions()).IncludeTypes = new Type[] { type };
return type.Assembly.GeneratePublicApi(options);
}
[Obsolete("Use `GeneratePublicApi(this Assembly assembly, ApiGeneratorOptions? options = null)` instead. Will be removed in the next major.")]
public static string GeneratePublicApi(Assembly assembly, Type[]? includeTypes = null, bool shouldIncludeAssemblyAttributes = true, string[]? whitelistedNamespacePrefixes = null, string[]? excludeAttributes = null)
{
var options = new ApiGeneratorOptions
{
IncludeTypes = includeTypes,
IncludeAssemblyAttributes = shouldIncludeAssemblyAttributes,
ExcludeAttributes = excludeAttributes,
};
if (whitelistedNamespacePrefixes != null)
{
options.WhitelistedNamespacePrefixes = whitelistedNamespacePrefixes;
}
return GeneratePublicApi(assembly, options);
}
// TODO: Assembly references?
// TODO: Better handle namespaces - using statements? - requires non-qualified type names
static string CreatePublicApiForAssembly(AssemblyDefinition assembly, Func<TypeDefinition, bool> shouldIncludeType, bool shouldIncludeAssemblyAttributes, string[] whitelistedNamespacePrefixes, AttributeFilter attributeFilter)
{
using (var provider = new CSharpCodeProvider())
{
var compileUnit = new CodeCompileUnit();
if (shouldIncludeAssemblyAttributes && assembly.HasCustomAttributes)
{
PopulateCustomAttributes(assembly, compileUnit.AssemblyCustomAttributes, attributeFilter);
}
var publicTypes = assembly.Modules.SelectMany(m => m.GetTypes())
.Where(shouldIncludeType)
.OrderBy(t => t.FullName, StringComparer.Ordinal);
foreach (var publicType in publicTypes)
{
var @namespace = compileUnit.Namespaces.Cast<CodeNamespace>()
.FirstOrDefault(n => n.Name == publicType.Namespace);
if (@namespace == null)
{
@namespace = new CodeNamespace(publicType.Namespace);
compileUnit.Namespaces.Add(@namespace);
}
using (NullableContext.Push(publicType))
{
var typeDeclaration = CreateTypeDeclaration(publicType, whitelistedNamespacePrefixes, attributeFilter);
@namespace.Types.Add(typeDeclaration);
}
}
using (var writer = new StringWriter())
{
var cgo = new CodeGeneratorOptions
{
BracingStyle = "C",
BlankLinesBetweenMembers = false,
VerbatimOrder = false,
IndentString = " "
};
provider.GenerateCodeFromCompileUnit(compileUnit, writer, cgo);
return CodeNormalizer.NormalizeGeneratedCode(writer);
}
}
}
static bool ShouldIncludeType(TypeDefinition t)
{
return (t.IsPublic || t.IsNestedPublic || t.IsNestedFamily || t.IsNestedFamilyOrAssembly) && !t.IsCompilerGenerated();
}
static bool ShouldIncludeMember(IMemberDefinition m, string[] whitelistedNamespacePrefixes)
{
return !m.IsCompilerGenerated() && !IsDotNetTypeMember(m, whitelistedNamespacePrefixes) && !(m is FieldDefinition);
}
static bool ShouldIncludeMember(MemberAttributes memberAttributes)
{
switch (memberAttributes & MemberAttributes.AccessMask)
{
case 0: // This represents no CodeDOM keyword being specified.
case MemberAttributes.Private:
case MemberAttributes.Assembly:
case MemberAttributes.FamilyAndAssembly:
return false;
default:
return true;
}
}
static bool IsDotNetTypeMember(IMemberDefinition m, string[] whitelistedNamespacePrefixes)
{
if (m.DeclaringType?.FullName == null)
return false;
return (m.DeclaringType.FullName.StartsWith("System") || m.DeclaringType.FullName.StartsWith("Microsoft"))
&& !whitelistedNamespacePrefixes.Any(prefix => m.DeclaringType.FullName.StartsWith(prefix));
}
static void AddMemberToTypeDeclaration(CodeTypeDeclaration typeDeclaration,
IMemberDefinition typeDeclarationInfo,
IMemberDefinition memberInfo,
AttributeFilter attributeFilter)
{
using (NullableContext.Push(memberInfo))
{
if (memberInfo is MethodDefinition methodDefinition)
{
if (methodDefinition.IsConstructor)
AddCtorToTypeDeclaration(typeDeclaration, methodDefinition, attributeFilter);
else
AddMethodToTypeDeclaration(typeDeclaration, methodDefinition, attributeFilter);
}
else if (memberInfo is PropertyDefinition propertyDefinition)
{
AddPropertyToTypeDeclaration(typeDeclaration, typeDeclarationInfo, propertyDefinition, attributeFilter);
}
else if (memberInfo is EventDefinition eventDefinition)
{
AddEventToTypeDeclaration(typeDeclaration, eventDefinition, attributeFilter);
}
else if (memberInfo is FieldDefinition fieldDefinition)
{
AddFieldToTypeDeclaration(typeDeclaration, fieldDefinition, attributeFilter);
}
}
}
static CodeTypeDeclaration CreateTypeDeclaration(TypeDefinition publicType, string[] whitelistedNamespacePrefixes, AttributeFilter attributeFilter)
{
if (publicType.IsDelegate())
return CreateDelegateDeclaration(publicType, attributeFilter);
var @static = false;
TypeAttributes attributes = 0;
if (publicType.IsPublic || publicType.IsNestedPublic)
attributes |= TypeAttributes.Public;
if (publicType.IsNestedFamily || publicType.IsNestedFamilyOrAssembly)
attributes |= TypeAttributes.NestedFamily;
if (publicType.IsSealed && !publicType.IsAbstract)
attributes |= TypeAttributes.Sealed;
else if (!publicType.IsSealed && publicType.IsAbstract && !publicType.IsInterface)
attributes |= TypeAttributes.Abstract;
else if (publicType.IsSealed && publicType.IsAbstract)
@static = true;
// Static support is a hack. CodeDOM does support it, and this isn't
// correct C#, but it's good enough for our API outline
var name = publicType.Name;
var isStruct = publicType.IsValueType && !publicType.IsPrimitive && !publicType.IsEnum;
var @readonly = isStruct && publicType.CustomAttributes.Any(a =>
a.AttributeType.FullName == "System.Runtime.CompilerServices.IsReadOnlyAttribute");
var index = name.IndexOf('`');
if (index != -1)
name = name.Substring(0, index);
var declarationName = string.Empty;
if (@readonly)
declarationName += CodeNormalizer.ReadonlyMarker;
if (@static)
declarationName += CodeNormalizer.StaticMarker;
declarationName += name;
var declaration = new CodeTypeDeclaration(declarationName)
{
CustomAttributes = CreateCustomAttributes(publicType, attributeFilter),
// TypeAttributes must be specified before the IsXXX as they manipulate TypeAttributes!
TypeAttributes = attributes,
IsClass = publicType.IsClass,
IsEnum = publicType.IsEnum,
IsInterface = publicType.IsInterface,
IsStruct = isStruct,
};
if (declaration.IsInterface && publicType.BaseType != null)
throw new NotImplementedException("Base types for interfaces needs testing");
PopulateGenericParameters(publicType, declaration.TypeParameters, attributeFilter, parameter =>
{
var declaringType = publicType.DeclaringType;
while (declaringType != null)
{
if (declaringType.GenericParameters.Any(p => p.Name == parameter.Name))
return false; // https://github.com/PublicApiGenerator/PublicApiGenerator/issues/108
declaringType = declaringType.DeclaringType;
}
return true;
});
if (publicType.BaseType != null && ShouldOutputBaseType(publicType))
{
if (publicType.BaseType.FullName == "System.Enum")
{
var underlyingType = publicType.GetEnumUnderlyingType();
if (underlyingType.FullName != "System.Int32")
declaration.BaseTypes.Add(underlyingType.CreateCodeTypeReference());
}
else
declaration.BaseTypes.Add(publicType.BaseType.CreateCodeTypeReference(publicType));
}
foreach (var @interface in publicType.Interfaces.OrderBy(i => i.InterfaceType.FullName, StringComparer.Ordinal)
.Select(t => new { Reference = t, Definition = t.InterfaceType.Resolve() })
.Where(t => ShouldIncludeType(t.Definition))
.Select(t => t.Reference))
declaration.BaseTypes.Add(@interface.InterfaceType.CreateCodeTypeReference(@interface));
foreach (var memberInfo in publicType.GetMembers().Where(memberDefinition => ShouldIncludeMember(memberDefinition, whitelistedNamespacePrefixes)).OrderBy(m => m.Name, StringComparer.Ordinal))
AddMemberToTypeDeclaration(declaration, publicType, memberInfo, attributeFilter);
// Fields should be in defined order for an enum
var fields = !publicType.IsEnum
? publicType.Fields.OrderBy(f => f.Name, StringComparer.Ordinal)
: (IEnumerable<FieldDefinition>)publicType.Fields;
foreach (var field in fields)
AddMemberToTypeDeclaration(declaration, publicType, field, attributeFilter);
foreach (var nestedType in publicType.NestedTypes.Where(ShouldIncludeType).OrderBy(t => t.FullName, StringComparer.Ordinal))
{
using (NullableContext.Push(nestedType))
{
var nestedTypeDeclaration = CreateTypeDeclaration(nestedType, whitelistedNamespacePrefixes, attributeFilter);
declaration.Members.Add(nestedTypeDeclaration);
}
}
return declaration.Sort();
}
static CodeTypeDeclaration CreateDelegateDeclaration(TypeDefinition publicType, AttributeFilter attributeFilter)
{
var invokeMethod = publicType.Methods.Single(m => m.Name == "Invoke");
using (NullableContext.Push(invokeMethod)) // for delegates NullableContextAttribute is stored on Invoke method
{
var name = publicType.Name;
var index = name.IndexOf('`');
if (index != -1)
name = name.Substring(0, index);
var declaration = new CodeTypeDelegate(name)
{
Attributes = MemberAttributes.Public,
CustomAttributes = CreateCustomAttributes(publicType, attributeFilter),
ReturnType = invokeMethod.ReturnType.CreateCodeTypeReference(invokeMethod.MethodReturnType),
};
// CodeDOM. No support. Return type attributes.
PopulateCustomAttributes(invokeMethod.MethodReturnType, declaration.CustomAttributes, type => type.MakeReturn(), attributeFilter);
PopulateGenericParameters(publicType, declaration.TypeParameters, attributeFilter, _ => true);
PopulateMethodParameters(invokeMethod, declaration.Parameters, attributeFilter);
// Of course, CodeDOM doesn't support generic type parameters for delegates. Of course.
if (declaration.TypeParameters.Count > 0)
{
var parameterNames = from parameterType in declaration.TypeParameters.Cast<CodeTypeParameter>()
select parameterType.Name;
declaration.Name = string.Format(CultureInfo.InvariantCulture, "{0}<{1}>", declaration.Name, string.Join(", ", parameterNames));
}
return declaration;
}
}
static bool ShouldOutputBaseType(TypeDefinition publicType)
{
return publicType.BaseType.FullName != "System.Object" && publicType.BaseType.FullName != "System.ValueType";
}
static void PopulateGenericParameters(IGenericParameterProvider publicType, CodeTypeParameterCollection parameters, AttributeFilter attributeFilter, Func<GenericParameter, bool> shouldUseParameter)
{
foreach (var parameter in publicType.GenericParameters.Where(shouldUseParameter))
{
// A little hacky. Means we get "in" and "out" prefixed on any constraints, but it's either that
// or add it as a custom attribute
var name = parameter.Name;
if (parameter.IsCovariant)
name = "out " + name;
if (parameter.IsContravariant)
name = "in " + name;
var attributeCollection = new CodeAttributeDeclarationCollection();
if (parameter.HasCustomAttributes)
{
PopulateCustomAttributes(parameter, attributeCollection, attributeFilter);
}
var typeParameter = new CodeTypeParameter(name)
{
HasConstructorConstraint =
parameter.HasDefaultConstructorConstraint && !parameter.HasNotNullableValueTypeConstraint
};
typeParameter.CustomAttributes.AddRange(attributeCollection.OfType<CodeAttributeDeclaration>().ToArray());
var nullableConstraint = parameter.GetNullabilityMap().First();
var unmanagedConstraint = parameter.CustomAttributes.Any(attr => attr.AttributeType.FullName == "System.Runtime.CompilerServices.IsUnmanagedAttribute");
if (parameter.HasNotNullableValueTypeConstraint)
typeParameter.Constraints.Add(unmanagedConstraint ? " unmanaged" : " struct");
if (parameter.HasReferenceTypeConstraint)
typeParameter.Constraints.Add(nullableConstraint == true ? " class?" : " class");
else if (nullableConstraint == false)
typeParameter.Constraints.Add(" notnull");
using (NullableContext.Push(parameter))
{
foreach (var constraint in parameter.Constraints.Where(constraint => !IsSpecialConstraint(constraint)))
{
// for generic constraints like IEnumerable<T> call to GetElementType() returns TypeReference with Name = !0
var typeReference = constraint.ConstraintType /*.GetElementType()*/.CreateCodeTypeReference(constraint);
typeParameter.Constraints.Add(typeReference);
}
}
parameters.Add(typeParameter);
}
bool IsSpecialConstraint(GenericParameterConstraint constraint)
{
// struct
if (constraint.ConstraintType is TypeReference reference && reference.FullName == "System.ValueType")
return true;
// unmanaged
if (constraint.ConstraintType.IsUnmanaged())
return true;
return false;
}
}
static CodeAttributeDeclarationCollection CreateCustomAttributes(ICustomAttributeProvider type,
AttributeFilter attributeFilter)
{
var attributes = new CodeAttributeDeclarationCollection();
PopulateCustomAttributes(type, attributes, attributeFilter);
return attributes;
}
static void PopulateCustomAttributes(ICustomAttributeProvider type,
CodeAttributeDeclarationCollection attributes,
AttributeFilter attributeFilter)
{
PopulateCustomAttributes(type, attributes, ctr => ctr, attributeFilter);
}
static void PopulateCustomAttributes(ICustomAttributeProvider type,
CodeAttributeDeclarationCollection attributes,
Func<CodeTypeReference, CodeTypeReference> codeTypeModifier,
AttributeFilter attributeFilter)
{
foreach (var customAttribute in type.CustomAttributes.Where(attributeFilter.ShouldIncludeAttribute).OrderBy(a => a.AttributeType.FullName, StringComparer.Ordinal).ThenBy(a => ConvertAttributeToCode(codeTypeModifier, a), StringComparer.Ordinal))
{
var attribute = GenerateCodeAttributeDeclaration(codeTypeModifier, customAttribute);
attributes.Add(attribute);
}
// so this is not very cool but at least all the attribute creation is in the same place
PopulateAttributesThatDontAppearInCustomAttributes(type, attributes);
}
static void PopulateAttributesThatDontAppearInCustomAttributes(ICustomAttributeProvider type,
CodeAttributeDeclarationCollection attributes)
{
if (type is TypeDefinition typeDefinition)
{
if (typeDefinition.Attributes.HasFlag(Mono.Cecil.TypeAttributes.Serializable))
{
var attribute = new CodeAttributeDeclaration("System.SerializableAttribute");
attribute.Name = AttributeNameBuilder.Get(attribute.Name);
attributes.Add(attribute);
}
}
}
static CodeAttributeDeclaration GenerateCodeAttributeDeclaration(Func<CodeTypeReference, CodeTypeReference> codeTypeModifier, CustomAttribute customAttribute)
{
var attribute = new CodeAttributeDeclaration(codeTypeModifier(customAttribute.AttributeType.CreateCodeTypeReference(mode: NullableMode.Disable)));
attribute.Name = AttributeNameBuilder.Get(attribute.Name);
foreach (var arg in customAttribute.ConstructorArguments)
{
attribute.Arguments.Add(new CodeAttributeArgument(CreateInitialiserExpression(arg)));
}
foreach (var field in customAttribute.Fields.OrderBy(f => f.Name, StringComparer.Ordinal))
{
attribute.Arguments.Add(new CodeAttributeArgument(field.Name, CreateInitialiserExpression(field.Argument)));
}
foreach (var property in customAttribute.Properties.OrderBy(p => p.Name, StringComparer.Ordinal))
{
attribute.Arguments.Add(new CodeAttributeArgument(property.Name, CreateInitialiserExpression(property.Argument)));
}
return attribute;
}
// Litee: This method is used for additional sorting of custom attributes when multiple values are allowed
static string ConvertAttributeToCode(Func<CodeTypeReference, CodeTypeReference> codeTypeModifier, CustomAttribute customAttribute)
{
using (var provider = new CSharpCodeProvider())
{
var cgo = new CodeGeneratorOptions
{
BracingStyle = "C",
BlankLinesBetweenMembers = false,
VerbatimOrder = false
};
var attribute = GenerateCodeAttributeDeclaration(codeTypeModifier, customAttribute);
var declaration = new CodeTypeDeclaration("DummyClass")
{
CustomAttributes = new CodeAttributeDeclarationCollection(new[] { attribute }),
};
using (var writer = new StringWriter())
{
provider.GenerateCodeFromType(declaration, writer, cgo);
return writer.ToString();
}
}
}
static CodeExpression CreateInitialiserExpression(CustomAttributeArgument attributeArgument)
{
if (attributeArgument.Value is CustomAttributeArgument customAttributeArgument)
{
return CreateInitialiserExpression(customAttributeArgument);
}
if (attributeArgument.Value is CustomAttributeArgument[] customAttributeArguments)
{
var initialisers = from argument in customAttributeArguments
select CreateInitialiserExpression(argument);
return new CodeArrayCreateExpression(attributeArgument.Type.CreateCodeTypeReference(), initialisers.ToArray());
}
var type = attributeArgument.Type.Resolve();
var value = attributeArgument.Value;
if (type.BaseType != null && type.BaseType.FullName == "System.Enum")
{
var originalValue = Convert.ToInt64(value);
if (type.CustomAttributes.Any(a => a.AttributeType.FullName == "System.FlagsAttribute"))
{
//var allFlags = from f in type.Fields
// where f.Constant != null
// let v = Convert.ToInt64(f.Constant)
// where v == 0 || (originalValue & v) != 0
// select (CodeExpression)new CodeFieldReferenceExpression(typeExpression, f.Name);
//return allFlags.Aggregate((current, next) => new CodeBinaryOperatorExpression(current, CodeBinaryOperatorType.BitwiseOr, next));
// I'd rather use the above, as it's just using the CodeDOM, but it puts
// brackets around each CodeBinaryOperatorExpression
var flags = from f in type.Fields
where f.Constant != null
let v = Convert.ToInt64(f.Constant)
where v == 0 || (originalValue & v) == v
select type.FullName + "." + f.Name;
return new CodeSnippetExpression(flags.Aggregate((current, next) => current + " | " + next));
}
var allFlags = from f in type.Fields
where f.Constant != null
let v = Convert.ToInt64(f.Constant)
where v == originalValue
select new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(type.CreateCodeTypeReference()), f.Name);
return allFlags.FirstOrDefault();
}
if (type.FullName == "System.Type" && value is TypeReference typeRef)
{
return new CodeTypeOfExpression(typeRef.CreateCodeTypeReference());
}
if (value is string)
{
// CodeDOM outputs a verbatim string. Any string with \n is treated as such, so normalize
// it to make it easier for comparisons
value = Regex.Replace((string)value, @"\n", "\\n");
value = Regex.Replace((string)value, @"\r\n|\r\\n", "\\r\\n");
}
return new CodePrimitiveExpression(value);
}
static void AddCtorToTypeDeclaration(CodeTypeDeclaration typeDeclaration, MethodDefinition member, AttributeFilter attributeFilter)
{
var attributes = member.GetMethodAttributes();
if (!ShouldIncludeMember(attributes))
return;
var method = new CodeConstructor
{
CustomAttributes = CreateCustomAttributes(member, attributeFilter),
Name = member.Name,
Attributes = attributes
};
PopulateMethodParameters(member, method.Parameters, attributeFilter);
typeDeclaration.Members.Add(method);
}
static void AddMethodToTypeDeclaration(CodeTypeDeclaration typeDeclaration, MethodDefinition member, AttributeFilter attributeFilter)
{
var attributes = member.GetMethodAttributes();
if (!ShouldIncludeMember(attributes))
return;
if (member.IsSpecialName && !member.Name.StartsWith("op_")) return;
var returnType = member.ReturnType.CreateCodeTypeReference(member.MethodReturnType);
if (member.ReturnType.IsUnsafeSignatureType() || member.Parameters.Any(p => p.ParameterType.IsUnsafeSignatureType()))
returnType = returnType.MakeUnsafe();
var method = new CodeMemberMethod
{
Name = MethodNameBuilder.AugmentMethodNameWithMethodModifierMarkerTemplate(member, attributes),
Attributes = attributes,
CustomAttributes = CreateCustomAttributes(member, attributeFilter),
ReturnType = returnType,
};
PopulateCustomAttributes(member.MethodReturnType, method.ReturnTypeCustomAttributes, attributeFilter);
PopulateGenericParameters(member, method.TypeParameters, attributeFilter, _ => true);
PopulateMethodParameters(member, method.Parameters, attributeFilter, member.IsExtensionMethod());
typeDeclaration.Members.Add(method);
}
static void PopulateMethodParameters(IMethodSignature member,
CodeParameterDeclarationExpressionCollection parameters,
AttributeFilter attributeFilter,
bool isExtension = false)
{
foreach (var parameter in member.Parameters)
{
FieldDirection direction = 0;
if (parameter.IsOut)
direction |= FieldDirection.Out;
else if (parameter.ParameterType.IsByReference)
direction |= FieldDirection.Ref;
var parameterType = parameter.ParameterType;
if (parameterType is RequiredModifierType requiredModifierType)
{
parameterType = requiredModifierType.ElementType;
}
// order is crucial because a RequiredModifierType can be a ByReferenceType
if (parameterType is ByReferenceType byReferenceType)
{
parameterType = byReferenceType.ElementType;
}
var type = parameterType.CreateCodeTypeReference(parameter);
if (isExtension)
{
type = type.MakeThis();
isExtension = false;
}
// special case of ref is in
// TODO: Move CustomAttributes.Any(a => a.AttributeType.FullName == "System.Runtime.CompilerServices.IsReadOnlyAttribute") to extension method once other PR is merged
if (parameter.CustomAttributes.Any(a =>
a.AttributeType.FullName == "System.Runtime.CompilerServices.IsReadOnlyAttribute"))
{
type = type.MakeIn();
direction = FieldDirection.In;
}
var name = parameter.HasConstant
? string.Format(CultureInfo.InvariantCulture, "{0} = {1}", parameter.Name, FormatParameterConstant(parameter))
: parameter.Name;
var expression = new CodeParameterDeclarationExpression(type, name)
{
Direction = direction,
CustomAttributes = CreateCustomAttributes(parameter, attributeFilter)
};
parameters.Add(expression);
}
}
static object FormatParameterConstant(ParameterDefinition parameter)
{
if (parameter.Constant is string)
return string.Format(CultureInfo.InvariantCulture, "\"{0}\"", parameter.Constant);
if (parameter.Constant is bool b)
return b ? "true" : "false";
if (parameter.Constant != null)
return parameter.Constant;
if (parameter.ParameterType is GenericParameter genericParam)
{
if (genericParam.HasReferenceTypeConstraint)
return "null";
if (genericParam.HasNotNullableValueTypeConstraint)
return "default";
// this seems right for default
return "default";
}
return parameter.ParameterType.IsValueType ? "default" : "null";
}
static void AddPropertyToTypeDeclaration(CodeTypeDeclaration typeDeclaration, IMemberDefinition typeDeclarationInfo, PropertyDefinition member, AttributeFilter attributeFilter)
{
var getterAttributes = member.GetMethod?.GetMethodAttributes() ?? 0;
var setterAttributes = member.SetMethod?.GetMethodAttributes() ?? 0;
var hasGet = ShouldIncludeMember(getterAttributes);
var hasSet = ShouldIncludeMember(setterAttributes);
if (!(hasGet | hasSet))
return;
var propertyAttributes = CecilEx.CombineAccessorAttributes(getterAttributes, setterAttributes);
var propertyType = member.PropertyType.IsGenericParameter
? new CodeTypeReference(member.PropertyType.Name)
: member.PropertyType.CreateCodeTypeReference(member);
if (member.PropertyType.IsUnsafeSignatureType())
propertyType = propertyType.MakeUnsafe();
var property = new CodeMemberProperty
{
Name = PropertyNameBuilder.AugmentPropertyNameWithPropertyModifierMarkerTemplate(member, getterAttributes, setterAttributes),
Type = propertyType,
Attributes = propertyAttributes,
CustomAttributes = CreateCustomAttributes(member, attributeFilter),
HasGet = hasGet,
HasSet = hasSet
};
// DefaultMemberAttribute on type gets propagated to IndexerNameAttribute
var defaultMemberAttributeValue = typeDeclarationInfo.CustomAttributes.SingleOrDefault(x =>
x.AttributeType.FullName == "System.Reflection.DefaultMemberAttribute")
?.ConstructorArguments.Select(x => x.Value).OfType<string>().SingleOrDefault();
if (!string.IsNullOrEmpty(defaultMemberAttributeValue) && member.Name == defaultMemberAttributeValue && member.Name != "Item")
{
property.Name = "Item";
property.CustomAttributes.Add(
new CodeAttributeDeclaration(
AttributeNameBuilder.Get("System.Runtime.CompilerServices.IndexerNameAttribute"))
{
Arguments = {new CodeAttributeArgument(new CodePrimitiveExpression(defaultMemberAttributeValue))}
});
}
// Here's a nice hack, because hey, guess what, the CodeDOM doesn't support
// attributes on getters or setters
if (member.GetMethod != null && member.GetMethod.HasCustomAttributes)
{
PopulateCustomAttributes(member.GetMethod, property.CustomAttributes, type => type.MakeGet(), attributeFilter);
}
if (member.SetMethod != null && member.SetMethod.HasCustomAttributes)
{
PopulateCustomAttributes(member.SetMethod, property.CustomAttributes, type => type.MakeSet(), attributeFilter);
}
foreach (var parameter in member.Parameters)
{
property.Parameters.Add(
new CodeParameterDeclarationExpression(parameter.ParameterType.CreateCodeTypeReference(parameter),
parameter.Name));
}
// TODO: CodeDOM has no support for different access modifiers for getters and setters
// TODO: CodeDOM has no support for attributes on setters or getters - promote to property?
typeDeclaration.Members.Add(property);
}
static void AddEventToTypeDeclaration(CodeTypeDeclaration typeDeclaration, EventDefinition eventDefinition, AttributeFilter attributeFilter)
{
var addAccessorAttributes = eventDefinition.AddMethod.GetMethodAttributes();
var removeAccessorAttributes = eventDefinition.RemoveMethod.GetMethodAttributes();
if (!(ShouldIncludeMember(addAccessorAttributes) || ShouldIncludeMember(removeAccessorAttributes)))
return;
var @event = new CodeMemberEvent
{
Name = EventNameBuilder.AugmentEventNameWithEventModifierMarkerTemplate(eventDefinition, addAccessorAttributes, removeAccessorAttributes),
Attributes = CecilEx.CombineAccessorAttributes(addAccessorAttributes, removeAccessorAttributes),
CustomAttributes = CreateCustomAttributes(eventDefinition, attributeFilter),
Type = eventDefinition.EventType.CreateCodeTypeReference(eventDefinition)
};
typeDeclaration.Members.Add(@event);
}
static void AddFieldToTypeDeclaration(CodeTypeDeclaration typeDeclaration, FieldDefinition memberInfo, AttributeFilter attributeFilter)
{
if (memberInfo.IsPrivate || memberInfo.IsAssembly || memberInfo.IsFamilyAndAssembly || memberInfo.IsSpecialName)
return;
MemberAttributes attributes = 0;
if (memberInfo.HasConstant)
attributes |= MemberAttributes.Const;
if (memberInfo.IsFamily || memberInfo.IsFamilyOrAssembly)
attributes |= MemberAttributes.Family;
if (memberInfo.IsPublic)
attributes |= MemberAttributes.Public;
if (memberInfo.IsStatic && !memberInfo.HasConstant)
attributes |= MemberAttributes.Static;
// TODO: Values for readonly fields are set in the ctor
var codeTypeReference = memberInfo.FieldType.CreateCodeTypeReference(memberInfo);
if (memberInfo.IsInitOnly)
codeTypeReference = codeTypeReference.MakeReadonly();
if (memberInfo.FieldType.IsUnsafeSignatureType())
codeTypeReference = codeTypeReference.MakeUnsafe();
if (memberInfo.FieldType.IsVolatile())
codeTypeReference = codeTypeReference.MakeVolatile();
var field = new CodeMemberField(codeTypeReference, memberInfo.Name)
{
Attributes = attributes,
CustomAttributes = CreateCustomAttributes(memberInfo, attributeFilter)
};
if (memberInfo.HasConstant)
field.InitExpression = new CodePrimitiveExpression(memberInfo.Constant);
typeDeclaration.Members.Add(field);
}
}
}
| |
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace Lucene.Net.Util
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// A <see cref="PriorityQueue{T}"/> maintains a partial ordering of its elements such that the
/// element with least priority can always be found in constant time. Put()'s and Pop()'s
/// require log(size) time.
///
/// <para/><b>NOTE</b>: this class will pre-allocate a full array of
/// length <c>maxSize+1</c> if instantiated via the
/// <see cref="PriorityQueue(int, bool)"/> constructor with
/// <c>prepopulate</c> set to <c>true</c>. That maximum
/// size can grow as we insert elements over the time.
/// <para/>
/// @lucene.internal
/// </summary>
#if FEATURE_SERIALIZABLE
[Serializable]
#endif
public abstract class PriorityQueue<T>
{
private int size = 0;
private int maxSize;
private T[] heap;
public PriorityQueue(int maxSize)
: this(maxSize, true)
{
}
public PriorityQueue(int maxSize, bool prepopulate)
{
int heapSize;
if (0 == maxSize)
{
// We allocate 1 extra to avoid if statement in top()
heapSize = 2;
}
else
{
if (maxSize > ArrayUtil.MAX_ARRAY_LENGTH)
{
// Don't wrap heapSize to -1, in this case, which
// causes a confusing NegativeArraySizeException.
// Note that very likely this will simply then hit
// an OOME, but at least that's more indicative to
// caller that this values is too big. We don't +1
// in this case, but it's very unlikely in practice
// one will actually insert this many objects into
// the PQ:
// Throw exception to prevent confusing OOME:
throw new ArgumentException("maxSize must be <= " + ArrayUtil.MAX_ARRAY_LENGTH + "; got: " + maxSize);
}
else
{
// NOTE: we add +1 because all access to heap is
// 1-based not 0-based. heap[0] is unused.
heapSize = maxSize + 1;
}
}
// T is unbounded type, so this unchecked cast works always:
T[] h = new T[heapSize];
this.heap = h;
this.maxSize = maxSize;
if (prepopulate)
{
// If sentinel objects are supported, populate the queue with them
T sentinel = GetSentinelObject();
if (!EqualityComparer<T>.Default.Equals(sentinel, default(T)))
{
heap[1] = sentinel;
for (int i = 2; i < heap.Length; i++)
{
heap[i] = GetSentinelObject();
}
size = maxSize;
}
}
}
/// <summary>
/// Determines the ordering of objects in this priority queue. Subclasses
/// must define this one method. </summary>
/// <returns> <c>true</c> if parameter <paramref name="a"/> is less than parameter <paramref name="b"/>. </returns>
protected internal abstract bool LessThan(T a, T b);
/// <summary>
/// This method can be overridden by extending classes to return a sentinel
/// object which will be used by the <see cref="PriorityQueue(int, bool)"/>
/// constructor to fill the queue, so that the code which uses that queue can always
/// assume it's full and only change the top without attempting to insert any new
/// object.
/// <para/>
/// Those sentinel values should always compare worse than any non-sentinel
/// value (i.e., <see cref="LessThan(T, T)"/> should always favor the
/// non-sentinel values).
/// <para/>
/// By default, this method returns <c>false</c>, which means the queue will not be
/// filled with sentinel values. Otherwise, the value returned will be used to
/// pre-populate the queue. Adds sentinel values to the queue.
/// <para/>
/// If this method is extended to return a non-null value, then the following
/// usage pattern is recommended:
///
/// <code>
/// // extends GetSentinelObject() to return a non-null value.
/// PriorityQueue<MyObject> pq = new MyQueue<MyObject>(numHits);
/// // save the 'top' element, which is guaranteed to not be null.
/// MyObject pqTop = pq.Top;
/// <...>
/// // now in order to add a new element, which is 'better' than top (after
/// // you've verified it is better), it is as simple as:
/// pqTop.Change().
/// pqTop = pq.UpdateTop();
/// </code>
/// <para/>
/// <b>NOTE:</b> if this method returns a non-<c>null</c> value, it will be called by
/// the <see cref="PriorityQueue(int, bool)"/> constructor
/// <see cref="Count"/> times, relying on a new object to be returned and will not
/// check if it's <c>null</c> again. Therefore you should ensure any call to this
/// method creates a new instance and behaves consistently, e.g., it cannot
/// return <c>null</c> if it previously returned non-<c>null</c>.
/// </summary>
/// <returns> The sentinel object to use to pre-populate the queue, or <c>null</c> if
/// sentinel objects are not supported. </returns>
protected virtual T GetSentinelObject()
{
return default(T);
}
/// <summary>
/// Adds an Object to a <see cref="PriorityQueue{T}"/> in log(size) time. If one tries to add
/// more objects than <see cref="maxSize"/> from initialize and it is not possible to resize
/// the heap, an <see cref="IndexOutOfRangeException"/> is thrown.
/// </summary>
/// <returns> The new 'top' element in the queue. </returns>
public T Add(T element)
{
size++;
heap[size] = element;
UpHeap();
return heap[1];
}
/// <summary>
/// Adds an Object to a <see cref="PriorityQueue{T}"/> in log(size) time.
/// It returns the object (if any) that was
/// dropped off the heap because it was full. This can be
/// the given parameter (in case it is smaller than the
/// full heap's minimum, and couldn't be added), or another
/// object that was previously the smallest value in the
/// heap and now has been replaced by a larger one, or <c>null</c>
/// if the queue wasn't yet full with <see cref="maxSize"/> elements.
/// </summary>
public virtual T InsertWithOverflow(T element)
{
if (size < maxSize)
{
Add(element);
return default(T);
}
else if (size > 0 && !LessThan(element, heap[1]))
{
T ret = heap[1];
heap[1] = element;
UpdateTop();
return ret;
}
else
{
return element;
}
}
/// <summary>
/// Returns the least element of the <see cref="PriorityQueue{T}"/> in constant time.
/// Returns <c>null</c> if the queue is empty. </summary>
public T Top
{
get
{
// We don't need to check size here: if maxSize is 0,
// then heap is length 2 array with both entries null.
// If size is 0 then heap[1] is already null.
return heap[1];
}
}
/// <summary>
/// Removes and returns the least element of the <see cref="PriorityQueue{T}"/> in log(size)
/// time.
/// </summary>
public T Pop()
{
if (size > 0)
{
T result = heap[1]; // save first value
heap[1] = heap[size]; // move last to first
heap[size] = default(T); // permit GC of objects
size--;
DownHeap(); // adjust heap
return result;
}
else
{
return default(T);
}
}
/// <summary>
/// Should be called when the Object at top changes values. Still log(n) worst
/// case, but it's at least twice as fast to
///
/// <code>
/// pq.Top.Change();
/// pq.UpdateTop();
/// </code>
///
/// instead of
///
/// <code>
/// o = pq.Pop();
/// o.Change();
/// pq.Push(o);
/// </code>
/// </summary>
/// <returns> The new 'top' element. </returns>
public T UpdateTop()
{
DownHeap();
return heap[1];
}
/// <summary>
/// Returns the number of elements currently stored in the <see cref="PriorityQueue{T}"/>.
/// NOTE: This was size() in Lucene.
/// </summary>
public int Count
{
get { return size; }
}
/// <summary>
/// Removes all entries from the <see cref="PriorityQueue{T}"/>. </summary>
public void Clear()
{
for (int i = 0; i <= size; i++)
{
heap[i] = default(T);
}
size = 0;
}
private void UpHeap()
{
int i = size;
T node = heap[i]; // save bottom node
int j = (int)((uint)i >> 1);
while (j > 0 && LessThan(node, heap[j]))
{
heap[i] = heap[j]; // shift parents down
i = j;
j = (int)((uint)j >> 1);
}
heap[i] = node; // install saved node
}
private void DownHeap()
{
int i = 1;
T node = heap[i]; // save top node
int j = i << 1; // find smaller child
int k = j + 1;
if (k <= size && LessThan(heap[k], heap[j]))
{
j = k;
}
while (j <= size && LessThan(heap[j], node))
{
heap[i] = heap[j]; // shift up child
i = j;
j = i << 1;
k = j + 1;
if (k <= size && LessThan(heap[k], heap[j]))
{
j = k;
}
}
heap[i] = node; // install saved node
}
/// <summary>
/// This method returns the internal heap array as T[].
/// <para/>
/// @lucene.internal
/// </summary>
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
protected T[] HeapArray
{
get { return heap; }
}
}
}
| |
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Itinero.Algorithms.Collections;
using Itinero.Algorithms.Contracted.Witness;
using Itinero.Algorithms.PriorityQueues;
using Itinero.Algorithms.Weights;
using Itinero.Graphs.Directed;
using Itinero.Logging;
namespace Itinero.Algorithms.Contracted
{
public class FastHierarchyBuilder<T> : AlgorithmBase
where T : struct
{
protected readonly DirectedMetaGraph _graph;
private readonly static Logger _logger = Logger.Create("HierarchyBuilder");
protected readonly WeightHandler<T> _weightHandler;
private readonly HugeDictionary<uint, int> _contractionCount;
private readonly HugeDictionary<long, int> _depth;
protected VertexInfo<T> _vertexInfo;
public const float E = 0.001f;
#if PCL
NeighbourWitnessCalculator WitnessCalculators = new NeighbourWitnessCalculator();
#else
ThreadLocal<NeighbourWitnessCalculator> WitnessCalculators = new ThreadLocal<NeighbourWitnessCalculator>(() =>
{
return new NeighbourWitnessCalculator();
});
#endif
/// <summary>
/// Creates a new hierarchy builder.
/// </summary>
public FastHierarchyBuilder(DirectedMetaGraph graph,
WeightHandler<T> weightHandler)
{
weightHandler.CheckCanUse(graph);
_graph = graph;
_weightHandler = weightHandler;
_vertexInfo = new VertexInfo<T>();
_depth = new HugeDictionary<long, int>();
_contractionCount = new HugeDictionary<uint, int>();
this.DifferenceFactor = 4;
this.DepthFactor = 14;
this.ContractedFactor = 1;
}
private BinaryHeap<uint> _queue; // the vertex-queue.
private DirectedGraph _witnessGraph; // the graph with all the witnesses.
protected BitArray32 _contractedFlags; // contains flags for contracted vertices.
private int _k = 200; // The amount of queue 'misses' before recalculation of queue.
private int _misses; // Holds a counter of all misses.
private Queue<bool> _missesQueue; // Holds the misses queue.
/// <summary>
/// Gets or sets the difference factor.
/// </summary>
public int DifferenceFactor { get; set; }
/// <summary>
/// Gets or sets the depth factor.
/// </summary>
public int DepthFactor { get; set; }
/// <summary>
/// Gets or sets the contracted factor.
/// </summary>
public int ContractedFactor { get; set; }
//private Itinero.Algorithms.Contracted.Dual.Witness.NeighbourWitnessCalculator _witnessCalculator = null;
private void InitializeWitnessGraph()
{
_logger.Log(TraceEventType.Information, "Initializing witness graph...");
_witnessGraph = new DirectedGraph(2, _graph.VertexCount);
#if NETSTANDARD2_0
System.Threading.Tasks.Parallel.For(0, _graph.VertexCount, (v) =>
{
WitnessCalculators.Value.Run(_graph.Graph, _witnessGraph, (uint) v, null);
});
#elif PCL
for (uint v = 0; v < _graph.VertexCount; v++)
{
WitnessCalculators.Run(_graph.Graph, _witnessGraph, (uint)v, null);
}
#else
for (uint v = 0; v < _graph.VertexCount; v++)
{
WitnessCalculators.Value.Run(_graph.Graph, _witnessGraph, (uint) v, null);
}
#endif
}
/// <summary>
/// Remove all witnessed edges.
/// </summary>
private void RemoveWitnessedEdges()
{
_logger.Log(TraceEventType.Information, "Removing witnessed edges...");
var witnessEdgeEnumerator = _witnessGraph.GetEdgeEnumerator();
var edgeEnumerator = _graph.GetEdgeEnumerator();
var edges = new List<MetaEdge>();
for (uint vertex = 0; vertex < _graph.VertexCount; vertex++)
{
// collect all relevant edges.
edges.Clear();
if (witnessEdgeEnumerator.MoveTo(vertex) &&
edgeEnumerator.MoveTo(vertex))
{
while (edgeEnumerator.MoveNext())
{
if (vertex < edgeEnumerator.Neighbour)
{ // only check in on directions, all edges are added twice initially.
edges.Add(edgeEnumerator.Current);
}
}
}
// check witness paths.
for (var i = 0; i < edges.Count; i++)
{
var edge = edges[0];
while (witnessEdgeEnumerator.MoveNext())
{
if (witnessEdgeEnumerator.Neighbour == edge.Neighbour)
{ // this edge is witnessed, figure out how.
var forwardWitnessWeight = DirectedGraphExtensions.FromData(witnessEdgeEnumerator.Data0);
var backwardWitnessWeight = DirectedGraphExtensions.FromData(witnessEdgeEnumerator.Data1);
var weightAndDir = _weightHandler.GetEdgeWeight(edge);
var weight = _weightHandler.GetMetric(weightAndDir.Weight);
var witnessed = false;
if (weightAndDir.Direction.F &&
weight > forwardWitnessWeight)
{ // witnessed in forward direction.
weightAndDir.Direction = new Dir(false, weightAndDir.Direction.B);
witnessed = true;
}
if (weightAndDir.Direction.B &&
weight > backwardWitnessWeight)
{ // witnessed in backward direction.
weightAndDir.Direction = new Dir(weightAndDir.Direction.F, false);
witnessed = true;
}
if (witnessed)
{ // edge was witnessed, do something.
// remove the edge (in both directions)
_graph.RemoveEdge(vertex, edge.Neighbour);
_graph.RemoveEdge(edge.Neighbour, vertex);
if (weightAndDir.Direction.B || weightAndDir.Direction.F)
{ // add it again if there is something relevant still left.
_weightHandler.AddEdge(_graph, vertex, edge.Neighbour, Constants.NO_VERTEX,
weightAndDir.Direction.AsNullableBool(), weightAndDir.Weight);
weightAndDir.Direction.Reverse();
_weightHandler.AddEdge(_graph, edge.Neighbour, vertex, Constants.NO_VERTEX,
weightAndDir.Direction.AsNullableBool(), weightAndDir.Weight);
}
}
}
}
}
}
}
/// <summary>
/// Updates the vertex info object with the given vertex.
/// </summary>
/// <returns>True if succeeded, false if a witness calculation is required.</returns>
private bool UpdateVertexInfo(uint v)
{
var contracted = 0;
var depth = 0;
// update vertex info.
_vertexInfo.Clear();
_vertexInfo.Vertex = v;
_contractionCount.TryGetValue(v, out contracted);
_vertexInfo.ContractedNeighbours = contracted;
_depth.TryGetValue(v, out depth);
_vertexInfo.Depth = depth;
// add neighbours.
_vertexInfo.AddRelevantEdges(_graph.GetEdgeEnumerator());
// check if any of neighbours are in witness queue.
if (_witnessQueue.Count > 0)
{
for (var i = 0; i < _vertexInfo.Count; i++)
{
var m = _vertexInfo[i];
if (_witnessQueue.Contains(m.Neighbour))
{
//this.DoWitnessQueue();
//break;
return false;
}
}
}
// build shortcuts.
_vertexInfo.BuildShortcuts(_weightHandler);
// remove witnessed shortcuts.
_vertexInfo.RemoveShortcuts(_witnessGraph, _weightHandler);
return true;
}
/// <summary>
/// Excutes the actual run.
/// </summary>
protected override void DoRun(CancellationToken cancellationToken)
{
_queue = new BinaryHeap<uint>((uint) _graph.VertexCount);
_contractedFlags = new BitArray32(_graph.VertexCount); // is this strictly needed?
_missesQueue = new Queue<bool>();
this.InitializeWitnessGraph();
this.RemoveWitnessedEdges();
this.CalculateQueue((uint) _graph.VertexCount);
_logger.Log(TraceEventType.Information, "Started contraction...");
this.SelectNext((uint) _graph.VertexCount);
var latestProgress = 0f;
var current = 0;
var total = _graph.VertexCount;
var toDoCount = total;
while (_queue.Count > 0)
{
// contract...
this.Contract();
// ... and select next.
this.SelectNext((uint) _graph.VertexCount);
// calculate and log progress.
var progress = (float) (System.Math.Floor(((double) current / (double) total) * 10000) / 100.0);
if (progress < 99)
{
progress = (float) (System.Math.Floor(((double) current / (double) total) * 100) / 1.0);
}
if (progress != latestProgress)
{
latestProgress = progress;
int totaEdges = 0;
int totalUncontracted = 0;
int maxCardinality = 0;
var neighbourCount = new Dictionary<uint, int>();
for (uint v = 0; v < _graph.VertexCount; v++)
{
if (!_contractedFlags[v])
{
neighbourCount.Clear();
var edges = _graph.GetEdgeEnumerator(v);
if (edges != null)
{
var edgesCount = edges.Count;
totaEdges = edgesCount + totaEdges;
if (maxCardinality < edgesCount)
{
maxCardinality = edgesCount;
}
}
totalUncontracted++;
}
}
var density = (double) totaEdges / (double) totalUncontracted;
_logger.Log(TraceEventType.Information, "Preprocessing... {0}% [{1}/{2}] {3}q #{4} max {5}",
progress, current, total, _queue.Count, density, maxCardinality);
}
current++;
}
}
/// <summary>
/// Calculates the entire queue.
/// </summary>
private void CalculateQueue(uint size)
{
_logger.Log(TraceEventType.Information, "Calculating queue...");
this.DoWitnessQueue();
localQueue.Clear();
long witnessed = 0;
long total = 0;
_queue.Clear();
for (uint v = 0; v < _graph.VertexCount; v++)
{
if (!_contractedFlags[v])
{
// update vertex info.
if (this.UpdateVertexInfo(v))
{
witnessed++;
}
total++;
// calculate priority.
var priority = _vertexInfo.Priority(_graph, _weightHandler, this.DifferenceFactor, this.ContractedFactor, this.DepthFactor);
// queue vertex.
_queue.Push(v, priority);
if (_queue.Count >= size)
{
break;
}
}
}
// _logger.Log(TraceEventType.Information, "Queue calculated: {0}/{1} have witnesses.",
// witnessed, total);
}
private HashSet<uint> localQueue = new HashSet<uint>();
private int MaxLocalQueueSize = 1;
private void FlushLocalQueue()
{
this.DoWitnessQueue();
foreach (var queued in localQueue)
{
this.UpdateVertexInfo(queued);
var localPriority = _vertexInfo.Priority(_graph, _weightHandler, this.DifferenceFactor, this.ContractedFactor,
this.DepthFactor);
_queue.Push(queued, localPriority);
}
localQueue.Clear();
}
/// <summary>
/// Select the next vertex to contract.
/// </summary>
/// <returns></returns>
protected virtual void SelectNext(uint queueSize)
{
// first check the first of the current queue.
while (_queue.Count > 0)
{ // get the first vertex and check.
var first = _queue.Peek();
if (_contractedFlags[first])
{ // already contracted, priority was updated.
_queue.Pop();
continue;
}
//this.UpdateVertexInfo(first);
//keep trying until local queue is full.
while (true)
{
if (this.UpdateVertexInfo(first))
{ // update succeed.
break;
}
// move queues.
_queue.Pop();
localQueue.Add(first);
if (localQueue.Count > MaxLocalQueueSize ||
_queue.Count == 0)
{ // if over max or queue empty do local queue.
this.FlushLocalQueue();
this.SelectNext(queueSize);
return;
}
// checkout the next one.
first = _queue.Peek();
while (_contractedFlags[first])
{ // already contracted, priority was updated.
_queue.Pop();
if (_queue.Count == 0)
{
this.FlushLocalQueue();
this.SelectNext(queueSize);
return;
}
first = _queue.Peek();
}
}
// the lazy updating part!
var queuedPriority = _queue.PeekWeight();
// calculate priority
var priority = _vertexInfo.Priority(_graph, _weightHandler, this.DifferenceFactor, this.ContractedFactor,
this.DepthFactor);
if (priority != queuedPriority)
{ // a succesfull update.
_missesQueue.Enqueue(true);
_misses++;
}
else
{ // an unsuccessfull update.
_missesQueue.Enqueue(false);
}
if (_missesQueue.Count > _k)
{ // dequeue and update the misses.
if (_missesQueue.Dequeue())
{
_misses--;
}
}
// if the misses are _k
if (_misses == _k)
{ // recalculation.
this.CalculateQueue(queueSize);
// clear misses.
_missesQueue.Clear();
_misses = 0;
}
else
{ // recalculation.
if (priority != queuedPriority)
{ // re-enqueue.
_queue.Pop();
_queue.Push(first, priority);
}
else
{ // selection succeeded.
_queue.Pop();
return;
}
}
}
return; // all nodes have been contracted.
}
protected HashSet<uint> _witnessQueue = new HashSet<uint>();
/// <summary>
/// Contracts the given vertex.
/// </summary>
protected virtual void Contract()
{
var vertex = _vertexInfo.Vertex;
// remove 'downward' edge to vertex.
var i = 0;
while (i < _vertexInfo.Count)
{
var edge = _vertexInfo[i];
_graph.RemoveEdge(edge.Neighbour, vertex);
i++;
// TOOD: what to do when stuff is only removed, is nothing ok?
//_witnessQueue.Add(edge.Neighbour);
}
// add shortcuts.
foreach (var s in _vertexInfo.Shortcuts)
{
var shortcut = s.Value;
var edge = s.Key;
if (edge.Vertex1 == edge.Vertex2)
{ // TODO: figure out how this is possible, it shouldn't!
continue;
}
var forwardMetric = _weightHandler.GetMetric(shortcut.Forward);
var backwardMetric = _weightHandler.GetMetric(shortcut.Backward);
if (forwardMetric > 0 && forwardMetric < float.MaxValue &&
backwardMetric > 0 && backwardMetric < float.MaxValue &&
System.Math.Abs(backwardMetric - forwardMetric) < FastHierarchyBuilder<float>.E)
{ // forward and backward and identical weights.
_weightHandler.AddOrUpdateEdge(_graph, edge.Vertex1, edge.Vertex2,
vertex, null, shortcut.Forward);
_weightHandler.AddOrUpdateEdge(_graph, edge.Vertex2, edge.Vertex1,
vertex, null, shortcut.Backward);
_witnessQueue.Add(edge.Vertex1);
_witnessQueue.Add(edge.Vertex2);
}
else
{
if (forwardMetric > 0 && forwardMetric < float.MaxValue)
{
_weightHandler.AddOrUpdateEdge(_graph, edge.Vertex1, edge.Vertex2,
vertex, true, shortcut.Forward);
_weightHandler.AddOrUpdateEdge(_graph, edge.Vertex2, edge.Vertex1,
vertex, false, shortcut.Forward);
_witnessQueue.Add(edge.Vertex1);
_witnessQueue.Add(edge.Vertex2);
}
if (backwardMetric > 0 && backwardMetric < float.MaxValue)
{
_weightHandler.AddOrUpdateEdge(_graph, edge.Vertex1, edge.Vertex2,
vertex, false, shortcut.Backward);
_weightHandler.AddOrUpdateEdge(_graph, edge.Vertex2, edge.Vertex1,
vertex, true, shortcut.Backward);
_witnessQueue.Add(edge.Vertex1);
_witnessQueue.Add(edge.Vertex2);
}
}
}
_contractedFlags[vertex] = true;
this.NotifyContracted(vertex);
}
private void DoWitnessQueue()
{
if (_witnessQueue.Count > 0)
{
#if NETSTANDARD2_0
System.Threading.Tasks.Parallel.ForEach(_witnessQueue, (v) =>
{
WitnessCalculators.Value.Run(_graph.Graph, _witnessGraph, (uint) v, _witnessQueue);
});
#elif PCL
for (uint v = 0; v < _graph.VertexCount; v++)
{
WitnessCalculators.Run(_graph.Graph, _witnessGraph, (uint)v, _witnessQueue);
}
#else
foreach (var v in _witnessQueue)
{
WitnessCalculators.Value.Run(_graph.Graph, _witnessGraph, (uint)v, _witnessQueue);
}
#endif
_witnessQueue.Clear();
if (_witnessGraph.EdgeSpaceCount > _witnessGraph.EdgeCount * 8)
{
_witnessGraph.Compress();
_logger.Log(TraceEventType.Information, "Witnessgraph size: {0}", _witnessGraph.EdgeCount);
}
}
}
private DirectedMetaGraph.EdgeEnumerator _edgeEnumerator = null;
/// <summary>
/// Notifies this calculator that the given vertex was contracted.
/// </summary>
public void NotifyContracted(uint vertex)
{
// removes the contractions count.
_contractionCount.Remove(vertex);
// loop over all neighbours.
if (_edgeEnumerator == null)
{
_edgeEnumerator = _graph.GetEdgeEnumerator();
}
_edgeEnumerator.MoveTo(vertex);
int vertexDepth = 0;
_depth.TryGetValue(vertex, out vertexDepth);
_depth.Remove(vertex);
vertexDepth++;
// store the depth.
_edgeEnumerator.Reset();
while (_edgeEnumerator.MoveNext())
{
var neighbour = _edgeEnumerator.Neighbour;
int depth = 0;
_depth.TryGetValue(neighbour, out depth);
if (vertexDepth >= depth)
{
_depth[neighbour] = vertexDepth;
}
int count;
if (!_contractionCount.TryGetValue(neighbour, out count))
{
_contractionCount[neighbour] = 1;
}
else
{
count++;
_contractionCount[neighbour] = count;
}
if (_witnessGraph.VertexCount > vertex &&
_witnessGraph.VertexCount > neighbour)
{
_witnessGraph.RemoveEdge(neighbour, vertex);
}
}
if (_witnessGraph.VertexCount > vertex)
{
_witnessGraph.RemoveEdges(vertex);
}
}
}
public sealed class FastHierarchyBuilder : FastHierarchyBuilder<float>
{
/// <summary>
/// Creates a new hierarchy builder.
/// </summary>
public FastHierarchyBuilder(DirectedMetaGraph graph,
WeightHandler<float> weightHandler) : base(graph, weightHandler)
{
}
/// <summary>
/// Contracts the given vertex.
/// </summary>
protected override void Contract()
{
var vertex = _vertexInfo.Vertex;
// remove 'downward' edge to vertex.
var i = 0;
while (i < _vertexInfo.Count)
{
var edge = _vertexInfo[i];
_graph.RemoveEdge(edge.Neighbour, vertex);
i++;
// TOOD: what to do when stuff is only removed, is nothing ok?
//_witnessQueue.Add(edge.Neighbour);
}
// add shortcuts.
foreach (var s in _vertexInfo.Shortcuts)
{
var shortcut = s.Value;
var edge = s.Key;
if (edge.Vertex1 == edge.Vertex2)
{ // TODO: figure out how this is possible, it shouldn't!
continue;
}
var forwardMetric = shortcut.Forward;
var backwardMetric = shortcut.Backward;
if (forwardMetric > 0 && forwardMetric < float.MaxValue &&
backwardMetric > 0 && backwardMetric < float.MaxValue &&
System.Math.Abs(backwardMetric - forwardMetric) < FastHierarchyBuilder<float>.E)
{ // forward and backward and identical weights.
_weightHandler.AddOrUpdateEdge(_graph, edge.Vertex1, edge.Vertex2,
vertex, null, shortcut.Forward);
_weightHandler.AddOrUpdateEdge(_graph, edge.Vertex2, edge.Vertex1,
vertex, null, shortcut.Backward);
_witnessQueue.Add(edge.Vertex1);
_witnessQueue.Add(edge.Vertex2);
}
else
{
if (forwardMetric > 0 && forwardMetric < float.MaxValue)
{
_weightHandler.AddOrUpdateEdge(_graph, edge.Vertex1, edge.Vertex2,
vertex, true, shortcut.Forward);
_weightHandler.AddOrUpdateEdge(_graph, edge.Vertex2, edge.Vertex1,
vertex, false, shortcut.Forward);
_witnessQueue.Add(edge.Vertex1);
_witnessQueue.Add(edge.Vertex2);
}
if (backwardMetric > 0 && backwardMetric < float.MaxValue)
{
_weightHandler.AddOrUpdateEdge(_graph, edge.Vertex1, edge.Vertex2,
vertex, false, shortcut.Backward);
_weightHandler.AddOrUpdateEdge(_graph, edge.Vertex2, edge.Vertex1,
vertex, true, shortcut.Backward);
_witnessQueue.Add(edge.Vertex1);
_witnessQueue.Add(edge.Vertex2);
}
}
}
_contractedFlags[vertex] = true;
this.NotifyContracted(vertex);
}
}
public static class DirectedGraphExtensions
{
public static void AddOrUpdateEdge(this DirectedGraph graph, uint vertex1, uint vertex2, float forward, float backward)
{
if (vertex1 > vertex2)
{
var t = vertex2;
vertex2 = vertex1;
vertex1 = t;
var tw = backward;
backward = forward;
forward = tw;
}
var dataForward = ToData(forward);
var dataBackward = ToData(backward);
var data = new uint[] { dataForward, dataBackward };
if (graph.UpdateEdgeIfBetter(vertex1, vertex2, (d) =>
{
var existingForward = FromData(d[0]);
var existingBackward = FromData(d[1]);
var update = false;
if (existingForward > forward)
{ // update, what we have here is better.
update = true;
}
else
{ // take what's there, it's better.
data[0] = d[0];
}
if (existingBackward > backward)
{ // update, what we have here is better.
update = true;
}
else
{ // take what's there, it's better.
data[1] = d[1];
}
return update;
}, data) == Constants.NO_EDGE)
{ // was not updated.
graph.AddEdge(vertex1, vertex2, data);
}
}
public static uint ToData(float weight)
{
if (weight == float.MaxValue)
{
return uint.MaxValue;
}
return (uint) (weight * 1000);
}
public static float FromData(uint data)
{
if (data == uint.MaxValue)
{
return float.MaxValue;
}
return data / 1000.0f;
}
}
}
| |
// #define EnableTokensOutput
// Copyright (c) Alexandre Mutel. All rights reserved.
// Licensed under the BSD-Clause 2 license. See license.txt file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using DotLiquid.Tests.Tags;
using NUnit.Framework;
using Scriban.Helpers;
using Scriban.Parsing;
using Scriban.Runtime;
using Scriban.Syntax;
using static Scriban.Tests.TestFilesHelper;
namespace Scriban.Tests
{
[TestFixture]
public class TestParser
{
private const string BuiltinMarkdownDocFile = @"..\..\..\..\..\doc\builtins.md";
[Test]
public void TestRoundtrip()
{
var text = "This is a text {{ code # With some comment }} and a text";
AssertRoundtrip(text);
}
[Test]
public void TestScribanIfElseFunction()
{
var template = Template.Parse(@"
func testIfElse
if $0 < 0
ret 1
else
ret 0
end
ret -1
end
testIfElse testValue
", lexerOptions: new LexerOptions { KeepTrivia = false, Mode = ScriptMode.ScriptOnly });
var templateContext = new TemplateContext
{
LoopLimit = int.MaxValue,
};
templateContext.BuiltinObject.SetValue("testValue", -1, true);
var result = template.Evaluate(templateContext);
Assert.AreEqual(1, result);
templateContext.BuiltinObject.SetValue("testValue", 1, true);
result = template.Evaluate(templateContext);
Assert.AreEqual(0, result); // returns null
}
[Test]
public void TestRoundtrip1()
{
var text = "This is a text {{ code | pipe a b c | a + b }} and a text";
AssertRoundtrip(text);
}
[Test]
public void TestLiquidMissingClosingBrace()
{
var template = Template.ParseLiquid("{%endunless");
Assert.True(template.HasErrors);
Assert.AreEqual(1, template.Messages.Count);
Assert.AreEqual("<input>(1,3) : error : Unable to find a pending `unless` for this `endunless`", template.Messages[0].ToString());
}
[Test]
public void TestLiquidInvalidStringEscape()
{
var template = Template.ParseLiquid(@"{%""\u""");
Assert.True(template.HasErrors);
}
[TestCase("1-2", -1, "1 - 2")]
[TestCase("-5|>math.abs", 5, "-5 |> math.abs")]
[TestCase("-5*2|>math.abs", 10, "-5 * 2 |> math.abs")]
[TestCase("2x", 2, "2 * x")]
[TestCase("10x/2", 5.0, "(10 * x) / 2")]
[TestCase("10x y + y", 22, "10 * x * y + y")]
[TestCase("10x * y + 3y + 1 + 2", 29, "10 * x * y + 3 * y + 1 + 2")]
[TestCase("2 y math.abs z * 5 // 2 + 1 + z", 91, "2 * y * math.abs((z * 5) // 2) + 1 + z")] // 2 * 2 * abs(-10) * 5 / 2 + 1 + (-10) = 91
[TestCase("2 y math.abs z * 5 // 2 + 1 * 3 + z + 17", 110, "2 * y * math.abs((z * 5) // 2) + 1 * 3 + z + 17")] // 2 * 2 * abs(-10) * 5 / 2 + 3 + (-10) + 17 = 110
[TestCase("2^3^4", 4096, "(2 ^ 3) ^ 4")]
[TestCase("3y^2 + 3x", 15, "3 * (y ^ 2) + 3 * x")]
[TestCase("1 + 2 + 3x + 4y + z", 4, "1 + 2 + 3 * x + 4 * y + z")]
[TestCase("y^5 * 2 + 1", 65, "(y ^ 5) * 2 + 1")]
[TestCase("y^5 // 2 + 1", 17, "((y ^ 5) // 2) + 1")]
[TestCase("f(x)= x*2 +1* 50; f(10* 2)", 90, "f(x) = x * 2 + 1 * 50; f(10 * 2)")]
[TestCase("f(x)= x*2 +1* 50; 10* 2|>f", 90, "f(x) = x * 2 + 1 * 50; 10 * 2 |> f")]
// int binaries
[TestCase("1 << 2", 4, "1 << 2")]
[TestCase("8 >> 2", 2, "8 >> 2")]
[TestCase("1 | 2", 3, "1 | 2")]
[TestCase("3 & 2", 2, "3 & 2")]
// long
[TestCase("10000000000 + 1", (long)10000000000 + 1, "10000000000 + 1")]
[TestCase("10000000000 - 1", (long)10000000000 - 1, "10000000000 - 1")]
[TestCase("10000000000 * 3", (long)10000000000 * 3, "10000000000 * 3")]
[TestCase("10000000000 / 3", (double)10000000000 / 3, "10000000000 / 3")]
[TestCase("10000000000 // 3", (long)10000000000 / 3, "10000000000 // 3")]
[TestCase("10000000000 << 2", (long)10000000000 << 2, "10000000000 << 2")]
[TestCase("10000000000 >> 2", (long)10000000000 >> 2, "10000000000 >> 2")]
[TestCase("10000000001 | 2", (long)10000000001 | 2, "10000000001 | 2")]
[TestCase("10000000003 & 2", (long)10000000003 & 2, "10000000003 & 2")]
[TestCase("10000000003 % 7", (long)10000000003 % 7, "10000000003 % 7")]
[TestCase("10000000003 == 7", 10000000003 == 7, "10000000003 == 7")]
[TestCase("10000000003 != 7", 10000000003 != 7, "10000000003 != 7")]
[TestCase("10000000003 < 7", 10000000003 < 7, "10000000003 < 7")]
[TestCase("10000000003 > 7", 10000000003 > 7, "10000000003 > 7")]
[TestCase("10000000003 <= 7", 10000000003 <= 7, "10000000003 <= 7")]
[TestCase("10000000003 >= 7", 10000000003 >= 7, "10000000003 >= 7")]
// float
[TestCase("1.0f + 2.0f", 1.0f + 2.0f, "1.0f + 2.0f")]
[TestCase("1.0f - 2.0f", 1.0f - 2.0f, "1.0f - 2.0f")]
[TestCase("2.0f * 3.0f", 2.0f * 3.0f, "2.0f * 3.0f")]
[TestCase("2.0f / 3.0f", 2.0f / 3.0f, "2.0f / 3.0f")]
[TestCase("4.0f // 3.0f", (float)(int)(4.0f / 3.0f), "4.0f // 3.0f")]
[TestCase("4.0f ^ 2.0f", (float)16.0, "4.0f ^ 2.0f")]
[TestCase("4.0f << 1", (float)4.0f * 2.0f, "4.0f << 1")]
[TestCase("4.0f >> 1", (float)4.0f / 2.0f, "4.0f >> 1")]
[TestCase("4.0f % 3.0f", (float)4.0f % 3.0f, "4.0f % 3.0f")]
[TestCase("4.0f == 3.0f", 4.0f == 3.0f, "4.0f == 3.0f")]
[TestCase("4.0f != 3.0f", 4.0f != 3.0f, "4.0f != 3.0f")]
[TestCase("4.0f < 3.0f", 4.0f < 3.0f, "4.0f < 3.0f")]
[TestCase("4.0f > 3.0f", 4.0f > 3.0f, "4.0f > 3.0f")]
[TestCase("4.0f <= 3.0f", 4.0f <= 3.0f, "4.0f <= 3.0f")]
[TestCase("4.0f >= 3.0f", 4.0f >= 3.0f, "4.0f >= 3.0f")]
// double
[TestCase("4.0 // 3.0", (double)(int)(4.0f / 3.0), "4.0 // 3.0")]
[TestCase("4.0 ^ 2.0", (double)16.0, "4.0 ^ 2.0")]
[TestCase("4.0 << 1", (double)4.0 * 2.0, "4.0 << 1")]
[TestCase("4.0 >> 1", (double)4.0 / 2.0, "4.0 >> 1")]
[TestCase("4.0d", 4.0, "4.0")]
[TestCase("4.0D", 4.0, "4.0")]
// decimal
[TestCase("4.0m", 4.0, "4.0m")]
[TestCase("4.0M", 4.0, "4.0m")]
[TestCase("4.0m + 2.0m", 6.0, "4.0m + 2.0m")]
[TestCase("4.0m - 2.0m", 2.0, "4.0m - 2.0m")]
[TestCase("4.0m * 2.0m", 8.0, "4.0m * 2.0m")]
[TestCase("8.0m / 2.0m", 4.0, "8.0m / 2.0m")]
[TestCase("5.0m // 2.0m", 2.0, "5.0m // 2.0m")]
[TestCase("2.0m ^ 3.0m", 8.0, "2.0m ^ 3.0m")]
[TestCase("2.0m << 1", 4.0, "2.0m << 1")]
[TestCase("4.0m >> 1", 2.0, "4.0m >> 1")]
[TestCase("4.0m % 3.0m", 1.0, "4.0m % 3.0m")]
[TestCase("4.0m == 3.0m", 4.0m == 3.0m, "4.0m == 3.0m")]
[TestCase("4.0m != 3.0m", 4.0m != 3.0m, "4.0m != 3.0m")]
[TestCase("4.0m < 3.0m", 4.0m < 3.0m, "4.0m < 3.0m")]
[TestCase("4.0m > 3.0m", 4.0m > 3.0m, "4.0m > 3.0m")]
[TestCase("4.0m <= 3.0m", 4.0m <= 3.0m, "4.0m <= 3.0m")]
[TestCase("4.0m >= 3.0m", 4.0m >= 3.0m, "4.0m >= 3.0m")]
[TestCase("3.0ff", 12.0, "3.0 * ff")]
public void TestScientific(string script, object value, string scriptReformat)
{
var template = Template.Parse(script, lexerOptions: new LexerOptions() {Mode = ScriptMode.ScriptOnly, Lang = ScriptLang.Scientific});
Assert.False(template.HasErrors, $"Template has errors: {template.Messages}");
var context = new TemplateContext();
context.CurrentGlobal.SetValue("x", 1, false);
context.CurrentGlobal.SetValue("y", 2, false);
context.CurrentGlobal.SetValue("z", -10, false);
context.CurrentGlobal.SetValue("ff", 4, false);
var result = template.Evaluate(context);
Assert.AreEqual(value, result);
var resultAsync = template.EvaluateAsync(context).Result;
Assert.AreEqual(value, resultAsync, "Invalid async result");
var reformat = template.Page.Format(new ScriptFormatterOptions(context, ScriptLang.Scientific, ScriptFormatterFlags.ExplicitClean));
var exprAsString = reformat.ToString();
Assert.AreEqual(exprAsString, scriptReformat, "Format string don't match");
}
[Test]
public void RoundtripFunction()
{
var text = @"{{ func inc
ret $0 + 1
end }}";
AssertRoundtrip(text);
}
[Test]
public void RoundtripFunction2()
{
var text = @"{{
func inc
ret $0 + 1
end
xxx 1
}}";
AssertRoundtrip(text);
}
[Test]
public void RoundtripIf()
{
var text = @"{{
if true
""yes""
end
}}
raw
";
AssertRoundtrip(text);
}
[Test]
public void RoundtripIfElse()
{
var text = @"{{
if true
""yes""
else
""no""
end
}}
raw
";
AssertRoundtrip(text);
}
[Test]
public void RoundtripIfElseIf()
{
var text = @"{{
if true
""yes""
else if yo
""no""
end
y
}}
raw
";
AssertRoundtrip(text);
}
[Test]
public void RoundtripCapture()
{
var text = @" {{ capture variable -}}
This is a capture
{{- end -}}
{{ variable }}";
AssertRoundtrip(text);
}
[Test]
public void RoundtripRaw()
{
var text = @"This is a raw {{~ x ~}} end";
AssertRoundtrip(text);
}
[Test]
public void TestDateNow()
{
// default is dd MM yyyy
var dateNow = DateTime.Now.ToString("dd MMM yyyy", CultureInfo.InvariantCulture);
var template = ParseTemplate(@"{{ date.now }}");
var result = template.Render();
Assert.AreEqual(dateNow, result);
template = ParseTemplate(@"{{ date.format = '%Y'; date.now }}");
result = template.Render();
Assert.AreEqual(DateTime.Now.ToString("yyyy", CultureInfo.InvariantCulture), result);
template = ParseTemplate(@"{{ date.format = '%Y'; date.now | date.add_years 1 }}");
result = template.Render();
Assert.AreEqual(DateTime.Now.AddYears(1).ToString("yyyy", CultureInfo.InvariantCulture), result);
}
[Test]
public void TestHelloWorld()
{
var template = ParseTemplate(@"This is a {{ text }} World from scriban!");
var result = template.Render(new { text = "Hello" });
Assert.AreEqual("This is a Hello World from scriban!", result);
}
[Test]
public void TestFrontMatter()
{
var options = new LexerOptions() {Mode = ScriptMode.FrontMatterAndContent};
var input = @"+++
variable = 1
name = 'yes'
+++
This is after the frontmatter: {{ name }}
{{
variable + 1
}}";
input = input.Replace("\r\n", "\n");
var template = ParseTemplate(input, options);
// Make sure that we have a front matter
Assert.NotNull(template.Page.FrontMatter);
var context = new TemplateContext();
// Evaluate front-matter
var frontResult = context.Evaluate(template.Page.FrontMatter);
Assert.Null(frontResult);
// Evaluate page-content
context.Evaluate(template.Page);
var pageResult = context.Output.ToString();
TextAssert.AreEqual("This is after the frontmatter: yes\n2", pageResult);
}
[Test]
public void TestFrontMatterOnly()
{
var options = new ParserOptions();
var input = @"+++
variable = 1
name = 'yes'
+++
This is after the frontmatter: {{ name }}
{{
variable + 1
}}";
input = input.Replace("\r\n", "\n");
var lexer = new Lexer(input, null, new LexerOptions() { Mode = ScriptMode.FrontMatterOnly });
var parser = new Parser(lexer, options);
var page = parser.Run();
foreach (var message in parser.Messages)
{
Console.WriteLine(message);
}
Assert.False(parser.HasErrors);
// Check that the parser finished parsing on the first code exit }}
// and hasn't tried to run the lexer on the remaining text
Assert.AreEqual(new TextPosition(34, 4, 0), parser.CurrentSpan.Start);
var startPositionAfterFrontMatter = page.FrontMatter.TextPositionAfterEndMarker;
// Make sure that we have a front matter
Assert.NotNull(page.FrontMatter);
Assert.Null(page.Body);
var context = new TemplateContext();
// Evaluate front-matter
var frontResult = context.Evaluate(page.FrontMatter);
Assert.Null(frontResult);
lexer = new Lexer(input, null, new LexerOptions() { StartPosition = startPositionAfterFrontMatter });
parser = new Parser(lexer);
page = parser.Run();
foreach (var message in parser.Messages)
{
Console.WriteLine(message);
}
Assert.False(parser.HasErrors);
context.Evaluate(page);
var pageResult = context.Output.ToString();
TextAssert.AreEqual("This is after the frontmatter: yes\n2", pageResult);
}
[Test]
public void TestScriptOnly()
{
var options = new LexerOptions() { Mode = ScriptMode.ScriptOnly };
var template = ParseTemplate(@"
variable = 1
name = 'yes'
", options);
var context = new TemplateContext();
template.Render(context);
var outputStr = context.Output.ToString();
Assert.AreEqual(string.Empty, outputStr);
var global = context.CurrentGlobal;
object value;
Assert.True(global.TryGetValue("name", out value));
Assert.AreEqual("yes", value);
Assert.True(global.TryGetValue("variable", out value));
Assert.AreEqual(1, value);
}
private static Template ParseTemplate(string text, LexerOptions? lexerOptions = null, ParserOptions? parserOptions = null)
{
var template = Template.Parse(text, "text", parserOptions, lexerOptions);
foreach (var message in template.Messages)
{
Console.WriteLine(message);
}
Assert.False(template.HasErrors);
return template;
}
[Test]
public void TestFunctionCallInExpression()
{
var lexer = new Lexer(@"{{
with math
round pi
end
}}");
var parser = new Parser(lexer);
var scriptPage = parser.Run();
foreach (var message in parser.Messages)
{
Console.WriteLine(message);
}
Assert.False(parser.HasErrors);
Assert.NotNull(scriptPage);
var rootObject = new ScriptObject();
rootObject.SetValue("math", ScriptObject.From(typeof(MathObject)), true);
var context = new TemplateContext();
context.PushGlobal(rootObject);
context.Evaluate(scriptPage);
context.PopGlobal();
// Result
var result = context.Output.ToString();
Console.WriteLine(result);
}
[TestCaseSource("ListTestFiles", new object[] { "000-basic" })]
public static void A000_basic(string inputName)
{
TestFile(inputName);
}
[TestCaseSource("ListTestFiles", new object[] { "010-literals" })]
public static void A010_literals(string inputName)
{
TestFile(inputName);
}
[TestCaseSource("ListTestFiles", new object[] { "100-expressions" })]
public static void A100_expressions(string inputName)
{
TestFile(inputName);
}
[TestCaseSource("ListTestFiles", new object[] { "200-statements" })]
public static void A200_statements(string inputName)
{
TestFile(inputName);
}
[TestCaseSource("ListTestFiles", new object[] { "300-functions" })]
public static void A300_functions(string inputName)
{
TestFile(inputName);
}
[TestCaseSource("ListTestFiles", new object[] { "400-builtins" })]
public static void A400_builtins(string inputName)
{
TestFile(inputName);
}
[TestCaseSource("ListTestFiles", new object[] { "500-liquid" })]
public static void A500_liquid(string inputName)
{
TestFile(inputName);
}
[TestCaseSource("ListBuiltinFunctionTests", new object[] { "array" })]
public static void Doc_array(string inputName, string input, string output)
{
AssertTemplate(output, input);
}
[TestCaseSource("ListBuiltinFunctionTests", new object[] { "date" })]
public static void Doc_date(string inputName, string input, string output)
{
AssertTemplate(output, input);
}
[TestCaseSource("ListBuiltinFunctionTests", new object[] { "html" })]
public static void Doc_html(string inputName, string input, string output)
{
AssertTemplate(output, input);
}
[TestCaseSource("ListBuiltinFunctionTests", new object[] { "math" })]
public static void Doc_math(string inputName, string input, string output)
{
AssertTemplate(output, input);
}
[TestCaseSource("ListBuiltinFunctionTests", new object[] { "object" })]
public static void Doc_object(string inputName, string input, string output)
{
AssertTemplate(output, input);
}
[TestCaseSource("ListBuiltinFunctionTests", new object[] { "regex" })]
public static void Doc_regex(string inputName, string input, string output)
{
AssertTemplate(output, input);
}
[TestCaseSource("ListBuiltinFunctionTests", new object[] { "string" })]
public static void Doc_string(string inputName, string input, string output)
{
AssertTemplate(output, input);
}
[TestCaseSource("ListBuiltinFunctionTests", new object[] { "timespan" })]
public static void Doc_timespan(string inputName, string input, string output)
{
AssertTemplate(output, input);
}
private static void TestFile(string inputName)
{
var filename = Path.GetFileName(inputName);
var isSupportingExactRoundtrip = !NotSupportingExactRoundtrip.Contains(filename);
var inputText = LoadTestFile(inputName);
var expectedOutputName = Path.ChangeExtension(inputName, OutputEndFileExtension);
var expectedOutputText = LoadTestFile(expectedOutputName);
Assert.NotNull(expectedOutputText, $"Expecting output result file `{expectedOutputName}` for input file `{inputName}`");
var lang = ScriptLang.Default;
if (inputName.Contains("liquid"))
{
lang = ScriptLang.Liquid;
}
else if (inputName.Contains("scientific"))
{
lang = ScriptLang.Scientific;
}
AssertTemplate(expectedOutputText, inputText, lang, false, isSupportingExactRoundtrip, expectParsingErrorForRountrip: filename == "513-liquid-statement-for.variables.txt");
}
private void AssertRoundtrip(string inputText, bool isLiquid = false)
{
inputText = inputText.Replace("\r\n", "\n");
AssertTemplate(inputText, inputText, isLiquid ? ScriptLang.Liquid : ScriptLang.Default, true);
}
/// <summary>
/// Lists of the tests that don't support exact byte-to-byte roundtrip (due to reformatting...etc.)
/// </summary>
private static readonly HashSet<string> NotSupportingExactRoundtrip = new HashSet<string>()
{
"003-whitespaces.txt",
"010-literals.txt",
"205-case-when-statement2.txt",
"230-capture-statement2.txt",
"470-html.txt"
};
public static void AssertTemplate(string expected, string input, ScriptLang lang = ScriptLang.Default, bool isRoundtripTest = false, bool supportExactRoundtrip = true, object model = null, bool specialLiquid = false, bool expectParsingErrorForRountrip = false, bool supportRoundTrip = true)
{
bool isLiquid = lang == ScriptLang.Liquid;
var parserOptions = new ParserOptions()
{
LiquidFunctionsToScriban = isLiquid,
};
var lexerOptions = new LexerOptions()
{
Lang = lang
};
if (isRoundtripTest)
{
lexerOptions.KeepTrivia = true;
}
if (specialLiquid)
{
parserOptions.ExpressionDepthLimit = 500;
}
#if EnableTokensOutput
{
Console.WriteLine("Tokens");
Console.WriteLine("======================================");
var lexer = new Lexer(input, options: lexerOptions);
foreach (var token in lexer)
{
Console.WriteLine($"{token.Type}: {token.GetText(input)}");
}
Console.WriteLine();
}
#endif
string roundtripText = null;
// We loop first on input text, then on roundtrip
while (true)
{
bool isRoundtrip = roundtripText != null;
bool hasErrors = false;
bool hasException = false;
if (isRoundtrip)
{
Console.WriteLine("Roundtrip");
Console.WriteLine("======================================");
Console.WriteLine(roundtripText);
lexerOptions.Lang = lang == ScriptLang.Scientific ? lang : ScriptLang.Default;
if (!isLiquid && supportExactRoundtrip)
{
Console.WriteLine("Checking Exact Roundtrip - Input");
Console.WriteLine("======================================");
TextAssert.AreEqual(input, roundtripText);
}
input = roundtripText;
}
else
{
Console.WriteLine("Input");
Console.WriteLine("======================================");
Console.WriteLine(input);
}
var template = Template.Parse(input, "text", parserOptions, lexerOptions);
var result = string.Empty;
var resultAsync = string.Empty;
if (template.HasErrors)
{
hasErrors = true;
for (int i = 0; i < template.Messages.Count; i++)
{
var message = template.Messages[i];
if (i > 0)
{
result += "\n";
}
result += message;
}
if (specialLiquid && !isRoundtrip)
{
throw new InvalidOperationException("Parser errors: " + result);
}
}
else
{
if (isRoundtripTest)
{
result = template.ToText();
}
else
{
Assert.NotNull(template.Page);
if (!isRoundtrip)
{
// Dumps the roundtrip version
var lexerOptionsForTrivia = lexerOptions;
lexerOptionsForTrivia.KeepTrivia = true;
var templateWithTrivia = Template.Parse(input, "input", parserOptions, lexerOptionsForTrivia);
roundtripText = templateWithTrivia.ToText();
}
try
{
// Setup a default model context for the tests
if (model == null)
{
var scriptObj = new ScriptObject
{
["page"] = new ScriptObject {["title"] = "This is a title"},
["user"] = new ScriptObject {["name"] = "John"},
["product"] = new ScriptObject {["title"] = "Orange", ["type"] = "fruit"},
["products"] = new ScriptArray()
{
new ScriptObject {["title"] = "Orange", ["type"] = "fruit"},
new ScriptObject {["title"] = "Banana", ["type"] = "fruit"},
new ScriptObject {["title"] = "Apple", ["type"] = "fruit"},
new ScriptObject {["title"] = "Computer", ["type"] = "electronics"},
new ScriptObject {["title"] = "Mobile Phone", ["type"] = "electronics"},
new ScriptObject {["title"] = "Table", ["type"] = "furniture"},
new ScriptObject {["title"] = "Sofa", ["type"] = "furniture"},
}
};
scriptObj.Import(typeof(SpecialFunctionProvider));
model = scriptObj;
}
// Render sync
{
var context = NewTemplateContext(lang);
context.PushOutput(new TextWriterOutput(new StringWriter() {NewLine = "\n"}));
var contextObj = new ScriptObject();
contextObj.Import(model);
context.PushGlobal(contextObj);
result = template.Render(context);
}
// Render async
{
var asyncContext = NewTemplateContext(lang);
asyncContext.PushOutput(new TextWriterOutput(new StringWriter() {NewLine = "\n"}));
var contextObj = new ScriptObject();
contextObj.Import(model);
asyncContext.PushGlobal(contextObj);
resultAsync = template.RenderAsync(asyncContext).Result;
}
}
catch (Exception exception)
{
hasException = true;
if (specialLiquid)
{
throw;
}
else
{
result = GetReason(exception);
}
}
}
}
var testContext = isRoundtrip ? "Roundtrip - " : String.Empty;
Console.WriteLine($"{testContext}Result");
Console.WriteLine("======================================");
Console.WriteLine(result);
Console.WriteLine($"{testContext}Expected");
Console.WriteLine("======================================");
Console.WriteLine(expected);
if (isRoundtrip && expectParsingErrorForRountrip)
{
Assert.True(hasErrors, "The roundtrip test is expecting an error");
Assert.AreNotEqual(expected, result);
}
else
{
TextAssert.AreEqual(expected, result);
}
if (!isRoundtrip && !isRoundtripTest && !hasErrors && !hasException)
{
Console.WriteLine("Checking async");
Console.WriteLine("======================================");
TextAssert.AreEqual(expected, resultAsync);
}
if (!supportRoundTrip || isRoundtripTest || isRoundtrip || hasErrors)
{
break;
}
}
}
private static TemplateContext NewTemplateContext(ScriptLang lang)
{
var isLiquid = lang == ScriptLang.Liquid;
var context = isLiquid
? new LiquidTemplateContext()
{
TemplateLoader = new LiquidCustomTemplateLoader()
}
: new TemplateContext()
{
TemplateLoader = new CustomTemplateLoader()
};
if (lang == ScriptLang.Scientific)
{
context.UseScientific = true;
}
// We use a custom output to make sure that all output is using the "\n"
context.NewLine = "\n";
return context;
}
private static string GetReason(Exception ex)
{
var text = new StringBuilder();
while (ex != null)
{
text.Append(ex);
if (ex.InnerException != null)
{
text.Append(". Reason: ");
}
ex = ex.InnerException;
}
return text.ToString();
}
public static IEnumerable ListBuiltinFunctionTests(string functionObject)
{
var builtinDocFile = Path.GetFullPath(Path.Combine(BaseDirectory, BuiltinMarkdownDocFile));
var lines = File.ReadAllLines(builtinDocFile);
var matchFunctionSection = new Regex($@"^###\s+`({functionObject}\.\w+)`");
var tests = new List<TestCaseData>();
string nextFunctionName = null;
int processState = 0;
// states:
// - 0 function section or wait for ```scriban-html (input)
// - 2 parse input (wait for ```)
// - 3 wait for ```html (output)
// - 4 parse input (wait for ```)
var input = new StringBuilder();
var output = new StringBuilder();
foreach (var line in lines)
{
// Match first:
//### `array.add_range`
switch (processState)
{
case 0:
var match = matchFunctionSection.Match(line);
if (match.Success)
{
nextFunctionName = match.Groups[1].Value;
}
// We have reached another object section, we can exit
if (line.StartsWith("## ") && nextFunctionName != null)
{
return tests;
}
if (nextFunctionName != null && line.StartsWith("```scriban-html"))
{
processState = 1;
input = new StringBuilder();
output = new StringBuilder();
}
break;
case 1:
if (line.Equals("```"))
{
processState = 2;
}
else
{
input.AppendLine(line);
}
break;
case 2:
if (line.StartsWith("```html"))
{
processState = 3;
}
break;
case 3:
if (line.Equals("```"))
{
tests.Add(new TestCaseData(nextFunctionName, input.ToString(), output.ToString()));
processState = 0;
}
else
{
output.AppendLine(line);
}
break;
}
}
return tests;
}
public static IEnumerable ListTestFiles(string folder)
{
return ListTestFilesInFolder(folder);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using AccessTokenMvcWebApp.Areas.HelpPage.ModelDescriptions;
using AccessTokenMvcWebApp.Areas.HelpPage.Models;
namespace AccessTokenMvcWebApp.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
//----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------
namespace System.ServiceModel.Diagnostics
{
using System.Diagnostics;
using System.Reflection;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.Diagnostics;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.Threading;
using System.Security;
using System.ServiceModel.Configuration;
using System.ServiceModel.Activation;
using System.Xml;
using System.ServiceModel.Diagnostics.Application;
using System.Globalization;
using System.Collections.Generic;
static class TraceUtility
{
const string ActivityIdKey = "ActivityId";
const string AsyncOperationActivityKey = "AsyncOperationActivity";
const string AsyncOperationStartTimeKey = "AsyncOperationStartTime";
static bool shouldPropagateActivity;
static bool shouldPropagateActivityGlobal;
static bool activityTracing;
static bool messageFlowTracing;
static bool messageFlowTracingOnly;
static long messageNumber = 0;
static Func<Action<AsyncCallback, IAsyncResult>> asyncCallbackGenerator;
static SortedList<int, string> traceCodes = new SortedList<int, string>(382)
{
// Administration trace codes (TraceCode.Administration)
{ TraceCode.WmiPut, "WmiPut" },
// Diagnostic trace codes (TraceCode.Diagnostics)
{ TraceCode.AppDomainUnload, "AppDomainUnload" },
{ TraceCode.EventLog, "EventLog" },
{ TraceCode.ThrowingException, "ThrowingException" },
{ TraceCode.TraceHandledException, "TraceHandledException" },
{ TraceCode.UnhandledException, "UnhandledException" },
{ TraceCode.FailedToAddAnActivityIdHeader, "FailedToAddAnActivityIdHeader" },
{ TraceCode.FailedToReadAnActivityIdHeader, "FailedToReadAnActivityIdHeader" },
{ TraceCode.FilterNotMatchedNodeQuotaExceeded, "FilterNotMatchedNodeQuotaExceeded" },
{ TraceCode.MessageCountLimitExceeded, "MessageCountLimitExceeded" },
{ TraceCode.DiagnosticsFailedMessageTrace, "DiagnosticsFailedMessageTrace" },
{ TraceCode.MessageNotLoggedQuotaExceeded, "MessageNotLoggedQuotaExceeded" },
{ TraceCode.TraceTruncatedQuotaExceeded, "TraceTruncatedQuotaExceeded" },
{ TraceCode.ActivityBoundary, "ActivityBoundary" },
// Serialization trace codes (TraceCode.Serialization)
{ TraceCode.ElementIgnored, "" }, // shared by ServiceModel, need to investigate if should put this one in the SM section
// Channels trace codes (TraceCode.Channels)
{ TraceCode.ConnectionAbandoned, "ConnectionAbandoned" },
{ TraceCode.ConnectionPoolCloseException, "ConnectionPoolCloseException" },
{ TraceCode.ConnectionPoolIdleTimeoutReached, "ConnectionPoolIdleTimeoutReached" },
{ TraceCode.ConnectionPoolLeaseTimeoutReached, "ConnectionPoolLeaseTimeoutReached" },
{ TraceCode.ConnectionPoolMaxOutboundConnectionsPerEndpointQuotaReached, "ConnectionPoolMaxOutboundConnectionsPerEndpointQuotaReached" },
{ TraceCode.ServerMaxPooledConnectionsQuotaReached, "ServerMaxPooledConnectionsQuotaReached" },
{ TraceCode.EndpointListenerClose, "EndpointListenerClose" },
{ TraceCode.EndpointListenerOpen, "EndpointListenerOpen" },
{ TraceCode.HttpResponseReceived, "HttpResponseReceived" },
{ TraceCode.HttpChannelConcurrentReceiveQuotaReached, "HttpChannelConcurrentReceiveQuotaReached" },
{ TraceCode.HttpChannelMessageReceiveFailed, "HttpChannelMessageReceiveFailed" },
{ TraceCode.HttpChannelUnexpectedResponse, "HttpChannelUnexpectedResponse" },
{ TraceCode.HttpChannelRequestAborted, "HttpChannelRequestAborted" },
{ TraceCode.HttpChannelResponseAborted, "HttpChannelResponseAborted" },
{ TraceCode.HttpsClientCertificateInvalid, "HttpsClientCertificateInvalid" },
{ TraceCode.HttpsClientCertificateNotPresent, "HttpsClientCertificateNotPresent" },
{ TraceCode.NamedPipeChannelMessageReceiveFailed, "NamedPipeChannelMessageReceiveFailed" },
{ TraceCode.NamedPipeChannelMessageReceived, "NamedPipeChannelMessageReceived" },
{ TraceCode.MessageReceived, "MessageReceived" },
{ TraceCode.MessageSent, "MessageSent" },
{ TraceCode.RequestChannelReplyReceived, "RequestChannelReplyReceived" },
{ TraceCode.TcpChannelMessageReceiveFailed, "TcpChannelMessageReceiveFailed" },
{ TraceCode.TcpChannelMessageReceived, "TcpChannelMessageReceived" },
{ TraceCode.ConnectToIPEndpoint, "ConnectToIPEndpoint" },
{ TraceCode.SocketConnectionCreate, "SocketConnectionCreate" },
{ TraceCode.SocketConnectionClose, "SocketConnectionClose" },
{ TraceCode.SocketConnectionAbort, "SocketConnectionAbort" },
{ TraceCode.SocketConnectionAbortClose, "SocketConnectionAbortClose" },
{ TraceCode.PipeConnectionAbort, "PipeConnectionAbort" },
{ TraceCode.RequestContextAbort, "RequestContextAbort" },
{ TraceCode.ChannelCreated, "ChannelCreated" },
{ TraceCode.ChannelDisposed, "ChannelDisposed" },
{ TraceCode.ListenerCreated, "ListenerCreated" },
{ TraceCode.ListenerDisposed, "ListenerDisposed" },
{ TraceCode.PrematureDatagramEof, "PrematureDatagramEof" },
{ TraceCode.MaxPendingConnectionsReached, "MaxPendingConnectionsReached" },
{ TraceCode.MaxAcceptedChannelsReached, "MaxAcceptedChannelsReached" },
{ TraceCode.ChannelConnectionDropped, "ChannelConnectionDropped" },
{ TraceCode.HttpAuthFailed, "HttpAuthFailed" },
{ TraceCode.NoExistingTransportManager, "NoExistingTransportManager" },
{ TraceCode.IncompatibleExistingTransportManager, "IncompatibleExistingTransportManager" },
{ TraceCode.InitiatingNamedPipeConnection, "InitiatingNamedPipeConnection" },
{ TraceCode.InitiatingTcpConnection, "InitiatingTcpConnection" },
{ TraceCode.OpenedListener, "OpenedListener" },
{ TraceCode.SslClientCertMissing, "SslClientCertMissing" },
{ TraceCode.StreamSecurityUpgradeAccepted, "StreamSecurityUpgradeAccepted" },
{ TraceCode.TcpConnectError, "TcpConnectError" },
{ TraceCode.FailedAcceptFromPool, "FailedAcceptFromPool" },
{ TraceCode.FailedPipeConnect, "FailedPipeConnect" },
{ TraceCode.SystemTimeResolution, "SystemTimeResolution" },
{ TraceCode.PeerNeighborCloseFailed, "PeerNeighborCloseFailed" },
{ TraceCode.PeerNeighborClosingFailed, "PeerNeighborClosingFailed" },
{ TraceCode.PeerNeighborNotAccepted, "PeerNeighborNotAccepted" },
{ TraceCode.PeerNeighborNotFound, "PeerNeighborNotFound" },
{ TraceCode.PeerNeighborOpenFailed, "PeerNeighborOpenFailed" },
{ TraceCode.PeerNeighborStateChanged, "PeerNeighborStateChanged" },
{ TraceCode.PeerNeighborStateChangeFailed, "PeerNeighborStateChangeFailed" },
{ TraceCode.PeerNeighborMessageReceived, "PeerNeighborMessageReceived" },
{ TraceCode.PeerNeighborManagerOffline, "PeerNeighborManagerOffline" },
{ TraceCode.PeerNeighborManagerOnline, "PeerNeighborManagerOnline" },
{ TraceCode.PeerChannelMessageReceived, "PeerChannelMessageReceived" },
{ TraceCode.PeerChannelMessageSent, "PeerChannelMessageSent" },
{ TraceCode.PeerNodeAddressChanged, "PeerNodeAddressChanged" },
{ TraceCode.PeerNodeOpening, "PeerNodeOpening" },
{ TraceCode.PeerNodeOpened, "PeerNodeOpened" },
{ TraceCode.PeerNodeOpenFailed, "PeerNodeOpenFailed" },
{ TraceCode.PeerNodeClosing, "PeerNodeClosing" },
{ TraceCode.PeerNodeClosed, "PeerNodeClosed" },
{ TraceCode.PeerFloodedMessageReceived, "PeerFloodedMessageReceived" },
{ TraceCode.PeerFloodedMessageNotPropagated, "PeerFloodedMessageNotPropagated" },
{ TraceCode.PeerFloodedMessageNotMatched, "PeerFloodedMessageNotMatched" },
{ TraceCode.PnrpRegisteredAddresses, "PnrpRegisteredAddresses" },
{ TraceCode.PnrpUnregisteredAddresses, "PnrpUnregisteredAddresses" },
{ TraceCode.PnrpResolvedAddresses, "PnrpResolvedAddresses" },
{ TraceCode.PnrpResolveException, "PnrpResolveException" },
{ TraceCode.PeerReceiveMessageAuthenticationFailure, "PeerReceiveMessageAuthenticationFailure" },
{ TraceCode.PeerNodeAuthenticationFailure, "PeerNodeAuthenticationFailure" },
{ TraceCode.PeerNodeAuthenticationTimeout, "PeerNodeAuthenticationTimeout" },
{ TraceCode.PeerFlooderReceiveMessageQuotaExceeded, "PeerFlooderReceiveMessageQuotaExceeded" },
{ TraceCode.PeerServiceOpened, "PeerServiceOpened" },
{ TraceCode.PeerMaintainerActivity, "PeerMaintainerActivity" },
{ TraceCode.MsmqCannotPeekOnQueue, "MsmqCannotPeekOnQueue" },
{ TraceCode.MsmqCannotReadQueues, "MsmqCannotReadQueues" },
{ TraceCode.MsmqDatagramSent, "MsmqDatagramSent" },
{ TraceCode.MsmqDatagramReceived, "MsmqDatagramReceived" },
{ TraceCode.MsmqDetected, "MsmqDetected" },
{ TraceCode.MsmqEnteredBatch, "MsmqEnteredBatch" },
{ TraceCode.MsmqExpectedException, "MsmqExpectedException" },
{ TraceCode.MsmqFoundBaseAddress, "MsmqFoundBaseAddress" },
{ TraceCode.MsmqLeftBatch, "MsmqLeftBatch" },
{ TraceCode.MsmqMatchedApplicationFound, "MsmqMatchedApplicationFound" },
{ TraceCode.MsmqMessageDropped, "MsmqMessageDropped" },
{ TraceCode.MsmqMessageLockedUnderTheTransaction, "MsmqMessageLockedUnderTheTransaction" },
{ TraceCode.MsmqMessageRejected, "MsmqMessageRejected" },
{ TraceCode.MsmqMoveOrDeleteAttemptFailed, "MsmqMoveOrDeleteAttemptFailed" },
{ TraceCode.MsmqPoisonMessageMovedPoison, "MsmqPoisonMessageMovedPoison" },
{ TraceCode.MsmqPoisonMessageMovedRetry, "MsmqPoisonMessageMovedRetry" },
{ TraceCode.MsmqPoisonMessageRejected, "MsmqPoisonMessageRejected" },
{ TraceCode.MsmqPoolFull, "MsmqPoolFull" },
{ TraceCode.MsmqPotentiallyPoisonMessageDetected, "MsmqPotentiallyPoisonMessageDetected" },
{ TraceCode.MsmqQueueClosed, "MsmqQueueClosed" },
{ TraceCode.MsmqQueueOpened, "MsmqQueueOpened" },
{ TraceCode.MsmqQueueTransactionalStatusUnknown, "MsmqQueueTransactionalStatusUnknown" },
{ TraceCode.MsmqScanStarted, "MsmqScanStarted" },
{ TraceCode.MsmqSessiongramReceived, "MsmqSessiongramReceived" },
{ TraceCode.MsmqSessiongramSent, "MsmqSessiongramSent" },
{ TraceCode.MsmqStartingApplication, "MsmqStartingApplication" },
{ TraceCode.MsmqStartingService, "MsmqStartingService" },
{ TraceCode.MsmqUnexpectedAcknowledgment, "MsmqUnexpectedAcknowledgment" },
{ TraceCode.WsrmNegativeElapsedTimeDetected, "WsrmNegativeElapsedTimeDetected" },
{ TraceCode.TcpTransferError, "TcpTransferError" },
{ TraceCode.TcpConnectionResetError, "TcpConnectionResetError" },
{ TraceCode.TcpConnectionTimedOut, "TcpConnectionTimedOut" },
// ComIntegration trace codes (TraceCode.ComIntegration)
{ TraceCode.ComIntegrationServiceHostStartingService, "ComIntegrationServiceHostStartingService" },
{ TraceCode.ComIntegrationServiceHostStartedService, "ComIntegrationServiceHostStartedService" },
{ TraceCode.ComIntegrationServiceHostCreatedServiceContract, "ComIntegrationServiceHostCreatedServiceContract" },
{ TraceCode.ComIntegrationServiceHostStartedServiceDetails, "ComIntegrationServiceHostStartedServiceDetails" },
{ TraceCode.ComIntegrationServiceHostCreatedServiceEndpoint, "ComIntegrationServiceHostCreatedServiceEndpoint" },
{ TraceCode.ComIntegrationServiceHostStoppingService, "ComIntegrationServiceHostStoppingService" },
{ TraceCode.ComIntegrationServiceHostStoppedService, "ComIntegrationServiceHostStoppedService" },
{ TraceCode.ComIntegrationDllHostInitializerStarting, "ComIntegrationDllHostInitializerStarting" },
{ TraceCode.ComIntegrationDllHostInitializerAddingHost, "ComIntegrationDllHostInitializerAddingHost" },
{ TraceCode.ComIntegrationDllHostInitializerStarted, "ComIntegrationDllHostInitializerStarted" },
{ TraceCode.ComIntegrationDllHostInitializerStopping, "ComIntegrationDllHostInitializerStopping" },
{ TraceCode.ComIntegrationDllHostInitializerStopped, "ComIntegrationDllHostInitializerStopped" },
{ TraceCode.ComIntegrationTLBImportStarting, "ComIntegrationTLBImportStarting" },
{ TraceCode.ComIntegrationTLBImportFromAssembly, "ComIntegrationTLBImportFromAssembly" },
{ TraceCode.ComIntegrationTLBImportFromTypelib, "ComIntegrationTLBImportFromTypelib" },
{ TraceCode.ComIntegrationTLBImportConverterEvent, "ComIntegrationTLBImportConverterEvent" },
{ TraceCode.ComIntegrationTLBImportFinished, "ComIntegrationTLBImportFinished" },
{ TraceCode.ComIntegrationInstanceCreationRequest, "ComIntegrationInstanceCreationRequest" },
{ TraceCode.ComIntegrationInstanceCreationSuccess, "ComIntegrationInstanceCreationSuccess" },
{ TraceCode.ComIntegrationInstanceReleased, "ComIntegrationInstanceReleased" },
{ TraceCode.ComIntegrationEnteringActivity, "ComIntegrationEnteringActivity" },
{ TraceCode.ComIntegrationExecutingCall, "ComIntegrationExecutingCall" },
{ TraceCode.ComIntegrationLeftActivity, "ComIntegrationLeftActivity" },
{ TraceCode.ComIntegrationInvokingMethod, "ComIntegrationInvokingMethod" },
{ TraceCode.ComIntegrationInvokedMethod, "ComIntegrationInvokedMethod" },
{ TraceCode.ComIntegrationInvokingMethodNewTransaction, "ComIntegrationInvokingMethodNewTransaction" },
{ TraceCode.ComIntegrationInvokingMethodContextTransaction, "ComIntegrationInvokingMethodContextTransaction" },
{ TraceCode.ComIntegrationServiceMonikerParsed, "ComIntegrationServiceMonikerParsed" },
{ TraceCode.ComIntegrationWsdlChannelBuilderLoaded, "ComIntegrationWsdlChannelBuilderLoaded" },
{ TraceCode.ComIntegrationTypedChannelBuilderLoaded, "ComIntegrationTypedChannelBuilderLoaded" },
{ TraceCode.ComIntegrationChannelCreated, "ComIntegrationChannelCreated" },
{ TraceCode.ComIntegrationDispatchMethod, "ComIntegrationDispatchMethod" },
{ TraceCode.ComIntegrationTxProxyTxCommitted, "ComIntegrationTxProxyTxCommitted" },
{ TraceCode.ComIntegrationTxProxyTxAbortedByContext, "ComIntegrationTxProxyTxAbortedByContext" },
{ TraceCode.ComIntegrationTxProxyTxAbortedByTM, "ComIntegrationTxProxyTxAbortedByTM" },
{ TraceCode.ComIntegrationMexMonikerMetadataExchangeComplete, "ComIntegrationMexMonikerMetadataExchangeComplete" },
{ TraceCode.ComIntegrationMexChannelBuilderLoaded, "ComIntegrationMexChannelBuilderLoaded" },
// Security trace codes (TraceCode.Security)
{ TraceCode.Security, "Security" },
{ TraceCode.SecurityIdentityVerificationSuccess, "SecurityIdentityVerificationSuccess" },
{ TraceCode.SecurityIdentityVerificationFailure, "SecurityIdentityVerificationFailure" },
{ TraceCode.SecurityIdentityDeterminationSuccess, "SecurityIdentityDeterminationSuccess" },
{ TraceCode.SecurityIdentityDeterminationFailure, "SecurityIdentityDeterminationFailure" },
{ TraceCode.SecurityIdentityHostNameNormalizationFailure, "SecurityIdentityHostNameNormalizationFailure" },
{ TraceCode.SecurityImpersonationSuccess, "SecurityImpersonationSuccess" },
{ TraceCode.SecurityImpersonationFailure, "SecurityImpersonationFailure" },
{ TraceCode.SecurityNegotiationProcessingFailure, "SecurityNegotiationProcessingFailure" },
{ TraceCode.IssuanceTokenProviderRemovedCachedToken, "IssuanceTokenProviderRemovedCachedToken" },
{ TraceCode.IssuanceTokenProviderUsingCachedToken, "IssuanceTokenProviderUsingCachedToken" },
{ TraceCode.IssuanceTokenProviderBeginSecurityNegotiation, "IssuanceTokenProviderBeginSecurityNegotiation" },
{ TraceCode.IssuanceTokenProviderEndSecurityNegotiation, "IssuanceTokenProviderEndSecurityNegotiation" },
{ TraceCode.IssuanceTokenProviderRedirectApplied, "IssuanceTokenProviderRedirectApplied" },
{ TraceCode.IssuanceTokenProviderServiceTokenCacheFull, "IssuanceTokenProviderServiceTokenCacheFull" },
{ TraceCode.NegotiationTokenProviderAttached, "NegotiationTokenProviderAttached" },
{ TraceCode.SpnegoClientNegotiationCompleted, "SpnegoClientNegotiationCompleted" },
{ TraceCode.SpnegoServiceNegotiationCompleted, "SpnegoServiceNegotiationCompleted" },
{ TraceCode.SpnegoClientNegotiation, "SpnegoClientNegotiation" },
{ TraceCode.SpnegoServiceNegotiation, "SpnegoServiceNegotiation" },
{ TraceCode.NegotiationAuthenticatorAttached, "NegotiationAuthenticatorAttached" },
{ TraceCode.ServiceSecurityNegotiationCompleted, "ServiceSecurityNegotiationCompleted" },
{ TraceCode.SecurityContextTokenCacheFull, "SecurityContextTokenCacheFull" },
{ TraceCode.ExportSecurityChannelBindingEntry, "ExportSecurityChannelBindingEntry" },
{ TraceCode.ExportSecurityChannelBindingExit, "ExportSecurityChannelBindingExit" },
{ TraceCode.ImportSecurityChannelBindingEntry, "ImportSecurityChannelBindingEntry" },
{ TraceCode.ImportSecurityChannelBindingExit, "ImportSecurityChannelBindingExit" },
{ TraceCode.SecurityTokenProviderOpened, "SecurityTokenProviderOpened" },
{ TraceCode.SecurityTokenProviderClosed, "SecurityTokenProviderClosed" },
{ TraceCode.SecurityTokenAuthenticatorOpened, "SecurityTokenAuthenticatorOpened" },
{ TraceCode.SecurityTokenAuthenticatorClosed, "SecurityTokenAuthenticatorClosed" },
{ TraceCode.SecurityBindingOutgoingMessageSecured, "SecurityBindingOutgoingMessageSecured" },
{ TraceCode.SecurityBindingIncomingMessageVerified, "SecurityBindingIncomingMessageVerified" },
{ TraceCode.SecurityBindingSecureOutgoingMessageFailure, "SecurityBindingSecureOutgoingMessageFailure" },
{ TraceCode.SecurityBindingVerifyIncomingMessageFailure, "SecurityBindingVerifyIncomingMessageFailure" },
{ TraceCode.SecuritySpnToSidMappingFailure, "SecuritySpnToSidMappingFailure" },
{ TraceCode.SecuritySessionRedirectApplied, "SecuritySessionRedirectApplied" },
{ TraceCode.SecurityClientSessionCloseSent, "SecurityClientSessionCloseSent" },
{ TraceCode.SecurityClientSessionCloseResponseSent, "SecurityClientSessionCloseResponseSent" },
{ TraceCode.SecurityClientSessionCloseMessageReceived, "SecurityClientSessionCloseMessageReceived" },
{ TraceCode.SecuritySessionKeyRenewalFaultReceived, "SecuritySessionKeyRenewalFaultReceived" },
{ TraceCode.SecuritySessionAbortedFaultReceived, "SecuritySessionAbortedFaultReceived" },
{ TraceCode.SecuritySessionClosedResponseReceived, "SecuritySessionClosedResponseReceived" },
{ TraceCode.SecurityClientSessionPreviousKeyDiscarded, "SecurityClientSessionPreviousKeyDiscarded" },
{ TraceCode.SecurityClientSessionKeyRenewed, "SecurityClientSessionKeyRenewed" },
{ TraceCode.SecurityPendingServerSessionAdded, "SecurityPendingServerSessionAdded" },
{ TraceCode.SecurityPendingServerSessionClosed, "SecurityPendingServerSessionClosed" },
{ TraceCode.SecurityPendingServerSessionActivated, "SecurityPendingServerSessionActivated" },
{ TraceCode.SecurityActiveServerSessionRemoved, "SecurityActiveServerSessionRemoved" },
{ TraceCode.SecurityNewServerSessionKeyIssued, "SecurityNewServerSessionKeyIssued" },
{ TraceCode.SecurityInactiveSessionFaulted, "SecurityInactiveSessionFaulted" },
{ TraceCode.SecurityServerSessionKeyUpdated, "SecurityServerSessionKeyUpdated" },
{ TraceCode.SecurityServerSessionCloseReceived, "SecurityServerSessionCloseReceived" },
{ TraceCode.SecurityServerSessionRenewalFaultSent, "SecurityServerSessionRenewalFaultSent" },
{ TraceCode.SecurityServerSessionAbortedFaultSent, "SecurityServerSessionAbortedFaultSent" },
{ TraceCode.SecuritySessionCloseResponseSent, "SecuritySessionCloseResponseSent" },
{ TraceCode.SecuritySessionServerCloseSent, "SecuritySessionServerCloseSent" },
{ TraceCode.SecurityServerSessionCloseResponseReceived, "SecurityServerSessionCloseResponseReceived" },
{ TraceCode.SecuritySessionRenewFaultSendFailure, "SecuritySessionRenewFaultSendFailure" },
{ TraceCode.SecuritySessionAbortedFaultSendFailure, "SecuritySessionAbortedFaultSendFailure" },
{ TraceCode.SecuritySessionClosedResponseSendFailure, "SecuritySessionClosedResponseSendFailure" },
{ TraceCode.SecuritySessionServerCloseSendFailure, "SecuritySessionServerCloseSendFailure" },
{ TraceCode.SecuritySessionRequestorStartOperation, "SecuritySessionRequestorStartOperation" },
{ TraceCode.SecuritySessionRequestorOperationSuccess, "SecuritySessionRequestorOperationSuccess" },
{ TraceCode.SecuritySessionRequestorOperationFailure, "SecuritySessionRequestorOperationFailure" },
{ TraceCode.SecuritySessionResponderOperationFailure, "SecuritySessionResponderOperationFailure" },
{ TraceCode.SecuritySessionDemuxFailure, "SecuritySessionDemuxFailure" },
{ TraceCode.SecurityAuditWrittenSuccess, "SecurityAuditWrittenSuccess" },
{ TraceCode.SecurityAuditWrittenFailure, "SecurityAuditWrittenFailure" },
// ServiceModel trace codes (TraceCode.ServiceModel)
{ TraceCode.AsyncCallbackThrewException, "AsyncCallbackThrewException" },
{ TraceCode.CommunicationObjectAborted, "CommunicationObjectAborted" },
{ TraceCode.CommunicationObjectAbortFailed, "CommunicationObjectAbortFailed" },
{ TraceCode.CommunicationObjectCloseFailed, "CommunicationObjectCloseFailed" },
{ TraceCode.CommunicationObjectOpenFailed, "CommunicationObjectOpenFailed" },
{ TraceCode.CommunicationObjectClosing, "CommunicationObjectClosing" },
{ TraceCode.CommunicationObjectClosed, "CommunicationObjectClosed" },
{ TraceCode.CommunicationObjectCreated, "CommunicationObjectCreated" },
{ TraceCode.CommunicationObjectDisposing, "CommunicationObjectDisposing" },
{ TraceCode.CommunicationObjectFaultReason, "CommunicationObjectFaultReason" },
{ TraceCode.CommunicationObjectFaulted, "CommunicationObjectFaulted" },
{ TraceCode.CommunicationObjectOpening, "CommunicationObjectOpening" },
{ TraceCode.CommunicationObjectOpened, "CommunicationObjectOpened" },
{ TraceCode.DidNotUnderstandMessageHeader, "DidNotUnderstandMessageHeader" },
{ TraceCode.UnderstoodMessageHeader, "UnderstoodMessageHeader" },
{ TraceCode.MessageClosed, "MessageClosed" },
{ TraceCode.MessageClosedAgain, "MessageClosedAgain" },
{ TraceCode.MessageCopied, "MessageCopied" },
{ TraceCode.MessageRead, "MessageRead" },
{ TraceCode.MessageWritten, "MessageWritten" },
{ TraceCode.BeginExecuteMethod, "BeginExecuteMethod" },
{ TraceCode.ConfigurationIsReadOnly, "ConfigurationIsReadOnly" },
{ TraceCode.ConfiguredExtensionTypeNotFound, "ConfiguredExtensionTypeNotFound" },
{ TraceCode.EvaluationContextNotFound, "EvaluationContextNotFound" },
{ TraceCode.EndExecuteMethod, "EndExecuteMethod" },
{ TraceCode.ExtensionCollectionDoesNotExist, "ExtensionCollectionDoesNotExist" },
{ TraceCode.ExtensionCollectionNameNotFound, "ExtensionCollectionNameNotFound" },
{ TraceCode.ExtensionCollectionIsEmpty, "ExtensionCollectionIsEmpty" },
{ TraceCode.ExtensionElementAlreadyExistsInCollection, "ExtensionElementAlreadyExistsInCollection" },
{ TraceCode.ElementTypeDoesntMatchConfiguredType, "ElementTypeDoesntMatchConfiguredType" },
{ TraceCode.ErrorInvokingUserCode, "ErrorInvokingUserCode" },
{ TraceCode.GetBehaviorElement, "GetBehaviorElement" },
{ TraceCode.GetCommonBehaviors, "GetCommonBehaviors" },
{ TraceCode.GetConfiguredBinding, "GetConfiguredBinding" },
{ TraceCode.GetChannelEndpointElement, "GetChannelEndpointElement" },
{ TraceCode.GetConfigurationSection, "GetConfigurationSection" },
{ TraceCode.GetDefaultConfiguredBinding, "GetDefaultConfiguredBinding" },
{ TraceCode.GetServiceElement, "GetServiceElement" },
{ TraceCode.MessageProcessingPaused, "MessageProcessingPaused" },
{ TraceCode.ManualFlowThrottleLimitReached, "ManualFlowThrottleLimitReached" },
{ TraceCode.OverridingDuplicateConfigurationKey, "OverridingDuplicateConfigurationKey" },
{ TraceCode.RemoveBehavior, "RemoveBehavior" },
{ TraceCode.ServiceChannelLifetime, "ServiceChannelLifetime" },
{ TraceCode.ServiceHostCreation, "ServiceHostCreation" },
{ TraceCode.ServiceHostBaseAddresses, "ServiceHostBaseAddresses" },
{ TraceCode.ServiceHostTimeoutOnClose, "ServiceHostTimeoutOnClose" },
{ TraceCode.ServiceHostFaulted, "ServiceHostFaulted" },
{ TraceCode.ServiceHostErrorOnReleasePerformanceCounter, "ServiceHostErrorOnReleasePerformanceCounter" },
{ TraceCode.ServiceThrottleLimitReached, "ServiceThrottleLimitReached" },
{ TraceCode.ServiceOperationMissingReply, "ServiceOperationMissingReply" },
{ TraceCode.ServiceOperationMissingReplyContext, "ServiceOperationMissingReplyContext" },
{ TraceCode.ServiceOperationExceptionOnReply, "ServiceOperationExceptionOnReply" },
{ TraceCode.SkipBehavior, "SkipBehavior" },
{ TraceCode.TransportListen, "TransportListen" },
{ TraceCode.UnhandledAction, "UnhandledAction" },
{ TraceCode.PerformanceCounterFailedToLoad, "PerformanceCounterFailedToLoad" },
{ TraceCode.PerformanceCountersFailed, "PerformanceCountersFailed" },
{ TraceCode.PerformanceCountersFailedDuringUpdate, "PerformanceCountersFailedDuringUpdate" },
{ TraceCode.PerformanceCountersFailedForService, "PerformanceCountersFailedForService" },
{ TraceCode.PerformanceCountersFailedOnRelease, "PerformanceCountersFailedOnRelease" },
{ TraceCode.WsmexNonCriticalWsdlExportError, "WsmexNonCriticalWsdlExportError" },
{ TraceCode.WsmexNonCriticalWsdlImportError, "WsmexNonCriticalWsdlImportError" },
{ TraceCode.FailedToOpenIncomingChannel, "FailedToOpenIncomingChannel" },
{ TraceCode.UnhandledExceptionInUserOperation, "UnhandledExceptionInUserOperation" },
{ TraceCode.DroppedAMessage, "DroppedAMessage" },
{ TraceCode.CannotBeImportedInCurrentFormat, "CannotBeImportedInCurrentFormat" },
{ TraceCode.GetConfiguredEndpoint, "GetConfiguredEndpoint" },
{ TraceCode.GetDefaultConfiguredEndpoint, "GetDefaultConfiguredEndpoint" },
{ TraceCode.ExtensionTypeNotFound, "ExtensionTypeNotFound" },
{ TraceCode.DefaultEndpointsAdded, "DefaultEndpointsAdded" },
//ServiceModel Metadata codes
{ TraceCode.MetadataExchangeClientSendRequest, "MetadataExchangeClientSendRequest" },
{ TraceCode.MetadataExchangeClientReceiveReply, "MetadataExchangeClientReceiveReply" },
{ TraceCode.WarnHelpPageEnabledNoBaseAddress, "WarnHelpPageEnabledNoBaseAddress" },
// PortSharingtrace codes (TraceCode.PortSharing)
{ TraceCode.PortSharingClosed, "PortSharingClosed" },
{ TraceCode.PortSharingDuplicatedPipe, "PortSharingDuplicatedPipe" },
{ TraceCode.PortSharingDupHandleGranted, "PortSharingDupHandleGranted" },
{ TraceCode.PortSharingDuplicatedSocket, "PortSharingDuplicatedSocket" },
{ TraceCode.PortSharingListening, "PortSharingListening" },
{ TraceCode.SharedManagerServiceEndpointNotExist, "SharedManagerServiceEndpointNotExist" },
//Indigo Tx trace codes (TraceCode.ServiceModelTransaction)
{ TraceCode.TxSourceTxScopeRequiredIsTransactedTransport, "TxSourceTxScopeRequiredIsTransactedTransport" },
{ TraceCode.TxSourceTxScopeRequiredIsTransactionFlow, "TxSourceTxScopeRequiredIsTransactionFlow" },
{ TraceCode.TxSourceTxScopeRequiredIsAttachedTransaction, "TxSourceTxScopeRequiredIsAttachedTransaction" },
{ TraceCode.TxSourceTxScopeRequiredIsCreateNewTransaction, "TxSourceTxScopeRequiredIsCreateNewTransaction" },
{ TraceCode.TxCompletionStatusCompletedForAutocomplete, "TxCompletionStatusCompletedForAutocomplete" },
{ TraceCode.TxCompletionStatusCompletedForError, "TxCompletionStatusCompletedForError" },
{ TraceCode.TxCompletionStatusCompletedForSetComplete, "TxCompletionStatusCompletedForSetComplete" },
{ TraceCode.TxCompletionStatusCompletedForTACOSC, "TxCompletionStatusCompletedForTACOSC" },
{ TraceCode.TxCompletionStatusCompletedForAsyncAbort, "TxCompletionStatusCompletedForAsyncAbort" },
{ TraceCode.TxCompletionStatusRemainsAttached, "TxCompletionStatusRemainsAttached" },
{ TraceCode.TxCompletionStatusAbortedOnSessionClose, "TxCompletionStatusAbortedOnSessionClose" },
{ TraceCode.TxReleaseServiceInstanceOnCompletion, "TxReleaseServiceInstanceOnCompletion" },
{ TraceCode.TxAsyncAbort, "TxAsyncAbort" },
{ TraceCode.TxFailedToNegotiateOleTx, "TxFailedToNegotiateOleTx" },
{ TraceCode.TxSourceTxScopeRequiredUsingExistingTransaction, "TxSourceTxScopeRequiredUsingExistingTransaction" },
//CfxGreen trace codes (TraceCode.NetFx35)
{ TraceCode.ActivatingMessageReceived, "ActivatingMessageReceived" },
{ TraceCode.InstanceContextBoundToDurableInstance, "InstanceContextBoundToDurableInstance" },
{ TraceCode.InstanceContextDetachedFromDurableInstance, "InstanceContextDetachedFromDurableInstance" },
{ TraceCode.ContextChannelFactoryChannelCreated, "ContextChannelFactoryChannelCreated" },
{ TraceCode.ContextChannelListenerChannelAccepted, "ContextChannelListenerChannelAccepted" },
{ TraceCode.ContextProtocolContextAddedToMessage, "ContextProtocolContextAddedToMessage" },
{ TraceCode.ContextProtocolContextRetrievedFromMessage, "ContextProtocolContextRetrievedFromMessage" },
{ TraceCode.DICPInstanceContextCached, "DICPInstanceContextCached" },
{ TraceCode.DICPInstanceContextRemovedFromCache, "DICPInstanceContextRemovedFromCache" },
{ TraceCode.ServiceDurableInstanceDeleted, "ServiceDurableInstanceDeleted" },
{ TraceCode.ServiceDurableInstanceDisposed, "ServiceDurableInstanceDisposed" },
{ TraceCode.ServiceDurableInstanceLoaded, "ServiceDurableInstanceLoaded" },
{ TraceCode.ServiceDurableInstanceSaved, "ServiceDurableInstanceSaved" },
{ TraceCode.SqlPersistenceProviderSQLCallStart, "SqlPersistenceProviderSQLCallStart" },
{ TraceCode.SqlPersistenceProviderSQLCallEnd, "SqlPersistenceProviderSQLCallEnd" },
{ TraceCode.SqlPersistenceProviderOpenParameters, "SqlPersistenceProviderOpenParameters" },
{ TraceCode.SyncContextSchedulerServiceTimerCancelled, "SyncContextSchedulerServiceTimerCancelled" },
{ TraceCode.SyncContextSchedulerServiceTimerCreated, "SyncContextSchedulerServiceTimerCreated" },
{ TraceCode.WorkflowDurableInstanceLoaded, "WorkflowDurableInstanceLoaded" },
{ TraceCode.WorkflowDurableInstanceAborted, "WorkflowDurableInstanceAborted" },
{ TraceCode.WorkflowDurableInstanceActivated, "WorkflowDurableInstanceActivated" },
{ TraceCode.WorkflowOperationInvokerItemQueued, "WorkflowOperationInvokerItemQueued" },
{ TraceCode.WorkflowRequestContextReplySent, "WorkflowRequestContextReplySent" },
{ TraceCode.WorkflowRequestContextFaultSent, "WorkflowRequestContextFaultSent" },
{ TraceCode.WorkflowServiceHostCreated, "WorkflowServiceHostCreated" },
{ TraceCode.SyndicationReadFeedBegin, "SyndicationReadFeedBegin" },
{ TraceCode.SyndicationReadFeedEnd, "SyndicationReadFeedEnd" },
{ TraceCode.SyndicationReadItemBegin, "SyndicationReadItemBegin" },
{ TraceCode.SyndicationReadItemEnd, "SyndicationReadItemEnd" },
{ TraceCode.SyndicationWriteFeedBegin, "SyndicationWriteFeedBegin" },
{ TraceCode.SyndicationWriteFeedEnd, "SyndicationWriteFeedEnd" },
{ TraceCode.SyndicationWriteItemBegin, "SyndicationWriteItemBegin" },
{ TraceCode.SyndicationWriteItemEnd, "SyndicationWriteItemEnd" },
{ TraceCode.SyndicationProtocolElementIgnoredOnRead, "SyndicationProtocolElementIgnoredOnRead" },
{ TraceCode.SyndicationProtocolElementIgnoredOnWrite, "SyndicationProtocolElementIgnoredOnWrite" },
{ TraceCode.SyndicationProtocolElementInvalid, "SyndicationProtocolElementInvalid" },
{ TraceCode.WebUnknownQueryParameterIgnored, "WebUnknownQueryParameterIgnored" },
{ TraceCode.WebRequestMatchesOperation, "WebRequestMatchesOperation" },
{ TraceCode.WebRequestDoesNotMatchOperations, "WebRequestDoesNotMatchOperations" },
{ TraceCode.WebRequestRedirect, "WebRequestRedirect" },
{ TraceCode.SyndicationReadServiceDocumentBegin, "SyndicationReadServiceDocumentBegin" },
{ TraceCode.SyndicationReadServiceDocumentEnd, "SyndicationReadServiceDocumentEnd" },
{ TraceCode.SyndicationReadCategoriesDocumentBegin, "SyndicationReadCategoriesDocumentBegin" },
{ TraceCode.SyndicationReadCategoriesDocumentEnd, "SyndicationReadCategoriesDocumentEnd" },
{ TraceCode.SyndicationWriteServiceDocumentBegin, "SyndicationWriteServiceDocumentBegin" },
{ TraceCode.SyndicationWriteServiceDocumentEnd, "SyndicationWriteServiceDocumentEnd" },
{ TraceCode.SyndicationWriteCategoriesDocumentBegin, "SyndicationWriteCategoriesDocumentBegin" },
{ TraceCode.SyndicationWriteCategoriesDocumentEnd, "SyndicationWriteCategoriesDocumentEnd" },
{ TraceCode.AutomaticFormatSelectedOperationDefault, "AutomaticFormatSelectedOperationDefault" },
{ TraceCode.AutomaticFormatSelectedRequestBased, "AutomaticFormatSelectedRequestBased" },
{ TraceCode.RequestFormatSelectedFromContentTypeMapper, "RequestFormatSelectedFromContentTypeMapper" },
{ TraceCode.RequestFormatSelectedByEncoderDefaults, "RequestFormatSelectedByEncoderDefaults" },
{ TraceCode.AddingResponseToOutputCache, "AddingResponseToOutputCache" },
{ TraceCode.AddingAuthenticatedResponseToOutputCache, "AddingAuthenticatedResponseToOutputCache" },
{ TraceCode.JsonpCallbackNameSet, "JsonpCallbackNameSet" },
};
public const string E2EActivityId = "E2EActivityId";
public const string TraceApplicationReference = "TraceApplicationReference";
public static InputQueue<T> CreateInputQueue<T>() where T : class
{
if (asyncCallbackGenerator == null)
{
asyncCallbackGenerator = new Func<Action<AsyncCallback, IAsyncResult>>(CallbackGenerator);
}
return new InputQueue<T>(asyncCallbackGenerator)
{
DisposeItemCallback = value =>
{
if (value is ICommunicationObject)
{
((ICommunicationObject)value).Abort();
}
}
};
}
static Action<AsyncCallback, IAsyncResult> CallbackGenerator()
{
if (DiagnosticUtility.ShouldUseActivity)
{
ServiceModelActivity callbackActivity = ServiceModelActivity.Current;
if (callbackActivity != null)
{
return delegate(AsyncCallback callback, IAsyncResult result)
{
using (ServiceModelActivity.BoundOperation(callbackActivity))
{
callback(result);
}
};
}
}
return null;
}
static internal void AddActivityHeader(Message message)
{
try
{
ActivityIdHeader activityIdHeader = new ActivityIdHeader(TraceUtility.ExtractActivityId(message));
activityIdHeader.AddTo(message);
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
TraceUtility.TraceEvent(TraceEventType.Error, TraceCode.FailedToAddAnActivityIdHeader,
SR.GetString(SR.TraceCodeFailedToAddAnActivityIdHeader), e, message);
}
}
static internal void AddAmbientActivityToMessage(Message message)
{
try
{
ActivityIdHeader activityIdHeader = new ActivityIdHeader(DiagnosticTraceBase.ActivityId);
activityIdHeader.AddTo(message);
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
TraceUtility.TraceEvent(TraceEventType.Error, TraceCode.FailedToAddAnActivityIdHeader,
SR.GetString(SR.TraceCodeFailedToAddAnActivityIdHeader), e, message);
}
}
static internal void CopyActivity(Message source, Message destination)
{
if (DiagnosticUtility.ShouldUseActivity)
{
TraceUtility.SetActivity(destination, TraceUtility.ExtractActivity(source));
}
}
internal static long GetUtcBasedDurationForTrace(long startTicks)
{
if (startTicks > 0)
{
TimeSpan elapsedTime = new TimeSpan(DateTime.UtcNow.Ticks - startTicks);
return (long)elapsedTime.TotalMilliseconds;
}
return 0;
}
internal static ServiceModelActivity ExtractActivity(Message message)
{
ServiceModelActivity retval = null;
if ((DiagnosticUtility.ShouldUseActivity || TraceUtility.ShouldPropagateActivityGlobal) &&
(message != null) &&
(message.State != MessageState.Closed))
{
object property;
if (message.Properties.TryGetValue(TraceUtility.ActivityIdKey, out property))
{
retval = property as ServiceModelActivity;
}
}
return retval;
}
internal static ServiceModelActivity ExtractActivity(RequestContext request)
{
try
{
return TraceUtility.ExtractActivity(request.RequestMessage);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
}
return null;
}
internal static Guid ExtractActivityId(Message message)
{
if (TraceUtility.MessageFlowTracingOnly)
{
return ActivityIdHeader.ExtractActivityId(message);
}
ServiceModelActivity activity = ExtractActivity(message);
return activity == null ? Guid.Empty : activity.Id;
}
internal static Guid GetReceivedActivityId(OperationContext operationContext)
{
object activityIdFromProprties;
if (!operationContext.IncomingMessageProperties.TryGetValue(E2EActivityId, out activityIdFromProprties))
{
return TraceUtility.ExtractActivityId(operationContext.IncomingMessage);
}
else
{
return (Guid)activityIdFromProprties;
}
}
internal static ServiceModelActivity ExtractAndRemoveActivity(Message message)
{
ServiceModelActivity retval = TraceUtility.ExtractActivity(message);
if (retval != null)
{
// If the property is just removed, the item is disposed and we don't want the thing
// to be disposed of.
message.Properties[TraceUtility.ActivityIdKey] = false;
}
return retval;
}
internal static void ProcessIncomingMessage(Message message, EventTraceActivity eventTraceActivity)
{
ServiceModelActivity activity = ServiceModelActivity.Current;
if (activity != null && DiagnosticUtility.ShouldUseActivity)
{
ServiceModelActivity incomingActivity = TraceUtility.ExtractActivity(message);
if (null != incomingActivity && incomingActivity.Id != activity.Id)
{
using (ServiceModelActivity.BoundOperation(incomingActivity))
{
if (null != FxTrace.Trace)
{
FxTrace.Trace.TraceTransfer(activity.Id);
}
}
}
TraceUtility.SetActivity(message, activity);
}
TraceUtility.MessageFlowAtMessageReceived(message, null, eventTraceActivity, true);
if (MessageLogger.LogMessagesAtServiceLevel)
{
MessageLogger.LogMessage(ref message, MessageLoggingSource.ServiceLevelReceiveReply | MessageLoggingSource.LastChance);
}
}
internal static void ProcessOutgoingMessage(Message message, EventTraceActivity eventTraceActivity)
{
ServiceModelActivity activity = ServiceModelActivity.Current;
if (DiagnosticUtility.ShouldUseActivity)
{
TraceUtility.SetActivity(message, activity);
}
if (TraceUtility.PropagateUserActivity || TraceUtility.ShouldPropagateActivity)
{
TraceUtility.AddAmbientActivityToMessage(message);
}
TraceUtility.MessageFlowAtMessageSent(message, eventTraceActivity);
if (MessageLogger.LogMessagesAtServiceLevel)
{
MessageLogger.LogMessage(ref message, MessageLoggingSource.ServiceLevelSendRequest | MessageLoggingSource.LastChance);
}
}
internal static void SetActivity(Message message, ServiceModelActivity activity)
{
if (DiagnosticUtility.ShouldUseActivity && message != null && message.State != MessageState.Closed)
{
message.Properties[TraceUtility.ActivityIdKey] = activity;
}
}
internal static void TraceDroppedMessage(Message message, EndpointDispatcher dispatcher)
{
if (DiagnosticUtility.ShouldTraceInformation)
{
EndpointAddress endpointAddress = null;
if (dispatcher != null)
{
endpointAddress = dispatcher.EndpointAddress;
}
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.DroppedAMessage,
SR.GetString(SR.TraceCodeDroppedAMessage), new MessageDroppedTraceRecord(message, endpointAddress));
}
}
internal static void TraceEvent(TraceEventType severity, int traceCode, string traceDescription)
{
TraceEvent(severity, traceCode, traceDescription, null, traceDescription, (Exception)null);
}
internal static void TraceEvent(TraceEventType severity, int traceCode, string traceDescription, TraceRecord extendedData)
{
TraceEvent(severity, traceCode, traceDescription, extendedData, null, (Exception)null);
}
internal static void TraceEvent(TraceEventType severity, int traceCode, string traceDescription, object source)
{
TraceEvent(severity, traceCode, traceDescription, null, source, (Exception)null);
}
internal static void TraceEvent(TraceEventType severity, int traceCode, string traceDescription, object source, Exception exception)
{
TraceEvent(severity, traceCode, traceDescription, null, source, exception);
}
internal static void TraceEvent(TraceEventType severity, int traceCode, string traceDescription, Message message)
{
if (message == null)
{
TraceEvent(severity, traceCode, traceDescription, null, (Exception)null);
}
else
{
TraceEvent(severity, traceCode, traceDescription, message, message);
}
}
internal static void TraceEvent(TraceEventType severity, int traceCode, string traceDescription, object source, Message message)
{
Guid activityId = TraceUtility.ExtractActivityId(message);
if (DiagnosticUtility.ShouldTrace(severity))
{
DiagnosticUtility.DiagnosticTrace.TraceEvent(severity, traceCode, GenerateMsdnTraceCode(traceCode), traceDescription, new MessageTraceRecord(message), null, activityId, message);
}
}
internal static void TraceEvent(TraceEventType severity, int traceCode, string traceDescription, Exception exception, Message message)
{
Guid activityId = TraceUtility.ExtractActivityId(message);
if (DiagnosticUtility.ShouldTrace(severity))
{
DiagnosticUtility.DiagnosticTrace.TraceEvent(severity, traceCode, GenerateMsdnTraceCode(traceCode), traceDescription, new MessageTraceRecord(message), exception, activityId, null);
}
}
internal static void TraceEventNoCheck(TraceEventType severity, int traceCode, string traceDescription, TraceRecord extendedData, object source, Exception exception)
{
DiagnosticUtility.DiagnosticTrace.TraceEvent(severity, traceCode, GenerateMsdnTraceCode(traceCode), traceDescription, extendedData, exception, source);
}
// These methods require a TraceRecord to be allocated, so we want them to show up on profiles if the caller didn't avoid
// allocating the TraceRecord by using ShouldTrace.
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void TraceEvent(TraceEventType severity, int traceCode, string traceDescription, TraceRecord extendedData, object source, Exception exception)
{
if (DiagnosticUtility.ShouldTrace(severity))
{
DiagnosticUtility.DiagnosticTrace.TraceEvent(severity, traceCode, GenerateMsdnTraceCode(traceCode), traceDescription, extendedData, exception, source);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void TraceEvent(TraceEventType severity, int traceCode, string traceDescription, TraceRecord extendedData, object source, Exception exception, Message message)
{
Guid activityId = TraceUtility.ExtractActivityId(message);
if (DiagnosticUtility.ShouldTrace(severity))
{
DiagnosticUtility.DiagnosticTrace.TraceEvent(severity, traceCode, GenerateMsdnTraceCode(traceCode),
traceDescription, extendedData, exception, activityId, source);
}
}
internal static void TraceEventNoCheck(TraceEventType severity, int traceCode, string traceDescription, TraceRecord extendedData, object source, Exception exception, Guid activityId)
{
DiagnosticUtility.DiagnosticTrace.TraceEvent(severity, traceCode, GenerateMsdnTraceCode(traceCode),
traceDescription, extendedData, exception, activityId, source);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void TraceEvent(TraceEventType severity, int traceCode, string traceDescription, TraceRecord extendedData, object source, Exception exception, Guid activityId)
{
if (DiagnosticUtility.ShouldTrace(severity))
{
DiagnosticUtility.DiagnosticTrace.TraceEvent(severity, traceCode, GenerateMsdnTraceCode(traceCode),
traceDescription, extendedData, exception, activityId, source);
}
}
static string GenerateMsdnTraceCode(int traceCode)
{
int group = (int)(traceCode & 0xFFFF0000);
string terminatorUri = null;
switch (group)
{
case TraceCode.Administration:
terminatorUri = "System.ServiceModel.Administration";
break;
case TraceCode.Channels:
terminatorUri = "System.ServiceModel.Channels";
break;
case TraceCode.ComIntegration:
terminatorUri = "System.ServiceModel.ComIntegration";
break;
case TraceCode.Diagnostics:
terminatorUri = "System.ServiceModel.Diagnostics";
break;
case TraceCode.PortSharing:
terminatorUri = "System.ServiceModel.PortSharing";
break;
case TraceCode.Security:
terminatorUri = "System.ServiceModel.Security";
break;
case TraceCode.Serialization:
terminatorUri = "System.Runtime.Serialization";
break;
case TraceCode.ServiceModel:
case TraceCode.ServiceModelTransaction:
terminatorUri = "System.ServiceModel";
break;
default:
terminatorUri = string.Empty;
break;
}
Fx.Assert(traceCodes.ContainsKey(traceCode),
string.Format(CultureInfo.InvariantCulture, "Unsupported trace code: Please add trace code 0x{0} to the SortedList TraceUtility.traceCodes in {1}",
traceCode.ToString("X", CultureInfo.InvariantCulture), typeof(TraceUtility)));
return LegacyDiagnosticTrace.GenerateMsdnTraceCode(terminatorUri, traceCodes[traceCode]);
}
internal static Exception ThrowHelperError(Exception exception, Message message)
{
// If the message is closed, we won't get an activity
Guid activityId = TraceUtility.ExtractActivityId(message);
if (DiagnosticUtility.ShouldTraceError)
{
DiagnosticUtility.DiagnosticTrace.TraceEvent(TraceEventType.Error, TraceCode.ThrowingException, GenerateMsdnTraceCode(TraceCode.ThrowingException),
TraceSR.GetString(TraceSR.ThrowingException), null, exception, activityId, null);
}
return exception;
}
internal static Exception ThrowHelperError(Exception exception, Guid activityId, object source)
{
if (DiagnosticUtility.ShouldTraceError)
{
DiagnosticUtility.DiagnosticTrace.TraceEvent(TraceEventType.Error, TraceCode.ThrowingException, GenerateMsdnTraceCode(TraceCode.ThrowingException),
TraceSR.GetString(TraceSR.ThrowingException), null, exception, activityId, source);
}
return exception;
}
internal static Exception ThrowHelperWarning(Exception exception, Message message)
{
if (DiagnosticUtility.ShouldTraceWarning)
{
Guid activityId = TraceUtility.ExtractActivityId(message);
DiagnosticUtility.DiagnosticTrace.TraceEvent(TraceEventType.Warning, TraceCode.ThrowingException, GenerateMsdnTraceCode(TraceCode.ThrowingException),
TraceSR.GetString(TraceSR.ThrowingException), null, exception, activityId, null);
}
return exception;
}
internal static ArgumentException ThrowHelperArgument(string paramName, string message, Message msg)
{
return (ArgumentException)TraceUtility.ThrowHelperError(new ArgumentException(message, paramName), msg);
}
internal static ArgumentNullException ThrowHelperArgumentNull(string paramName, Message message)
{
return (ArgumentNullException)TraceUtility.ThrowHelperError(new ArgumentNullException(paramName), message);
}
internal static string CreateSourceString(object source)
{
return source.GetType().ToString() + "/" + source.GetHashCode().ToString(CultureInfo.CurrentCulture);
}
internal static void TraceHttpConnectionInformation(string localEndpoint, string remoteEndpoint, object source)
{
if (DiagnosticUtility.ShouldTraceInformation)
{
Dictionary<string, string> values = new Dictionary<string, string>(2)
{
{ "LocalEndpoint", localEndpoint },
{ "RemoteEndpoint", remoteEndpoint }
};
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.ConnectToIPEndpoint,
SR.GetString(SR.TraceCodeConnectToIPEndpoint), new DictionaryTraceRecord(values), source, null);
}
}
internal static void TraceUserCodeException(Exception e, MethodInfo method)
{
if (DiagnosticUtility.ShouldTraceWarning)
{
StringTraceRecord record = new StringTraceRecord("Comment",
SR.GetString(SR.SFxUserCodeThrewException, method.DeclaringType.FullName, method.Name));
DiagnosticUtility.DiagnosticTrace.TraceEvent(TraceEventType.Warning,
TraceCode.UnhandledExceptionInUserOperation, GenerateMsdnTraceCode(TraceCode.UnhandledExceptionInUserOperation),
SR.GetString(SR.TraceCodeUnhandledExceptionInUserOperation, method.DeclaringType.FullName, method.Name),
record,
e, null);
}
}
static TraceUtility()
{
//Maintain the order of calls
TraceUtility.SetEtwProviderId();
TraceUtility.SetEndToEndTracingFlags();
if (DiagnosticUtility.DiagnosticTrace != null)
{
DiagnosticTraceSource ts = (DiagnosticTraceSource)DiagnosticUtility.DiagnosticTrace.TraceSource;
TraceUtility.shouldPropagateActivity = (ts.PropagateActivity || TraceUtility.shouldPropagateActivityGlobal);
}
}
[Fx.Tag.SecurityNote(Critical = "Calls critical method DiagnosticSection.UnsafeGetSection.",
Safe = "Doesn't leak config section instance, just reads and stores bool values.")]
[SecuritySafeCritical]
static void SetEndToEndTracingFlags()
{
EndToEndTracingElement element = DiagnosticSection.UnsafeGetSection().EndToEndTracing;
TraceUtility.shouldPropagateActivityGlobal = element.PropagateActivity;
// if Sys.Diag trace is not enabled then the value is true if shouldPropagateActivityGlobal is true
TraceUtility.shouldPropagateActivity = TraceUtility.shouldPropagateActivityGlobal || TraceUtility.shouldPropagateActivity;
//Activity tracing is enabled by either of the flags (Sys.Diag trace source or E2E config element)
DiagnosticUtility.ShouldUseActivity = (DiagnosticUtility.ShouldUseActivity || element.ActivityTracing);
TraceUtility.activityTracing = DiagnosticUtility.ShouldUseActivity;
TraceUtility.messageFlowTracing = element.MessageFlowTracing || TraceUtility.activityTracing;
TraceUtility.messageFlowTracingOnly = element.MessageFlowTracing && !element.ActivityTracing;
//Set the flag if activity tracing is enabled through the E2E config element as well
DiagnosticUtility.TracingEnabled = (DiagnosticUtility.TracingEnabled || TraceUtility.activityTracing);
}
static public long RetrieveMessageNumber()
{
return Interlocked.Increment(ref TraceUtility.messageNumber);
}
static public bool PropagateUserActivity
{
get
{
return TraceUtility.ShouldPropagateActivity &&
TraceUtility.PropagateUserActivityCore;
}
}
// Most of the time, shouldPropagateActivity will be false.
// This property will rarely be executed as a result.
static bool PropagateUserActivityCore
{
[MethodImpl(MethodImplOptions.NoInlining)]
get
{
return !(DiagnosticUtility.TracingEnabled) &&
DiagnosticTraceBase.ActivityId != Guid.Empty;
}
}
static internal string GetCallerInfo(OperationContext context)
{
if (context != null && context.IncomingMessageProperties != null)
{
object endpointMessageProperty;
if (context.IncomingMessageProperties.TryGetValue(RemoteEndpointMessageProperty.Name, out endpointMessageProperty))
{
RemoteEndpointMessageProperty endpoint = endpointMessageProperty as RemoteEndpointMessageProperty;
if (endpoint != null)
{
return string.Format(CultureInfo.InvariantCulture, "{0}:{1}", endpoint.Address, endpoint.Port);
}
}
}
return "null";
}
[Fx.Tag.SecurityNote(Critical = "Calls critical method DiagnosticSection.UnsafeGetSection.",
Safe = "Doesn't leak config section instance, just reads and stores string values for Guid")]
[SecuritySafeCritical]
static internal void SetEtwProviderId()
{
// Get section should not trace as the ETW provider id is not set yet
DiagnosticSection diagnostics = DiagnosticSection.UnsafeGetSectionNoTrace();
Guid etwProviderId = Guid.Empty;
//set the Id in PT if specified in the config file. If not, ETW tracing is off.
if (PartialTrustHelpers.HasEtwPermissions() || diagnostics.IsEtwProviderIdFromConfigFile())
{
etwProviderId = Fx.CreateGuid(diagnostics.EtwProviderId);
}
System.Runtime.Diagnostics.EtwDiagnosticTrace.DefaultEtwProviderId = etwProviderId;
}
static internal void SetActivityId(MessageProperties properties)
{
Guid activityId;
if ((null != properties) && properties.TryGetValue(TraceUtility.E2EActivityId, out activityId))
{
DiagnosticTraceBase.ActivityId = activityId;
}
}
static internal bool ShouldPropagateActivity
{
get { return TraceUtility.shouldPropagateActivity; }
}
static internal bool ShouldPropagateActivityGlobal
{
get { return TraceUtility.shouldPropagateActivityGlobal; }
}
static internal bool ActivityTracing
{
get { return TraceUtility.activityTracing; }
}
static internal bool MessageFlowTracing
{
get { return TraceUtility.messageFlowTracing; }
}
static internal bool MessageFlowTracingOnly
{
get { return TraceUtility.messageFlowTracingOnly; }
}
static internal void MessageFlowAtMessageSent(Message message, EventTraceActivity eventTraceActivity)
{
if (TraceUtility.MessageFlowTracing)
{
Guid activityId;
Guid correlationId;
bool activityIdFound = ActivityIdHeader.ExtractActivityAndCorrelationId(message, out activityId, out correlationId);
if (TraceUtility.MessageFlowTracingOnly)
{
if (activityIdFound && activityId != DiagnosticTraceBase.ActivityId)
{
DiagnosticTraceBase.ActivityId = activityId;
}
}
if (TD.MessageSentToTransportIsEnabled())
{
TD.MessageSentToTransport(eventTraceActivity, correlationId);
}
}
}
static internal void MessageFlowAtMessageReceived(Message message, OperationContext context, EventTraceActivity eventTraceActivity, bool createNewActivityId)
{
if (TraceUtility.MessageFlowTracing)
{
Guid activityId;
Guid correlationId;
bool activityIdFound = ActivityIdHeader.ExtractActivityAndCorrelationId(message, out activityId, out correlationId);
if (TraceUtility.MessageFlowTracingOnly)
{
if (createNewActivityId)
{
if (!activityIdFound)
{
activityId = Guid.NewGuid();
activityIdFound = true;
}
//message flow tracing only - start fresh
DiagnosticTraceBase.ActivityId = Guid.Empty;
}
if (activityIdFound)
{
FxTrace.Trace.SetAndTraceTransfer(activityId, !createNewActivityId);
message.Properties[TraceUtility.E2EActivityId] = Trace.CorrelationManager.ActivityId;
}
}
if (TD.MessageReceivedFromTransportIsEnabled())
{
if (context == null)
{
context = OperationContext.Current;
}
TD.MessageReceivedFromTransport(eventTraceActivity, correlationId, TraceUtility.GetAnnotation(context));
}
}
}
internal static string GetAnnotation(OperationContext context)
{
object hostReference;
if (context != null && null != context.IncomingMessage && (MessageState.Closed != context.IncomingMessage.State))
{
if (!context.IncomingMessageProperties.TryGetValue(TraceApplicationReference, out hostReference))
{
hostReference = AspNetEnvironment.Current.GetAnnotationFromHost(context.Host);
context.IncomingMessageProperties.Add(TraceApplicationReference, hostReference);
}
}
else
{
hostReference = AspNetEnvironment.Current.GetAnnotationFromHost(null);
}
return (string)hostReference;
}
internal static void TransferFromTransport(Message message)
{
if (message != null && DiagnosticUtility.ShouldUseActivity)
{
Guid guid = Guid.Empty;
// Only look if we are allowing user propagation
if (TraceUtility.ShouldPropagateActivity)
{
guid = ActivityIdHeader.ExtractActivityId(message);
}
if (guid == Guid.Empty)
{
guid = Guid.NewGuid();
}
ServiceModelActivity activity = null;
bool emitStart = true;
if (ServiceModelActivity.Current != null)
{
if ((ServiceModelActivity.Current.Id == guid) ||
(ServiceModelActivity.Current.ActivityType == ActivityType.ProcessAction))
{
activity = ServiceModelActivity.Current;
emitStart = false;
}
else if (ServiceModelActivity.Current.PreviousActivity != null &&
ServiceModelActivity.Current.PreviousActivity.Id == guid)
{
activity = ServiceModelActivity.Current.PreviousActivity;
emitStart = false;
}
}
if (activity == null)
{
activity = ServiceModelActivity.CreateActivity(guid);
}
if (DiagnosticUtility.ShouldUseActivity)
{
if (emitStart)
{
if (null != FxTrace.Trace)
{
FxTrace.Trace.TraceTransfer(guid);
}
ServiceModelActivity.Start(activity, SR.GetString(SR.ActivityProcessAction, message.Headers.Action), ActivityType.ProcessAction);
}
}
message.Properties[TraceUtility.ActivityIdKey] = activity;
}
}
static internal void UpdateAsyncOperationContextWithActivity(object activity)
{
if (OperationContext.Current != null && activity != null)
{
OperationContext.Current.OutgoingMessageProperties[TraceUtility.AsyncOperationActivityKey] = activity;
}
}
static internal object ExtractAsyncOperationContextActivity()
{
object data = null;
if (OperationContext.Current != null && OperationContext.Current.OutgoingMessageProperties.TryGetValue(TraceUtility.AsyncOperationActivityKey, out data))
{
OperationContext.Current.OutgoingMessageProperties.Remove(TraceUtility.AsyncOperationActivityKey);
}
return data;
}
static internal void UpdateAsyncOperationContextWithStartTime(EventTraceActivity eventTraceActivity, long startTime)
{
if (OperationContext.Current != null)
{
OperationContext.Current.OutgoingMessageProperties[TraceUtility.AsyncOperationStartTimeKey] = new EventTraceActivityTimeProperty(eventTraceActivity, startTime);
}
}
static internal void ExtractAsyncOperationStartTime(out EventTraceActivity eventTraceActivity, out long startTime)
{
EventTraceActivityTimeProperty data = null;
eventTraceActivity = null;
startTime = 0;
if (OperationContext.Current != null && OperationContext.Current.OutgoingMessageProperties.TryGetValue<EventTraceActivityTimeProperty>(TraceUtility.AsyncOperationStartTimeKey, out data))
{
OperationContext.Current.OutgoingMessageProperties.Remove(TraceUtility.AsyncOperationStartTimeKey);
eventTraceActivity = data.EventTraceActivity;
startTime = data.StartTime;
}
}
internal class TracingAsyncCallbackState
{
object innerState;
Guid activityId;
internal TracingAsyncCallbackState(object innerState)
{
this.innerState = innerState;
this.activityId = DiagnosticTraceBase.ActivityId;
}
internal object InnerState
{
get { return this.innerState; }
}
internal Guid ActivityId
{
get { return this.activityId; }
}
}
internal static AsyncCallback WrapExecuteUserCodeAsyncCallback(AsyncCallback callback)
{
return (DiagnosticUtility.ShouldUseActivity && callback != null) ?
(new ExecuteUserCodeAsync(callback)).Callback
: callback;
}
sealed class ExecuteUserCodeAsync
{
AsyncCallback callback;
public ExecuteUserCodeAsync(AsyncCallback callback)
{
this.callback = callback;
}
public AsyncCallback Callback
{
get
{
return Fx.ThunkCallback(new AsyncCallback(this.ExecuteUserCode));
}
}
void ExecuteUserCode(IAsyncResult result)
{
using (ServiceModelActivity activity = ServiceModelActivity.CreateBoundedActivity())
{
ServiceModelActivity.Start(activity, SR.GetString(SR.ActivityCallback), ActivityType.ExecuteUserCode);
this.callback(result);
}
}
}
class EventTraceActivityTimeProperty
{
long startTime;
EventTraceActivity eventTraceActivity;
public EventTraceActivityTimeProperty(EventTraceActivity eventTraceActivity, long startTime)
{
this.eventTraceActivity = eventTraceActivity;
this.startTime = startTime;
}
internal long StartTime
{
get { return this.startTime; }
}
internal EventTraceActivity EventTraceActivity
{
get { return this.eventTraceActivity; }
}
}
internal static string GetRemoteEndpointAddressPort(Net.IPEndPoint iPEndPoint)
{
//We really don't want any exceptions out of TraceUtility.
if (iPEndPoint != null)
{
try
{
return iPEndPoint.Address.ToString() + ":" + iPEndPoint.Port;
}
catch (Exception exception)
{
if (Fx.IsFatal(exception))
{
throw;
}
//ignore and continue with all non-fatal exceptions.
}
}
return string.Empty;
}
internal static string GetRemoteEndpointAddressPort(RemoteEndpointMessageProperty remoteEndpointMessageProperty)
{
try
{
if (remoteEndpointMessageProperty != null)
{
return remoteEndpointMessageProperty.Address + ":" + remoteEndpointMessageProperty.Port;
}
}
catch (Exception exception)
{
if (Fx.IsFatal(exception))
{
throw;
}
//ignore and continue with all non-fatal exceptions.
}
return string.Empty;
}
}
}
| |
//
// MonoTests.Remoting.BaseCalls.cs
//
// Author: Lluis Sanchez Gual ([email protected])
//
// 2003 (C) Copyright, Ximian, Inc.
//
using System;
using System.Net;
using System.Text;
using System.Threading;
using System.Collections;
using System.Globalization;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Lifetime;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting.Activation;
using System.Runtime.Remoting.Contexts;
using System.Runtime.InteropServices;
using NUnit.Framework;
namespace MonoTests.Remoting
{
public abstract class BaseCallTest
{
IChannelSender chs;
string[] remoteUris;
CallsDomainServer server;
int remoteDomId;
[TestFixtureSetUp]
public void Run()
{
remoteDomId = CreateServer ();
}
[TestFixtureTearDown]
public void End ()
{
ShutdownServer ();
}
protected virtual int CreateServer ()
{
ChannelManager cm = CreateChannelManager ();
chs = cm.CreateClientChannel ();
ChannelServices.RegisterChannel (chs);
AppDomain domain = AppDomain.CreateDomain ("testdomain");
server = (CallsDomainServer) domain.CreateInstanceAndUnwrap(GetType().Assembly.FullName,"MonoTests.Remoting.CallsDomainServer");
remoteUris = server.Start (cm);
return server.GetDomId ();
}
protected virtual void ShutdownServer ()
{
if (server != null) {
server.Stop ();
if (chs != null)
ChannelServices.UnregisterChannel (chs);
}
}
protected virtual RemoteObject CreateRemoteInstance ()
{
return (RemoteObject) Activator.GetObject (typeof(RemoteObject), remoteUris[0]);
}
protected virtual AbstractRemoteObject CreateRemoteAbstract ()
{
return (AbstractRemoteObject) Activator.GetObject (typeof(AbstractRemoteObject), remoteUris[1]);
}
protected virtual IRemoteObject CreateRemoteInterface ()
{
return (IRemoteObject) Activator.GetObject (typeof(IRemoteObject), remoteUris[2]);
}
public InstanceSurrogate InternalGetInstanceSurrogate ()
{
InstanceSurrogate s = GetInstanceSurrogate ();
s.RemoteObject = CreateRemoteInstance ();
return s;
}
public AbstractSurrogate InternalGetAbstractSurrogate ()
{
AbstractSurrogate s = GetAbstractSurrogate ();
s.RemoteObject = CreateRemoteAbstract ();
return s;
}
public InterfaceSurrogate InternalGetInterfaceSurrogate ()
{
InterfaceSurrogate s = GetInterfaceSurrogate ();
s.RemoteObject = CreateRemoteInterface ();
return s;
}
public abstract InstanceSurrogate GetInstanceSurrogate ();
public abstract AbstractSurrogate GetAbstractSurrogate ();
public abstract InterfaceSurrogate GetInterfaceSurrogate ();
public virtual ChannelManager CreateChannelManager ()
{
return null;
}
//
// The tests
//
[Test]
public void TestInstanceSimple ()
{
RunTestSimple (InternalGetInstanceSurrogate());
}
[Test]
public void TestAbstractSimple ()
{
RunTestSimple (InternalGetAbstractSurrogate());
}
[Test]
public void TestInterfaceSimple ()
{
RunTestSimple (InternalGetInterfaceSurrogate());
}
[Test]
public void TestInstancePrimitiveParams ()
{
RunTestPrimitiveParams (InternalGetInstanceSurrogate());
}
[Test]
public void TestAbstractPrimitiveParams ()
{
RunTestPrimitiveParams (InternalGetAbstractSurrogate());
}
[Test]
public void TestInterfacePrimitiveParams ()
{
RunTestPrimitiveParams (InternalGetInterfaceSurrogate());
}
[Test]
public void TestInstancePrimitiveParamsInOut ()
{
RunTestPrimitiveParamsInOut (InternalGetInstanceSurrogate());
}
[Test]
public void TestAbstractPrimitiveParamsInOut ()
{
RunTestPrimitiveParamsInOut (InternalGetAbstractSurrogate());
}
[Test]
public void TestInterfacePrimitiveParamsInOut ()
{
RunTestPrimitiveParamsInOut (InternalGetInterfaceSurrogate());
}
[Test]
public void TestInstanceComplexParams ()
{
RunTestComplexParams (InternalGetInstanceSurrogate());
}
[Test]
public void TestAbstractComplexParams ()
{
RunTestComplexParams (InternalGetAbstractSurrogate());
}
[Test]
public void TestInterfaceComplexParams ()
{
RunTestComplexParams (InternalGetInterfaceSurrogate());
}
[Test]
public void TestInstanceComplexParamsInOut ()
{
RunTestComplexParamsInOut (InternalGetInstanceSurrogate());
}
[Test]
public void TestAbstractComplexParamsInOut ()
{
RunTestComplexParamsInOut (InternalGetAbstractSurrogate());
}
[Test]
public void TestInterfaceComplexParamsInOut ()
{
RunTestComplexParamsInOut (InternalGetInterfaceSurrogate());
}
[Test]
public void TestInstanceProcessContextData ()
{
RunTestProcessContextData (InternalGetInstanceSurrogate());
}
[Test]
public void TestAbstractProcessContextData ()
{
RunTestProcessContextData (InternalGetAbstractSurrogate());
}
[Test]
public void TestInterfaceProcessContextData ()
{
RunTestProcessContextData (InternalGetInterfaceSurrogate());
}
//
// The tests runners
//
public void RunTestSimple (IRemoteObject testerSurrogate)
{
Assert.AreEqual (130772 + remoteDomId, testerSurrogate.Simple (), "ReturnValue");
}
public void RunTestPrimitiveParams (IRemoteObject testerSurrogate)
{
Assert.AreEqual ("11-22-L-SG@"+remoteDomId, testerSurrogate.PrimitiveParams (11, 22, 'L', "SG"), "ReturnValue");
}
public void RunTestPrimitiveParamsInOut (IRemoteObject testerSurrogate)
{
int a2, a1 = 9876543;
float b2, b1 = 82437.83f;
char c2, c1 = 's';
string d2, d1 = "asdASDzxcZXC";
string res = testerSurrogate.PrimitiveParamsInOut (ref a1, out a2, ref b1, out b2, 9821, ref c1, out c2, ref d1, out d2);
Assert.AreEqual ("9876543-82437.83-s-asdASDzxcZXC@" + remoteDomId, res, "ReturnValue");
Assert.AreEqual (12345678, a2, "a2");
Assert.AreEqual (53455.345f, b2, "b2");
Assert.AreEqual ('g', c2, "c2");
Assert.AreEqual ("sfARREG$5345DGDfgY7656gDFG>><<dasdasd", d2, "d2");
Assert.AreEqual (65748392, a1, "a1");
Assert.AreEqual (98395.654f, b1, "b1");
Assert.AreEqual ('l', c1, "c1");
Assert.AreEqual ("aasbasbdyhasbduybo234243", d1, "d1");
}
public void RunTestComplexParams (IRemoteObject testerSurrogate)
{
ArrayList list = new ArrayList ();
list.Add (new Complex (11,"first"));
Complex c = new Complex (22,"second");
Complex r = testerSurrogate.ComplexParams (list, c, "third");
Assert.IsNotNull (r, "ReturnValue is null");
Assert.IsNotNull (r.Child, "ReturnValue.Child is null");
Assert.IsNotNull (r.Child.Child, "ReturnValue.Child.Child is null");
Assert.AreEqual (33, r.Id, "ReturnValue.Id");
Assert.AreEqual ("third@"+remoteDomId, r.Name, "ReturnValue.Name");
Assert.AreEqual (22, r.Child.Id, "ReturnValue.Child.Id");
Assert.AreEqual ("second", r.Child.Name, "ReturnValue.Child.Name");
Assert.AreEqual (11, r.Child.Child.Id, "ReturnValue.Child.Child.Id");
Assert.AreEqual ("first", r.Child.Child.Name, "ReturnValue.Child.Child.Name");
}
public void RunTestComplexParamsInOut (IRemoteObject testerSurrogate)
{
ArrayList list = new ArrayList ();
list.Add (new Complex (11,"first"));
list.Add (new Complex (22,"second"));
byte[] bytes = new byte [100];
for (byte n=0; n<100; n++) bytes[n] = n;
StringBuilder sb = new StringBuilder ("hello from client");
Complex c;
Complex r = testerSurrogate.ComplexParamsInOut (ref list, out c, bytes, sb, "third");
Assert.IsNotNull (r, "ReturnValue is null");
Assert.IsNotNull (c, "c is null");
Assert.IsNotNull (list, "list is null");
Assert.IsTrue (list.Count == 3, "Invalid list count");
Assert.IsNotNull (list[0], "list[0] is null");
Assert.IsNotNull (list[1], "list[1] is null");
Assert.IsNotNull (list[2], "list[2] is null");
Assert.IsNotNull (bytes, "bytes is null");
Assert.IsNotNull (sb, "sb is null");
Assert.AreEqual (33, r.Id, "ReturnValue.Id");
Assert.AreEqual ("third@"+remoteDomId, r.Name, "ReturnValue.Name");
Assert.AreEqual (33, c.Id, "c.Id");
Assert.AreEqual ("third@"+remoteDomId, c.Name, "c.Name");
Assert.AreEqual (33, ((Complex)list[2]).Id, "list[2].Id");
Assert.AreEqual ("third@"+remoteDomId, ((Complex)list[2]).Name, "list[2].Name");
Assert.AreEqual (22, ((Complex)list[1]).Id, "list[1].Id");
Assert.AreEqual ("second", ((Complex)list[1]).Name, "list[1].Name");
Assert.AreEqual (11, ((Complex)list[0]).Id, "list[0].Id");
Assert.AreEqual ("first", ((Complex)list[0]).Name, "list[0].Name");
Assert.AreEqual ("hello from client and from server", sb.ToString (), "sb");
for (int n=0; n<100; n++)
Assert.AreEqual (n+1, bytes[n], "bytes["+n+"]");
}
public void RunTestProcessContextData (IRemoteObject testerSurrogate)
{
CallContext.FreeNamedDataSlot ("clientData");
CallContext.FreeNamedDataSlot ("serverData");
CallContext.FreeNamedDataSlot ("mustNotPass");
ContextData cdata = new ContextData ();
cdata.data = "hi from client";
cdata.id = 1123;
CallContext.SetData ("clientData", cdata);
CallContext.SetData ("mustNotPass", "more data");
testerSurrogate.ProcessContextData ();
cdata = CallContext.GetData ("clientData") as ContextData;
Assert.IsNotNull (cdata, "clientData is null");
Assert.AreEqual ("hi from client", cdata.data, "clientData.data");
Assert.AreEqual (1123, cdata.id, "clientData.id");
cdata = CallContext.GetData ("serverData") as ContextData;
Assert.IsNotNull (cdata, "serverData is null");
Assert.AreEqual ("hi from server", cdata.data, "serverData.data");
Assert.AreEqual (3211, cdata.id, "serverData.id");
string mdata = CallContext.GetData ("mustNotPass") as string;
Assert.IsNotNull (mdata, "mustNotPass is null");
Assert.AreEqual ("more data", mdata, "mustNotPass");
}
}
//
// The server running in the remote domain
//
class CallsDomainServer: MarshalByRefObject
{
IChannelReceiver ch;
public string[] Start(ChannelManager cm)
{
try
{
ch = cm.CreateServerChannel ();
ChannelServices.RegisterChannel ((IChannel)ch);
RemotingConfiguration.RegisterWellKnownServiceType (typeof (RemoteObject), "test1", WellKnownObjectMode.SingleCall);
RemotingConfiguration.RegisterWellKnownServiceType (typeof (RemoteObject), "test2", WellKnownObjectMode.SingleCall);
RemotingConfiguration.RegisterWellKnownServiceType (typeof (RemoteObject), "test3", WellKnownObjectMode.SingleCall);
string[] uris = new string[3];
uris[0] = ch.GetUrlsForUri ("test1")[0];
uris[1] = ch.GetUrlsForUri ("test2")[0];
uris[2] = ch.GetUrlsForUri ("test3")[0];
return uris;
}
catch (Exception ex)
{
Console.WriteLine (ex.ToString());
throw;
}
}
public void Stop ()
{
if (ch != null)
ChannelServices.UnregisterChannel (ch);
}
public int GetDomId ()
{
return Thread.GetDomainID();
}
}
[Serializable]
public class ContextData : ILogicalThreadAffinative
{
public string data;
public int id;
}
[Serializable]
public abstract class ChannelManager
{
public abstract IChannelSender CreateClientChannel ();
public abstract IChannelReceiver CreateServerChannel ();
}
//
// Test interface
//
public interface IRemoteObject
{
int Simple ();
string PrimitiveParams (int a, uint b, char c, string d);
string PrimitiveParamsInOut (ref int a1, out int a2, ref float b1, out float b2, int filler, ref char c1, out char c2, ref string d1, out string d2);
Complex ComplexParams (ArrayList a, Complex b, string c);
Complex ComplexParamsInOut (ref ArrayList a, out Complex b, [In,Out] byte[] bytes, [In,Out] StringBuilder sb, string c);
void ProcessContextData ();
}
// Base classes for tester surrogates
public abstract class InstanceSurrogate : IRemoteObject
{
public RemoteObject RemoteObject;
public abstract int Simple ();
public abstract string PrimitiveParams (int a, uint b, char c, string d);
public abstract string PrimitiveParamsInOut (ref int a1, out int a2, ref float b1, out float b2, int filler, ref char c1, out char c2, ref string d1, out string d2);
public abstract Complex ComplexParams (ArrayList a, Complex b, string c);
public abstract Complex ComplexParamsInOut (ref ArrayList a, out Complex b, [In,Out] byte[] bytes, [In,Out] StringBuilder sb, string c);
public abstract void ProcessContextData ();
}
public abstract class AbstractSurrogate : IRemoteObject
{
public AbstractRemoteObject RemoteObject;
public abstract int Simple ();
public abstract string PrimitiveParams (int a, uint b, char c, string d);
public abstract string PrimitiveParamsInOut (ref int a1, out int a2, ref float b1, out float b2, int filler, ref char c1, out char c2, ref string d1, out string d2);
public abstract Complex ComplexParams (ArrayList a, Complex b, string c);
public abstract Complex ComplexParamsInOut (ref ArrayList a, out Complex b, [In,Out] byte[] bytes, [In,Out] StringBuilder sb, string c);
public abstract void ProcessContextData ();
}
public abstract class InterfaceSurrogate : IRemoteObject
{
public IRemoteObject RemoteObject;
public abstract int Simple ();
public abstract string PrimitiveParams (int a, uint b, char c, string d);
public abstract string PrimitiveParamsInOut (ref int a1, out int a2, ref float b1, out float b2, int filler, ref char c1, out char c2, ref string d1, out string d2);
public abstract Complex ComplexParams (ArrayList a, Complex b, string c);
public abstract Complex ComplexParamsInOut (ref ArrayList a, out Complex b, [In,Out] byte[] bytes, [In,Out] StringBuilder sb, string c);
public abstract void ProcessContextData ();
}
//
// Test abstract base class
//
public abstract class AbstractRemoteObject : MarshalByRefObject
{
public abstract int Simple ();
public abstract string PrimitiveParams (int a, uint b, char c, string d);
public abstract string PrimitiveParamsInOut (ref int a1, out int a2, ref float b1, out float b2, int filler, ref char c1, out char c2, ref string d1, out string d2);
public abstract Complex ComplexParams (ArrayList a, Complex b, string c);
public abstract Complex ComplexParamsInOut (ref ArrayList a, out Complex b, [In,Out] byte[] bytes, [In,Out] StringBuilder sb, string c);
public abstract void ProcessContextData ();
}
//
// Test class
//
public class RemoteObject : AbstractRemoteObject, IRemoteObject
{
public override int Simple ()
{
return 130772 + Thread.GetDomainID();
}
public override string PrimitiveParams (int a, uint b, char c, string d)
{
return "" + a + "-" + b + "-" + c + "-" + d + "@" + Thread.GetDomainID();
}
public override string PrimitiveParamsInOut (ref int a1, out int a2, ref float b1, out float b2, int filler, ref char c1, out char c2, ref string d1, out string d2)
{
string res = "" + a1 + "-" + b1.ToString(CultureInfo.InvariantCulture) + "-" + c1 + "-" + d1 + "@" + Thread.GetDomainID();
a2 = 12345678;
b2 = 53455.345f;
c2 = 'g';
d2 = "sfARREG$5345DGDfgY7656gDFG>><<dasdasd";
a1 = 65748392;
b1 = 98395.654f;
c1 = 'l';
d1 = "aasbasbdyhasbduybo234243";
return res;
}
public override Complex ComplexParams (ArrayList a, Complex b, string c)
{
Complex cp = new Complex (33,c+ "@" + Thread.GetDomainID());
cp.Child = b;
cp.Child.Child = (Complex)a[0];
return cp;
}
public override Complex ComplexParamsInOut (ref ArrayList a, out Complex b, [In,Out] byte[] bytes, [In,Out] StringBuilder sb, string c)
{
b = new Complex (33,c+ "@" + Thread.GetDomainID());
a.Add (b);
for (byte n=0; n<100; n++) bytes[n] = (byte)(bytes[n] + 1);
sb.Append (" and from server");
return b;
}
public override void ProcessContextData ()
{
ContextData cdata = CallContext.GetData ("clientData") as ContextData;
if (cdata == null)
throw new Exception ("server: clientData is null");
if (cdata.data != "hi from client" || cdata.id != 1123)
throw new Exception ("server: clientData is not valid");
cdata = new ContextData ();
cdata.data = "hi from server";
cdata.id = 3211;
CallContext.SetData ("serverData", cdata);
string mdata = CallContext.GetData ("mustNotPass") as string;
if (mdata != null) throw new Exception ("mustNotPass is not null");
}
}
[Serializable]
public class Complex
{
public Complex (int id, string name)
{
Id = id;
Name = name;
}
public string Name;
public int Id;
public Complex Child;
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Org.Apache.Http.Client.Params.cs
//
// 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.
#pragma warning disable 1717
namespace Org.Apache.Http.Client.Params
{
/// <java-name>
/// org/apache/http/client/params/CookiePolicy
/// </java-name>
[Dot42.DexImport("org/apache/http/client/params/CookiePolicy", AccessFlags = 49)]
public sealed partial class CookiePolicy
/* scope: __dot42__ */
{
/// <summary>
/// <para>The policy that provides high degree of compatibilty with common cookie management of popular HTTP agents. </para>
/// </summary>
/// <java-name>
/// BROWSER_COMPATIBILITY
/// </java-name>
[Dot42.DexImport("BROWSER_COMPATIBILITY", "Ljava/lang/String;", AccessFlags = 25)]
public const string BROWSER_COMPATIBILITY = "compatibility";
/// <summary>
/// <para>The Netscape cookie draft compliant policy. </para>
/// </summary>
/// <java-name>
/// NETSCAPE
/// </java-name>
[Dot42.DexImport("NETSCAPE", "Ljava/lang/String;", AccessFlags = 25)]
public const string NETSCAPE = "netscape";
/// <summary>
/// <para>The RFC 2109 compliant policy. </para>
/// </summary>
/// <java-name>
/// RFC_2109
/// </java-name>
[Dot42.DexImport("RFC_2109", "Ljava/lang/String;", AccessFlags = 25)]
public const string RFC_2109 = "rfc2109";
/// <summary>
/// <para>The RFC 2965 compliant policy. </para>
/// </summary>
/// <java-name>
/// RFC_2965
/// </java-name>
[Dot42.DexImport("RFC_2965", "Ljava/lang/String;", AccessFlags = 25)]
public const string RFC_2965 = "rfc2965";
/// <summary>
/// <para>The default 'best match' policy. </para>
/// </summary>
/// <java-name>
/// BEST_MATCH
/// </java-name>
[Dot42.DexImport("BEST_MATCH", "Ljava/lang/String;", AccessFlags = 25)]
public const string BEST_MATCH = "best-match";
[Dot42.DexImport("<init>", "()V", AccessFlags = 0)]
internal CookiePolicy() /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>An adaptor for accessing HTTP client parameters in HttpParams.</para><para><para></para><para></para><title>Revision:</title><para>659595 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/params/HttpClientParams
/// </java-name>
[Dot42.DexImport("org/apache/http/client/params/HttpClientParams", AccessFlags = 33)]
public partial class HttpClientParams
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 0)]
internal HttpClientParams() /* MethodBuilder.Create */
{
}
/// <java-name>
/// isRedirecting
/// </java-name>
[Dot42.DexImport("isRedirecting", "(Lorg/apache/http/params/HttpParams;)Z", AccessFlags = 9)]
public static bool IsRedirecting(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// setRedirecting
/// </java-name>
[Dot42.DexImport("setRedirecting", "(Lorg/apache/http/params/HttpParams;Z)V", AccessFlags = 9)]
public static void SetRedirecting(global::Org.Apache.Http.Params.IHttpParams @params, bool value) /* MethodBuilder.Create */
{
}
/// <java-name>
/// isAuthenticating
/// </java-name>
[Dot42.DexImport("isAuthenticating", "(Lorg/apache/http/params/HttpParams;)Z", AccessFlags = 9)]
public static bool IsAuthenticating(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// setAuthenticating
/// </java-name>
[Dot42.DexImport("setAuthenticating", "(Lorg/apache/http/params/HttpParams;Z)V", AccessFlags = 9)]
public static void SetAuthenticating(global::Org.Apache.Http.Params.IHttpParams @params, bool value) /* MethodBuilder.Create */
{
}
/// <java-name>
/// getCookiePolicy
/// </java-name>
[Dot42.DexImport("getCookiePolicy", "(Lorg/apache/http/params/HttpParams;)Ljava/lang/String;", AccessFlags = 9)]
public static string GetCookiePolicy(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// setCookiePolicy
/// </java-name>
[Dot42.DexImport("setCookiePolicy", "(Lorg/apache/http/params/HttpParams;Ljava/lang/String;)V", AccessFlags = 9)]
public static void SetCookiePolicy(global::Org.Apache.Http.Params.IHttpParams @params, string cookiePolicy) /* MethodBuilder.Create */
{
}
}
/// <java-name>
/// org/apache/http/client/params/AuthPolicy
/// </java-name>
[Dot42.DexImport("org/apache/http/client/params/AuthPolicy", AccessFlags = 49)]
public sealed partial class AuthPolicy
/* scope: __dot42__ */
{
/// <summary>
/// <para>The NTLM scheme is a proprietary Microsoft Windows Authentication protocol (considered to be the most secure among currently supported authentication schemes). </para>
/// </summary>
/// <java-name>
/// NTLM
/// </java-name>
[Dot42.DexImport("NTLM", "Ljava/lang/String;", AccessFlags = 25)]
public const string NTLM = "NTLM";
/// <summary>
/// <para>Digest authentication scheme as defined in RFC2617. </para>
/// </summary>
/// <java-name>
/// DIGEST
/// </java-name>
[Dot42.DexImport("DIGEST", "Ljava/lang/String;", AccessFlags = 25)]
public const string DIGEST = "Digest";
/// <summary>
/// <para>Basic authentication scheme as defined in RFC2617 (considered inherently insecure, but most widely supported) </para>
/// </summary>
/// <java-name>
/// BASIC
/// </java-name>
[Dot42.DexImport("BASIC", "Ljava/lang/String;", AccessFlags = 25)]
public const string BASIC = "Basic";
[Dot42.DexImport("<init>", "()V", AccessFlags = 0)]
internal AuthPolicy() /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>Collected parameter names for the HttpClient module. This interface combines the parameter definitions of the HttpClient module and all dependency modules or informational units. It does not define additional parameter names, but references other interfaces defining parameter names. <br></br> This interface is meant as a navigation aid for developers. When referring to parameter names, you should use the interfaces in which the respective constants are actually defined.</para><para><para></para><title>Revision:</title><para>576078 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/params/AllClientPNames
/// </java-name>
[Dot42.DexImport("org/apache/http/client/params/AllClientPNames", AccessFlags = 1537)]
public partial interface IAllClientPNames : global::Org.Apache.Http.Params.ICoreConnectionPNames, global::Org.Apache.Http.Params.ICoreProtocolPNames, global::Org.Apache.Http.Client.Params.IClientPNames, global::Org.Apache.Http.Auth.Params.IAuthPNames, global::Org.Apache.Http.Cookie.Params.ICookieSpecPNames, global::Org.Apache.Http.Conn.Params.IConnConnectionPNames, global::Org.Apache.Http.Conn.Params.IConnManagerPNames, global::Org.Apache.Http.Conn.Params.IConnRoutePNames
/* scope: __dot42__ */
{
}
/// <summary>
/// <para>Parameter names for the HttpClient module. This does not include parameters for informational units HttpAuth, HttpCookie, or HttpConn.</para><para><para></para><title>Revision:</title><para>659595 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/params/ClientPNames
/// </java-name>
[Dot42.DexImport("org/apache/http/client/params/ClientPNames", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class IClientPNamesConstants
/* scope: __dot42__ */
{
/// <summary>
/// <para>Defines the class name of the default org.apache.http.conn.ClientConnectionManager </para><para>This parameter expects a value of type String. </para>
/// </summary>
/// <java-name>
/// CONNECTION_MANAGER_FACTORY_CLASS_NAME
/// </java-name>
[Dot42.DexImport("CONNECTION_MANAGER_FACTORY_CLASS_NAME", "Ljava/lang/String;", AccessFlags = 25)]
public const string CONNECTION_MANAGER_FACTORY_CLASS_NAME = "http.connection-manager.factory-class-name";
/// <summary>
/// <para>Defines the factory to create a default org.apache.http.conn.ClientConnectionManager. </para><para>This parameters expects a value of type org.apache.http.conn.ClientConnectionManagerFactory. </para>
/// </summary>
/// <java-name>
/// CONNECTION_MANAGER_FACTORY
/// </java-name>
[Dot42.DexImport("CONNECTION_MANAGER_FACTORY", "Ljava/lang/String;", AccessFlags = 25)]
public const string CONNECTION_MANAGER_FACTORY = "http.connection-manager.factory-object";
/// <summary>
/// <para>Defines whether redirects should be handled automatically </para><para>This parameter expects a value of type Boolean. </para>
/// </summary>
/// <java-name>
/// HANDLE_REDIRECTS
/// </java-name>
[Dot42.DexImport("HANDLE_REDIRECTS", "Ljava/lang/String;", AccessFlags = 25)]
public const string HANDLE_REDIRECTS = "http.protocol.handle-redirects";
/// <summary>
/// <para>Defines whether relative redirects should be rejected. </para><para>This parameter expects a value of type Boolean. </para>
/// </summary>
/// <java-name>
/// REJECT_RELATIVE_REDIRECT
/// </java-name>
[Dot42.DexImport("REJECT_RELATIVE_REDIRECT", "Ljava/lang/String;", AccessFlags = 25)]
public const string REJECT_RELATIVE_REDIRECT = "http.protocol.reject-relative-redirect";
/// <summary>
/// <para>Defines the maximum number of redirects to be followed. The limit on number of redirects is intended to prevent infinite loops. </para><para>This parameter expects a value of type Integer. </para>
/// </summary>
/// <java-name>
/// MAX_REDIRECTS
/// </java-name>
[Dot42.DexImport("MAX_REDIRECTS", "Ljava/lang/String;", AccessFlags = 25)]
public const string MAX_REDIRECTS = "http.protocol.max-redirects";
/// <summary>
/// <para>Defines whether circular redirects (redirects to the same location) should be allowed. The HTTP spec is not sufficiently clear whether circular redirects are permitted, therefore optionally they can be enabled </para><para>This parameter expects a value of type Boolean. </para>
/// </summary>
/// <java-name>
/// ALLOW_CIRCULAR_REDIRECTS
/// </java-name>
[Dot42.DexImport("ALLOW_CIRCULAR_REDIRECTS", "Ljava/lang/String;", AccessFlags = 25)]
public const string ALLOW_CIRCULAR_REDIRECTS = "http.protocol.allow-circular-redirects";
/// <summary>
/// <para>Defines whether authentication should be handled automatically. </para><para>This parameter expects a value of type Boolean. </para>
/// </summary>
/// <java-name>
/// HANDLE_AUTHENTICATION
/// </java-name>
[Dot42.DexImport("HANDLE_AUTHENTICATION", "Ljava/lang/String;", AccessFlags = 25)]
public const string HANDLE_AUTHENTICATION = "http.protocol.handle-authentication";
/// <summary>
/// <para>Defines the name of the cookie specification to be used for HTTP state management. </para><para>This parameter expects a value of type String. </para>
/// </summary>
/// <java-name>
/// COOKIE_POLICY
/// </java-name>
[Dot42.DexImport("COOKIE_POLICY", "Ljava/lang/String;", AccessFlags = 25)]
public const string COOKIE_POLICY = "http.protocol.cookie-policy";
/// <summary>
/// <para>Defines the virtual host name. </para><para>This parameter expects a value of type org.apache.http.HttpHost. </para>
/// </summary>
/// <java-name>
/// VIRTUAL_HOST
/// </java-name>
[Dot42.DexImport("VIRTUAL_HOST", "Ljava/lang/String;", AccessFlags = 25)]
public const string VIRTUAL_HOST = "http.virtual-host";
/// <summary>
/// <para>Defines the request headers to be sent per default with each request. </para><para>This parameter expects a value of type java.util.Collection. The collection is expected to contain org.apache.http.Headers. </para>
/// </summary>
/// <java-name>
/// DEFAULT_HEADERS
/// </java-name>
[Dot42.DexImport("DEFAULT_HEADERS", "Ljava/lang/String;", AccessFlags = 25)]
public const string DEFAULT_HEADERS = "http.default-headers";
/// <summary>
/// <para>Defines the default host. The default value will be used if the target host is not explicitly specified in the request URI. </para><para>This parameter expects a value of type org.apache.http.HttpHost. </para>
/// </summary>
/// <java-name>
/// DEFAULT_HOST
/// </java-name>
[Dot42.DexImport("DEFAULT_HOST", "Ljava/lang/String;", AccessFlags = 25)]
public const string DEFAULT_HOST = "http.default-host";
}
/// <summary>
/// <para>Parameter names for the HttpClient module. This does not include parameters for informational units HttpAuth, HttpCookie, or HttpConn.</para><para><para></para><title>Revision:</title><para>659595 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/params/ClientPNames
/// </java-name>
[Dot42.DexImport("org/apache/http/client/params/ClientPNames", AccessFlags = 1537)]
public partial interface IClientPNames
/* scope: __dot42__ */
{
}
/// <java-name>
/// org/apache/http/client/params/ClientParamBean
/// </java-name>
[Dot42.DexImport("org/apache/http/client/params/ClientParamBean", AccessFlags = 33)]
public partial class ClientParamBean : global::Org.Apache.Http.Params.HttpAbstractParamBean
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)]
public ClientParamBean(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setConnectionManagerFactoryClassName
/// </java-name>
[Dot42.DexImport("setConnectionManagerFactoryClassName", "(Ljava/lang/String;)V", AccessFlags = 1)]
public virtual void SetConnectionManagerFactoryClassName(string factory) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setConnectionManagerFactory
/// </java-name>
[Dot42.DexImport("setConnectionManagerFactory", "(Lorg/apache/http/conn/ClientConnectionManagerFactory;)V", AccessFlags = 1)]
public virtual void SetConnectionManagerFactory(global::Org.Apache.Http.Conn.IClientConnectionManagerFactory factory) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setHandleRedirects
/// </java-name>
[Dot42.DexImport("setHandleRedirects", "(Z)V", AccessFlags = 1)]
public virtual void SetHandleRedirects(bool handle) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setRejectRelativeRedirect
/// </java-name>
[Dot42.DexImport("setRejectRelativeRedirect", "(Z)V", AccessFlags = 1)]
public virtual void SetRejectRelativeRedirect(bool reject) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setMaxRedirects
/// </java-name>
[Dot42.DexImport("setMaxRedirects", "(I)V", AccessFlags = 1)]
public virtual void SetMaxRedirects(int maxRedirects) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setAllowCircularRedirects
/// </java-name>
[Dot42.DexImport("setAllowCircularRedirects", "(Z)V", AccessFlags = 1)]
public virtual void SetAllowCircularRedirects(bool allow) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setHandleAuthentication
/// </java-name>
[Dot42.DexImport("setHandleAuthentication", "(Z)V", AccessFlags = 1)]
public virtual void SetHandleAuthentication(bool handle) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setCookiePolicy
/// </java-name>
[Dot42.DexImport("setCookiePolicy", "(Ljava/lang/String;)V", AccessFlags = 1)]
public virtual void SetCookiePolicy(string policy) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setVirtualHost
/// </java-name>
[Dot42.DexImport("setVirtualHost", "(Lorg/apache/http/HttpHost;)V", AccessFlags = 1)]
public virtual void SetVirtualHost(global::Org.Apache.Http.HttpHost host) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setDefaultHeaders
/// </java-name>
[Dot42.DexImport("setDefaultHeaders", "(Ljava/util/Collection;)V", AccessFlags = 1, Signature = "(Ljava/util/Collection<Lorg/apache/http/Header;>;)V")]
public virtual void SetDefaultHeaders(global::Java.Util.ICollection<global::Org.Apache.Http.IHeader> headers) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setDefaultHost
/// </java-name>
[Dot42.DexImport("setDefaultHost", "(Lorg/apache/http/HttpHost;)V", AccessFlags = 1)]
public virtual void SetDefaultHost(global::Org.Apache.Http.HttpHost host) /* MethodBuilder.Create */
{
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal ClientParamBean() /* TypeBuilder.AddDefaultConstructor */
{
}
}
}
| |
/*
* 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.Net;
using System.Reflection;
using System.Threading;
using log4net;
using OpenMetaverse;
using OpenMetaverse.Packets;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Framework.Client;
namespace OpenSim.Tests.Common.Mock
{
public class TestClient : IClientAPI, IClientCore
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
EventWaitHandle wh = new EventWaitHandle (false, EventResetMode.AutoReset, "Crossing");
private Scene m_scene;
// Properties so that we can get at received data for test purposes
public List<uint> ReceivedKills { get; private set; }
public List<UUID> ReceivedOfflineNotifications { get; private set; }
public List<UUID> ReceivedOnlineNotifications { get; private set; }
public List<UUID> ReceivedFriendshipTerminations { get; private set; }
public List<ImageDataPacket> SentImageDataPackets { get; private set; }
public List<ImagePacketPacket> SentImagePacketPackets { get; private set; }
public List<ImageNotInDatabasePacket> SentImageNotInDatabasePackets { get; private set; }
// Test client specific events - for use by tests to implement some IClientAPI behaviour.
public event Action<RegionInfo, Vector3, Vector3> OnReceivedMoveAgentIntoRegion;
public event Action<ulong, IPEndPoint> OnTestClientInformClientOfNeighbour;
public event TestClientOnSendRegionTeleportDelegate OnTestClientSendRegionTeleport;
public event Action<ISceneEntity, PrimUpdateFlags> OnReceivedEntityUpdate;
public event Action<GridInstantMessage> OnReceivedInstantMessage;
public event Action<UUID> OnReceivedSendRebakeAvatarTextures;
public delegate void TestClientOnSendRegionTeleportDelegate(
ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint,
uint locationID, uint flags, string capsURL);
// disable warning: public events, part of the public API
#pragma warning disable 67
public event Action<IClientAPI> OnLogout;
public event ObjectPermissions OnObjectPermissions;
public event MoneyTransferRequest OnMoneyTransferRequest;
public event ParcelBuy OnParcelBuy;
public event Action<IClientAPI> OnConnectionClosed;
public event ImprovedInstantMessage OnInstantMessage;
public event ChatMessage OnChatFromClient;
public event TextureRequest OnRequestTexture;
public event RezObject OnRezObject;
public event ModifyTerrain OnModifyTerrain;
public event BakeTerrain OnBakeTerrain;
public event SetAppearance OnSetAppearance;
public event AvatarNowWearing OnAvatarNowWearing;
public event RezSingleAttachmentFromInv OnRezSingleAttachmentFromInv;
public event RezMultipleAttachmentsFromInv OnRezMultipleAttachmentsFromInv;
public event UUIDNameRequest OnDetachAttachmentIntoInv;
public event ObjectAttach OnObjectAttach;
public event ObjectDeselect OnObjectDetach;
public event ObjectDrop OnObjectDrop;
public event StartAnim OnStartAnim;
public event StopAnim OnStopAnim;
public event LinkObjects OnLinkObjects;
public event DelinkObjects OnDelinkObjects;
public event RequestMapBlocks OnRequestMapBlocks;
public event RequestMapName OnMapNameRequest;
public event TeleportLocationRequest OnTeleportLocationRequest;
public event TeleportLandmarkRequest OnTeleportLandmarkRequest;
public event TeleportCancel OnTeleportCancel;
public event DisconnectUser OnDisconnectUser;
public event RequestAvatarProperties OnRequestAvatarProperties;
public event SetAlwaysRun OnSetAlwaysRun;
public event DeRezObject OnDeRezObject;
public event Action<IClientAPI> OnRegionHandShakeReply;
public event GenericCall1 OnRequestWearables;
public event Action<IClientAPI, bool> OnCompleteMovementToRegion;
public event UpdateAgent OnPreAgentUpdate;
public event UpdateAgent OnAgentUpdate;
public event UpdateAgent OnAgentCameraUpdate;
public event AgentRequestSit OnAgentRequestSit;
public event AgentSit OnAgentSit;
public event AvatarPickerRequest OnAvatarPickerRequest;
public event Action<IClientAPI> OnRequestAvatarsData;
public event AddNewPrim OnAddPrim;
public event RequestGodlikePowers OnRequestGodlikePowers;
public event GodKickUser OnGodKickUser;
public event ObjectDuplicate OnObjectDuplicate;
public event GrabObject OnGrabObject;
public event DeGrabObject OnDeGrabObject;
public event MoveObject OnGrabUpdate;
public event SpinStart OnSpinStart;
public event SpinObject OnSpinUpdate;
public event SpinStop OnSpinStop;
public event ViewerEffectEventHandler OnViewerEffect;
public event FetchInventory OnAgentDataUpdateRequest;
public event TeleportLocationRequest OnSetStartLocationRequest;
public event UpdateShape OnUpdatePrimShape;
public event ObjectExtraParams OnUpdateExtraParams;
public event RequestObjectPropertiesFamily OnRequestObjectPropertiesFamily;
public event ObjectSelect OnObjectSelect;
public event ObjectRequest OnObjectRequest;
public event GenericCall7 OnObjectDescription;
public event GenericCall7 OnObjectName;
public event GenericCall7 OnObjectClickAction;
public event GenericCall7 OnObjectMaterial;
public event UpdatePrimFlags OnUpdatePrimFlags;
public event UpdatePrimTexture OnUpdatePrimTexture;
public event UpdateVector OnUpdatePrimGroupPosition;
public event UpdateVector OnUpdatePrimSinglePosition;
public event UpdatePrimRotation OnUpdatePrimGroupRotation;
public event UpdatePrimSingleRotation OnUpdatePrimSingleRotation;
public event UpdatePrimSingleRotationPosition OnUpdatePrimSingleRotationPosition;
public event UpdatePrimGroupRotation OnUpdatePrimGroupMouseRotation;
public event UpdateVector OnUpdatePrimScale;
public event UpdateVector OnUpdatePrimGroupScale;
public event StatusChange OnChildAgentStatus;
public event GenericCall2 OnStopMovement;
public event Action<UUID> OnRemoveAvatar;
public event CreateNewInventoryItem OnCreateNewInventoryItem;
public event LinkInventoryItem OnLinkInventoryItem;
public event CreateInventoryFolder OnCreateNewInventoryFolder;
public event UpdateInventoryFolder OnUpdateInventoryFolder;
public event MoveInventoryFolder OnMoveInventoryFolder;
public event RemoveInventoryFolder OnRemoveInventoryFolder;
public event RemoveInventoryItem OnRemoveInventoryItem;
public event FetchInventoryDescendents OnFetchInventoryDescendents;
public event PurgeInventoryDescendents OnPurgeInventoryDescendents;
public event FetchInventory OnFetchInventory;
public event RequestTaskInventory OnRequestTaskInventory;
public event UpdateInventoryItem OnUpdateInventoryItem;
public event CopyInventoryItem OnCopyInventoryItem;
public event MoveInventoryItem OnMoveInventoryItem;
public event UDPAssetUploadRequest OnAssetUploadRequest;
public event RequestTerrain OnRequestTerrain;
public event RequestTerrain OnUploadTerrain;
public event XferReceive OnXferReceive;
public event RequestXfer OnRequestXfer;
public event ConfirmXfer OnConfirmXfer;
public event AbortXfer OnAbortXfer;
public event RezScript OnRezScript;
public event UpdateTaskInventory OnUpdateTaskInventory;
public event MoveTaskInventory OnMoveTaskItem;
public event RemoveTaskInventory OnRemoveTaskItem;
public event RequestAsset OnRequestAsset;
public event GenericMessage OnGenericMessage;
public event UUIDNameRequest OnNameFromUUIDRequest;
public event UUIDNameRequest OnUUIDGroupNameRequest;
public event ParcelPropertiesRequest OnParcelPropertiesRequest;
public event ParcelDivideRequest OnParcelDivideRequest;
public event ParcelJoinRequest OnParcelJoinRequest;
public event ParcelPropertiesUpdateRequest OnParcelPropertiesUpdateRequest;
public event ParcelAbandonRequest OnParcelAbandonRequest;
public event ParcelGodForceOwner OnParcelGodForceOwner;
public event ParcelReclaim OnParcelReclaim;
public event ParcelReturnObjectsRequest OnParcelReturnObjectsRequest;
public event ParcelAccessListRequest OnParcelAccessListRequest;
public event ParcelAccessListUpdateRequest OnParcelAccessListUpdateRequest;
public event ParcelSelectObjects OnParcelSelectObjects;
public event ParcelObjectOwnerRequest OnParcelObjectOwnerRequest;
public event ParcelDeedToGroup OnParcelDeedToGroup;
public event ObjectDeselect OnObjectDeselect;
public event RegionInfoRequest OnRegionInfoRequest;
public event EstateCovenantRequest OnEstateCovenantRequest;
public event EstateChangeInfo OnEstateChangeInfo;
public event EstateManageTelehub OnEstateManageTelehub;
public event CachedTextureRequest OnCachedTextureRequest;
public event ObjectDuplicateOnRay OnObjectDuplicateOnRay;
public event FriendActionDelegate OnApproveFriendRequest;
public event FriendActionDelegate OnDenyFriendRequest;
public event FriendshipTermination OnTerminateFriendship;
public event GrantUserFriendRights OnGrantUserRights;
public event EconomyDataRequest OnEconomyDataRequest;
public event MoneyBalanceRequest OnMoneyBalanceRequest;
public event UpdateAvatarProperties OnUpdateAvatarProperties;
public event ObjectIncludeInSearch OnObjectIncludeInSearch;
public event UUIDNameRequest OnTeleportHomeRequest;
public event ScriptAnswer OnScriptAnswer;
public event RequestPayPrice OnRequestPayPrice;
public event ObjectSaleInfo OnObjectSaleInfo;
public event ObjectBuy OnObjectBuy;
public event BuyObjectInventory OnBuyObjectInventory;
public event AgentSit OnUndo;
public event AgentSit OnRedo;
public event LandUndo OnLandUndo;
public event ForceReleaseControls OnForceReleaseControls;
public event GodLandStatRequest OnLandStatRequest;
public event RequestObjectPropertiesFamily OnObjectGroupRequest;
public event DetailedEstateDataRequest OnDetailedEstateDataRequest;
public event SetEstateFlagsRequest OnSetEstateFlagsRequest;
public event SetEstateTerrainBaseTexture OnSetEstateTerrainBaseTexture;
public event SetEstateTerrainDetailTexture OnSetEstateTerrainDetailTexture;
public event SetEstateTerrainTextureHeights OnSetEstateTerrainTextureHeights;
public event CommitEstateTerrainTextureRequest OnCommitEstateTerrainTextureRequest;
public event SetRegionTerrainSettings OnSetRegionTerrainSettings;
public event EstateRestartSimRequest OnEstateRestartSimRequest;
public event EstateChangeCovenantRequest OnEstateChangeCovenantRequest;
public event UpdateEstateAccessDeltaRequest OnUpdateEstateAccessDeltaRequest;
public event SimulatorBlueBoxMessageRequest OnSimulatorBlueBoxMessageRequest;
public event EstateBlueBoxMessageRequest OnEstateBlueBoxMessageRequest;
public event EstateDebugRegionRequest OnEstateDebugRegionRequest;
public event EstateTeleportOneUserHomeRequest OnEstateTeleportOneUserHomeRequest;
public event EstateTeleportAllUsersHomeRequest OnEstateTeleportAllUsersHomeRequest;
public event ScriptReset OnScriptReset;
public event GetScriptRunning OnGetScriptRunning;
public event SetScriptRunning OnSetScriptRunning;
public event Action<Vector3, bool, bool> OnAutoPilotGo;
public event TerrainUnacked OnUnackedTerrain;
public event RegionHandleRequest OnRegionHandleRequest;
public event ParcelInfoRequest OnParcelInfoRequest;
public event ActivateGesture OnActivateGesture;
public event DeactivateGesture OnDeactivateGesture;
public event ObjectOwner OnObjectOwner;
public event DirPlacesQuery OnDirPlacesQuery;
public event DirFindQuery OnDirFindQuery;
public event DirLandQuery OnDirLandQuery;
public event DirPopularQuery OnDirPopularQuery;
public event DirClassifiedQuery OnDirClassifiedQuery;
public event EventInfoRequest OnEventInfoRequest;
public event ParcelSetOtherCleanTime OnParcelSetOtherCleanTime;
public event MapItemRequest OnMapItemRequest;
public event OfferCallingCard OnOfferCallingCard;
public event AcceptCallingCard OnAcceptCallingCard;
public event DeclineCallingCard OnDeclineCallingCard;
public event SoundTrigger OnSoundTrigger;
public event StartLure OnStartLure;
public event TeleportLureRequest OnTeleportLureRequest;
public event NetworkStats OnNetworkStatsUpdate;
public event ClassifiedInfoRequest OnClassifiedInfoRequest;
public event ClassifiedInfoUpdate OnClassifiedInfoUpdate;
public event ClassifiedDelete OnClassifiedDelete;
public event ClassifiedDelete OnClassifiedGodDelete;
public event EventNotificationAddRequest OnEventNotificationAddRequest;
public event EventNotificationRemoveRequest OnEventNotificationRemoveRequest;
public event EventGodDelete OnEventGodDelete;
public event ParcelDwellRequest OnParcelDwellRequest;
public event UserInfoRequest OnUserInfoRequest;
public event UpdateUserInfo OnUpdateUserInfo;
public event RetrieveInstantMessages OnRetrieveInstantMessages;
public event PickDelete OnPickDelete;
public event PickGodDelete OnPickGodDelete;
public event PickInfoUpdate OnPickInfoUpdate;
public event AvatarNotesUpdate OnAvatarNotesUpdate;
public event MuteListRequest OnMuteListRequest;
public event AvatarInterestUpdate OnAvatarInterestUpdate;
public event PlacesQuery OnPlacesQuery;
public event FindAgentUpdate OnFindAgent;
public event TrackAgentUpdate OnTrackAgent;
public event NewUserReport OnUserReport;
public event SaveStateHandler OnSaveState;
public event GroupAccountSummaryRequest OnGroupAccountSummaryRequest;
public event GroupAccountDetailsRequest OnGroupAccountDetailsRequest;
public event GroupAccountTransactionsRequest OnGroupAccountTransactionsRequest;
public event FreezeUserUpdate OnParcelFreezeUser;
public event EjectUserUpdate OnParcelEjectUser;
public event ParcelBuyPass OnParcelBuyPass;
public event ParcelGodMark OnParcelGodMark;
public event GroupActiveProposalsRequest OnGroupActiveProposalsRequest;
public event GroupVoteHistoryRequest OnGroupVoteHistoryRequest;
public event SimWideDeletesDelegate OnSimWideDeletes;
public event SendPostcard OnSendPostcard;
public event MuteListEntryUpdate OnUpdateMuteListEntry;
public event MuteListEntryRemove OnRemoveMuteListEntry;
public event GodlikeMessage onGodlikeMessage;
public event GodUpdateRegionInfoUpdate OnGodUpdateRegionInfoUpdate;
#pragma warning restore 67
/// <value>
/// This agent's UUID
/// </value>
private UUID m_agentId;
public ISceneAgent SceneAgent { get; set; }
/// <value>
/// The last caps seed url that this client was given.
/// </value>
public string CapsSeedUrl;
private Vector3 startPos = new Vector3(((int)Constants.RegionSize * 0.5f), ((int)Constants.RegionSize * 0.5f), 2);
public virtual Vector3 StartPos
{
get { return startPos; }
set { }
}
public virtual UUID AgentId
{
get { return m_agentId; }
}
public UUID SessionId { get; set; }
public UUID SecureSessionId { get; set; }
public virtual string FirstName
{
get { return m_firstName; }
}
private string m_firstName;
public virtual string LastName
{
get { return m_lastName; }
}
private string m_lastName;
public virtual String Name
{
get { return FirstName + " " + LastName; }
}
public bool IsActive
{
get { return true; }
set { }
}
public bool IsLoggingOut { get; set; }
public UUID ActiveGroupId
{
get { return UUID.Zero; }
}
public string ActiveGroupName
{
get { return String.Empty; }
}
public ulong ActiveGroupPowers
{
get { return 0; }
}
public bool IsGroupMember(UUID groupID)
{
return false;
}
public ulong GetGroupPowers(UUID groupID)
{
return 0;
}
public virtual int NextAnimationSequenceNumber
{
get { return 1; }
}
public IScene Scene
{
get { return m_scene; }
}
public bool SendLogoutPacketWhenClosing
{
set { }
}
private uint m_circuitCode;
public uint CircuitCode
{
get { return m_circuitCode; }
set { m_circuitCode = value; }
}
public IPEndPoint RemoteEndPoint
{
get { return new IPEndPoint(IPAddress.Loopback, (ushort)m_circuitCode); }
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="agentData"></param>
/// <param name="scene"></param>
/// <param name="sceneManager"></param>
public TestClient(AgentCircuitData agentData, Scene scene)
{
m_agentId = agentData.AgentID;
m_firstName = agentData.firstname;
m_lastName = agentData.lastname;
m_circuitCode = agentData.circuitcode;
m_scene = scene;
SessionId = agentData.SessionID;
SecureSessionId = agentData.SecureSessionID;
CapsSeedUrl = agentData.CapsPath;
ReceivedKills = new List<uint>();
ReceivedOfflineNotifications = new List<UUID>();
ReceivedOnlineNotifications = new List<UUID>();
ReceivedFriendshipTerminations = new List<UUID>();
SentImageDataPackets = new List<ImageDataPacket>();
SentImagePacketPackets = new List<ImagePacketPacket>();
SentImageNotInDatabasePackets = new List<ImageNotInDatabasePacket>();
}
/// <summary>
/// Attempt a teleport to the given region.
/// </summary>
/// <param name="regionHandle"></param>
/// <param name="position"></param>
/// <param name="lookAt"></param>
public void Teleport(ulong regionHandle, Vector3 position, Vector3 lookAt)
{
OnTeleportLocationRequest(this, regionHandle, position, lookAt, 16);
}
public void CompleteMovement()
{
if (OnCompleteMovementToRegion != null)
OnCompleteMovementToRegion(this, true);
}
/// <summary>
/// Emulate sending an IM from the viewer to the simulator.
/// </summary>
/// <param name='im'></param>
public void HandleImprovedInstantMessage(GridInstantMessage im)
{
ImprovedInstantMessage handlerInstantMessage = OnInstantMessage;
if (handlerInstantMessage != null)
handlerInstantMessage(this, im);
}
public virtual void ActivateGesture(UUID assetId, UUID gestureId)
{
}
public virtual void SendWearables(AvatarWearable[] wearables, int serial)
{
}
public virtual void SendAppearance(UUID agentID, byte[] visualParams, byte[] textureEntry)
{
}
public void SendCachedTextureResponse(ISceneEntity avatar, int serial, List<CachedTextureResponseArg> cachedTextures)
{
}
public virtual void Kick(string message)
{
}
public virtual void SendStartPingCheck(byte seq)
{
}
public virtual void SendAvatarPickerReply(AvatarPickerReplyAgentDataArgs AgentData, List<AvatarPickerReplyDataArgs> Data)
{
}
public virtual void SendAgentDataUpdate(UUID agentid, UUID activegroupid, string firstname, string lastname, ulong grouppowers, string groupname, string grouptitle)
{
}
public virtual void SendKillObject(List<uint> localID)
{
ReceivedKills.AddRange(localID);
}
public virtual void SetChildAgentThrottle(byte[] throttle)
{
}
public byte[] GetThrottlesPacked(float multiplier)
{
return new byte[0];
}
public virtual void SendAnimations(UUID[] animations, int[] seqs, UUID sourceAgentId, UUID[] objectIDs)
{
}
public virtual void SendChatMessage(
string message, byte type, Vector3 fromPos, string fromName,
UUID fromAgentID, UUID ownerID, byte source, byte audible)
{
}
public void SendInstantMessage(GridInstantMessage im)
{
if (OnReceivedInstantMessage != null)
OnReceivedInstantMessage(im);
}
public void SendGenericMessage(string method, UUID invoice, List<string> message)
{
}
public void SendGenericMessage(string method, UUID invoice, List<byte[]> message)
{
}
public virtual void SendLayerData(float[] map)
{
}
public virtual void SendLayerData(int px, int py, float[] map)
{
}
public virtual void SendLayerData(int px, int py, float[] map, bool track)
{
}
public virtual void SendWindData(Vector2[] windSpeeds) { }
public virtual void SendCloudData(float[] cloudCover) { }
public virtual void MoveAgentIntoRegion(RegionInfo regInfo, Vector3 pos, Vector3 look)
{
if (OnReceivedMoveAgentIntoRegion != null)
OnReceivedMoveAgentIntoRegion(regInfo, pos, look);
}
public virtual AgentCircuitData RequestClientInfo()
{
AgentCircuitData agentData = new AgentCircuitData();
agentData.AgentID = AgentId;
agentData.SessionID = SessionId;
agentData.SecureSessionID = UUID.Zero;
agentData.circuitcode = m_circuitCode;
agentData.child = false;
agentData.firstname = m_firstName;
agentData.lastname = m_lastName;
ICapabilitiesModule capsModule = m_scene.RequestModuleInterface<ICapabilitiesModule>();
if (capsModule != null)
{
agentData.CapsPath = capsModule.GetCapsPath(m_agentId);
agentData.ChildrenCapSeeds = new Dictionary<ulong, string>(capsModule.GetChildrenSeeds(m_agentId));
}
return agentData;
}
public virtual void InformClientOfNeighbour(ulong neighbourHandle, IPEndPoint neighbourExternalEndPoint)
{
if (OnTestClientInformClientOfNeighbour != null)
OnTestClientInformClientOfNeighbour(neighbourHandle, neighbourExternalEndPoint);
}
public virtual void SendRegionTeleport(
ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint,
uint locationID, uint flags, string capsURL)
{
m_log.DebugFormat(
"[TEST CLIENT]: Received SendRegionTeleport for {0} {1} on {2}", m_firstName, m_lastName, m_scene.Name);
CapsSeedUrl = capsURL;
if (OnTestClientSendRegionTeleport != null)
OnTestClientSendRegionTeleport(
regionHandle, simAccess, regionExternalEndPoint, locationID, flags, capsURL);
}
public virtual void SendTeleportFailed(string reason)
{
m_log.DebugFormat(
"[TEST CLIENT]: Teleport failed for {0} {1} on {2} with reason {3}",
m_firstName, m_lastName, m_scene.Name, reason);
}
public virtual void CrossRegion(ulong newRegionHandle, Vector3 pos, Vector3 lookAt,
IPEndPoint newRegionExternalEndPoint, string capsURL)
{
// This is supposed to send a packet to the client telling it's ready to start region crossing.
// Instead I will just signal I'm ready, mimicking the communication behavior.
// It's ugly, but avoids needless communication setup. This is used in ScenePresenceTests.cs.
// Arthur V.
wh.Set();
}
public virtual void SendMapBlock(List<MapBlockData> mapBlocks, uint flag)
{
}
public virtual void SendLocalTeleport(Vector3 position, Vector3 lookAt, uint flags)
{
}
public virtual void SendTeleportStart(uint flags)
{
}
public void SendTeleportProgress(uint flags, string message)
{
}
public virtual void SendMoneyBalance(UUID transaction, bool success, byte[] description, int balance, int transactionType, UUID sourceID, bool sourceIsGroup, UUID destID, bool destIsGroup, int amount, string item)
{
}
public virtual void SendPayPrice(UUID objectID, int[] payPrice)
{
}
public virtual void SendCoarseLocationUpdate(List<UUID> users, List<Vector3> CoarseLocations)
{
}
public virtual void SendDialog(string objectname, UUID objectID, UUID ownerID, string ownerFirstName, string ownerLastName, string msg, UUID textureID, int ch, string[] buttonlabels)
{
}
public void SendAvatarDataImmediate(ISceneEntity avatar)
{
}
public void SendEntityUpdate(ISceneEntity entity, PrimUpdateFlags updateFlags)
{
if (OnReceivedEntityUpdate != null)
OnReceivedEntityUpdate(entity, updateFlags);
}
public void ReprioritizeUpdates()
{
}
public void FlushPrimUpdates()
{
}
public virtual void SendInventoryFolderDetails(UUID ownerID, UUID folderID,
List<InventoryItemBase> items,
List<InventoryFolderBase> folders,
int version,
bool fetchFolders,
bool fetchItems)
{
}
public virtual void SendInventoryItemDetails(UUID ownerID, InventoryItemBase item)
{
}
public virtual void SendInventoryItemCreateUpdate(InventoryItemBase Item, uint callbackID)
{
}
public virtual void SendRemoveInventoryItem(UUID itemID)
{
}
public virtual void SendBulkUpdateInventory(InventoryNodeBase node)
{
}
public void SendTakeControls(int controls, bool passToAgent, bool TakeControls)
{
}
public virtual void SendTaskInventory(UUID taskID, short serial, byte[] fileName)
{
}
public virtual void SendXferPacket(ulong xferID, uint packet, byte[] data)
{
}
public virtual void SendAbortXferPacket(ulong xferID)
{
}
public virtual void SendEconomyData(float EnergyEfficiency, int ObjectCapacity, int ObjectCount, int PriceEnergyUnit,
int PriceGroupCreate, int PriceObjectClaim, float PriceObjectRent, float PriceObjectScaleFactor,
int PriceParcelClaim, float PriceParcelClaimFactor, int PriceParcelRent, int PricePublicObjectDecay,
int PricePublicObjectDelete, int PriceRentLight, int PriceUpload, int TeleportMinPrice, float TeleportPriceExponent)
{
}
public virtual void SendNameReply(UUID profileId, string firstname, string lastname)
{
}
public virtual void SendPreLoadSound(UUID objectID, UUID ownerID, UUID soundID)
{
}
public virtual void SendPlayAttachedSound(UUID soundID, UUID objectID, UUID ownerID, float gain,
byte flags)
{
}
public void SendTriggeredSound(UUID soundID, UUID ownerID, UUID objectID, UUID parentID, ulong handle, Vector3 position, float gain)
{
}
public void SendAttachedSoundGainChange(UUID objectID, float gain)
{
}
public void SendAlertMessage(string message)
{
}
public void SendAgentAlertMessage(string message, bool modal)
{
}
public void SendSystemAlertMessage(string message)
{
}
public void SendLoadURL(string objectname, UUID objectID, UUID ownerID, bool groupOwned, string message,
string url)
{
}
public virtual void SendRegionHandshake(RegionInfo regionInfo, RegionHandshakeArgs args)
{
if (OnRegionHandShakeReply != null)
{
OnRegionHandShakeReply(this);
}
}
public void SendAssetUploadCompleteMessage(sbyte AssetType, bool Success, UUID AssetFullID)
{
}
public void SendConfirmXfer(ulong xferID, uint PacketID)
{
}
public void SendXferRequest(ulong XferID, short AssetType, UUID vFileID, byte FilePath, byte[] FileName)
{
}
public void SendInitiateDownload(string simFileName, string clientFileName)
{
}
public void SendImageFirstPart(ushort numParts, UUID ImageUUID, uint ImageSize, byte[] ImageData, byte imageCodec)
{
ImageDataPacket im = new ImageDataPacket();
im.Header.Reliable = false;
im.ImageID.Packets = numParts;
im.ImageID.ID = ImageUUID;
if (ImageSize > 0)
im.ImageID.Size = ImageSize;
im.ImageData.Data = ImageData;
im.ImageID.Codec = imageCodec;
im.Header.Zerocoded = true;
SentImageDataPackets.Add(im);
}
public void SendImageNextPart(ushort partNumber, UUID imageUuid, byte[] imageData)
{
ImagePacketPacket im = new ImagePacketPacket();
im.Header.Reliable = false;
im.ImageID.Packet = partNumber;
im.ImageID.ID = imageUuid;
im.ImageData.Data = imageData;
SentImagePacketPackets.Add(im);
}
public void SendImageNotFound(UUID imageid)
{
ImageNotInDatabasePacket p = new ImageNotInDatabasePacket();
p.ImageID.ID = imageid;
SentImageNotInDatabasePackets.Add(p);
}
public void SendShutdownConnectionNotice()
{
}
public void SendSimStats(SimStats stats)
{
}
public void SendObjectPropertiesFamilyData(ISceneEntity Entity, uint RequestFlags)
{
}
public void SendObjectPropertiesReply(ISceneEntity entity)
{
}
public void SendAgentOffline(UUID[] agentIDs)
{
ReceivedOfflineNotifications.AddRange(agentIDs);
}
public void SendAgentOnline(UUID[] agentIDs)
{
ReceivedOnlineNotifications.AddRange(agentIDs);
}
public void SendSitResponse(UUID TargetID, Vector3 OffsetPos, Quaternion SitOrientation, bool autopilot,
Vector3 CameraAtOffset, Vector3 CameraEyeOffset, bool ForceMouseLook)
{
}
public void SendAdminResponse(UUID Token, uint AdminLevel)
{
}
public void SendGroupMembership(GroupMembershipData[] GroupMembership)
{
}
public void SendSunPos(Vector3 sunPos, Vector3 sunVel, ulong time, uint dlen, uint ylen, float phase)
{
}
public void SendViewerEffect(ViewerEffectPacket.EffectBlock[] effectBlocks)
{
}
public void SendViewerTime(int phase)
{
}
public void SendAvatarProperties(UUID avatarID, string aboutText, string bornOn, Byte[] charterMember,
string flAbout, uint flags, UUID flImageID, UUID imageID, string profileURL,
UUID partnerID)
{
}
public int DebugPacketLevel { get; set; }
public void InPacket(object NewPack)
{
}
public void ProcessInPacket(Packet NewPack)
{
}
/// <summary>
/// This is a TestClient only method to do shutdown tasks that are normally carried out by LLUDPServer.RemoveClient()
/// </summary>
public void Logout()
{
// We must set this here so that the presence is removed from the PresenceService by the PresenceDetector
IsLoggingOut = true;
Close();
}
public void Close()
{
Close(false);
}
public void Close(bool force)
{
// Fire the callback for this connection closing
// This is necesary to get the presence detector to notice that a client has logged out.
if (OnConnectionClosed != null)
OnConnectionClosed(this);
m_scene.RemoveClient(AgentId, true);
}
public void Start()
{
throw new NotImplementedException();
}
public void Stop()
{
}
public void SendBlueBoxMessage(UUID FromAvatarID, String FromAvatarName, String Message)
{
}
public void SendLogoutPacket()
{
}
public void Terminate()
{
}
public ClientInfo GetClientInfo()
{
return null;
}
public void SetClientInfo(ClientInfo info)
{
}
public void SendScriptQuestion(UUID objectID, string taskName, string ownerName, UUID itemID, int question)
{
}
public void SendHealth(float health)
{
}
public void SendTelehubInfo(UUID ObjectID, string ObjectName, Vector3 ObjectPos, Quaternion ObjectRot, List<Vector3> SpawnPoint)
{
}
public void SendEstateList(UUID invoice, int code, UUID[] Data, uint estateID)
{
}
public void SendBannedUserList(UUID invoice, EstateBan[] banlist, uint estateID)
{
}
public void SendRegionInfoToEstateMenu(RegionInfoForEstateMenuArgs args)
{
}
public void SendEstateCovenantInformation(UUID covenant)
{
}
public void SendDetailedEstateData(UUID invoice, string estateName, uint estateID, uint parentEstate, uint estateFlags, uint sunPosition, UUID covenant, uint covenantChanged, string abuseEmail, UUID estateOwner)
{
}
public void SendLandProperties(int sequence_id, bool snap_selection, int request_result, ILandObject lo, float simObjectBonusFactor, int parcelObjectCapacity, int simObjectCapacity, uint regionFlags)
{
}
public void SendLandAccessListData(List<LandAccessEntry> accessList, uint accessFlag, int localLandID)
{
}
public void SendForceClientSelectObjects(List<uint> objectIDs)
{
}
public void SendCameraConstraint(Vector4 ConstraintPlane)
{
}
public void SendLandObjectOwners(LandData land, List<UUID> groups, Dictionary<UUID, int> ownersAndCount)
{
}
public void SendLandParcelOverlay(byte[] data, int sequence_id)
{
}
public void SendParcelMediaCommand(uint flags, ParcelMediaCommandEnum command, float time)
{
}
public void SendParcelMediaUpdate(string mediaUrl, UUID mediaTextureID, byte autoScale, string mediaType,
string mediaDesc, int mediaWidth, int mediaHeight, byte mediaLoop)
{
}
public void SendGroupNameReply(UUID groupLLUID, string GroupName)
{
}
public void SendLandStatReply(uint reportType, uint requestFlags, uint resultCount, LandStatReportItem[] lsrpia)
{
}
public void SendScriptRunningReply(UUID objectID, UUID itemID, bool running)
{
}
public void SendAsset(AssetRequestToClient req)
{
}
public void SendTexture(AssetBase TextureAsset)
{
}
public void SendSetFollowCamProperties (UUID objectID, SortedDictionary<int, float> parameters)
{
}
public void SendClearFollowCamProperties (UUID objectID)
{
}
public void SendRegionHandle (UUID regoinID, ulong handle)
{
}
public void SendParcelInfo (RegionInfo info, LandData land, UUID parcelID, uint x, uint y)
{
}
public void SetClientOption(string option, string value)
{
}
public string GetClientOption(string option)
{
return string.Empty;
}
public void SendScriptTeleportRequest(string objName, string simName, Vector3 pos, Vector3 lookAt)
{
}
public void SendDirPlacesReply(UUID queryID, DirPlacesReplyData[] data)
{
}
public void SendDirPeopleReply(UUID queryID, DirPeopleReplyData[] data)
{
}
public void SendDirEventsReply(UUID queryID, DirEventsReplyData[] data)
{
}
public void SendDirGroupsReply(UUID queryID, DirGroupsReplyData[] data)
{
}
public void SendDirClassifiedReply(UUID queryID, DirClassifiedReplyData[] data)
{
}
public void SendDirLandReply(UUID queryID, DirLandReplyData[] data)
{
}
public void SendDirPopularReply(UUID queryID, DirPopularReplyData[] data)
{
}
public void SendMapItemReply(mapItemReply[] replies, uint mapitemtype, uint flags)
{
}
public void SendEventInfoReply (EventData info)
{
}
public void SendOfferCallingCard (UUID destID, UUID transactionID)
{
}
public void SendAcceptCallingCard (UUID transactionID)
{
}
public void SendDeclineCallingCard (UUID transactionID)
{
}
public void SendAvatarGroupsReply(UUID avatarID, GroupMembershipData[] data)
{
}
public void SendJoinGroupReply(UUID groupID, bool success)
{
}
public void SendEjectGroupMemberReply(UUID agentID, UUID groupID, bool succss)
{
}
public void SendLeaveGroupReply(UUID groupID, bool success)
{
}
public void SendTerminateFriend(UUID exFriendID)
{
ReceivedFriendshipTerminations.Add(exFriendID);
}
public bool AddGenericPacketHandler(string MethodName, GenericMessage handler)
{
//throw new NotImplementedException();
return false;
}
public void SendAvatarClassifiedReply(UUID targetID, UUID[] classifiedID, string[] name)
{
}
public void SendClassifiedInfoReply(UUID classifiedID, UUID creatorID, uint creationDate, uint expirationDate, uint category, string name, string description, UUID parcelID, uint parentEstate, UUID snapshotID, string simName, Vector3 globalPos, string parcelName, byte classifiedFlags, int price)
{
}
public void SendAgentDropGroup(UUID groupID)
{
}
public void SendAvatarNotesReply(UUID targetID, string text)
{
}
public void SendAvatarPicksReply(UUID targetID, Dictionary<UUID, string> picks)
{
}
public void SendAvatarClassifiedReply(UUID targetID, Dictionary<UUID, string> classifieds)
{
}
public void SendParcelDwellReply(int localID, UUID parcelID, float dwell)
{
}
public void SendUserInfoReply(bool imViaEmail, bool visible, string email)
{
}
public void SendCreateGroupReply(UUID groupID, bool success, string message)
{
}
public void RefreshGroupMembership()
{
}
public void SendUseCachedMuteList()
{
}
public void SendMuteListUpdate(string filename)
{
}
public void SendPickInfoReply(UUID pickID,UUID creatorID, bool topPick, UUID parcelID, string name, string desc, UUID snapshotID, string user, string originalName, string simName, Vector3 posGlobal, int sortOrder, bool enabled)
{
}
public bool TryGet<T>(out T iface)
{
iface = default(T);
return false;
}
public T Get<T>()
{
return default(T);
}
public void Disconnect(string reason)
{
}
public void Disconnect()
{
}
public void SendRebakeAvatarTextures(UUID textureID)
{
if (OnReceivedSendRebakeAvatarTextures != null)
OnReceivedSendRebakeAvatarTextures(textureID);
}
public void SendAvatarInterestsReply(UUID avatarID, uint wantMask, string wantText, uint skillsMask, string skillsText, string languages)
{
}
public void SendGroupAccountingDetails(IClientAPI sender,UUID groupID, UUID transactionID, UUID sessionID, int amt)
{
}
public void SendGroupAccountingSummary(IClientAPI sender,UUID groupID, uint moneyAmt, int totalTier, int usedTier)
{
}
public void SendGroupTransactionsSummaryDetails(IClientAPI sender,UUID groupID, UUID transactionID, UUID sessionID,int amt)
{
}
public void SendGroupVoteHistory(UUID groupID, UUID transactionID, GroupVoteHistory[] Votes)
{
}
public void SendGroupActiveProposals(UUID groupID, UUID transactionID, GroupActiveProposals[] Proposals)
{
}
public void SendChangeUserRights(UUID agentID, UUID friendID, int rights)
{
}
public void SendTextBoxRequest(string message, int chatChannel, string objectname, UUID ownerID, string ownerFirstName, string ownerLastName, UUID objectId)
{
}
public void SendAgentTerseUpdate(ISceneEntity presence)
{
}
public void SendPlacesReply(UUID queryID, UUID transactionID, PlacesReplyData[] data)
{
}
public void SendPartPhysicsProprieties(ISceneEntity entity)
{
}
}
}
| |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Infoplus.Model
{
/// <summary>
///
/// </summary>
[DataContract]
public partial class CartonContent : IEquatable<CartonContent>
{
/// <summary>
/// Initializes a new instance of the <see cref="CartonContent" /> class.
/// Initializes a new instance of the <see cref="CartonContent" />class.
/// </summary>
/// <param name="GroupOrderId">GroupOrderId.</param>
/// <param name="OrderNo">OrderNo (required).</param>
/// <param name="CartonNoId">CartonNoId (required).</param>
/// <param name="LineItemId">LineItemId (required).</param>
/// <param name="Location">Location.</param>
/// <param name="Quantity">Quantity (required).</param>
/// <param name="QuantityScanned">QuantityScanned.</param>
/// <param name="Completed">Completed.</param>
/// <param name="ToteId">ToteId.</param>
/// <param name="PickerId">PickerId.</param>
/// <param name="Status">Status.</param>
/// <param name="CustomFields">CustomFields.</param>
public CartonContent(double? GroupOrderId = null, double? OrderNo = null, int? CartonNoId = null, int? LineItemId = null, string Location = null, int? Quantity = null, int? QuantityScanned = null, DateTime? Completed = null, string ToteId = null, string PickerId = null, string Status = null, Dictionary<string, Object> CustomFields = null)
{
// to ensure "OrderNo" is required (not null)
if (OrderNo == null)
{
throw new InvalidDataException("OrderNo is a required property for CartonContent and cannot be null");
}
else
{
this.OrderNo = OrderNo;
}
// to ensure "CartonNoId" is required (not null)
if (CartonNoId == null)
{
throw new InvalidDataException("CartonNoId is a required property for CartonContent and cannot be null");
}
else
{
this.CartonNoId = CartonNoId;
}
// to ensure "LineItemId" is required (not null)
if (LineItemId == null)
{
throw new InvalidDataException("LineItemId is a required property for CartonContent and cannot be null");
}
else
{
this.LineItemId = LineItemId;
}
// to ensure "Quantity" is required (not null)
if (Quantity == null)
{
throw new InvalidDataException("Quantity is a required property for CartonContent and cannot be null");
}
else
{
this.Quantity = Quantity;
}
this.GroupOrderId = GroupOrderId;
this.Location = Location;
this.QuantityScanned = QuantityScanned;
this.Completed = Completed;
this.ToteId = ToteId;
this.PickerId = PickerId;
this.Status = Status;
this.CustomFields = CustomFields;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=false)]
public int? Id { get; private set; }
/// <summary>
/// Gets or Sets GroupOrderId
/// </summary>
[DataMember(Name="groupOrderId", EmitDefaultValue=false)]
public double? GroupOrderId { get; set; }
/// <summary>
/// Gets or Sets OrderNo
/// </summary>
[DataMember(Name="orderNo", EmitDefaultValue=false)]
public double? OrderNo { get; set; }
/// <summary>
/// Gets or Sets CartonNoId
/// </summary>
[DataMember(Name="cartonNoId", EmitDefaultValue=false)]
public int? CartonNoId { get; set; }
/// <summary>
/// Gets or Sets LineItemId
/// </summary>
[DataMember(Name="lineItemId", EmitDefaultValue=false)]
public int? LineItemId { get; set; }
/// <summary>
/// Gets or Sets Location
/// </summary>
[DataMember(Name="location", EmitDefaultValue=false)]
public string Location { get; set; }
/// <summary>
/// Gets or Sets Quantity
/// </summary>
[DataMember(Name="quantity", EmitDefaultValue=false)]
public int? Quantity { get; set; }
/// <summary>
/// Gets or Sets QuantityScanned
/// </summary>
[DataMember(Name="quantityScanned", EmitDefaultValue=false)]
public int? QuantityScanned { get; set; }
/// <summary>
/// Gets or Sets Completed
/// </summary>
[DataMember(Name="completed", EmitDefaultValue=false)]
public DateTime? Completed { get; set; }
/// <summary>
/// Gets or Sets ToteId
/// </summary>
[DataMember(Name="toteId", EmitDefaultValue=false)]
public string ToteId { get; set; }
/// <summary>
/// Gets or Sets PickerId
/// </summary>
[DataMember(Name="pickerId", EmitDefaultValue=false)]
public string PickerId { get; set; }
/// <summary>
/// Gets or Sets Status
/// </summary>
[DataMember(Name="status", EmitDefaultValue=false)]
public string Status { get; set; }
/// <summary>
/// Gets or Sets CustomFields
/// </summary>
[DataMember(Name="customFields", EmitDefaultValue=false)]
public Dictionary<string, Object> CustomFields { 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 CartonContent {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" GroupOrderId: ").Append(GroupOrderId).Append("\n");
sb.Append(" OrderNo: ").Append(OrderNo).Append("\n");
sb.Append(" CartonNoId: ").Append(CartonNoId).Append("\n");
sb.Append(" LineItemId: ").Append(LineItemId).Append("\n");
sb.Append(" Location: ").Append(Location).Append("\n");
sb.Append(" Quantity: ").Append(Quantity).Append("\n");
sb.Append(" QuantityScanned: ").Append(QuantityScanned).Append("\n");
sb.Append(" Completed: ").Append(Completed).Append("\n");
sb.Append(" ToteId: ").Append(ToteId).Append("\n");
sb.Append(" PickerId: ").Append(PickerId).Append("\n");
sb.Append(" Status: ").Append(Status).Append("\n");
sb.Append(" CustomFields: ").Append(CustomFields).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 CartonContent);
}
/// <summary>
/// Returns true if CartonContent instances are equal
/// </summary>
/// <param name="other">Instance of CartonContent to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(CartonContent other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.GroupOrderId == other.GroupOrderId ||
this.GroupOrderId != null &&
this.GroupOrderId.Equals(other.GroupOrderId)
) &&
(
this.OrderNo == other.OrderNo ||
this.OrderNo != null &&
this.OrderNo.Equals(other.OrderNo)
) &&
(
this.CartonNoId == other.CartonNoId ||
this.CartonNoId != null &&
this.CartonNoId.Equals(other.CartonNoId)
) &&
(
this.LineItemId == other.LineItemId ||
this.LineItemId != null &&
this.LineItemId.Equals(other.LineItemId)
) &&
(
this.Location == other.Location ||
this.Location != null &&
this.Location.Equals(other.Location)
) &&
(
this.Quantity == other.Quantity ||
this.Quantity != null &&
this.Quantity.Equals(other.Quantity)
) &&
(
this.QuantityScanned == other.QuantityScanned ||
this.QuantityScanned != null &&
this.QuantityScanned.Equals(other.QuantityScanned)
) &&
(
this.Completed == other.Completed ||
this.Completed != null &&
this.Completed.Equals(other.Completed)
) &&
(
this.ToteId == other.ToteId ||
this.ToteId != null &&
this.ToteId.Equals(other.ToteId)
) &&
(
this.PickerId == other.PickerId ||
this.PickerId != null &&
this.PickerId.Equals(other.PickerId)
) &&
(
this.Status == other.Status ||
this.Status != null &&
this.Status.Equals(other.Status)
) &&
(
this.CustomFields == other.CustomFields ||
this.CustomFields != null &&
this.CustomFields.SequenceEqual(other.CustomFields)
);
}
/// <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.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.GroupOrderId != null)
hash = hash * 59 + this.GroupOrderId.GetHashCode();
if (this.OrderNo != null)
hash = hash * 59 + this.OrderNo.GetHashCode();
if (this.CartonNoId != null)
hash = hash * 59 + this.CartonNoId.GetHashCode();
if (this.LineItemId != null)
hash = hash * 59 + this.LineItemId.GetHashCode();
if (this.Location != null)
hash = hash * 59 + this.Location.GetHashCode();
if (this.Quantity != null)
hash = hash * 59 + this.Quantity.GetHashCode();
if (this.QuantityScanned != null)
hash = hash * 59 + this.QuantityScanned.GetHashCode();
if (this.Completed != null)
hash = hash * 59 + this.Completed.GetHashCode();
if (this.ToteId != null)
hash = hash * 59 + this.ToteId.GetHashCode();
if (this.PickerId != null)
hash = hash * 59 + this.PickerId.GetHashCode();
if (this.Status != null)
hash = hash * 59 + this.Status.GetHashCode();
if (this.CustomFields != null)
hash = hash * 59 + this.CustomFields.GetHashCode();
return hash;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using NDesk.Options;
using Sep.Git.Tfs.Core;
using StructureMap;
using Sep.Git.Tfs.Util;
using Sep.Git.Tfs.Core.TfsInterop;
namespace Sep.Git.Tfs.Commands
{
[Pluggable("clone")]
[Description("clone [options] tfs-url-or-instance-name repository-path <git-repository-path>\n ex : git tfs clone http://myTfsServer:8080/tfs/TfsRepository $/ProjectName/ProjectBranch\n")]
public class Clone : GitTfsCommand
{
private readonly Fetch fetch;
private readonly Init init;
private readonly Globals globals;
private readonly InitBranch initBranch;
private bool withBranches;
private bool resumable;
private TextWriter stdout;
public Clone(Globals globals, Fetch fetch, Init init, InitBranch initBranch, TextWriter stdout)
{
this.fetch = fetch;
this.init = init;
this.globals = globals;
this.initBranch = initBranch;
this.stdout = stdout;
globals.GcCountdown = globals.GcPeriod;
}
public OptionSet OptionSet
{
get
{
return init.OptionSet.Merge(fetch.OptionSet)
.Add("with-branches", "init all the TFS branches during the clone", v => withBranches = v != null)
.Add("resumable", "if an error occurred, try to continue when you restart clone with same parameters", v => resumable = v != null);
}
}
public int Run(string tfsUrl, string tfsRepositoryPath)
{
return Run(tfsUrl, tfsRepositoryPath, Path.GetFileName(tfsRepositoryPath));
}
public int Run(string tfsUrl, string tfsRepositoryPath, string gitRepositoryPath)
{
var currentDir = Environment.CurrentDirectory;
var repositoryDirCreated = InitGitDir(gitRepositoryPath);
// TFS string representations of repository paths do not end in trailing slashes
if (tfsRepositoryPath != GitTfsConstants.TfsRoot)
tfsRepositoryPath = (tfsRepositoryPath ?? string.Empty).TrimEnd('/');
int retVal = 0;
try
{
if (repositoryDirCreated)
{
retVal = init.Run(tfsUrl, tfsRepositoryPath, gitRepositoryPath);
}
else
{
try
{
Environment.CurrentDirectory = gitRepositoryPath;
globals.Repository = init.GitHelper.MakeRepository(globals.GitDir);
}
catch (Exception)
{
retVal = init.Run(tfsUrl, tfsRepositoryPath, gitRepositoryPath);
}
}
VerifyTfsPathToClone(tfsRepositoryPath);
}
catch
{
if (!resumable)
{
try
{
// if we appeared to be inside repository dir when exception was thrown - we won't be able to delete it
Environment.CurrentDirectory = currentDir;
if (repositoryDirCreated)
Directory.Delete(gitRepositoryPath, recursive: true);
else
CleanDirectory(gitRepositoryPath);
}
catch (IOException e)
{
// swallow IOException. Smth went wrong before this and we're much more interested in that error
string msg = String.Format("warning: Something went wrong while cleaning file after internal error (See below).\n Can't cleanup files because of IOException:\n{0}\n", e.IndentExceptionMessage());
Trace.WriteLine(msg);
}
catch (UnauthorizedAccessException e)
{
// swallow it also
string msg = String.Format("warning: Something went wrong while cleaning file after internal error (See below).\n Can't cleanup files because of UnauthorizedAccessException:\n{0}\n", e.IndentExceptionMessage());
Trace.WriteLine(msg);
}
}
throw;
}
bool errorOccurs = false;
try
{
if (withBranches && initBranch != null)
fetch.IgnoreBranches = false;
if (tfsRepositoryPath == GitTfsConstants.TfsRoot)
fetch.IgnoreBranches = true;
globals.Repository.SetConfig(GitTfsConstants.IgnoreBranches, fetch.IgnoreBranches.ToString());
if (retVal == 0)
{
fetch.Run(withBranches);
globals.Repository.GarbageCollect();
}
if (withBranches && initBranch != null)
{
initBranch.CloneAllBranches = true;
retVal = initBranch.Run();
}
}
catch (GitTfsException)
{
errorOccurs = true;
throw;
}
catch (Exception ex)
{
errorOccurs = true;
throw new GitTfsException("error: a problem occured when trying to clone the repository. Try to solve the problem described below.\nIn any case, after, try to continue using command `git tfs "
+ (withBranches ? "branch init --all" : "fetch") + "`\n", ex);
}
finally
{
try
{
if (!init.IsBare) globals.Repository.Merge(globals.Repository.ReadTfsRemote(globals.RemoteId).RemoteRef);
}
catch (Exception)
{
//Swallow exception because the previously thrown exception is more important...
if (!errorOccurs)
throw;
}
}
return retVal;
}
private void VerifyTfsPathToClone(string tfsRepositoryPath)
{
if (initBranch == null)
return;
try
{
var remote = globals.Repository.ReadTfsRemote(GitTfsConstants.DefaultRepositoryId);
if (!remote.Tfs.IsExistingInTfs(tfsRepositoryPath))
throw new GitTfsException("error: the path " + tfsRepositoryPath + " you want to clone doesn't exist!")
.WithRecommendation("To discover which branch to clone, you could use the command :\ngit tfs list-remote-branches " + remote.TfsUrl);
if (!remote.Tfs.CanGetBranchInformation)
return;
var tfsTrunkRepository = remote.Tfs.GetRootTfsBranchForRemotePath(tfsRepositoryPath, false);
if (tfsTrunkRepository == null)
{
var tfsRootBranches = remote.Tfs.GetAllTfsRootBranchesOrderedByCreation();
if (!tfsRootBranches.Any())
{
stdout.WriteLine("info: no TFS root found !\n\nPS:perhaps you should convert your trunk folder into a branch in TFS.");
return;
}
var cloneMsg = " => If you want to manage branches with git-tfs, clone one of this branch instead :\n"
+ " - " + tfsRootBranches.Aggregate((s1, s2) => s1 + "\n - " + s2)
+ "\n\nPS:if your branch is not listed here, perhaps you should convert the containing folder to a branch in TFS.";
if (withBranches)
throw new GitTfsException("error: cloning the whole repository or too high in the repository path doesn't permit to manage branches!\n" + cloneMsg);
stdout.WriteLine("warning: you are going to clone the whole repository or too high in the repository path !\n" + cloneMsg);
return;
}
var tfsBranchesPath = tfsTrunkRepository.GetAllChildren();
var tfsPathToClone = tfsRepositoryPath.TrimEnd('/').ToLower();
var tfsTrunkRepositoryPath = tfsTrunkRepository.Path;
if (tfsPathToClone != tfsTrunkRepositoryPath.ToLower())
{
if (tfsBranchesPath.Select(e=>e.Path.ToLower()).Contains(tfsPathToClone))
stdout.WriteLine("info: you are going to clone a branch instead of the trunk ( {0} )\n"
+ " => If you want to manage branches with git-tfs, clone {0} with '--with-branches' option instead...)", tfsTrunkRepositoryPath);
else
stdout.WriteLine("warning: you are going to clone a subdirectory of a branch and won't be able to manage branches :(\n"
+ " => If you want to manage branches with git-tfs, clone " + tfsTrunkRepositoryPath + " with '--with-branches' option instead...)");
}
}
catch (GitTfsException)
{
throw;
}
catch (Exception ex)
{
stdout.WriteLine("warning: a server error occurs when trying to verify the tfs path cloned:\n " + ex.Message
+ "\n try to continue anyway...");
}
}
private bool InitGitDir(string gitRepositoryPath)
{
bool repositoryDirCreated = false;
var di = new DirectoryInfo(gitRepositoryPath);
if (di.Exists)
{
bool isDebuggerAttached = false;
#if DEBUG
isDebuggerAttached = Debugger.IsAttached;
#endif
if (!isDebuggerAttached && !resumable)
{
if (di.EnumerateFileSystemInfos().Any())
throw new GitTfsException("error: Specified git repository directory is not empty");
}
}
else
{
repositoryDirCreated = true;
di.Create();
}
return repositoryDirCreated;
}
private static void CleanDirectory(string gitRepositoryPath)
{
var di = new DirectoryInfo(gitRepositoryPath);
foreach (var fileSystemInfo in di.EnumerateDirectories())
fileSystemInfo.Delete(true);
foreach (var fileSystemInfo in di.EnumerateFiles())
fileSystemInfo.Delete();
}
}
}
| |
using System;
using Castle.Core;
using MbUnit.Framework;
using Rhino.Mocks;
using Rhino.Mocks.Exceptions;
namespace Rhino.Testing.Tests.AutoMocking
{
[TestFixture]
public class AutoMockingContainerTests : AutoMockingTests
{
[Test]
public void Create_WillReturnInstanceOfRequestedComponent()
{
ComponentBeingConfigured target = container.Create<ComponentBeingConfigured>();
Assert.IsNotNull(target, "component created");
Assert.IsInstanceOfType(typeof(ComponentBeingConfigured), target, "expected type created");
}
[Test]
public void Create_WillResolveDependencies()
{
ComponentBeingConfigured target = container.Create<ComponentBeingConfigured>();
Assert.IsNotNull(target.ReallyCoolService, "mocked ReallyCoolService dependency");
Assert.IsNotNull(target.Services, "mocked Services dependency");
}
// It might be nice to test this on a class in a separate assembly...
[Test]
public void Create_WillResolveDependenciesOnInternalClassWithInternalConstructor()
{
InternalComponentBeingConfigured target = container.Create<InternalComponentBeingConfigured>();
Assert.IsNotNull(target.ReallyCoolService, "mocked ReallyCoolService dependency");
Assert.IsNotNull(target.Services, "mocked Services dependency");
}
[Test]
public void Create_WillResolveDependenciesPreferringInternalConstructor()
{
ComponentBeingConfiguredWithInternalCtor target = container.Create<ComponentBeingConfiguredWithInternalCtor>();
Assert.IsNotNull(target.ReallyCoolService, "mocked ReallyCoolService dependency");
Assert.IsNotNull(target.Services, "mocked Services dependency");
}
[Test]
public void Create_WillResolveDependenciesPreferringInternalConstructor_WithResolvePropertiesEnabled()
{
ComponentBeingConfiguredWithInternalCtor target = containerThatResolvesProperties.Create<ComponentBeingConfiguredWithInternalCtor>();
Assert.IsNotNull(target.ReallyCoolService, "mocked ReallyCoolService dependency");
Assert.IsNotNull(target.Services, "mocked Services dependency");
}
[Test]
public void Create_WillResolveDependenciesPreferringPrivateConstructor()
{
ComponentBeingConfiguredWithPrivateCtor target = container.Create<ComponentBeingConfiguredWithPrivateCtor>();
Assert.IsNotNull(target.ReallyCoolService, "mocked ReallyCoolService dependency");
Assert.IsNotNull(target.Services, "mocked Services dependency");
}
[Test]
public void Create_WillResolveDependenciesAsMocks_ByDefault()
{
ComponentBeingConfigured target = container.Create<ComponentBeingConfigured>();
VerifyIsMock(target.ReallyCoolService);
}
[Test]
public void Create_CanResolveDependenciesAsStubs()
{
container.Mark<ICollectionOfServices>().Stubbed();
ComponentBeingConfigured target = container.Create<ComponentBeingConfigured>();
VerifyIsStub(target.Services);
}
[Test]
public void Create_CanResolveDepdendenciesAsExplicitlyRegisteredTypes()
{
container.AddComponent("DefaultCollectionOfServices", typeof(ICollectionOfServices),
typeof(DefaultCollectionOfServices));
ComponentBeingConfigured target = container.Create<ComponentBeingConfigured>();
Assert.IsInstanceOfType(typeof(DefaultCollectionOfServices), target.Services);
}
[Test]
public void Create_WillIgnorePropertiesWhenResolvingDependencies()
{
ComponentWithComplexProperty target = container.Create<ComponentWithComplexProperty>();
Assert.IsNull(target.ComplexProperty);
}
[Test]
public void Create_WillNotIgnorePropertiesWhenResolvingDependencies()
{
ComponentWithComplexProperty target = containerThatResolvesProperties.Create<ComponentWithComplexProperty>();
Assert.IsNotNull(target.ComplexProperty);
}
[Test]
public void CanStopContainerResolvingSpecificDependencies()
{
container.MarkMissing<ICollectionOfServices>();
ComponentBeingConfigured target = container.Create<ComponentBeingConfigured>();
Assert.IsNull(target.Services);
}
[Test]
public void Create_WillResolveDependencyOnKernelToIntanceFromContainer()
{
NeedIKernel needIKernel = container.Create<NeedIKernel>();
Assert.AreSame(needIKernel.Kernel, container.Kernel);
}
[Test]
public void Create_WillReturnSingletons_ByDefault()
{
ComponentBeingConfigured target1 = container.Create<ComponentBeingConfigured>();
ComponentBeingConfigured target2 = container.Create<ComponentBeingConfigured>();
Assert.AreSame(target1, target2);
}
[Test]
public void Create_CanReturnTransientInstances()
{
Type targetType = typeof (ComponentBeingConfigured);
container.AddComponentLifeStyle(targetType.FullName, targetType, LifestyleType.Transient);
ComponentBeingConfigured target1 = container.Create<ComponentBeingConfigured>();
ComponentBeingConfigured target2 = container.Create<ComponentBeingConfigured>();
Assert.AreNotSame(target1, target2);
}
[Test]
public void Create_ReturningTransientInstances_WillResolveDependenciesToTheSameMockObjects()
{
Type targetType = typeof (ComponentBeingConfigured);
container.AddComponentLifeStyle(targetType.FullName, targetType, LifestyleType.Transient);
ComponentBeingConfigured target1 = container.Create<ComponentBeingConfigured>();
ComponentBeingConfigured target2 = container.Create<ComponentBeingConfigured>();
Assert.AreSame(target1.ReallyCoolService, target2.ReallyCoolService);
}
[Test]
public void Create_WillIgnoreLifestyleOfExplictlyRegisteredTypes_WhenResolvingDependencies()
{
//make sure that container will create two instances of ComponentBeingConfigured
Type targetType = typeof(ComponentBeingConfigured);
container.AddComponentLifeStyle(targetType.FullName, targetType, LifestyleType.Transient);
//explictly register dependency to be resolved as transient
container.AddComponentLifeStyle("DefaultCollectionOfServices", typeof(ICollectionOfServices),
typeof(DefaultCollectionOfServices), LifestyleType.Transient);
ComponentBeingConfigured target1 = container.Create<ComponentBeingConfigured>();
ComponentBeingConfigured target2 = container.Create<ComponentBeingConfigured>();
Assert.AreNotSame(target1, target2, "two instances of components created");
Assert.AreSame(target1.Services, target2.Services, "dependencies are same even when this was not requested");
}
[Test]
public void Get_ReturnsMock_ByDefault()
{
VerifyIsMock(container.Get<IReallyCoolService>());
}
[Test]
public void Get_CanReturnStub()
{
container.Mark<ICollectionOfServices>().Stubbed();
VerifyIsStub(container.Get<ICollectionOfServices>());
}
[Test]
public void Get_Twice_ReturnsSameMock()
{
Assert.AreSame(container.Get<IReallyCoolService>(), container.Get<IReallyCoolService>());
}
[Test]
public void Get_ReturnsStubs_ThatAreReadyForRecording()
{
container.Mark<IReallyCoolService>().Stubbed();
IReallyCoolService service = container.Get<IReallyCoolService>();
SetupResult.For(service.GetName()).Return("Ayende");
mocks.ReplayAll();
Assert.AreEqual("Ayende", service.GetName());
}
[Test]
public void Get_WillReturnMockEvenForTypesMarkedAsMissing()
{
container.MarkMissing<IReallyCoolService>();
Assert.IsNotNull(container.Get<IReallyCoolService>());
}
[Test]
public void Resolve_ReturnsMock()
{
VerifyIsMock(container.Resolve<IReallyCoolService>());
}
[Test]
public void Resolve_CanReturnStub()
{
container.Mark<ICollectionOfServices>().Stubbed();
VerifyIsStub(container.Resolve<ICollectionOfServices>());
}
[Test]
public void Resolve_ReturnsWhatHasBeenGotten()
{
IReallyCoolService gotten = container.Get<IReallyCoolService>();
IReallyCoolService resolved = container.Resolve<IReallyCoolService>();
Assert.AreSame(gotten, resolved);
}
#region Test helpers
private void VerifyIsMock(IReallyCoolService mock)
{
Assert.IsNotNull(mock, "mock is not null");
mocks.BackToRecordAll(); // making sure there are no expectations other than the one created here
Expect.Call(mock.SayHello);
mocks.ReplayAll();
VerifyWillThrow<ExpectationViolationException>(
mocks.VerifyAll
);
}
private void VerifyIsStub(ICollectionOfServices objectToCheck)
{
IDisposable whatever = mocks.StrictMock<IDisposable>();
objectToCheck.SomethingToDispose = whatever;
Assert.AreSame(objectToCheck.SomethingToDispose, whatever, "stub has properties that behave like properties");
}
private delegate void VoidMethod();
private void VerifyWillThrow<ExpectedException>(VoidMethod proc)
{
try
{
proc();
Assert.Fail("Exception expected to be thrown");
}
catch (Exception e)
{
Assert.IsInstanceOfType(typeof(ExpectedException), e);
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
using System.ComponentModel;
namespace System.DirectoryServices.ActiveDirectory
{
public class ActiveDirectoryInterSiteTransport : IDisposable
{
private DirectoryContext _context = null;
private DirectoryEntry _cachedEntry = null;
private ActiveDirectoryTransportType _transport;
private bool _disposed = false;
private bool _linkRetrieved = false;
private bool _bridgeRetrieved = false;
private ReadOnlySiteLinkCollection _siteLinkCollection = new ReadOnlySiteLinkCollection();
private ReadOnlySiteLinkBridgeCollection _bridgeCollection = new ReadOnlySiteLinkBridgeCollection();
internal ActiveDirectoryInterSiteTransport(DirectoryContext context, ActiveDirectoryTransportType transport, DirectoryEntry entry)
{
_context = context;
_transport = transport;
_cachedEntry = entry;
}
public static ActiveDirectoryInterSiteTransport FindByTransportType(DirectoryContext context, ActiveDirectoryTransportType transport)
{
if (context == null)
throw new ArgumentNullException(nameof(context));
// if target is not specified, then we determin the target from the logon credential, so if it is a local user context, it should fail
if ((context.Name == null) && (!context.isRootDomain()))
{
throw new ArgumentException(SR.ContextNotAssociatedWithDomain, nameof(context));
}
// more validation for the context, if the target is not null, then it should be either forest name or server name
if (context.Name != null)
{
if (!(context.isRootDomain() || context.isServer() || context.isADAMConfigSet()))
throw new ArgumentException(SR.NotADOrADAM, nameof(context));
}
if (transport < ActiveDirectoryTransportType.Rpc || transport > ActiveDirectoryTransportType.Smtp)
throw new InvalidEnumArgumentException("value", (int)transport, typeof(ActiveDirectoryTransportType));
// work with copy of the context
context = new DirectoryContext(context);
// bind to the rootdse to get the configurationnamingcontext
DirectoryEntry de;
try
{
de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
string config = (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ConfigurationNamingContext);
string containerDN = "CN=Inter-Site Transports,CN=Sites," + config;
if (transport == ActiveDirectoryTransportType.Rpc)
containerDN = "CN=IP," + containerDN;
else
containerDN = "CN=SMTP," + containerDN;
de = DirectoryEntryManager.GetDirectoryEntry(context, containerDN);
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
catch (ActiveDirectoryObjectNotFoundException)
{
// this is the case where the context is a config set and we could not find an ADAM instance in that config set
throw new ActiveDirectoryOperationException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet , context.Name));
}
try
{
de.RefreshCache(new string[] { "options" });
}
catch (COMException e)
{
if (e.ErrorCode == unchecked((int)0x80072030))
{
// if it is ADAM and transport type is SMTP, throw NotSupportedException.
DirectoryEntry tmpDE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
if (Utils.CheckCapability(tmpDE, Capability.ActiveDirectoryApplicationMode) && transport == ActiveDirectoryTransportType.Smtp)
{
throw new NotSupportedException(SR.NotSupportTransportSMTP);
}
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.TransportNotFound, transport.ToString()), typeof(ActiveDirectoryInterSiteTransport), transport.ToString());
}
else
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
return new ActiveDirectoryInterSiteTransport(context, transport, de);
}
public ActiveDirectoryTransportType TransportType
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
return _transport;
}
}
public bool IgnoreReplicationSchedule
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
int option = 0;
try
{
if (_cachedEntry.Properties.Contains("options"))
option = (int)_cachedEntry.Properties["options"][0];
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(_context, e);
}
// NTDSTRANSPORT_OPT_IGNORE_SCHEDULES ( 1 << 0 ) Schedules disabled
if ((option & 0x1) != 0)
return true;
else
return false;
}
set
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
int option = 0;
try
{
if (_cachedEntry.Properties.Contains("options"))
option = (int)_cachedEntry.Properties["options"][0];
// NTDSTRANSPORT_OPT_IGNORE_SCHEDULES ( 1 << 0 ) Schedules disabled
if (value)
option |= 0x1;
else
option &= (~(0x1));
_cachedEntry.Properties["options"].Value = option;
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(_context, e);
}
}
}
public bool BridgeAllSiteLinks
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
int option = 0;
try
{
if (_cachedEntry.Properties.Contains("options"))
option = (int)_cachedEntry.Properties["options"][0];
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(_context, e);
}
// NTDSTRANSPORT_OPT_BRIDGES_REQUIRED (1 << 1 ) siteLink bridges are required
// That is to say, if this bit is set, it means that all site links are not bridged and user needs to create specific bridge
if ((option & 0x2) != 0)
return false;
else
return true;
}
set
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
int option = 0;
try
{
if (_cachedEntry.Properties.Contains("options"))
option = (int)_cachedEntry.Properties["options"][0];
// NTDSTRANSPORT_OPT_BRIDGES_REQUIRED (1 << 1 ) siteLink bridges are required, all site links are not bridged
// That is to say, if this bit is set, it means that all site links are not bridged and user needs to create specific bridge
// if this bit is not set, all the site links are bridged
if (value)
option &= (~(0x2));
else
option |= 0x2;
_cachedEntry.Properties["options"].Value = option;
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(_context, e);
}
}
}
public ReadOnlySiteLinkCollection SiteLinks
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (!_linkRetrieved)
{
_siteLinkCollection.Clear();
ADSearcher adSearcher = new ADSearcher(_cachedEntry,
"(&(objectClass=siteLink)(objectCategory=SiteLink))",
new string[] { "cn" },
SearchScope.OneLevel);
SearchResultCollection results = null;
try
{
results = adSearcher.FindAll();
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(_context, e);
}
try
{
foreach (SearchResult result in results)
{
DirectoryEntry connectionEntry = result.GetDirectoryEntry();
string cn = (string)PropertyManager.GetSearchResultPropertyValue(result, PropertyManager.Cn);
ActiveDirectorySiteLink link = new ActiveDirectorySiteLink(_context, cn, _transport, true, connectionEntry);
_siteLinkCollection.Add(link);
}
}
finally
{
results.Dispose();
}
_linkRetrieved = true;
}
return _siteLinkCollection;
}
}
public ReadOnlySiteLinkBridgeCollection SiteLinkBridges
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (!_bridgeRetrieved)
{
_bridgeCollection.Clear();
ADSearcher adSearcher = new ADSearcher(_cachedEntry,
"(&(objectClass=siteLinkBridge)(objectCategory=SiteLinkBridge))",
new string[] { "cn" },
SearchScope.OneLevel);
SearchResultCollection results = null;
try
{
results = adSearcher.FindAll();
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(_context, e);
}
try
{
foreach (SearchResult result in results)
{
DirectoryEntry connectionEntry = result.GetDirectoryEntry();
string cn = (string)PropertyManager.GetSearchResultPropertyValue(result, PropertyManager.Cn);
ActiveDirectorySiteLinkBridge bridge = new ActiveDirectorySiteLinkBridge(_context, cn, _transport, true);
bridge.cachedEntry = connectionEntry;
_bridgeCollection.Add(bridge);
}
}
finally
{
results.Dispose();
}
_bridgeRetrieved = true;
}
return _bridgeCollection;
}
}
public void Save()
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
try
{
_cachedEntry.CommitChanges();
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(_context, e);
}
}
public DirectoryEntry GetDirectoryEntry()
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
return DirectoryEntryManager.GetDirectoryEntryInternal(_context, _cachedEntry.Path);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public override string ToString()
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
return _transport.ToString();
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// free other state (managed objects)
if (_cachedEntry != null)
_cachedEntry.Dispose();
}
// free your own state (unmanaged objects)
_disposed = true;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Reflection;
using System.Diagnostics;
using System.Collections.Generic;
using System.Reflection.Runtime.General;
using System.Reflection.Runtime.TypeInfos;
using System.Reflection.Runtime.Assemblies;
using System.Reflection.Runtime.CustomAttributes;
using Internal.LowLevelLinq;
using Internal.Reflection.Tracing;
using Internal.Reflection.Core.Execution;
using StructLayoutAttribute = System.Runtime.InteropServices.StructLayoutAttribute;
namespace System.Reflection.Runtime.TypeInfos
{
//
// TypeInfos that represent type definitions (i.e. Foo or Foo<>, but not Foo<int> or arrays/pointers/byrefs.)
// that not opted into pay-for-play metadata.
//
internal sealed partial class RuntimeNoMetadataNamedTypeInfo : RuntimeTypeDefinitionTypeInfo
{
private RuntimeNoMetadataNamedTypeInfo(RuntimeTypeHandle typeHandle, bool isGenericTypeDefinition)
{
_typeHandle = typeHandle;
_isGenericTypeDefinition = isGenericTypeDefinition;
}
public sealed override Assembly Assembly
{
get
{
throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this);
}
}
public sealed override bool ContainsGenericParameters
{
get
{
return _isGenericTypeDefinition;
}
}
public sealed override IEnumerable<CustomAttributeData> CustomAttributes
{
get
{
throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this);
}
}
public sealed override string FullName
{
get
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.TypeInfo_FullName(this);
#endif
throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this);
}
}
public sealed override Guid GUID
{
get
{
throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this);
}
}
public sealed override bool IsGenericTypeDefinition
{
get
{
return _isGenericTypeDefinition;
}
}
#if DEBUG
public sealed override bool HasSameMetadataDefinitionAs(MemberInfo other) => base.HasSameMetadataDefinitionAs(other);
#endif
public sealed override string Namespace
{
get
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.TypeInfo_Namespace(this);
#endif
throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this);
}
}
public sealed override StructLayoutAttribute StructLayoutAttribute
{
get
{
throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this);
}
}
public sealed override string ToString()
{
return _typeHandle.LastResortString();
}
public sealed override int MetadataToken
{
get
{
throw new InvalidOperationException(SR.NoMetadataTokenAvailable);
}
}
protected sealed override TypeAttributes GetAttributeFlagsImpl()
{
throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this);
}
protected sealed override int InternalGetHashCode()
{
return _typeHandle.GetHashCode();
}
//
// Returns the anchoring typedef that declares the members that this type wants returned by the Declared*** properties.
// The Declared*** properties will project the anchoring typedef's members by overriding their DeclaringType property with "this"
// and substituting the value of this.TypeContext into any generic parameters.
//
// Default implementation returns null which causes the Declared*** properties to return no members.
//
// Note that this does not apply to DeclaredNestedTypes. Nested types and their containers have completely separate generic instantiation environments
// (despite what C# might lead you to think.) Constructed generic types return the exact same same nested types that its generic type definition does
// - i.e. their DeclaringTypes refer back to the generic type definition, not the constructed generic type.)
//
// Note also that we cannot use this anchoring concept for base types because of generic parameters. Generic parameters return
// baseclass and interfaces based on its constraints.
//
internal sealed override RuntimeNamedTypeInfo AnchoringTypeDefinitionForDeclaredMembers
{
get
{
throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this);
}
}
internal sealed override bool CanBrowseWithoutMissingMetadataExceptions => false;
internal sealed override Type InternalDeclaringType
{
get
{
throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this);
}
}
public sealed override string InternalGetNameIfAvailable(ref Type rootCauseForFailure)
{
rootCauseForFailure = this;
return null;
}
internal sealed override string InternalFullNameOfAssembly
{
get
{
throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this);
}
}
internal sealed override RuntimeTypeHandle InternalTypeHandleIfAvailable
{
get
{
return _typeHandle;
}
}
internal sealed override RuntimeTypeInfo[] RuntimeGenericTypeParameters
{
get
{
throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this);
}
}
//
// Returns the base type as a typeDef, Ref, or Spec. Default behavior is to QTypeDefRefOrSpec.Null, which causes BaseType to return null.
//
internal sealed override QTypeDefRefOrSpec TypeRefDefOrSpecForBaseType
{
get
{
throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this);
}
}
//
// Returns the *directly implemented* interfaces as typedefs, specs or refs. ImplementedInterfaces will take care of the transitive closure and
// insertion of the TypeContext.
//
internal sealed override QTypeDefRefOrSpec[] TypeRefDefOrSpecsForDirectlyImplementedInterfaces
{
get
{
throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this);
}
}
//
// Returns the generic parameter substitutions to use when enumerating declared members, base class and implemented interfaces.
//
internal sealed override TypeContext TypeContext
{
get
{
throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this);
}
}
private readonly RuntimeTypeHandle _typeHandle;
private readonly bool _isGenericTypeDefinition;
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans;
using Orleans.Runtime;
using Orleans.TestingHost;
using TestExtensions;
using UnitTests.GrainInterfaces;
using Xunit;
using Xunit.Abstractions;
namespace UnitTests.MembershipTests
{
public class LivenessTestsBase : TestClusterPerTest
{
private readonly ITestOutputHelper output;
private const int numAdditionalSilos = 1;
private const int numGrains = 20;
public LivenessTestsBase(ITestOutputHelper output)
{
this.output = output;
}
protected async Task Do_Liveness_OracleTest_1()
{
output.WriteLine("ClusterId= {0}", this.HostedCluster.Options.ClusterId);
SiloHandle silo3 = this.HostedCluster.StartAdditionalSilo();
IManagementGrain mgmtGrain = this.GrainFactory.GetGrain<IManagementGrain>(0);
Dictionary<SiloAddress, SiloStatus> statuses = await mgmtGrain.GetHosts(false);
foreach (var pair in statuses)
{
output.WriteLine(" ######## Silo {0}, status: {1}", pair.Key, pair.Value);
Assert.Equal(SiloStatus.Active, pair.Value);
}
Assert.Equal(3, statuses.Count);
IPEndPoint address = silo3.SiloAddress.Endpoint;
output.WriteLine("About to stop {0}", address);
this.HostedCluster.StopSilo(silo3);
// TODO: Should we be allowing time for changes to percolate?
output.WriteLine("----------------");
statuses = await mgmtGrain.GetHosts(false);
foreach (var pair in statuses)
{
output.WriteLine(" ######## Silo {0}, status: {1}", pair.Key, pair.Value);
IPEndPoint silo = pair.Key.Endpoint;
if (silo.Equals(address))
{
Assert.True(pair.Value == SiloStatus.ShuttingDown
|| pair.Value == SiloStatus.Stopping
|| pair.Value == SiloStatus.Dead,
string.Format("SiloStatus for {0} should now be ShuttingDown or Stopping or Dead instead of {1}", silo, pair.Value));
}
else
{
Assert.Equal(SiloStatus.Active, pair.Value);
}
}
}
protected async Task Do_Liveness_OracleTest_2(int silo2Kill, bool restart = true, bool startTimers = false)
{
await this.HostedCluster.StartAdditionalSilos(numAdditionalSilos);
await this.HostedCluster.WaitForLivenessToStabilizeAsync();
for (int i = 0; i < numGrains; i++)
{
await SendTraffic(i + 1, startTimers);
}
SiloHandle silo2KillHandle = this.HostedCluster.Silos[silo2Kill];
logger.Info("\n\n\n\nAbout to kill {0}\n\n\n", silo2KillHandle.SiloAddress.Endpoint);
if (restart)
this.HostedCluster.RestartSilo(silo2KillHandle);
else
this.HostedCluster.KillSilo(silo2KillHandle);
bool didKill = !restart;
await this.HostedCluster.WaitForLivenessToStabilizeAsync(didKill);
logger.Info("\n\n\n\nAbout to start sending msg to grain again\n\n\n");
for (int i = 0; i < numGrains; i++)
{
await SendTraffic(i + 1);
}
for (int i = numGrains; i < 2 * numGrains; i++)
{
await SendTraffic(i + 1);
}
logger.Info("======================================================");
}
protected async Task Do_Liveness_OracleTest_3()
{
var moreSilos = await this.HostedCluster.StartAdditionalSilos(1);
await this.HostedCluster.WaitForLivenessToStabilizeAsync();
await TestTraffic();
logger.Info("\n\n\n\nAbout to stop a first silo.\n\n\n");
var siloToStop = this.HostedCluster.SecondarySilos[0];
this.HostedCluster.StopSilo(siloToStop);
await TestTraffic();
logger.Info("\n\n\n\nAbout to re-start a first silo.\n\n\n");
this.HostedCluster.RestartStoppedSecondarySilo(siloToStop.Name);
await TestTraffic();
logger.Info("\n\n\n\nAbout to stop a second silo.\n\n\n");
this.HostedCluster.StopSilo(moreSilos[0]);
await TestTraffic();
logger.Info("======================================================");
}
private async Task TestTraffic()
{
logger.Info("\n\n\n\nAbout to start sending msg to grain again.\n\n\n");
// same grains
for (int i = 0; i < numGrains; i++)
{
await SendTraffic(i + 1);
}
// new random grains
for (int i = 0; i < numGrains; i++)
{
await SendTraffic(random.Next(10000));
}
}
private async Task SendTraffic(long key, bool startTimers = false)
{
try
{
ILivenessTestGrain grain = this.GrainFactory.GetGrain<ILivenessTestGrain>(key);
Assert.Equal(key, grain.GetPrimaryKeyLong());
Assert.Equal(key.ToString(CultureInfo.InvariantCulture), await grain.GetLabel());
await LogGrainIdentity(logger, grain);
if (startTimers)
{
await grain.StartTimer();
}
}
catch (Exception exc)
{
logger.Info("Exception making grain call: {0}", exc);
throw;
}
}
private async Task LogGrainIdentity(ILogger logger, ILivenessTestGrain grain)
{
logger.Info("Grain {0}, activation {1} on {2}",
await grain.GetGrainReference(),
await grain.GetUniqueId(),
await grain.GetRuntimeInstanceId());
}
}
public class LivenessTests_MembershipGrain : LivenessTestsBase
{
public LivenessTests_MembershipGrain(ITestOutputHelper output) : base(output)
{
}
protected override void ConfigureTestCluster(TestClusterBuilder builder)
{
builder.ConfigureLegacyConfiguration(legacy =>
{
legacy.ClientConfiguration.PreferedGatewayIndex = 1;
});
}
[Fact, TestCategory("Functional"), TestCategory("Membership")]
public async Task Liveness_Grain_1()
{
await Do_Liveness_OracleTest_1();
}
[Fact, TestCategory("Functional"), TestCategory("Membership")]
public async Task Liveness_Grain_2_Restart_GW()
{
await Do_Liveness_OracleTest_2(1);
}
[Fact, TestCategory("Functional"), TestCategory("Membership")]
public async Task Liveness_Grain_3_Restart_Silo_1()
{
await Do_Liveness_OracleTest_2(2);
}
[Fact, TestCategory("Functional"), TestCategory("Membership")]
public async Task Liveness_Grain_4_Kill_Silo_1_With_Timers()
{
await Do_Liveness_OracleTest_2(2, false, true);
}
//[Fact, TestCategory("Functional"), TestCategory("Membership")]
/*public async Task Liveness_Grain_5_ShutdownRestartZeroLoss()
{
await Do_Liveness_OracleTest_3();
}*/
}
}
| |
//
// Copyright (C) Microsoft. All rights reserved.
//
using Microsoft.PowerShell.Activities;
using System.Management.Automation;
using System.Activities;
using System.Collections.Generic;
using System.ComponentModel;
namespace Microsoft.PowerShell.Core.Activities
{
/// <summary>
/// Activity to invoke the Microsoft.PowerShell.Core\Get-Help command in a Workflow.
/// </summary>
[System.CodeDom.Compiler.GeneratedCode("Microsoft.PowerShell.Activities.ActivityGenerator.GenerateFromName", "3.0")]
public sealed class GetHelp : PSRemotingActivity
{
/// <summary>
/// Gets the display name of the command invoked by this activity.
/// </summary>
public GetHelp()
{
this.DisplayName = "Get-Help";
}
/// <summary>
/// Gets the fully qualified name of the command invoked by this activity.
/// </summary>
public override string PSCommandName { get { return "Microsoft.PowerShell.Core\\Get-Help"; } }
// Arguments
/// <summary>
/// Provides access to the Name parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> Name { get; set; }
/// <summary>
/// Provides access to the Path parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> Path { get; set; }
/// <summary>
/// Provides access to the Category parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String[]> Category { get; set; }
/// <summary>
/// Provides access to the Component parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String[]> Component { get; set; }
/// <summary>
/// Provides access to the Functionality parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String[]> Functionality { get; set; }
/// <summary>
/// Provides access to the Role parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String[]> Role { get; set; }
/// <summary>
/// Provides access to the Detailed parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> Detailed { get; set; }
/// <summary>
/// Provides access to the Full parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> Full { get; set; }
/// <summary>
/// Provides access to the Examples parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> Examples { get; set; }
/// <summary>
/// Provides access to the Parameter parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> Parameter { get; set; }
/// <summary>
/// Provides access to the Online parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> Online { get; set; }
/// <summary>
/// Provides access to the ShowWindow parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> ShowWindow { get; set; }
// Module defining this command
// Optional custom code for this activity
/// <summary>
/// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
/// </summary>
/// <param name="context">The NativeActivityContext for the currently running activity.</param>
/// <returns>A populated instance of Sytem.Management.Automation.PowerShell</returns>
/// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
{
System.Management.Automation.PowerShell invoker = global::System.Management.Automation.PowerShell.Create();
System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);
// Initialize the arguments
if(Name.Expression != null)
{
targetCommand.AddParameter("Name", Name.Get(context));
}
if(Path.Expression != null)
{
targetCommand.AddParameter("Path", Path.Get(context));
}
if(Category.Expression != null)
{
targetCommand.AddParameter("Category", Category.Get(context));
}
if(Component.Expression != null)
{
targetCommand.AddParameter("Component", Component.Get(context));
}
if(Functionality.Expression != null)
{
targetCommand.AddParameter("Functionality", Functionality.Get(context));
}
if(Role.Expression != null)
{
targetCommand.AddParameter("Role", Role.Get(context));
}
if(Detailed.Expression != null)
{
targetCommand.AddParameter("Detailed", Detailed.Get(context));
}
if(Full.Expression != null)
{
targetCommand.AddParameter("Full", Full.Get(context));
}
if(Examples.Expression != null)
{
targetCommand.AddParameter("Examples", Examples.Get(context));
}
if(Parameter.Expression != null)
{
targetCommand.AddParameter("Parameter", Parameter.Get(context));
}
if(Online.Expression != null)
{
targetCommand.AddParameter("Online", Online.Get(context));
}
if(ShowWindow.Expression != null)
{
targetCommand.AddParameter("ShowWindow", ShowWindow.Get(context));
}
return new ActivityImplementationContext() { PowerShellInstance = invoker };
}
}
}
| |
using System.Collections.Generic;
using System.Text;
namespace Eflat
{
/// <summary>
/// A class that can tranlate a stream of characters into a list of tokens.
/// NOTE: Once Tokenize() is called, it is left in an invalid state.
/// </summary>
public sealed class Tokenizer
{
/// <summary>
/// The name of the stream.
/// </summary>
private readonly string StreamName;
/// <summary>
/// The current line number of the stream.
/// </summary>
private uint Line = 1;
/// <summary>
/// The current column number of the stream.
/// </summary>
private uint Column = 1;
/// <summary>
/// The Stream we are tokenizing.
/// </summary>
private readonly string Stream;
/// <summary>
/// The index into the stream that shows our current location.
/// </summary>
private int Index = 0;
public Tokenizer(string streamName, string stream)
{
StreamName = streamName;
Stream = stream;
}
/// <summary>
/// Resets this tokenizer so that one can re-use it, if so desired.
/// </summary>
// NOTE(zac, 24/06/2017): I am unsure of the usefulness of this method, but it was
// really easy to implement, so I figured why not.
public void Reset()
{
Column = 1;
Line = 1;
Index = 0;
}
/// <summary>
/// Convert the stream passed into the tokenizer into a list of tokens.
/// Once called, the tokenizer should not be re-used, without calling Reset()
/// first.
/// </summary>
/// <returns>The stream as a list of tokens.</returns>
public List<Token> Tokenize()
{
List<Token> tokens = new List<Token>();
while (HasNext)
{
Token? token = ReadToken();
if (token.HasValue)
{
tokens.Add(token.Value);
}
}
// Add an end of file token.
// NOTE(zac, 24/06/2017): We can use this in the future when we parse multiple files
// to prevent statements going over multiple files.
Token eof = new Token(CurrentLocation, "EOF", TokenType.EndOfStream);
tokens.Add(eof);
return tokens;
}
/// <summary>
/// Attempts to read a token from the stream, returning null
/// if no token was read.
/// NOTE: Returning null does not mean that we are at the end of the stream.
/// It may mean that we are skipping whitespace.
/// </summary>
/// <returns>The next token, or null if we are skipping this one.</returns>
private Token? ReadToken()
{
Token? token = null;
char c = Peek();
if (char.IsWhiteSpace(c))
{
Next(); // TODO(zac, 24/06/2017): In future, we may want to keep whitespace in certain situations,
// like when tokenizing a string literal.
}
else if (char.IsLetter(c) || c == '_')
{
token = ReadIdentifierOrBool();
}
else if (char.IsDigit(c))
{
token = ReadNumber();
}
else // Assume it is a symbol.
{
token = ReadSymbol();
}
return token;
}
/// <summary>
/// Read in an identifier or boolean literal.
/// </summary>
/// <returns>The next token.</returns>
private Token ReadIdentifierOrBool()
{
StreamLocation location = CurrentLocation;
StringBuilder builder = new StringBuilder();
while (NextIsIdentifierChar())
{
builder.Append(Next());
}
string str = builder.ToString();
TokenType type;
if (str == "true" || str == "false")
{
type = TokenType.BooleanLiteral;
}
else
{
type = CheckForKeyword(str);
}
return new Token(location, str, type);
}
private TokenType CheckForKeyword(string str)
{
switch (str)
{
case Symbols.Keywords.WHILE:
return TokenType.Keyword_While;
case Symbols.Keywords.IF:
return TokenType.Keyword_If;
case Symbols.Keywords.ELSE:
return TokenType.Keyword_Else;
case Symbols.Keywords.STRUCT:
return TokenType.Keyword_Struct;
default:
return TokenType.Identifier;
}
}
/// <summary>
/// Reads a number literal from the stream.
/// </summary>
/// <returns>A Number (Integer or Float) token.</returns>
private Token ReadNumber()
{
StreamLocation location = CurrentLocation;
StringBuilder builder = new StringBuilder();
bool readDecimal = false;
while (NextIsNumberChar(readDecimal))
{
char c = Next();
builder.Append(c);
if (c == '.')
{
readDecimal = true;
}
}
string str = builder.ToString();
TokenType type = readDecimal ? TokenType.FloatLiteral : TokenType.IntegerLiteral;
return new Token(location, str, type);
}
/// <summary>
/// Reads a symbol token, unless it was a comment, in which case it will skip to the end of the line.
/// </summary>
/// <returns>The symbol token, or null if the symbol was a line-comment.</returns>
private Token? ReadSymbol()
{
StreamLocation location = CurrentLocation;
TokenType type = TokenType.Symbol;
StringBuilder builder = new StringBuilder();
char c = Next();
builder.Append(c);
// Check for mult-character symbols.
switch (c)
{
case '/':
// Check for line-comment.
if (HasNext && Peek() == '/')
{
ReadLineComment();
return null;
}
// Check for open multiline comment.
else if (HasNext && Peek() == '*')
{
builder.Append(Next());
type = TokenType.OpenMultilineComment;
}
break;
case '*':
// Check for end multiline comment.
if (HasNext && Peek() == '/')
{
builder.Append(Next());
type = TokenType.CloseMultilineComment;
}
break;
case '-':
// Check to see if it is arrow, or just a '-'.
if (HasNext && Peek() == '>')
{
builder.Append(Next());
}
break;
}
return new Token(location, builder.ToString(), type);
}
/// <summary>
/// Skip all characters until the end of the line or the stream.
/// </summary>
private void ReadLineComment()
{
// NOTE(zac, 24/06/2017): Next() modifies the index, so there is no need for
// a body to the while loop.
while (HasNext && Next() != '\n') ;
}
/// <summary>
/// Advances the Index into the Stream, returning the next character, and updating the
/// Line and Column counters.
/// </summary>
/// <returns>The next character in the stream.</returns>
private char Next()
{
if (!HasNext)
{
throw new InternalCompilerError("Attempted to get the next character when no character exists.");
}
char c = Stream[Index];
Index++;
if (c == '\n')
{
Line++;
Column = 1;
}
else
{
Column++;
}
return c;
}
/// <summary>
/// Reads the next character from the stream, without advancing the Index.
/// </summary>
/// <returns>The next character in the stream.</returns>
private char Peek()
{
if (HasNext)
{
char c = Stream[Index];
return c;
}
else throw new InternalCompilerError("Attempted to get the next token");
}
/// <summary>
/// Checks to see if the next character is a valid Identifier character.
/// </summary>
/// <returns>Whether or not this character can be part of an identifier.</returns>
private bool NextIsIdentifierChar()
{
if (HasNext)
{
char c = Peek();
return char.IsLetterOrDigit(c) || c == '_';
}
else
{
return false;
}
}
/// <summary>
/// Checks to see if the next character could be part of a number literal.
/// </summary>
/// <param name="readDecimal">Whether or not we have already read a decimal point.</param>
/// <returns>Whether or not this character can be part of a an integer or float.</returns>
private bool NextIsNumberChar(bool readDecimal)
{
if (HasNext)
{
char c = Peek();
return char.IsDigit(c) || c == '_' || (c == '.' && !readDecimal);
}
else
{
return false;
}
}
/// <summary>
/// Returns whether or not we are at the end of the stream.
/// </summary>
private bool HasNext => Index < Stream.Length;
/// <summary>
/// Retreives the current location in the stream.
/// </summary>
private StreamLocation CurrentLocation => new StreamLocation(StreamName, Line, Column);
}
}
| |
namespace KabMan.Test
{
partial class DataSetVisualizerForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.layoutControl1 = new DevExpress.XtraLayout.LayoutControl();
this.visualizerList = new DevExpress.XtraEditors.ComboBoxEdit();
this.visualizerGrid = new DevExpress.XtraGrid.GridControl();
this.visualizerView = new DevExpress.XtraGrid.Views.Grid.GridView();
this.layoutControlGroup1 = new DevExpress.XtraLayout.LayoutControlGroup();
this.layoutControlItem2 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem1 = new DevExpress.XtraLayout.LayoutControlItem();
this.barManager1 = new DevExpress.XtraBars.BarManager(this.components);
this.bar3 = new DevExpress.XtraBars.Bar();
this.barStaticItem1 = new DevExpress.XtraBars.BarStaticItem();
this.barDockControlTop = new DevExpress.XtraBars.BarDockControl();
this.barDockControlBottom = new DevExpress.XtraBars.BarDockControl();
this.barDockControlLeft = new DevExpress.XtraBars.BarDockControl();
this.barDockControlRight = new DevExpress.XtraBars.BarDockControl();
this.printingSystem1 = new DevExpress.XtraPrinting.PrintingSystem(this.components);
((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).BeginInit();
this.layoutControl1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.visualizerList.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.visualizerGrid)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.visualizerView)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.barManager1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.printingSystem1)).BeginInit();
this.SuspendLayout();
//
// layoutControl1
//
this.layoutControl1.Appearance.DisabledLayoutGroupCaption.ForeColor = System.Drawing.SystemColors.GrayText;
this.layoutControl1.Appearance.DisabledLayoutGroupCaption.Options.UseForeColor = true;
this.layoutControl1.Appearance.DisabledLayoutItem.ForeColor = System.Drawing.SystemColors.GrayText;
this.layoutControl1.Appearance.DisabledLayoutItem.Options.UseForeColor = true;
this.layoutControl1.Controls.Add(this.visualizerList);
this.layoutControl1.Controls.Add(this.visualizerGrid);
this.layoutControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.layoutControl1.Location = new System.Drawing.Point(0, 0);
this.layoutControl1.Name = "layoutControl1";
this.layoutControl1.Root = this.layoutControlGroup1;
this.layoutControl1.Size = new System.Drawing.Size(964, 509);
this.layoutControl1.TabIndex = 0;
this.layoutControl1.Text = "layoutControl1";
//
// visualizerList
//
this.visualizerList.Location = new System.Drawing.Point(45, 7);
this.visualizerList.Name = "visualizerList";
this.visualizerList.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)});
this.visualizerList.Size = new System.Drawing.Size(913, 20);
this.visualizerList.StyleController = this.layoutControl1;
this.visualizerList.TabIndex = 4;
this.visualizerList.SelectedIndexChanged += new System.EventHandler(this.visualizerList_SelectedIndexChanged);
//
// visualizerGrid
//
this.visualizerGrid.Location = new System.Drawing.Point(7, 38);
this.visualizerGrid.MainView = this.visualizerView;
this.visualizerGrid.Name = "visualizerGrid";
this.visualizerGrid.Size = new System.Drawing.Size(951, 465);
this.visualizerGrid.TabIndex = 1;
this.visualizerGrid.ViewCollection.AddRange(new DevExpress.XtraGrid.Views.Base.BaseView[] {
this.visualizerView});
//
// visualizerView
//
this.visualizerView.GridControl = this.visualizerGrid;
this.visualizerView.Name = "visualizerView";
this.visualizerView.OptionsBehavior.Editable = false;
this.visualizerView.OptionsView.EnableAppearanceEvenRow = true;
this.visualizerView.OptionsView.EnableAppearanceOddRow = true;
this.visualizerView.OptionsView.ShowGroupPanel = false;
this.visualizerView.OptionsView.ShowIndicator = false;
//
// layoutControlGroup1
//
this.layoutControlGroup1.CustomizationFormText = "layoutControlGroup1";
this.layoutControlGroup1.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] {
this.layoutControlItem2,
this.layoutControlItem1});
this.layoutControlGroup1.Location = new System.Drawing.Point(0, 0);
this.layoutControlGroup1.Name = "layoutControlGroup1";
this.layoutControlGroup1.Size = new System.Drawing.Size(964, 509);
this.layoutControlGroup1.Spacing = new DevExpress.XtraLayout.Utils.Padding(0, 0, 0, 0);
this.layoutControlGroup1.Text = "layoutControlGroup1";
this.layoutControlGroup1.TextVisible = false;
//
// layoutControlItem2
//
this.layoutControlItem2.Control = this.visualizerGrid;
this.layoutControlItem2.CustomizationFormText = "layoutControlItem2";
this.layoutControlItem2.Location = new System.Drawing.Point(0, 31);
this.layoutControlItem2.Name = "layoutControlItem2";
this.layoutControlItem2.Size = new System.Drawing.Size(962, 476);
this.layoutControlItem2.Text = "layoutControlItem2";
this.layoutControlItem2.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem2.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem2.TextToControlDistance = 0;
this.layoutControlItem2.TextVisible = false;
//
// layoutControlItem1
//
this.layoutControlItem1.Control = this.visualizerList;
this.layoutControlItem1.CustomizationFormText = "Source";
this.layoutControlItem1.Location = new System.Drawing.Point(0, 0);
this.layoutControlItem1.Name = "layoutControlItem1";
this.layoutControlItem1.Size = new System.Drawing.Size(962, 31);
this.layoutControlItem1.Text = "Source";
this.layoutControlItem1.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem1.TextSize = new System.Drawing.Size(33, 20);
//
// barManager1
//
this.barManager1.Bars.AddRange(new DevExpress.XtraBars.Bar[] {
this.bar3});
this.barManager1.DockControls.Add(this.barDockControlTop);
this.barManager1.DockControls.Add(this.barDockControlBottom);
this.barManager1.DockControls.Add(this.barDockControlLeft);
this.barManager1.DockControls.Add(this.barDockControlRight);
this.barManager1.Form = this;
this.barManager1.Items.AddRange(new DevExpress.XtraBars.BarItem[] {
this.barStaticItem1});
this.barManager1.MaxItemId = 2;
this.barManager1.StatusBar = this.bar3;
//
// bar3
//
this.bar3.BarName = "Status bar";
this.bar3.CanDockStyle = DevExpress.XtraBars.BarCanDockStyle.Bottom;
this.bar3.DockCol = 0;
this.bar3.DockRow = 0;
this.bar3.DockStyle = DevExpress.XtraBars.BarDockStyle.Bottom;
this.bar3.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.barStaticItem1)});
this.bar3.OptionsBar.AllowQuickCustomization = false;
this.bar3.OptionsBar.DrawDragBorder = false;
this.bar3.OptionsBar.UseWholeRow = true;
this.bar3.Text = "Status bar";
//
// barStaticItem1
//
this.barStaticItem1.Caption = "0";
this.barStaticItem1.Id = 1;
this.barStaticItem1.Name = "barStaticItem1";
this.barStaticItem1.TextAlignment = System.Drawing.StringAlignment.Near;
//
// DataSetVisualizerForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(964, 534);
this.Controls.Add(this.layoutControl1);
this.Controls.Add(this.barDockControlLeft);
this.Controls.Add(this.barDockControlRight);
this.Controls.Add(this.barDockControlBottom);
this.Controls.Add(this.barDockControlTop);
this.Name = "DataSetVisualizerForm";
this.Text = "DataSetVisualizerForm";
((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).EndInit();
this.layoutControl1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.visualizerList.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.visualizerGrid)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.visualizerView)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.barManager1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.printingSystem1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DevExpress.XtraLayout.LayoutControl layoutControl1;
private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup1;
private DevExpress.XtraEditors.ComboBoxEdit visualizerList;
private DevExpress.XtraGrid.GridControl visualizerGrid;
private DevExpress.XtraGrid.Views.Grid.GridView visualizerView;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem2;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem1;
private DevExpress.XtraBars.BarManager barManager1;
private DevExpress.XtraBars.Bar bar3;
private DevExpress.XtraBars.BarStaticItem barStaticItem1;
private DevExpress.XtraBars.BarDockControl barDockControlTop;
private DevExpress.XtraBars.BarDockControl barDockControlBottom;
private DevExpress.XtraBars.BarDockControl barDockControlLeft;
private DevExpress.XtraBars.BarDockControl barDockControlRight;
private DevExpress.XtraPrinting.PrintingSystem printingSystem1;
}
}
| |
// Copyright (c) MOSA Project. Licensed under the New BSD License.
using Mosa.Compiler.Framework;
namespace Mosa.Platform.x86.Stages
{
/// <summary>
/// This stages converts generic x86 instructions to specific load/store-type instructions.
/// This is a temporary stage until all the previous stages use the load/store-type instructions
/// </summary>
public sealed class ConversionPhaseStage : BaseTransformationStage
{
protected override void PopulateVisitationDictionary()
{
visitationDictionary[X86.Mov] = Mov;
visitationDictionary[X86.Movsx] = Movsx;
visitationDictionary[X86.Movzx] = Movzx;
visitationDictionary[X86.Movsd] = Movsd;
visitationDictionary[X86.Movss] = Movss;
visitationDictionary[X86.Movups] = Movups;
visitationDictionary[X86.Movaps] = Movaps;
}
#region Visitation Methods
/// <summary>
/// Visitation function for <see cref="IX86Visitor.Mov"/> instructions.
/// </summary>
/// <param name="context">The context.</param>
public void Mov(Context context)
{
if (context.Result.IsCPURegister && context.Operand1.IsMemoryAddress)
{
context.SetInstruction(X86.MovLoad,
//context.Size,
context.Result,
(context.Operand1.IsLabel || context.Operand1.IsSymbol || context.Operand1.IsField)
? context.Operand1
: Operand.CreateCPURegister(context.Operand1.Type, context.Operand1.EffectiveOffsetBase),
Operand.CreateConstant(MethodCompiler.TypeSystem, (int)context.Operand1.Displacement)
);
}
if (context.Result.IsMemoryAddress && (context.Operand1.IsCPURegister /*|| context.Operand1.IsConstant*/))
{
context.SetInstruction(X86.MovStore,
//InstructionSize.Size32,
null,
(context.Result.IsLabel || context.Result.IsSymbol || context.Result.IsField)
? context.Result
: Operand.CreateCPURegister(context.Result.Type, context.Result.EffectiveOffsetBase),
Operand.CreateConstant(MethodCompiler.TypeSystem, (int)context.Result.Displacement),
context.Operand1
);
}
}
/// <summary>
/// Visitation function for <see cref="IX86Visitor.Movzx"/> instructions.
/// </summary>
/// <param name="context">The context.</param>
public void Movzx(Context context)
{
if (context.Result.IsCPURegister && context.Operand1.IsMemoryAddress)
{
context.SetInstruction(X86.MovzxLoad,
context.Size,
context.Result,
(context.Operand1.IsLabel || context.Operand1.IsSymbol || context.Operand1.IsField)
? context.Operand1
: Operand.CreateCPURegister(context.Operand1.Type, context.Operand1.EffectiveOffsetBase),
Operand.CreateConstant(MethodCompiler.TypeSystem, (int)context.Operand1.Displacement)
);
}
}
/// <summary>
/// Visitation function for <see cref="IX86Visitor.Movsx"/> instructions.
/// </summary>
/// <param name="context">The context.</param>
public void Movsx(Context context)
{
if (context.Result.IsCPURegister && context.Operand1.IsMemoryAddress)
{
context.SetInstruction(X86.MovsxLoad,
context.Size,
context.Result,
(context.Operand1.IsLabel || context.Operand1.IsSymbol || context.Operand1.IsField)
? context.Operand1
: Operand.CreateCPURegister(context.Operand1.Type, context.Operand1.EffectiveOffsetBase),
Operand.CreateConstant(MethodCompiler.TypeSystem, (int)context.Operand1.Displacement)
);
}
}
/// <summary>
/// Visitation function for <see cref="IX86Visitor.Movsd"/> instructions.
/// </summary>
/// <param name="context">The context.</param>
public void Movsd(Context context)
{
if (context.Result.IsCPURegister && context.Operand1.IsMemoryAddress)
{
context.SetInstruction(X86.MovsdLoad,
context.Result,
(context.Operand1.IsLabel || context.Operand1.IsSymbol || context.Operand1.IsField)
? context.Operand1
: Operand.CreateCPURegister(context.Operand1.Type, context.Operand1.EffectiveOffsetBase),
Operand.CreateConstant(MethodCompiler.TypeSystem, (int)context.Operand1.Displacement)
);
}
if (context.Result.IsMemoryAddress && (context.Operand1.IsCPURegister /*|| context.Operand1.IsConstant*/))
{
context.SetInstruction(X86.MovsdStore,
null,
(context.Result.IsLabel || context.Result.IsSymbol || context.Result.IsField)
? context.Result
: Operand.CreateCPURegister(context.Result.Type, context.Result.EffectiveOffsetBase),
Operand.CreateConstant(MethodCompiler.TypeSystem, (int)context.Result.Displacement),
context.Operand1
);
}
}
/// <summary>
/// Visitation function for <see cref="IX86Visitor.Movss" /> instructions.
/// </summary>
/// <param name="context">The context.</param>
public void Movss(Context context)
{
if (context.Result.IsCPURegister && context.Operand1.IsMemoryAddress)
{
context.SetInstruction(X86.MovssLoad,
context.Result,
(context.Operand1.IsLabel || context.Operand1.IsSymbol || context.Operand1.IsField)
? context.Operand1
: Operand.CreateCPURegister(context.Operand1.Type, context.Operand1.EffectiveOffsetBase),
Operand.CreateConstant(MethodCompiler.TypeSystem, (int)context.Operand1.Displacement)
);
}
if (context.Result.IsMemoryAddress && (context.Operand1.IsCPURegister /*|| context.Operand1.IsConstant*/))
{
context.SetInstruction(X86.MovssStore,
null,
(context.Result.IsLabel || context.Result.IsSymbol || context.Result.IsField)
? context.Result
: Operand.CreateCPURegister(context.Result.Type, context.Result.EffectiveOffsetBase),
Operand.CreateConstant(MethodCompiler.TypeSystem, (int)context.Result.Displacement),
context.Operand1
);
}
}
/// <summary>
/// Visitation function for <see cref="IX86Visitor.Movups" /> instructions.
/// </summary>
/// <param name="context">The context.</param>
public void Movaps(Context context)
{
if (context.Result.IsCPURegister && context.Operand1.IsMemoryAddress)
{
context.SetInstruction(X86.MovapsLoad,
context.Result,
(context.Operand1.IsLabel || context.Operand1.IsSymbol || context.Operand1.IsField)
? context.Operand1
: Operand.CreateCPURegister(context.Operand1.Type, context.Operand1.EffectiveOffsetBase),
Operand.CreateConstant(MethodCompiler.TypeSystem, (int)context.Operand1.Displacement)
);
}
}
/// <summary>
/// Visitation function for <see cref="IX86Visitor.Movups" /> instructions.
/// </summary>
/// <param name="context">The context.</param>
public void Movups(Context context)
{
if (context.Result.IsCPURegister && context.Operand1.IsMemoryAddress)
{
context.SetInstruction(X86.MovupsLoad,
InstructionSize.Size128,
context.Result,
(context.Operand1.IsLabel || context.Operand1.IsSymbol || context.Operand1.IsField)
? context.Operand1
: Operand.CreateCPURegister(context.Operand1.Type, context.Operand1.EffectiveOffsetBase),
Operand.CreateConstant(MethodCompiler.TypeSystem, (int)context.Operand1.Displacement)
);
}
if (context.Result.IsMemoryAddress && (context.Operand1.IsCPURegister /*|| context.Operand1.IsConstant*/))
{
context.SetInstruction(X86.MovupsStore,
InstructionSize.Size128,
null,
(context.Result.IsLabel || context.Result.IsSymbol || context.Result.IsField)
? context.Result
: Operand.CreateCPURegister(context.Result.Type, context.Result.EffectiveOffsetBase),
Operand.CreateConstant(MethodCompiler.TypeSystem, (int)context.Result.Displacement),
context.Operand1
);
}
}
#endregion Visitation Methods
}
}
| |
using System;
using Avalonia.Controls.Metadata;
using Avalonia.Controls.Primitives;
using Avalonia.Layout;
using Avalonia.Media;
namespace Avalonia.Controls
{
/// <summary>
/// A control used to indicate the progress of an operation.
/// </summary>
[PseudoClasses(":vertical", ":horizontal", ":indeterminate")]
public class ProgressBar : RangeBase
{
public class ProgressBarTemplateProperties : AvaloniaObject
{
private double _container2Width;
private double _containerWidth;
private double _containerAnimationStartPosition;
private double _containerAnimationEndPosition;
private double _container2AnimationStartPosition;
private double _container2AnimationEndPosition;
public static readonly DirectProperty<ProgressBarTemplateProperties, double> ContainerAnimationStartPositionProperty =
AvaloniaProperty.RegisterDirect<ProgressBarTemplateProperties, double>(
nameof(ContainerAnimationStartPosition),
p => p.ContainerAnimationStartPosition,
(p, o) => p.ContainerAnimationStartPosition = o, 0d);
public static readonly DirectProperty<ProgressBarTemplateProperties, double> ContainerAnimationEndPositionProperty =
AvaloniaProperty.RegisterDirect<ProgressBarTemplateProperties, double>(
nameof(ContainerAnimationEndPosition),
p => p.ContainerAnimationEndPosition,
(p, o) => p.ContainerAnimationEndPosition = o, 0d);
public static readonly DirectProperty<ProgressBarTemplateProperties, double> Container2AnimationStartPositionProperty =
AvaloniaProperty.RegisterDirect<ProgressBarTemplateProperties, double>(
nameof(Container2AnimationStartPosition),
p => p.Container2AnimationStartPosition,
(p, o) => p.Container2AnimationStartPosition = o, 0d);
public static readonly DirectProperty<ProgressBarTemplateProperties, double> Container2AnimationEndPositionProperty =
AvaloniaProperty.RegisterDirect<ProgressBarTemplateProperties, double>(
nameof(Container2AnimationEndPosition),
p => p.Container2AnimationEndPosition,
(p, o) => p.Container2AnimationEndPosition = o);
public static readonly DirectProperty<ProgressBarTemplateProperties, double> Container2WidthProperty =
AvaloniaProperty.RegisterDirect<ProgressBarTemplateProperties, double>(
nameof(Container2Width),
p => p.Container2Width,
(p, o) => p.Container2Width = o);
public static readonly DirectProperty<ProgressBarTemplateProperties, double> ContainerWidthProperty =
AvaloniaProperty.RegisterDirect<ProgressBarTemplateProperties, double>(
nameof(ContainerWidth),
p => p.ContainerWidth,
(p, o) => p.ContainerWidth = o);
public double ContainerAnimationStartPosition
{
get => _containerAnimationStartPosition;
set => SetAndRaise(ContainerAnimationStartPositionProperty, ref _containerAnimationStartPosition, value);
}
public double ContainerAnimationEndPosition
{
get => _containerAnimationEndPosition;
set => SetAndRaise(ContainerAnimationEndPositionProperty, ref _containerAnimationEndPosition, value);
}
public double Container2AnimationStartPosition
{
get => _container2AnimationStartPosition;
set => SetAndRaise(Container2AnimationStartPositionProperty, ref _container2AnimationStartPosition, value);
}
public double Container2Width
{
get => _container2Width;
set => SetAndRaise(Container2WidthProperty, ref _container2Width, value);
}
public double ContainerWidth
{
get => _containerWidth;
set => SetAndRaise(ContainerWidthProperty, ref _containerWidth, value);
}
public double Container2AnimationEndPosition
{
get => _container2AnimationEndPosition;
set => SetAndRaise(Container2AnimationEndPositionProperty, ref _container2AnimationEndPosition, value);
}
}
private double _indeterminateStartingOffset;
private double _indeterminateEndingOffset;
private Border _indicator;
public static readonly StyledProperty<bool> IsIndeterminateProperty =
AvaloniaProperty.Register<ProgressBar, bool>(nameof(IsIndeterminate));
public static readonly StyledProperty<bool> ShowProgressTextProperty =
AvaloniaProperty.Register<ProgressBar, bool>(nameof(ShowProgressText));
public static readonly StyledProperty<Orientation> OrientationProperty =
AvaloniaProperty.Register<ProgressBar, Orientation>(nameof(Orientation), Orientation.Horizontal);
[Obsolete("To be removed when Avalonia.Themes.Default is discontinued.")]
public static readonly DirectProperty<ProgressBar, double> IndeterminateStartingOffsetProperty =
AvaloniaProperty.RegisterDirect<ProgressBar, double>(
nameof(IndeterminateStartingOffset),
p => p.IndeterminateStartingOffset,
(p, o) => p.IndeterminateStartingOffset = o);
[Obsolete("To be removed when Avalonia.Themes.Default is discontinued.")]
public static readonly DirectProperty<ProgressBar, double> IndeterminateEndingOffsetProperty =
AvaloniaProperty.RegisterDirect<ProgressBar, double>(
nameof(IndeterminateEndingOffset),
p => p.IndeterminateEndingOffset,
(p, o) => p.IndeterminateEndingOffset = o);
[Obsolete("To be removed when Avalonia.Themes.Default is discontinued.")]
public double IndeterminateStartingOffset
{
get => _indeterminateStartingOffset;
set => SetAndRaise(IndeterminateStartingOffsetProperty, ref _indeterminateStartingOffset, value);
}
[Obsolete("To be removed when Avalonia.Themes.Default is discontinued.")]
public double IndeterminateEndingOffset
{
get => _indeterminateEndingOffset;
set => SetAndRaise(IndeterminateEndingOffsetProperty, ref _indeterminateEndingOffset, value);
}
static ProgressBar()
{
ValueProperty.Changed.AddClassHandler<ProgressBar>((x, e) => x.UpdateIndicatorWhenPropChanged(e));
MinimumProperty.Changed.AddClassHandler<ProgressBar>((x, e) => x.UpdateIndicatorWhenPropChanged(e));
MaximumProperty.Changed.AddClassHandler<ProgressBar>((x, e) => x.UpdateIndicatorWhenPropChanged(e));
IsIndeterminateProperty.Changed.AddClassHandler<ProgressBar>((x, e) => x.UpdateIndicatorWhenPropChanged(e));
}
public ProgressBar()
{
UpdatePseudoClasses(IsIndeterminate, Orientation);
}
public ProgressBarTemplateProperties TemplateProperties { get; } = new ProgressBarTemplateProperties();
public bool IsIndeterminate
{
get => GetValue(IsIndeterminateProperty);
set => SetValue(IsIndeterminateProperty, value);
}
public bool ShowProgressText
{
get => GetValue(ShowProgressTextProperty);
set => SetValue(ShowProgressTextProperty, value);
}
public Orientation Orientation
{
get => GetValue(OrientationProperty);
set => SetValue(OrientationProperty, value);
}
/// <inheritdoc/>
protected override Size ArrangeOverride(Size finalSize)
{
UpdateIndicator(finalSize);
return base.ArrangeOverride(finalSize);
}
protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change)
{
base.OnPropertyChanged(change);
if (change.Property == IsIndeterminateProperty)
{
UpdatePseudoClasses(change.NewValue.GetValueOrDefault<bool>(), null);
}
else if (change.Property == OrientationProperty)
{
UpdatePseudoClasses(null, change.NewValue.GetValueOrDefault<Orientation>());
}
}
/// <inheritdoc/>
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
_indicator = e.NameScope.Get<Border>("PART_Indicator");
UpdateIndicator(Bounds.Size);
}
private void UpdateIndicator(Size bounds)
{
if (_indicator != null)
{
if (IsIndeterminate)
{
// Pulled from ModernWPF.
var dim = Orientation == Orientation.Horizontal ? bounds.Width : bounds.Height;
var barIndicatorWidth = dim * 0.4; // Indicator width at 40% of ProgressBar
var barIndicatorWidth2 = dim * 0.6; // Indicator width at 60% of ProgressBar
TemplateProperties.ContainerWidth = barIndicatorWidth;
TemplateProperties.Container2Width = barIndicatorWidth2;
TemplateProperties.ContainerAnimationStartPosition = barIndicatorWidth * -1.8; // Position at -180%
TemplateProperties.ContainerAnimationEndPosition = barIndicatorWidth * 3.0; // Position at 300%
TemplateProperties.Container2AnimationStartPosition = barIndicatorWidth2 * -1.5; // Position at -150%
TemplateProperties.Container2AnimationEndPosition = barIndicatorWidth2 * 1.66; // Position at 166%
#pragma warning disable CS0618 // Type or member is obsolete
// Remove these properties when we switch to fluent as default and removed the old one.
IndeterminateStartingOffset = -dim;
IndeterminateEndingOffset = dim;
#pragma warning restore CS0618 // Type or member is obsolete
var padding = Padding;
var rectangle = new RectangleGeometry(
new Rect(
padding.Left,
padding.Top,
bounds.Width - (padding.Right + padding.Left),
bounds.Height - (padding.Bottom + padding.Top)
));
}
else
{
double percent = Maximum == Minimum ? 1.0 : (Value - Minimum) / (Maximum - Minimum);
if (Orientation == Orientation.Horizontal)
_indicator.Width = bounds.Width * percent;
else
_indicator.Height = bounds.Height * percent;
}
}
}
private void UpdateIndicatorWhenPropChanged(AvaloniaPropertyChangedEventArgs e)
{
UpdateIndicator(Bounds.Size);
}
private void UpdatePseudoClasses(
bool? isIndeterminate,
Orientation? o)
{
if (isIndeterminate.HasValue)
{
PseudoClasses.Set(":indeterminate", isIndeterminate.Value);
}
if (o.HasValue)
{
PseudoClasses.Set(":vertical", o == Orientation.Vertical);
PseudoClasses.Set(":horizontal", o == Orientation.Horizontal);
}
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// GameMenuScreen.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using RobotGameData.GameObject;
#endregion
namespace RobotGameData.Screen
{
/// <summary>
/// Base class for screens that contatain a menu.
/// The user can move up and down to select an entry,
/// or cancel to back out of the screen.
/// </summary>
public class GameMenuScreen : GameScreen
{
#region Fields
List<Sprite2DObject> menuEntries = new List<Sprite2DObject>();
int[] selectedVerticalEntryIndex = new int[4];
int[] selectedHorizontalEntryIndex = new int[4];
#endregion
#region Properties
/// <summary>
/// Gets the list of menu entry strings, so derived classes can add
/// or change the menu contents.
/// </summary>
public IList<Sprite2DObject> MenuEntries
{
get { return menuEntries; }
}
public static int InputCount
{
get { return FrameworkCore.ScreenManager.ScreenInput.Length; }
}
#endregion
/// <summary>
/// Constructor.
/// </summary>
public GameMenuScreen()
{
for( int i=0; i<4; i++)
{
selectedVerticalEntryIndex[i] = 0;
selectedHorizontalEntryIndex[i] = 0;
}
menuEntries.Clear();
}
#region Handle Input
/// <summary>
/// Responds to user input, changing the selected entry and accepting
/// or cancelling the menu.
/// </summary>
public override void HandleInput(GameTime gameTime)
{
for (int i = 0; i < FrameworkCore.ScreenManager.InputCount; i++)
{
GameScreenInput input = FrameworkCore.ScreenManager.ScreenInput[i];
// Move to the previous menu entry?
if (input.MenuUp)
{
selectedVerticalEntryIndex[i]--;
OnFocusEntry(i, selectedVerticalEntryIndex[i],
selectedHorizontalEntryIndex[i]);
}
// Move to the next menu entry?
if (input.MenuDown)
{
selectedVerticalEntryIndex[i]++;
OnFocusEntry(i, selectedVerticalEntryIndex[i],
selectedHorizontalEntryIndex[i]);
}
// Move to the previous menu entry?
if (input.MenuLeft)
{
selectedHorizontalEntryIndex[i]--;
OnFocusEntry(i, selectedVerticalEntryIndex[i],
selectedHorizontalEntryIndex[i]);
}
// Move to the next menu entry?
if (input.MenuRight)
{
selectedHorizontalEntryIndex[i]++;
OnFocusEntry(i, selectedVerticalEntryIndex[i],
selectedHorizontalEntryIndex[i]);
}
// Accept or cancel the menu?
if (input.MenuSelect)
{
OnSelectedEntry(i, selectedVerticalEntryIndex[i],
selectedHorizontalEntryIndex[i]);
}
else
{
if (input.MenuCancel)
{
OnCancel(i);
}
if (input.MenuExit)
{
OnExit(i);
}
}
}
}
/// <summary>
/// Notifies derived classes that a menu entry has been chosen.
/// </summary>
public virtual void OnSelectedEntry(int inputIndex,
int verticalEntryIndex,
int horizontalEntryIndex) { }
/// <summary>
/// Notifies derived classes that a menu entry has been focused.
/// </summary>
public virtual void OnFocusEntry( int inputIndex,
int verticalEntryIndex,
int horizontalEntryIndex) { }
/// <summary>
/// Notifies derived classes that the menu has been cancelled.
/// </summary>
public virtual void OnCancel(int inputIndex) { }
/// <summary>
/// Notifies derived classes that a menu entry has been exited.
/// </summary>
public virtual void OnExit(int inputIndex) { }
/// <summary>
/// Notifies derived classes that a menu entry has been updated.
/// </summary>
public virtual void OnUpdateEntry(GameTime gameTime,
int[] verticalEntryIndex,
int[] horizontalEntryIndex) { }
#endregion
#region Update & Draw
/// <summary>
/// always calls the update function for the menu entry.
/// </summary>
/// <param name="gameTime"></param>
/// <param name="otherScreenHasFocus"></param>
/// <param name="coveredByOtherScreen"></param>
public override void Update(GameTime gameTime, bool otherScreenHasFocus,
bool coveredByOtherScreen)
{
base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
if (MenuEntries.Count > 0)
OnUpdateEntry(gameTime, selectedVerticalEntryIndex,
selectedHorizontalEntryIndex);
}
public override void Draw(GameTime gameTime)
{
throw new NotImplementedException(
"The method or operation is not implemented.");
}
#endregion
public void SetVerticalEntryIndex(int index, int value)
{
selectedVerticalEntryIndex[index] = value;
}
public void SetHorizontalEntryIndex(int index, int value)
{
selectedHorizontalEntryIndex[index] = value;
}
public void AddMenuEntry(Sprite2DObject item)
{
MenuEntries.Add(item);
}
public void RemoveMenuEntry(int index)
{
MenuEntries.RemoveAt(index);
}
public void RemoveMenuEntry(Sprite2DObject item)
{
MenuEntries.Remove(item);
}
public void RemoveAllMenuEntry()
{
MenuEntries.Clear();
}
}
}
| |
// 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.ObjectModel;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb
{
/// <summary>
/// the tree connect of smb server.
/// </summary>
public class SmbServerTreeConnect : IFileServiceServerTreeConnect
{
#region Fields of TD
/// <summary>
/// A numeric value that uniquely identifies a tree connect represented as a TID in the SMB header.
/// </summary>
private ushort treeId;
/// <summary>
/// A numeric value that indicates the number of files that are currently opened on TreeConnect.
/// </summary>
private int openCount;
#endregion
#region Fields of Sdk
/// <summary>
/// the open table
/// </summary>
private Collection<SmbServerOpen> openTable;
/// <summary>
/// The session on which the treeconnect was connected.
/// </summary>
private SmbServerSession session;
/// <summary>
/// the path of treeconnect
/// </summary>
private string path;
#endregion
#region Properties of TD
/// <summary>
/// A numeric value that uniquely identifies a tree connect represented as a TID in the SMB header.
/// </summary>
public ushort TreeId
{
get
{
return this.treeId;
}
set
{
this.treeId = value;
}
}
/// <summary>
/// A numeric value that indicates the number of files that are currently opened on TreeConnect.
/// </summary>
public int OpenCount
{
get
{
return this.openCount;
}
set
{
this.openCount = value;
}
}
/// <summary>
/// the path of treeconnect
/// </summary>
public string Path
{
get
{
return this.path;
}
set
{
this.path = value;
}
}
#endregion
#region Properties of Sdk
/// <summary>
/// The session on which the treeconnect was connected.
/// </summary>
public SmbServerSession Session
{
get
{
return this.session;
}
set
{
this.session = value;
}
}
/// <summary>
/// get the opens of treeconnect
/// </summary>
public ReadOnlyCollection<SmbServerOpen> OpenList
{
get
{
return new ReadOnlyCollection<SmbServerOpen>(this.openTable);
}
}
/// <summary>
/// get the opens of treeconnect
/// </summary>
public ReadOnlyCollection<IFileServiceServerOpen> OpenTable
{
get
{
Collection<IFileServiceServerOpen> ret = new Collection<IFileServiceServerOpen>();
foreach (SmbServerOpen open in this.openTable)
{
ret.Add(open);
}
return new ReadOnlyCollection<IFileServiceServerOpen>(ret);
}
}
#endregion
#region Constructor
/// <summary>
/// Constructor
/// </summary>
internal SmbServerTreeConnect()
{
this.openTable = new Collection<SmbServerOpen>();
}
#endregion
#region Access Opens
/// <summary>
/// get the identitied open
/// </summary>
/// <param name="smbFid">the identigy of open</param>
/// <returns>the identitied open</returns>
internal SmbServerOpen GetOpen(ushort smbFid)
{
lock (this.openTable)
{
foreach (SmbServerOpen open in this.openTable)
{
if (open.SmbFid == smbFid)
{
return open;
}
}
return null;
}
}
/// <summary>
/// add open to treeconnect
/// </summary>
/// <param name="open">the open to add</param>
/// <exception cref="InvalidOperationException">the open have exist in the treeconnect!</exception>
internal void AddOpen(SmbServerOpen open)
{
lock (this.openTable)
{
if (this.openTable.Contains(open))
{
throw new InvalidOperationException("the open have exist in the treeconnect!");
}
this.openTable.Add(open);
}
}
/// <summary>
/// remove the open.if does not exists, do nothing.
/// </summary>
/// <param name="open">the open to remove</param>
internal void RemoveOpen(SmbServerOpen open)
{
lock (this.openTable)
{
if (this.openTable.Contains(open))
{
this.openTable.Remove(open);
}
}
}
#endregion
/// <summary>
/// Inherit from FileServiceServerTreeConnect, equals to Session.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
IFileServiceServerSession IFileServiceServerTreeConnect.Session
{
get
{
return this.session;
}
}
/// <summary>
/// Inherit from FileServiceServerTreeConnect, equals to Path.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
string IFileServiceServerTreeConnect.Name
{
get
{
return this.path;
}
}
/// <summary>
/// Inherit from FileServiceServerTreeConnect, equals to TreeId.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
int IFileServiceServerTreeConnect.TreeConnectId
{
get
{
return this.treeId;
}
}
}
}
| |
/*
Copyright (c) 2004-2006 Tomas Matousek.
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger distribution. By using this software
in any fashion, you are agreeing to be bound by the terms of this license.
You must not remove this notice from this software.
*/
using System;
using System.IO;
using System.Text;
using System.Collections;
using System.Diagnostics;
using System.Security;
#if !SILVERLIGHT
using System.Web.Configuration;
#endif
namespace PHP.Core
{
/// <summary>
/// Provides functionality related to process execution.
/// </summary>
public class Execution
{
private Execution() { }
/// <summary>
/// How to handle external process output.
/// </summary>
public enum OutputHandling
{
/// <summary>
/// Split the result into lines and add them to the specified collection.
/// </summary>
ArrayOfLines,
/// <summary>
/// Return entire output as a string.
/// </summary>
String,
/// <summary>
/// Write each line to the current output and flush the output after each line.
/// </summary>
FlushLinesToScriptOutput,
/// <summary>
/// Redirect all output to binary sink of the current output.
/// </summary>
RedirectToScriptOutput
}
#if !SILVERLIGHT
/// <summary>
/// Executes a <c>cmd.exe</c> and passes it a specified command.
/// </summary>
/// <param name="command">The command to be passed.</param>
/// <returns>A string containing the entire output.</returns>
/// <remarks>Implements backticks operator (i.e. <code>`command`</code>).</remarks>
[Emitted]
public static string ShellExec(string command)
{
string result;
ShellExec(command, OutputHandling.String, null, out result);
return result;
}
/// <summary>
/// Executes a <c>cmd.exe</c> and passes it a specified command.
/// </summary>
/// <param name="command">The command to be passed.</param>
/// <param name="handling">How to handle the output.</param>
/// <param name="arrayOutput">
/// A list where output lines will be added if <paramref name="handling"/> is <see cref="OutputHandling.ArrayOfLines"/>.
/// </param>
/// <param name="stringOutput">
/// A string containing the entire output in if <paramref name="handling"/> is <see cref="OutputHandling.String"/>
/// or the last line of the output if <paramref name="handling"/> is <see cref="OutputHandling.ArrayOfLines"/> or
/// <see cref="OutputHandling.FlushLinesToScriptOutput"/>.
/// </param>
/// <returns>Exit code of the process.</returns>
public static int ShellExec(string command, OutputHandling handling, IList arrayOutput, out string stringOutput)
{
if (!MakeCommandSafe(ref command))
{
stringOutput = "";
return -1;
}
using (Process p = new Process())
{
IdentitySection identityConfig = null;
try { identityConfig = WebConfigurationManager.GetSection("system.web/identity") as IdentitySection; }
catch { }
if (identityConfig != null)
{
p.StartInfo.UserName = identityConfig.UserName;
if (identityConfig.Password != null)
{
p.StartInfo.Password = new SecureString();
foreach (char c in identityConfig.Password) p.StartInfo.Password.AppendChar(c);
p.StartInfo.Password.MakeReadOnly();
}
}
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/c " + command;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
stringOutput = null;
switch (handling)
{
case OutputHandling.String:
stringOutput = p.StandardOutput.ReadToEnd();
break;
case OutputHandling.ArrayOfLines:
{
string line;
while ((line = p.StandardOutput.ReadLine()) != null)
{
stringOutput = line;
if (arrayOutput != null) arrayOutput.Add(line);
}
break;
}
case OutputHandling.FlushLinesToScriptOutput:
{
ScriptContext context = ScriptContext.CurrentContext;
string line;
while ((line = p.StandardOutput.ReadLine()) != null)
{
stringOutput = line;
context.Output.WriteLine(line);
context.Output.Flush();
}
break;
}
case OutputHandling.RedirectToScriptOutput:
{
ScriptContext context = ScriptContext.CurrentContext;
byte[] buffer = new byte[1024];
int count;
while ((count = p.StandardOutput.BaseStream.Read(buffer, 0, buffer.Length)) > 0)
{
context.OutputStream.Write(buffer, 0, count);
}
break;
}
}
p.WaitForExit();
return p.ExitCode;
}
}
#endif
/// <summary>
/// Escape shell metacharacters in a specified shell command.
/// </summary>
/// <param name="command">The command to excape.</param>
/// <para>
/// On Windows platform, each occurance of a character that might be used to trick a shell command
/// is replaced with space. These characters are
/// <c>", ', #, &, ;, `, |, *, ?, ~, <, >, ^, (, ), [, ], {, }, $, \, \u000A, \u00FF, %</c>.
/// </para>
public static string EscapeCommand(string command)
{
if (command == null) return String.Empty;
StringBuilder sb = new StringBuilder(command);
// GENERICS:
// if (Environment.OSVersion.Platform!=PlatformID.Unix)
{
for (int i = 0; i < sb.Length; i++)
{
switch (sb[i])
{
case '"':
case '\'':
case '#':
case '&':
case ';':
case '`':
case '|':
case '*':
case '?':
case '~':
case '<':
case '>':
case '^':
case '(':
case ')':
case '[':
case ']':
case '{':
case '}':
case '$':
case '\\':
case '\u000A':
case '\u00FF':
case '%':
sb[i] = ' ';
break;
}
}
}
// else
// {
// // ???
// PhpException.FunctionNotSupported();
// }
return sb.ToString();
}
/// <summary>
/// Makes command safe in similar way PHP does.
/// </summary>
/// <param name="command">Potentially unsafe command.</param>
/// <returns>Safe command.</returns>
/// <remarks>
/// If safe mode is enabled, command is split by the first space into target path
/// and arguments (optionally) components. The target path must not contain '..' substring.
/// A file name is extracted from the target path and combined with
/// <see cref="GlobalConfiguration.SafeModeSection.ExecutionDirectory"/>.
/// The resulting path is checked for invalid path characters (Phalanger specific).
/// Finally, arguments are escaped by <see cref="EscapeCommand"/> and appended to the path.
/// If safe mode is disabled, the command remains unchanged.
/// </remarks>
public static bool MakeCommandSafe(ref string command)
{
if (command == null) return false;
#if SILVERLIGHT
return true;
#else
GlobalConfiguration global = Configuration.Global;
if (!global.SafeMode.Enabled) return true;
int first_space = command.IndexOf(' ');
if (first_space == -1) first_space = command.Length;
if (command.IndexOf("..", 0, first_space) >= 0)
{
PhpException.Throw(PhpError.Warning, "dotdot_not_allowed_in_path");
return false;
}
try
{
string file_name = Path.GetFileName(command.Substring(0, first_space));
string target_path = Path.Combine(global.SafeMode.ExecutionDirectory, file_name);
// <execution directory>/<file name> <escaped arguments>
command = String.Concat(target_path, EscapeCommand(command.Substring(first_space)));
}
catch (ArgumentException)
{
PhpException.Throw(PhpError.Warning, "path_contains_invalid_characters");
return false;
}
return true;
#endif
}
}
}
| |
/*
Copyright 2012-2022 Marco De Salvo
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 Microsoft.VisualStudio.TestTools.UnitTesting;
using RDFSharp.Model;
using System;
using System.Collections.Generic;
using System.Linq;
namespace RDFSharp.Test.Model
{
[TestClass]
public class RDFMaxLengthConstraintTest
{
#region Tests
[TestMethod]
public void ShouldCreateMaxLengthConstraint()
{
RDFMaxLengthConstraint maxLengthConstraint = new RDFMaxLengthConstraint(2);
Assert.IsNotNull(maxLengthConstraint);
Assert.IsTrue(maxLengthConstraint.MaxLength == 2);
}
[TestMethod]
public void ShouldCreateMaxLengthConstraintLowerThanZero()
{
RDFMaxLengthConstraint maxLengthConstraint = new RDFMaxLengthConstraint(-2);
Assert.IsNotNull(maxLengthConstraint);
Assert.IsTrue(maxLengthConstraint.MaxLength == 0);
}
[TestMethod]
public void ShouldExportMaxLengthConstraint()
{
RDFMaxLengthConstraint maxLengthConstraint = new RDFMaxLengthConstraint(2);
RDFGraph graph = maxLengthConstraint.ToRDFGraph(new RDFNodeShape(new RDFResource("ex:NodeShape")));
Assert.IsNotNull(graph);
Assert.IsTrue(graph.TriplesCount == 1);
Assert.IsTrue(graph.Triples.Any(t => t.Value.Subject.Equals(new RDFResource("ex:NodeShape"))
&& t.Value.Predicate.Equals(RDFVocabulary.SHACL.MAX_LENGTH)
&& t.Value.Object.Equals(new RDFTypedLiteral("2", RDFModelEnums.RDFDatatypes.XSD_INTEGER))));
}
//NS-CONFORMS:TRUE
[TestMethod]
public void ShouldConformNodeShapeWithClassTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape"));
nodeShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person")));
nodeShape.AddConstraint(new RDFMaxLengthConstraint(8));
shapesGraph.AddShape(nodeShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsTrue(validationReport.Conforms);
}
[TestMethod]
public void ShouldConformNodeShapeWithNodeTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape"));
nodeShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Alice")));
nodeShape.AddConstraint(new RDFMaxLengthConstraint(8));
shapesGraph.AddShape(nodeShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsTrue(validationReport.Conforms);
}
[TestMethod]
public void ShouldConformNodeShapeWithSubjectsOfTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape"));
nodeShape.AddTarget(new RDFTargetSubjectsOf(RDFVocabulary.FOAF.KNOWS));
nodeShape.AddConstraint(new RDFMaxLengthConstraint(8));
shapesGraph.AddShape(nodeShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsTrue(validationReport.Conforms);
}
[TestMethod]
public void ShouldConformNodeShapeWithObjectsOfTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape"));
nodeShape.AddTarget(new RDFTargetObjectsOf(RDFVocabulary.FOAF.KNOWS));
nodeShape.AddConstraint(new RDFMaxLengthConstraint(8));
shapesGraph.AddShape(nodeShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsTrue(validationReport.Conforms);
}
//PS-CONFORMS:TRUE
[TestMethod]
public void ShouldConformPropertyShapeWithClassTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.AGENT);
propertyShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person")));
propertyShape.AddConstraint(new RDFMaxLengthConstraint(8));
shapesGraph.AddShape(propertyShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsTrue(validationReport.Conforms);
}
[TestMethod]
public void ShouldConformPropertyShapeWithNodeTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.AGENT);
propertyShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Alice")));
propertyShape.AddConstraint(new RDFMaxLengthConstraint(8));
shapesGraph.AddShape(propertyShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsTrue(validationReport.Conforms);
}
[TestMethod]
public void ShouldConformPropertyShapeWithSubjectsOfTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.AGENT);
propertyShape.AddTarget(new RDFTargetSubjectsOf(RDFVocabulary.FOAF.KNOWS));
propertyShape.AddConstraint(new RDFMaxLengthConstraint(8));
shapesGraph.AddShape(propertyShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsTrue(validationReport.Conforms);
}
[TestMethod]
public void ShouldConformPropertyShapeWithObjectsOfTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.AGENT);
propertyShape.AddTarget(new RDFTargetObjectsOf(RDFVocabulary.FOAF.KNOWS));
propertyShape.AddConstraint(new RDFMaxLengthConstraint(8));
shapesGraph.AddShape(propertyShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsTrue(validationReport.Conforms);
}
//NS-CONFORMS:FALSE
[TestMethod]
public void ShouldNotConformNodeShapeWithClassTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape"));
nodeShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person")));
nodeShape.AddConstraint(new RDFMaxLengthConstraint(7));
nodeShape.AddMessage(new RDFPlainLiteral("ErrorMessage"));
shapesGraph.AddShape(nodeShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("ErrorMessage")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Alice")));
Assert.IsNull(validationReport.Results[0].ResultPath);
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MAX_LENGTH_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:NodeShape")));
}
[TestMethod]
public void ShouldNotConformNodeShapeWithNodeTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape"));
nodeShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Alice")));
nodeShape.AddConstraint(new RDFMaxLengthConstraint(7));
nodeShape.AddMessage(new RDFPlainLiteral("ErrorMessage"));
shapesGraph.AddShape(nodeShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("ErrorMessage")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Alice")));
Assert.IsNull(validationReport.Results[0].ResultPath);
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MAX_LENGTH_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:NodeShape")));
}
[TestMethod]
public void ShouldNotConformNodeShapeWithSubjectsOfTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape"));
nodeShape.AddTarget(new RDFTargetSubjectsOf(RDFVocabulary.FOAF.KNOWS));
nodeShape.AddConstraint(new RDFMaxLengthConstraint(7));
nodeShape.AddMessage(new RDFPlainLiteral("ErrorMessage"));
shapesGraph.AddShape(nodeShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("ErrorMessage")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Alice")));
Assert.IsNull(validationReport.Results[0].ResultPath);
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MAX_LENGTH_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:NodeShape")));
}
[TestMethod]
public void ShouldNotConformNodeShapeWithObjectsOfTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape"));
nodeShape.AddTarget(new RDFTargetObjectsOf(RDFVocabulary.FOAF.KNOWS));
nodeShape.AddConstraint(new RDFMaxLengthConstraint(5));
nodeShape.AddMessage(new RDFPlainLiteral("ErrorMessage"));
shapesGraph.AddShape(nodeShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("ErrorMessage")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Bob")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Bob")));
Assert.IsNull(validationReport.Results[0].ResultPath);
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MAX_LENGTH_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:NodeShape")));
}
//PS-CONFORMS:FALSE
[TestMethod]
public void ShouldNotConformPropertyShapeWithClassTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.AGENT);
propertyShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person")));
propertyShape.AddConstraint(new RDFMaxLengthConstraint(7));
shapesGraph.AddShape(propertyShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Must have a maximum length of 7 characters and can't be a blank node")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Bob")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Steve")));
Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(RDFVocabulary.FOAF.AGENT));
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MAX_LENGTH_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropertyShape")));
}
[TestMethod]
public void ShouldNotConformPropertyShapeWithNodeTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.AGENT);
propertyShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Bob")));
propertyShape.AddConstraint(new RDFMaxLengthConstraint(7));
shapesGraph.AddShape(propertyShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Must have a maximum length of 7 characters and can't be a blank node")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Bob")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Steve")));
Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(RDFVocabulary.FOAF.AGENT));
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MAX_LENGTH_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropertyShape")));
}
[TestMethod]
public void ShouldNotConformPropertyShapeWithSubjectsOfTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.AGENT);
propertyShape.AddTarget(new RDFTargetSubjectsOf(RDFVocabulary.FOAF.KNOWS));
propertyShape.AddConstraint(new RDFMaxLengthConstraint(7));
shapesGraph.AddShape(propertyShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Must have a maximum length of 7 characters and can't be a blank node")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Bob")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Steve")));
Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(RDFVocabulary.FOAF.AGENT));
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MAX_LENGTH_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropertyShape")));
}
[TestMethod]
public void ShouldNotConformPropertyShapeWithObjectsOfTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.AGENT);
propertyShape.AddTarget(new RDFTargetObjectsOf(RDFVocabulary.FOAF.KNOWS));
propertyShape.AddConstraint(new RDFMaxLengthConstraint(7));
shapesGraph.AddShape(propertyShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Must have a maximum length of 7 characters and can't be a blank node")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Bob")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Steve")));
Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(RDFVocabulary.FOAF.AGENT));
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MAX_LENGTH_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropertyShape")));
}
//MIXED-CONFORMS:TRUE
[TestMethod]
public void ShouldConformNodeShapeWithPropertyShape()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), new RDFResource("ex:name"), new RDFTypedLiteral("Bobby", RDFModelEnums.RDFDatatypes.XSD_STRING)));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:MaxLengthExampleShape"));
nodeShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Bob")));
RDFPropertyShape propShape = new RDFPropertyShape(new RDFResource("ex:PropShape"), new RDFResource("ex:name"));
propShape.AddConstraint(new RDFMaxLengthConstraint(5));
nodeShape.AddConstraint(new RDFPropertyConstraint(propShape));
shapesGraph.AddShape(nodeShape);
shapesGraph.AddShape(propShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsTrue(validationReport.Conforms);
}
//MIXED-CONFORMS:FALSE
[TestMethod]
public void ShouldNotConformNodeShapeWithPropertyShape()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), new RDFResource("ex:name"), new RDFTypedLiteral("Bobby", RDFModelEnums.RDFDatatypes.XSD_STRING)));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:MaxLengthExampleShape"));
nodeShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Bob")));
RDFPropertyShape propShape = new RDFPropertyShape(new RDFResource("ex:PropShape"), new RDFResource("ex:name"));
propShape.AddConstraint(new RDFMaxLengthConstraint(4));
nodeShape.AddConstraint(new RDFPropertyConstraint(propShape));
shapesGraph.AddShape(nodeShape);
shapesGraph.AddShape(propShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Must have a maximum length of 4 characters and can't be a blank node")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Bob")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFTypedLiteral("Bobby", RDFModelEnums.RDFDatatypes.XSD_STRING)));
Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(new RDFResource("ex:name")));
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MAX_LENGTH_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropShape")));
}
[TestMethod]
public void ShouldNotConformNodeShapeWithPropertyShapeBecauseBlankValue()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), new RDFResource("ex:hasBlank"), new RDFResource("bnode:12345")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:MaxLengthExampleShape"));
nodeShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Bob")));
RDFPropertyShape propShape = new RDFPropertyShape(new RDFResource("ex:PropShape"), new RDFResource("ex:hasBlank"));
propShape.AddConstraint(new RDFMaxLengthConstraint(4));
nodeShape.AddConstraint(new RDFPropertyConstraint(propShape));
shapesGraph.AddShape(nodeShape);
shapesGraph.AddShape(propShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Must have a maximum length of 4 characters and can't be a blank node")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Bob")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("bnode:12345")));
Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(new RDFResource("ex:hasBlank")));
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MAX_LENGTH_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropShape")));
}
#endregion
}
}
| |
using System;
using System.Data;
using System.Data.OleDb;
using System.Collections;
using System.Configuration;
using PCSComUtils.DataAccess;
using PCSComUtils.PCSExc;
using PCSComUtils.Common;
namespace PCSComProduction.DCP.DS
{
public class PRO_DCPResultDS
{
public PRO_DCPResultDS()
{
}
private const string THIS = "PCSComProduction.DCP.DS.PRO_DCPResultDS";
/// <summary>
/// This method uses to add data to PRO_DCPResult
/// </summary>
/// <Inputs>
/// PRO_DCPResultVO
/// </Inputs>
/// <Returns>
/// void
/// </Returns>
/// <History>
/// Tuesday, August 30, 2005
/// </History>
public void Add(object pobjObjectVO)
{
const string METHOD_NAME = THIS + ".Add()";
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS =null;
try
{
PRO_DCPResultVO objObject = (PRO_DCPResultVO) pobjObjectVO;
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand("", oconPCS);
strSql= "INSERT INTO PRO_DCPResult("
+ PRO_DCPResultTable.WOROUTINGID_FLD + ","
+ PRO_DCPResultTable.STARTDATETIME_FLD + ","
+ PRO_DCPResultTable.DUEDATETIME_FLD + ","
+ PRO_DCPResultTable.QUANTITY_FLD + ","
+ PRO_DCPResultTable.DCOPTIONMASTERID_FLD + ","
+ PRO_DCPResultTable.CHECKPOINTID_FLD + ","
+ PRO_DCPResultTable.PRODUCTID_FLD + ","
+ PRO_DCPResultTable.CPOID_FLD + ","
+ PRO_DCPResultTable.WORKORDERDETAILID_FLD + ","
+ PRO_DCPResultTable.WORKCENTERID_FLD + ")"
+ "VALUES(?,?,?,?,?,?,?,?,?,?)";
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultTable.WOROUTINGID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PRO_DCPResultTable.WOROUTINGID_FLD].Value = objObject.WORoutingID;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultTable.STARTDATETIME_FLD, OleDbType.Date));
ocmdPCS.Parameters[PRO_DCPResultTable.STARTDATETIME_FLD].Value = objObject.StartDateTime;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultTable.DUEDATETIME_FLD, OleDbType.Date));
ocmdPCS.Parameters[PRO_DCPResultTable.DUEDATETIME_FLD].Value = objObject.DueDateTime;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultTable.QUANTITY_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[PRO_DCPResultTable.QUANTITY_FLD].Value = objObject.Quantity;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultTable.DCOPTIONMASTERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PRO_DCPResultTable.DCOPTIONMASTERID_FLD].Value = objObject.DCOptionMasterID;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultTable.CHECKPOINTID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PRO_DCPResultTable.CHECKPOINTID_FLD].Value = objObject.CheckPointID;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultTable.PRODUCTID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PRO_DCPResultTable.PRODUCTID_FLD].Value = objObject.ProductID;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultTable.CPOID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PRO_DCPResultTable.CPOID_FLD].Value = objObject.CPOID;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultTable.WORKORDERDETAILID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PRO_DCPResultTable.WORKORDERDETAILID_FLD].Value = objObject.WorkOrderDetailID;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultTable.WORKCENTERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PRO_DCPResultTable.WORKCENTERID_FLD].Value = objObject.WorkCenterID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// This method uses to add data to PRO_DCPResult
/// </summary>
/// <Inputs>
/// PRO_DCPResultVO
/// </Inputs>
/// <Returns>
/// void
/// </Returns>
/// <History>
/// Tuesday, August 30, 2005
/// </History>
public void Delete(int pintID)
{
const string METHOD_NAME = THIS + ".Delete()";
string strSql = String.Empty;
strSql= "DELETE " + PRO_DCPResultTable.TABLE_NAME + " WHERE " + "DCPResultID" + "=" + pintID.ToString();
OleDbConnection oconPCS=null;
OleDbCommand ocmdPCS =null;
try
{
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
ocmdPCS = null;
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// This method uses to add data to PRO_DCPResult
/// </summary>
/// <Inputs>
/// PRO_DCPResultVO
/// </Inputs>
/// <Returns>
/// void
/// </Returns>
/// <History>
/// Tuesday, August 30, 2005
/// </History>
public object GetObjectVO(int pintID)
{
const string METHOD_NAME = THIS + ".GetObjectVO()";
DataSet dstPCS = new DataSet();
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ PRO_DCPResultTable.DCPRESULTID_FLD + ","
+ PRO_DCPResultTable.WOROUTINGID_FLD + ","
+ PRO_DCPResultTable.STARTDATETIME_FLD + ","
+ PRO_DCPResultTable.DUEDATETIME_FLD + ","
+ PRO_DCPResultTable.QUANTITY_FLD + ","
+ PRO_DCPResultTable.DCOPTIONMASTERID_FLD + ","
+ PRO_DCPResultTable.CHECKPOINTID_FLD + ","
+ PRO_DCPResultTable.PRODUCTID_FLD + ","
+ PRO_DCPResultTable.CPOID_FLD + ","
+ PRO_DCPResultTable.WORKORDERDETAILID_FLD + ","
+ PRO_DCPResultTable.WORKCENTERID_FLD
+ " FROM " + PRO_DCPResultTable.TABLE_NAME
+" WHERE " + PRO_DCPResultTable.DCPRESULTID_FLD + "=" + pintID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
PRO_DCPResultVO objObject = new PRO_DCPResultVO();
while (odrPCS.Read())
{
objObject.DCPResultID = int.Parse(odrPCS[PRO_DCPResultTable.DCPRESULTID_FLD].ToString().Trim());
objObject.WORoutingID = int.Parse(odrPCS[PRO_DCPResultTable.WOROUTINGID_FLD].ToString().Trim());
objObject.StartDateTime = DateTime.Parse(odrPCS[PRO_DCPResultTable.STARTDATETIME_FLD].ToString().Trim());
objObject.DueDateTime = DateTime.Parse(odrPCS[PRO_DCPResultTable.DUEDATETIME_FLD].ToString().Trim());
objObject.Quantity = Decimal.Parse(odrPCS[PRO_DCPResultTable.QUANTITY_FLD].ToString().Trim());
objObject.DCOptionMasterID = int.Parse(odrPCS[PRO_DCPResultTable.DCOPTIONMASTERID_FLD].ToString().Trim());
objObject.CheckPointID = int.Parse(odrPCS[PRO_DCPResultTable.CHECKPOINTID_FLD].ToString().Trim());
objObject.ProductID = int.Parse(odrPCS[PRO_DCPResultTable.PRODUCTID_FLD].ToString().Trim());
objObject.CPOID = int.Parse(odrPCS[PRO_DCPResultTable.CPOID_FLD].ToString().Trim());
objObject.WorkOrderDetailID = int.Parse(odrPCS[PRO_DCPResultTable.WORKORDERDETAILID_FLD].ToString().Trim());
objObject.WorkCenterID = int.Parse(odrPCS[PRO_DCPResultTable.WORKCENTERID_FLD].ToString().Trim());
}
return objObject;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// This method uses to add data to PRO_DCPResult
/// </summary>
/// <Inputs>
/// PRO_DCPResultVO
/// </Inputs>
/// <Returns>
/// void
/// </Returns>
/// <History>
/// Tuesday, August 30, 2005
/// </History>
public void Update(object pobjObjecVO)
{
const string METHOD_NAME = THIS + ".Update()";
PRO_DCPResultVO objObject = (PRO_DCPResultVO) pobjObjecVO;
//prepare value for parameters
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
strSql= "UPDATE PRO_DCPResult SET "
+ PRO_DCPResultTable.WOROUTINGID_FLD + "= ?" + ","
+ PRO_DCPResultTable.STARTDATETIME_FLD + "= ?" + ","
+ PRO_DCPResultTable.DUEDATETIME_FLD + "= ?" + ","
+ PRO_DCPResultTable.QUANTITY_FLD + "= ?" + ","
+ PRO_DCPResultTable.DCOPTIONMASTERID_FLD + "= ?" + ","
+ PRO_DCPResultTable.CHECKPOINTID_FLD + "= ?" + ","
+ PRO_DCPResultTable.PRODUCTID_FLD + "= ?" + ","
+ PRO_DCPResultTable.CPOID_FLD + "= ?" + ","
+ PRO_DCPResultTable.WORKORDERDETAILID_FLD + "= ?" + ","
+ PRO_DCPResultTable.WORKCENTERID_FLD + "= ?"
+" WHERE " + PRO_DCPResultTable.DCPRESULTID_FLD + "= ?";
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultTable.WOROUTINGID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PRO_DCPResultTable.WOROUTINGID_FLD].Value = objObject.WORoutingID;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultTable.STARTDATETIME_FLD, OleDbType.Date));
ocmdPCS.Parameters[PRO_DCPResultTable.STARTDATETIME_FLD].Value = objObject.StartDateTime;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultTable.DUEDATETIME_FLD, OleDbType.Date));
ocmdPCS.Parameters[PRO_DCPResultTable.DUEDATETIME_FLD].Value = objObject.DueDateTime;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultTable.QUANTITY_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[PRO_DCPResultTable.QUANTITY_FLD].Value = objObject.Quantity;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultTable.DCOPTIONMASTERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PRO_DCPResultTable.DCOPTIONMASTERID_FLD].Value = objObject.DCOptionMasterID;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultTable.CHECKPOINTID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PRO_DCPResultTable.CHECKPOINTID_FLD].Value = objObject.CheckPointID;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultTable.PRODUCTID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PRO_DCPResultTable.PRODUCTID_FLD].Value = objObject.ProductID;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultTable.CPOID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PRO_DCPResultTable.CPOID_FLD].Value = objObject.CPOID;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultTable.WORKORDERDETAILID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PRO_DCPResultTable.WORKORDERDETAILID_FLD].Value = objObject.WorkOrderDetailID;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultTable.WORKCENTERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PRO_DCPResultTable.WORKCENTERID_FLD].Value = objObject.WorkCenterID;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultTable.DCPRESULTID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PRO_DCPResultTable.DCPRESULTID_FLD].Value = objObject.DCPResultID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// This method uses to add data to PRO_DCPResult
/// </summary>
/// <Inputs>
/// PRO_DCPResultVO
/// </Inputs>
/// <Returns>
/// void
/// </Returns>
/// <History>
/// Tuesday, August 30, 2005
/// </History>
public DataSet List()
{
const string METHOD_NAME = THIS + ".List()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ PRO_DCPResultTable.DCPRESULTID_FLD + ","
+ PRO_DCPResultTable.WOROUTINGID_FLD + ","
+ PRO_DCPResultTable.STARTDATETIME_FLD + ","
+ PRO_DCPResultTable.DUEDATETIME_FLD + ","
+ PRO_DCPResultTable.QUANTITY_FLD + ","
+ PRO_DCPResultTable.DCOPTIONMASTERID_FLD + ","
+ PRO_DCPResultTable.CHECKPOINTID_FLD + ","
+ PRO_DCPResultTable.PRODUCTID_FLD + ","
+ PRO_DCPResultTable.CPOID_FLD + ","
+ PRO_DCPResultTable.WORKORDERDETAILID_FLD + ","
+ PRO_DCPResultTable.WORKCENTERID_FLD
+ " FROM " + PRO_DCPResultTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,PRO_DCPResultTable.TABLE_NAME);
return dstPCS;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// This method uses to add data to PRO_DCPResult
/// </summary>
/// <Inputs>
/// PRO_DCPResultVO
/// </Inputs>
/// <Returns>
/// void
/// </Returns>
/// <History>
/// Tuesday, August 30, 2005
/// </History>
public void UpdateDataSet(DataSet pdstData)
{
const string METHOD_NAME = THIS + ".UpdateDataSet()";
string strSql;
OleDbConnection oconPCS =null;
OleDbCommandBuilder odcbPCS ;
OleDbDataAdapter odadPCS = new OleDbDataAdapter();
try
{
strSql= "SELECT "
+ PRO_DCPResultTable.DCPRESULTID_FLD + ","
+ PRO_DCPResultTable.WOROUTINGID_FLD + ","
+ PRO_DCPResultTable.STARTDATETIME_FLD + ","
+ PRO_DCPResultTable.DUEDATETIME_FLD + ","
+ PRO_DCPResultTable.QUANTITY_FLD + ","
+ PRO_DCPResultTable.DCOPTIONMASTERID_FLD + ","
+ PRO_DCPResultTable.CHECKPOINTID_FLD + ","
+ PRO_DCPResultTable.PRODUCTID_FLD + ","
+ PRO_DCPResultTable.CPOID_FLD + ","
+ PRO_DCPResultTable.WORKORDERDETAILID_FLD + ","
+ PRO_DCPResultTable.WORKCENTERID_FLD
+ " FROM " + PRO_DCPResultTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS);
odcbPCS = new OleDbCommandBuilder(odadPCS);
pdstData.EnforceConstraints = false;
odadPCS.Update(pdstData,PRO_DCPResultTable.TABLE_NAME);
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
class ReferenceType
{
internal byte Value;
public ReferenceType(byte value) { Value = value; }
}
struct ValueTypeWithoutPointers
{
internal byte Value;
public ValueTypeWithoutPointers(byte value) { Value = value; }
}
struct ValueTypeWithPointers
{
internal object Reference;
public ValueTypeWithPointers(object reference) { Reference = reference; }
}
struct SevenBytesStruct
{
#pragma warning disable 0169
byte b1, b2, b3, b4, b5, b6, b7;
#pragma warning restore 0169
}
class My
{
static int Sum(Span<int> span)
{
int sum = 0;
for (int i = 0; i < span.Length; i++)
sum += span[i];
return sum;
}
static void Main()
{
int failedTestsCount = 0;
Test(CanAccessItemsViaIndexer, "CanAccessItemsViaIndexer", ref failedTestsCount);
Test(TestBoundaryEmptySpan, "TestBoundaryEmptySpan", ref failedTestsCount);
Test(ReferenceTypesAreSupported, "ReferenceTypesAreSupported", ref failedTestsCount);
Test(CanUpdateUnderlyingArray, "CanUpdateUnderlyingArray", ref failedTestsCount);
Test(MustNotMoveGcTypesToUnmanagedMemory, "MustNotMoveGcTypesToUnmanagedMemory", ref failedTestsCount);
Test(TestArrayCoVariance, "TestArrayCoVariance", ref failedTestsCount);
Test(TestArrayCoVarianceReadOnly, "TestArrayCoVarianceReadOnly", ref failedTestsCount);
Test(CanCopyValueTypesWithoutPointersToSlice, "CanCopyValueTypesWithoutPointersToSlice", ref failedTestsCount);
Test(CanCopyValueTypesWithoutPointersToArray, "CanCopyValueTypesWithoutPointersToArray", ref failedTestsCount);
Test(CanCopyReferenceTypesToSlice, "CanCopyReferenceTypesToSlice", ref failedTestsCount);
Test(CanCopyReferenceTypesToArray, "CanCopyReferenceTypesToArray", ref failedTestsCount);
Test(CanCopyValueTypesWithPointersToSlice, "CanCopyValueTypesWithPointersToSlice", ref failedTestsCount);
Test(CanCopyValueTypesWithPointersToArray, "CanCopyValueTypesWithPointersToArray", ref failedTestsCount);
Test(CanCopyValueTypesWithoutPointersToUnmanagedMemory, "CanCopyValueTypesWithoutPointersToUnmanagedMemory", ref failedTestsCount);
Test(CanCopyOverlappingSlicesOfValueTypeWithoutPointers, "CanCopyOverlappingSlicesOfValueTypeWithoutPointers", ref failedTestsCount);
Test(CanCopyOverlappingSlicesOfValueTypeWithPointers, "CanCopyOverlappingSlicesOfValueTypeWithPointers", ref failedTestsCount);
Test(CanCopyOverlappingSlicesOfReferenceTypes, "CanCopyOverlappingSlicesOfReferenceTypes", ref failedTestsCount);
Test(MustNotCastSpanOfValueTypesWithPointers, "MustNotCastSpanOfValueTypesWithPointers", ref failedTestsCount);
Test(IntArraySpanCastedToByteArraySpanHasSameBytesAsOriginalArray, "IntArraySpanCastedToByteArraySpanHasSameBytesAsOriginalArray", ref failedTestsCount);
Test(ByteArraySpanCastedToIntArraySpanHasSameBytesAsOriginalArray, "ByteArraySpanCastedToIntArraySpanHasSameBytesAsOriginalArray", ref failedTestsCount);
Test(SourceTypeLargerThanTargetOneCorrectlyCalcsTargetsLength, "SourceTypeLargerThanTargetOneCorrectlyCalcsTargetsLength", ref failedTestsCount);
Test(WhenSourceDoesntFitIntoTargetLengthIsZero, "WhenSourceDoesntFitIntoTargetLengthIsZero", ref failedTestsCount);
Test(WhenSourceFitsIntoTargetOnceLengthIsOne, "WhenSourceFitsIntoTargetOnceLengthIsOne", ref failedTestsCount);
Test(WhenSourceTypeLargerThaTargetAndOverflowsInt32ThrowsException, "WhenSourceTypeLargerThaTargetAndOverflowsInt32ThrowsException", ref failedTestsCount);
Test(CanCreateSpanFromString, "CanCreateSpanFromString", ref failedTestsCount);
Console.WriteLine(string.Format("{0} tests has failed", failedTestsCount));
Environment.Exit(failedTestsCount);
}
static void CanAccessItemsViaIndexer()
{
int[] a = new int[] { 1, 2, 3 };
Span<int> slice = new Span<int>(a);
AssertTrue(Sum(slice) == 6, "Failed to sum slice");
Span<int> subslice = slice.Slice(1, 2);
AssertTrue(Sum(subslice) == 5, "Failed to sum subslice");
}
static TestBoundaryEmptySpan()
{
int[] a = new byte[5];
Span<int> slice = new Span<int>(a, a.Length, 0);
AssertEqual(slice.Length, 0);
Span<int> subSlice = new Span<int>(a).Slice(a.Length, 0);
AssertEqual(subSlice.Length, 0);
}
static void ReferenceTypesAreSupported()
{
var underlyingArray = new ReferenceType[] { new ReferenceType(0), new ReferenceType(1), new ReferenceType(2) };
var slice = new Span<ReferenceType>(underlyingArray);
for (int i = 0; i < underlyingArray.Length; i++)
{
AssertTrue(underlyingArray[i].Value == slice[i].Value, "Values are different");
AssertTrue(object.ReferenceEquals(underlyingArray[i], slice[i]), "References are broken");
}
}
static unsafe void MustNotMoveGcTypesToUnmanagedMemory()
{
byte* pointerToStack = stackalloc byte[256];
try
{
new Span<ValueTypeWithPointers>(pointerToStack, 1);
AssertTrue(false, "Expected exception for value types with references not thrown");
}
catch (System.ArgumentException ex)
{
AssertTrue(ex.Message == "Cannot use type 'ValueTypeWithPointers'. Only value types without pointers or references are supported.",
"Exception message is incorrect");
}
try
{
new Span<ReferenceType>(pointerToStack, 1);
AssertTrue(false, "Expected exception for reference types not thrown");
}
catch (System.ArgumentException ex)
{
AssertTrue(ex.Message == "Cannot use type 'ReferenceType'. Only value types without pointers or references are supported.",
"Exception message is incorrect");
}
}
static void TestArrayCoVariance()
{
var array = new ReferenceType[1];
var objArray = (object[])array;
try
{
new Span<object>(objArray);
AssertTrue(false, "Expected exception not thrown");
}
catch (ArrayTypeMismatchException)
{
}
var objEmptyArray = Array.Empty<ReferenceType>();
try
{
new Span<object>(objEmptyArray);
AssertTrue(false, "Expected exception not thrown");
}
catch (ArrayTypeMismatchException)
{
}
}
static void TestArrayCoVarianceReadOnly()
{
var array = new ReferenceType[1];
var objArray = (object[])array;
AssertTrue(new ReadOnlySpan<object>(objArray).Length == 1, "Unexpected length");
var objEmptyArray = Array.Empty<ReferenceType>();
AssertTrue(new ReadOnlySpan<object>(objEmptyArray).Length == 0, "Unexpected length");
}
static void CanUpdateUnderlyingArray()
{
var underlyingArray = new int[] { 1, 2, 3 };
var slice = new Span<int>(underlyingArray);
slice[0] = 0;
slice[1] = 1;
slice[2] = 2;
AssertTrue(underlyingArray[0] == 0, "Failed to update underlying array");
AssertTrue(underlyingArray[1] == 1, "Failed to update underlying array");
AssertTrue(underlyingArray[2] == 2, "Failed to update underlying array");
}
static void CanCopyValueTypesWithoutPointersToSlice()
{
var source = new Span<ValueTypeWithoutPointers>(
new[]
{
new ValueTypeWithoutPointers(0),
new ValueTypeWithoutPointers(1),
new ValueTypeWithoutPointers(2),
new ValueTypeWithoutPointers(3)
});
var underlyingArray = new ValueTypeWithoutPointers[4];
var slice = new Span<ValueTypeWithoutPointers>(underlyingArray);
var result = source.TryCopyTo(slice);
AssertTrue(result, "Failed to copy value types without pointers");
for (int i = 0; i < 4; i++)
{
AssertTrue(source[i].Value == slice[i].Value, "Failed to copy value types without pointers, values were not equal");
AssertTrue(source[i].Value == underlyingArray[i].Value, "Failed to copy value types without pointers to underlying array, values were not equal");
}
}
static void CanCopyValueTypesWithoutPointersToArray()
{
var source = new Span<ValueTypeWithoutPointers>(
new[]
{
new ValueTypeWithoutPointers(0),
new ValueTypeWithoutPointers(1),
new ValueTypeWithoutPointers(2),
new ValueTypeWithoutPointers(3)
});
var array = new ValueTypeWithoutPointers[4];
var result = source.TryCopyTo(array);
AssertTrue(result, "Failed to copy value types without pointers");
for (int i = 0; i < 4; i++)
{
AssertTrue(source[i].Value == array[i].Value, "Failed to copy value types without pointers, values were not equal");
}
}
static void CanCopyReferenceTypesToSlice()
{
var source = new Span<ReferenceType>(
new[]
{
new ReferenceType(0),
new ReferenceType(1),
new ReferenceType(2),
new ReferenceType(3)
});
var underlyingArray = new ReferenceType[4];
var slice = new Span<ReferenceType>(underlyingArray);
var result = source.TryCopyTo(slice);
AssertTrue(result, "Failed to copy reference types");
for (int i = 0; i < 4; i++)
{
AssertTrue(source[i] != null && slice[i] != null, "Failed to copy reference types, references were null");
AssertTrue(object.ReferenceEquals(source[i], slice[i]), "Failed to copy reference types, references were not equal");
AssertTrue(source[i].Value == slice[i].Value, "Failed to copy reference types, values were not equal");
AssertTrue(underlyingArray[i] != null, "Failed to copy reference types to underlying array, references were null");
AssertTrue(object.ReferenceEquals(source[i], underlyingArray[i]), "Failed to copy reference types to underlying array, references were not equal");
AssertTrue(source[i].Value == underlyingArray[i].Value, "Failed to copy reference types to underlying array, values were not equal");
}
}
static void CanCopyReferenceTypesToArray()
{
var source = new Span<ReferenceType>(
new[]
{
new ReferenceType(0),
new ReferenceType(1),
new ReferenceType(2),
new ReferenceType(3)
});
var array = new ReferenceType[4];
var result = source.TryCopyTo(array);
AssertTrue(result, "Failed to copy reference types");
for (int i = 0; i < 4; i++)
{
AssertTrue(source[i] != null && array[i] != null, "Failed to copy reference types, references were null");
AssertTrue(object.ReferenceEquals(source[i], array[i]), "Failed to copy reference types, references were not equal");
AssertTrue(source[i].Value == array[i].Value, "Failed to copy reference types, values were not equal");
}
}
static void CanCopyValueTypesWithPointersToSlice()
{
var source = new Span<ValueTypeWithPointers>(
new[]
{
new ValueTypeWithPointers(new object()),
new ValueTypeWithPointers(new object()),
new ValueTypeWithPointers(new object()),
new ValueTypeWithPointers(new object())
});
var underlyingArray = new ValueTypeWithPointers[4];
var slice = new Span<ValueTypeWithPointers>(underlyingArray);
var result = source.TryCopyTo(slice);
AssertTrue(result, "Failed to copy value types with pointers");
for (int i = 0; i < 4; i++)
{
AssertTrue(object.ReferenceEquals(source[i].Reference, slice[i].Reference), "Failed to copy value types with pointers, references were not the same");
AssertTrue(object.ReferenceEquals(source[i].Reference, underlyingArray[i].Reference), "Failed to copy value types with pointers to underlying array, references were not the same");
}
}
static void CanCopyValueTypesWithPointersToArray()
{
var source = new Span<ValueTypeWithPointers>(
new[]
{
new ValueTypeWithPointers(new object()),
new ValueTypeWithPointers(new object()),
new ValueTypeWithPointers(new object()),
new ValueTypeWithPointers(new object())
});
var array = new ValueTypeWithPointers[4];
var result = source.TryCopyTo(array);
AssertTrue(result, "Failed to copy value types with pointers");
for (int i = 0; i < 4; i++)
{
AssertTrue(object.ReferenceEquals(source[i].Reference, array[i].Reference), "Failed to copy value types with pointers, references were not the same");
}
}
static unsafe void CanCopyValueTypesWithoutPointersToUnmanagedMemory()
{
var source = new Span<byte>(
new byte[]
{
0,
1,
2,
3
});
byte* pointerToStack = stackalloc byte[256];
var result = source.TryCopyTo(new Span<byte>(pointerToStack, 4));
AssertTrue(result, "Failed to copy value types without pointers to unamanaged memory");
for (int i = 0; i < 4; i++)
{
AssertTrue(source[i] == pointerToStack[i], "Failed to copy value types without pointers to unamanaged memory, values were not equal");
}
}
static void CanCopyOverlappingSlicesOfValueTypeWithoutPointers()
{
var sourceArray = new[]
{
new ValueTypeWithoutPointers(0),
new ValueTypeWithoutPointers(1),
new ValueTypeWithoutPointers(2)
};
var firstAndSecondElements = new Span<ValueTypeWithoutPointers>(sourceArray, 0, 2); // 0, 1
var secondAndThirdElements = new Span<ValueTypeWithoutPointers>(sourceArray, 1, 2); // 1, 2
// 0 1 2 sourceArray
// 0 1 - firstAndSecondElements
// - 1 2 secondAndThirdElements
var result = firstAndSecondElements.TryCopyTo(secondAndThirdElements); // to avoid overlap we should copy backward now
// - 0 1 secondAndThirdElements
// 0 0 - firstAndSecondElements
// 0 0 1 sourceArray
AssertTrue(result, "Failed to copy overlapping value types without pointers");
AssertTrue(secondAndThirdElements[1].Value == 1, "secondAndThirdElements[1] should get replaced by 1");
AssertTrue(secondAndThirdElements[0].Value == 0 && firstAndSecondElements[1].Value == 0, "secondAndThirdElements[0] and firstAndSecondElements[1] point to the same element, should get replaced by 0");
AssertTrue(firstAndSecondElements[0].Value == 0, "firstAndSecondElements[0] should remain the same");
// let's try the other direction to make sure it works as well!
sourceArray = new[]
{
new ValueTypeWithoutPointers(0),
new ValueTypeWithoutPointers(1),
new ValueTypeWithoutPointers(2)
};
firstAndSecondElements = new Span<ValueTypeWithoutPointers>(sourceArray, 0, 2); // 0, 1
secondAndThirdElements = new Span<ValueTypeWithoutPointers>(sourceArray, 1, 2); // 1, 2
// 0 1 2 sourceArray
// 0 1 - firstAndSecondElements
// - 1 2 secondAndThirdElements
result = secondAndThirdElements.TryCopyTo(firstAndSecondElements); // to avoid overlap we should copy forward now
// 1 2 - firstAndSecondElements
// - 2 2 secondAndThirdElements
// 1 2 2 sourceArray
AssertTrue(result, "Failed to copy overlapping value types without pointers");
AssertTrue(secondAndThirdElements[1].Value == 2, "secondAndThirdElements[1] should remain the same");
AssertTrue(firstAndSecondElements[1].Value == 2 && secondAndThirdElements[0].Value == 2, "secondAndThirdElements[0] && firstAndSecondElements[1] point to the same element, should get replaced by 2");
AssertTrue(firstAndSecondElements[0].Value == 1, "firstAndSecondElements[0] should get replaced by 1");
}
static void CanCopyOverlappingSlicesOfValueTypeWithPointers()
{
string zero = "0", one = "1", two = "2";
var sourceArray = new[]
{
new ValueTypeWithPointers(zero),
new ValueTypeWithPointers(one),
new ValueTypeWithPointers(two)
};
var firstAndSecondElements = new Span<ValueTypeWithPointers>(sourceArray, 0, 2); // 0, 1
var secondAndThirdElements = new Span<ValueTypeWithPointers>(sourceArray, 1, 2); // 1, 2
// 0 1 2 sourceArray
// 0 1 - firstAndSecondElements
// - 1 2 secondAndThirdElements
var result = firstAndSecondElements.TryCopyTo(secondAndThirdElements); // to avoid overlap we should copy backward now
// - 0 1 secondAndThirdElements
// 0 0 - firstAndSecondElements
// 0 0 1 sourceArray
AssertTrue(result, "Failed to copy overlapping value types with pointers");
AssertTrue(object.ReferenceEquals(secondAndThirdElements[1].Reference, one), "secondAndThirdElements[1] should get replaced by 1");
AssertTrue(object.ReferenceEquals(secondAndThirdElements[0].Reference, zero) && object.ReferenceEquals(firstAndSecondElements[1].Reference, zero), "secondAndThirdElements[0] and firstAndSecondElements[1] point to the same element, should get replaced by 0");
AssertTrue(object.ReferenceEquals(firstAndSecondElements[0].Reference, zero), "firstAndSecondElements[0] should remain the same");
// let's try the other direction to make sure it works as well!
sourceArray = new[]
{
new ValueTypeWithPointers(zero),
new ValueTypeWithPointers(one),
new ValueTypeWithPointers(two)
};
firstAndSecondElements = new Span<ValueTypeWithPointers>(sourceArray, 0, 2); // 0, 1
secondAndThirdElements = new Span<ValueTypeWithPointers>(sourceArray, 1, 2); // 1, 2
// 0 1 2 sourceArray
// 0 1 - firstAndSecondElements
// - 1 2 secondAndThirdElements
result = secondAndThirdElements.TryCopyTo(firstAndSecondElements); // to avoid overlap we should copy forward now
// 1 2 - firstAndSecondElements
// - 2 2 secondAndThirdElements
// 1 2 2 sourceArray
AssertTrue(result, "Failed to copy overlapping value types with pointers");
AssertTrue(object.ReferenceEquals(secondAndThirdElements[1].Reference, two), "secondAndThirdElements[1] should remain the same");
AssertTrue(object.ReferenceEquals(firstAndSecondElements[1].Reference, two) && object.ReferenceEquals(secondAndThirdElements[0].Reference, two), "secondAndThirdElements[0] && firstAndSecondElements[1] point to the same element, should get replaced by 2");
AssertTrue(object.ReferenceEquals(firstAndSecondElements[0].Reference, one), "firstAndSecondElements[0] should get replaced by 1");
}
static void CanCopyOverlappingSlicesOfReferenceTypes()
{
var sourceArray = new ReferenceType[] { new ReferenceType(0), new ReferenceType(1), new ReferenceType(2) };
var firstAndSecondElements = new Span<ReferenceType>(sourceArray, 0, 2); // 0, 1
var secondAndThirdElements = new Span<ReferenceType>(sourceArray, 1, 2); // 1, 2
// 0 1 2 sourceArray
// 0 1 - firstAndSecondElements
// - 1 2 secondAndThirdElements
var result = firstAndSecondElements.TryCopyTo(secondAndThirdElements); // to avoid overlap we should copy backward now
// - 0 1 secondAndThirdElements
// 0 0 - firstAndSecondElements
// 0 0 1 sourceArray
AssertTrue(result, "Failed to copy overlapping reference types");
AssertTrue(secondAndThirdElements[1].Value == 1, "secondAndThirdElements[1] should get replaced by 1");
AssertTrue(secondAndThirdElements[0].Value == 0 && firstAndSecondElements[1].Value == 0, "secondAndThirdElements[0] and firstAndSecondElements[1] point to the same element, should get replaced by 0");
AssertTrue(firstAndSecondElements[0].Value == 0, "firstAndSecondElements[0] should remain the same");
// let's try the other direction to make sure it works as well!
sourceArray = new[]
{
new ReferenceType(0),
new ReferenceType(1),
new ReferenceType(2)
};
firstAndSecondElements = new Span<ReferenceType>(sourceArray, 0, 2); // 0, 1
secondAndThirdElements = new Span<ReferenceType>(sourceArray, 1, 2); // 1, 2
// 0 1 2 sourceArray
// 0 1 - firstAndSecondElements
// - 1 2 secondAndThirdElements
result = secondAndThirdElements.TryCopyTo(firstAndSecondElements); // to avoid overlap we should copy forward now
// 1 2 - firstAndSecondElements
// - 2 2 secondAndThirdElements
// 1 2 2 sourceArray
AssertTrue(result, "Failed to copy overlapping reference types");
AssertTrue(secondAndThirdElements[1].Value == 2, "secondAndThirdElements[1] should remain the same");
AssertTrue(firstAndSecondElements[1].Value == 2 && secondAndThirdElements[0].Value == 2, "secondAndThirdElements[0] && firstAndSecondElements[1] point to the same element, should get replaced by 2");
AssertTrue(firstAndSecondElements[0].Value == 1, "firstAndSecondElements[0] should get replaced by 1");
}
static void MustNotCastSpanOfValueTypesWithPointers()
{
var spanOfValueTypeWithPointers = new Span<ValueTypeWithPointers>(new[] { new ValueTypeWithPointers(new object()) });
try
{
var impossible = spanOfValueTypeWithPointers.AsBytes();
AssertTrue(false, "Expected exception for wrong type not thrown");
}
catch (System.ArgumentException ex)
{
AssertTrue(ex.Message == "Cannot use type 'ValueTypeWithPointers'. Only value types without pointers or references are supported.",
"Exception message is incorrect");
}
try
{
var impossible = spanOfValueTypeWithPointers.NonPortableCast<ValueTypeWithPointers, byte>();
AssertTrue(false, "Expected exception for wrong type not thrown");
}
catch (System.ArgumentException ex)
{
AssertTrue(ex.Message == "Cannot use type 'ValueTypeWithPointers'. Only value types without pointers or references are supported.",
"Exception message is incorrect");
}
var spanOfBytes = new Span<byte>(new byte[10]);
try
{
var impossible = spanOfBytes.NonPortableCast<byte, ValueTypeWithPointers>();
AssertTrue(false, "Expected exception for wrong type not thrown");
}
catch (System.ArgumentException ex)
{
AssertTrue(ex.Message == "Cannot use type 'ValueTypeWithPointers'. Only value types without pointers or references are supported.",
"Exception message is incorrect");
}
}
static void IntArraySpanCastedToByteArraySpanHasSameBytesAsOriginalArray()
{
var ints = new int[100000];
Random r = new Random(42324232);
for (int i = 0; i < ints.Length; i++) { ints[i] = r.Next(); }
var bytes = new Span<int>(ints).AsBytes();
AssertEqual(bytes.Length, ints.Length * sizeof(int));
for (int i = 0; i < ints.Length; i++)
{
AssertEqual(bytes[i * 4], (ints[i] & 0xff));
AssertEqual(bytes[i * 4 + 1], (ints[i] >> 8 & 0xff));
AssertEqual(bytes[i * 4 + 2], (ints[i] >> 16 & 0xff));
AssertEqual(bytes[i * 4 + 3], (ints[i] >> 24 & 0xff));
}
}
static void ByteArraySpanCastedToIntArraySpanHasSameBytesAsOriginalArray()
{
var bytes = new byte[100000];
Random r = new Random(541345);
for (int i = 0; i < bytes.Length; i++) { bytes[i] = (byte)r.Next(256); }
var ints = new Span<byte>(bytes).NonPortableCast<byte, int>();
AssertEqual(ints.Length, bytes.Length / sizeof(int));
for (int i = 0; i < ints.Length; i++)
{
AssertEqual(BitConverter.ToInt32(bytes, i * 4), ints[i]);
}
}
static void SourceTypeLargerThanTargetOneCorrectlyCalcsTargetsLength()
{
for (int sourceLength = 0; sourceLength <= 4; sourceLength++)
{
var sourceSlice = new Span<SevenBytesStruct>(new SevenBytesStruct[sourceLength]);
var targetSlice = sourceSlice.NonPortableCast<SevenBytesStruct, short>();
AssertEqual((sourceLength * 7) / sizeof(short), targetSlice.Length);
}
}
static void WhenSourceDoesntFitIntoTargetLengthIsZero()
{
for (int sourceLength = 0; sourceLength <= 3; sourceLength++)
{
var sourceSlice = new Span<short>(new short[sourceLength]);
var targetSlice = sourceSlice.NonPortableCast<short, SevenBytesStruct>();
AssertEqual(0, targetSlice.Length);
}
}
static void WhenSourceFitsIntoTargetOnceLengthIsOne()
{
foreach (var sourceLength in new int[] { 4, 6 })
{
var sourceSlice = new Span<short>(new short[sourceLength]);
var targetSlice = sourceSlice.NonPortableCast<short, SevenBytesStruct>();
AssertEqual(1, targetSlice.Length);
}
}
static void WhenSourceTypeLargerThaTargetAndOverflowsInt32ThrowsException()
{
unsafe
{
byte dummy;
int sourceLength = 620000000;
var sourceSlice = new Span<SevenBytesStruct>(&dummy, sourceLength);
try
{
var targetSlice = sourceSlice.NonPortableCast<SevenBytesStruct, short>();
AssertTrue(false, "Expected exception for overflow not thrown");
}
catch (System.OverflowException)
{
}
}
}
static void CanCreateSpanFromString()
{
const string fullText = "new Span<byte>()";
var spanFromFull = fullText.Slice();
AssertEqualContent(fullText, spanFromFull);
string firstHalfOfString = fullText.Substring(0, fullText.Length / 2);
var spanFromFirstHalf = fullText.Slice(0, fullText.Length / 2);
AssertEqualContent(firstHalfOfString, spanFromFirstHalf);
string secondHalfOfString = fullText.Substring(fullText.Length / 2);
var spanFromSecondHalf = fullText.Slice(fullText.Length / 2);
AssertEqualContent(secondHalfOfString, spanFromSecondHalf);
}
static void Test(Action test, string testName, ref int failedTestsCount)
{
try
{
test();
Console.WriteLine(testName + " test has passed");
}
catch (System.Exception ex)
{
Console.WriteLine(testName + " test has failed with exception: " + ex.Message);
++failedTestsCount;
}
finally
{
Console.WriteLine("-------------------");
}
}
static void AssertTrue(bool condition, string errorMessage)
{
if (condition == false)
{
throw new Exception(errorMessage);
}
}
static void AssertEqual<T>(T left, T right)
where T : IEquatable<T>
{
if (left.Equals(right) == false)
{
throw new Exception(string.Format("Values were not equal! {0} and {1}", left, right));
}
}
static void AssertEqualContent(string text, ReadOnlySpan<char> span)
{
AssertEqual(text.Length, span.Length);
for (int i = 0; i < text.Length; i++)
{
AssertEqual(text[i], span[i]);
}
}
}
| |
// 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.Diagnostics;
using Microsoft.DiaSymReader;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal static class PdbHelpers
{
/// <remarks>
/// Test helper.
/// </remarks>
internal static void GetAllScopes(this ISymUnmanagedMethod method, ArrayBuilder<ISymUnmanagedScope> builder)
{
var unused = ArrayBuilder<ISymUnmanagedScope>.GetInstance();
GetAllScopes(method, builder, unused, offset: -1, isScopeEndInclusive: false);
unused.Free();
}
internal static void GetAllScopes(
this ISymUnmanagedMethod method,
ArrayBuilder<ISymUnmanagedScope> allScopes,
ArrayBuilder<ISymUnmanagedScope> containingScopes,
int offset,
bool isScopeEndInclusive)
{
GetAllScopes(method.GetRootScope(), allScopes, containingScopes, offset, isScopeEndInclusive);
}
private static void GetAllScopes(
ISymUnmanagedScope root,
ArrayBuilder<ISymUnmanagedScope> allScopes,
ArrayBuilder<ISymUnmanagedScope> containingScopes,
int offset,
bool isScopeEndInclusive)
{
var stack = ArrayBuilder<ISymUnmanagedScope>.GetInstance();
stack.Push(root);
while (stack.Any())
{
var scope = stack.Pop();
allScopes.Add(scope);
if (offset >= 0 && IsInScope(scope, offset, isScopeEndInclusive))
{
containingScopes.Add(scope);
}
foreach (var nested in scope.GetChildren())
{
stack.Push(nested);
}
}
stack.Free();
}
private static bool IsInScope(ISymUnmanagedScope scope, int offset, bool isEndInclusive)
{
int startOffset = scope.GetStartOffset();
if (offset < startOffset)
{
return false;
}
int endOffset = scope.GetEndOffset();
// In PDBs emitted by VB the end offset is inclusive,
// in PDBs emitted by C# the end offset is exclusive.
return isEndInclusive ? offset <= endOffset : offset < endOffset;
}
/// <summary>
/// Translates the value of a constant returned by <see cref="ISymUnmanagedConstant.GetValue(out object)"/> to a <see cref="ConstantValue"/>.
/// </summary>
public static ConstantValue GetSymConstantValue(ITypeSymbol type, object symValue)
{
if (type.TypeKind == TypeKind.Enum)
{
type = ((INamedTypeSymbol)type).EnumUnderlyingType;
}
short shortValue;
switch (type.SpecialType)
{
case SpecialType.System_Boolean:
if (!(symValue is short))
{
return ConstantValue.Bad;
}
return ConstantValue.Create((short)symValue != 0);
case SpecialType.System_Byte:
if (!(symValue is short))
{
return ConstantValue.Bad;
}
shortValue = (short)symValue;
if (unchecked((byte)shortValue) != shortValue)
{
return ConstantValue.Bad;
}
return ConstantValue.Create((byte)shortValue);
case SpecialType.System_SByte:
if (!(symValue is short))
{
return ConstantValue.Bad;
}
shortValue = (short)symValue;
if (unchecked((sbyte)shortValue) != shortValue)
{
return ConstantValue.Bad;
}
return ConstantValue.Create((sbyte)shortValue);
case SpecialType.System_Int16:
if (!(symValue is short))
{
return ConstantValue.Bad;
}
return ConstantValue.Create((short)symValue);
case SpecialType.System_Char:
if (!(symValue is ushort))
{
return ConstantValue.Bad;
}
return ConstantValue.Create((char)(ushort)symValue);
case SpecialType.System_UInt16:
if (!(symValue is ushort))
{
return ConstantValue.Bad;
}
return ConstantValue.Create((ushort)symValue);
case SpecialType.System_Int32:
if (!(symValue is int))
{
return ConstantValue.Bad;
}
return ConstantValue.Create((int)symValue);
case SpecialType.System_UInt32:
if (!(symValue is uint))
{
return ConstantValue.Bad;
}
return ConstantValue.Create((uint)symValue);
case SpecialType.System_Int64:
if (!(symValue is long))
{
return ConstantValue.Bad;
}
return ConstantValue.Create((long)symValue);
case SpecialType.System_UInt64:
if (!(symValue is ulong))
{
return ConstantValue.Bad;
}
return ConstantValue.Create((ulong)symValue);
case SpecialType.System_Single:
if (!(symValue is float))
{
return ConstantValue.Bad;
}
return ConstantValue.Create((float)symValue);
case SpecialType.System_Double:
if (!(symValue is double))
{
return ConstantValue.Bad;
}
return ConstantValue.Create((double)symValue);
case SpecialType.System_String:
if (symValue is int && (int)symValue == 0)
{
return ConstantValue.Null;
}
if (symValue == null)
{
return ConstantValue.Create(string.Empty);
}
var str = symValue as string;
if (str == null)
{
return ConstantValue.Bad;
}
return ConstantValue.Create(str);
case SpecialType.System_Object:
if (symValue is int && (int)symValue == 0)
{
return ConstantValue.Null;
}
return ConstantValue.Bad;
case SpecialType.System_Decimal:
if (!(symValue is decimal))
{
return ConstantValue.Bad;
}
return ConstantValue.Create((decimal)symValue);
case SpecialType.System_DateTime:
if (!(symValue is double))
{
return ConstantValue.Bad;
}
return ConstantValue.Create(DateTimeUtilities.ToDateTime((double)symValue));
case SpecialType.None:
if (type.IsReferenceType)
{
if (symValue is int && (int)symValue == 0)
{
return ConstantValue.Null;
}
return ConstantValue.Bad;
}
return ConstantValue.Bad;
default:
return ConstantValue.Bad;
}
}
}
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Diagnostics;
using System.Reflection;
using System.Text;
using System.Threading;
namespace System.Abstract.Parts
{
/// <summary>
/// IServiceManager
/// </summary>
public interface IServiceManager
{
}
/// <summary>
/// ServiceManagerBase
/// </summary>
public abstract partial class ServiceManagerBase<TIService, TServiceSetupAction, TServiceManagerDebugger> : IServiceManager
where TIService : class
{
private static readonly ConditionalWeakTable<Lazy<TIService>, ISetupDescriptor> _setupDescriptors = new ConditionalWeakTable<Lazy<TIService>, ISetupDescriptor>();
private static readonly object _lock = new object();
// Force "precise" initialization
static ServiceManagerBase() { }
/// <summary>
/// Gets or sets the DefaultServiceProvider.
/// </summary>
/// <value>
/// The DefaultServiceProvider.
/// </value>
public static Func<TIService> DefaultServiceProvider { get; set; }
/// <summary>
/// Gets or sets the lazy.
/// </summary>
/// <value>
/// The lazy.
/// </value>
public static Lazy<TIService> Lazy { get; protected set; }
/// <summary>
/// Gets or sets the last exception.
/// </summary>
/// <value>
/// The last exception.
/// </value>
public static Exception LastException { get; protected set; }
/// <summary>
/// Makes the by provider protected.
/// </summary>
/// <param name="provider">The provider.</param>
/// <param name="setupDescriptor">The setup descriptor.</param>
/// <returns></returns>
[DebuggerStepThroughAttribute]
public static Lazy<TIService> MakeByProviderProtected(Func<TIService> provider, ISetupDescriptor setupDescriptor)
{
if (provider == null)
throw new ArgumentNullException("provider");
var lazy = new Lazy<TIService>(provider, LazyThreadSafetyMode.PublicationOnly);
GetSetupDescriptorProtected(lazy, setupDescriptor);
return lazy;
}
/// <summary>
///
/// </summary>
protected static TIService LazyValue;
/// <summary>
/// Gets or sets the debugger.
/// </summary>
/// <value>
/// The debugger.
/// </value>
public static TServiceManagerDebugger Debugger { get; set; }
/// <summary>
/// Gets or sets the registration.
/// </summary>
/// <value>
/// The registration.
/// </value>
protected static ServiceRegistration Registration { get; set; }
/// <summary>
/// Gets the current.
/// </summary>
/// <returns></returns>
/// <exception cref="System.InvalidOperationException">Service undefined. Ensure SetProvider</exception>
/// <exception cref="System.Exception"></exception>
protected static TIService GetCurrent()
{
if (Lazy == null)
throw new InvalidOperationException("Service undefined. Ensure SetProvider");
if (LazyValue != null)
return LazyValue;
if (Lazy.IsValueCreated)
return Lazy.Value;
try { return Lazy.Value; }
catch (Exception e)
{
var reflectionTypeLoadException = (e as ReflectionTypeLoadException);
if (reflectionTypeLoadException != null)
{
var b = new StringBuilder();
foreach (var ex2 in reflectionTypeLoadException.LoaderExceptions)
b.AppendLine(ex2.Message);
throw new Exception(b.ToString(), e);
}
throw e.PrepareForRethrow();
}
//var value = Lazy.Value;
//if (LastException != null)
//{
// var reflectionTypeLoadException = (LastException as ReflectionTypeLoadException);
// if (reflectionTypeLoadException != null)
// {
// var b = new StringBuilder();
// foreach (var ex2 in reflectionTypeLoadException.LoaderExceptions)
// b.AppendLine(ex2.Message);
// throw new Exception(b.ToString(), LastException);
// }
// throw LastException.PrepareForRethrow();
//}
//return value;
}
#region Setup
/// <summary>
/// ISetupRegistration
/// </summary>
public interface ISetupRegistration
{
/// <summary>
/// Gets the on service registrar.
/// </summary>
Action<IServiceLocator, string> DefaultServiceRegistrar { get; }
}
/// <summary>
/// ServiceRegistration
/// </summary>
protected class ServiceRegistration
{
/// <summary>
/// Initializes a new instance of the <see cref="ServiceManagerBase<TIService, TServiceSetupAction, TServiceManagerDebugger>.ServiceRegistration"/> class.
/// </summary>
public ServiceRegistration()
{
DefaultServiceRegistrar = (service, locator, name) =>
{
//var behavior = (service.Registrar as IServiceRegistrarBehaviorAccessor);
//if (behavior != null && !behavior.RegisterInLocator)
// throw new InvalidOperationException();
RegisterInstance(service, locator, name);
// specific registration
var setupRegistration = (service as ISetupRegistration);
if (setupRegistration != null)
setupRegistration.DefaultServiceRegistrar(locator, name);
};
}
/// <summary>
/// Gets or sets the on setup.
/// </summary>
/// <value>
/// The on setup.
/// </value>
public Func<TIService, ISetupDescriptor, TIService> OnSetup { get; set; }
/// <summary>
/// Gets or sets the on change.
/// </summary>
/// <value>
/// The on change.
/// </value>
public Action<TIService, ISetupDescriptor> OnChange { get; set; }
/// <summary>
/// Gets or sets the on service registrar.
/// </summary>
/// <value>
/// The on service registrar.
/// </value>
public Action<TIService, IServiceLocator, string> DefaultServiceRegistrar { get; set; }
/// <summary>
/// Gets or sets the make action.
/// </summary>
/// <value>
/// The make action.
/// </value>
public Func<Action<TIService>, TServiceSetupAction> MakeAction { get; set; }
}
/// <summary>
/// RegisterInstance
/// </summary>
public static void RegisterInstance<T>(T service, IServiceLocator locator, string name)
where T : class
{
if (locator == null)
throw new ArgumentNullException("locator");
if (name == null)
locator.Registrar.RegisterInstance<T>(service);
else
locator.Registrar.RegisterInstance<T>(service, name);
}
#endregion
#region IServiceSetup
/// <summary>
/// ApplySetup
/// </summary>
private static TIService ApplySetup(Lazy<TIService> service, TIService newInstance)
{
if (service == null)
throw new ArgumentNullException("service");
if (newInstance == null)
throw new NullReferenceException("instance");
var registration = Registration;
if (registration == null)
throw new NullReferenceException("Registration");
var onSetup = registration.OnSetup;
if (onSetup == null)
return newInstance;
// find descriptor
ISetupDescriptor setupDescriptor;
if (_setupDescriptors.TryGetValue(service, out setupDescriptor))
_setupDescriptors.Remove(service);
return onSetup(newInstance, setupDescriptor);
}
/// <summary>
/// ApplyChanges
/// </summary>
private static void ApplyChange(Lazy<TIService> service, ISetupDescriptor changeDescriptor)
{
if (service == null)
throw new ArgumentNullException("service");
if (!service.IsValueCreated)
throw new InvalidOperationException("Service value has not been created yet.");
var registration = Registration;
if (registration == null)
throw new NullReferenceException("Registration");
var onChange = registration.OnChange;
if (onChange != null)
onChange(service.Value, changeDescriptor);
}
/// <summary>
/// GetSetupDescriptorProtected
/// </summary>
[DebuggerStepThroughAttribute]
protected static ISetupDescriptor GetSetupDescriptorProtected(Lazy<TIService> service, ISetupDescriptor firstDescriptor)
{
if (service == null)
throw new ArgumentNullException("service");
if (service.IsValueCreated)
return new SetupDescriptor(Registration, d => ApplyChange(service, d));
ISetupDescriptor descriptor;
if (_setupDescriptors.TryGetValue(service, out descriptor))
{
if (firstDescriptor == null)
return descriptor;
throw new InvalidOperationException(string.Format(Local.RedefineSetupDescriptorA, service.ToString()));
}
lock (_lock)
if (!_setupDescriptors.TryGetValue(service, out descriptor))
{
descriptor = (firstDescriptor ?? new SetupDescriptor(Registration, null));
_setupDescriptors.Add(service, descriptor);
service.HookValueFactory(valueFactory => ApplySetup(service, LazyValue = valueFactory()));
//service.HookValueFactory(valueFactory =>
//{
// TIService s = null;
// try { s = ApplySetup(service, LazyValue = valueFactory()); }
// catch (Exception e) { LastException = e; }
// return s;
//});
}
return descriptor;
}
/// <summary>
/// ISetupDescriptor
/// </summary>
public interface ISetupDescriptor
{
/// <summary>
/// Does the specified action.
/// </summary>
/// <param name="action">The action.</param>
void Do(Action<TIService> action);
/// <summary>
/// Does the specified action.
/// </summary>
/// <param name="action">The action.</param>
void Do(TServiceSetupAction action);
/// <summary>
/// Registers the with service locator.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="service">The service.</param>
/// <param name="locator">The locator.</param>
/// <param name="name">The name.</param>
void RegisterWithServiceLocator<T>(Lazy<TIService> service, Lazy<IServiceLocator> locator, string name)
where T : class, TIService;
/// <summary>
/// Registers the with service locator.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="locator">The locator.</param>
/// <param name="name">The name.</param>
void RegisterWithServiceLocator(Lazy<TIService> service, Lazy<IServiceLocator> locator, string name);
/// <summary>
/// Registers the with service locator.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="service">The service.</param>
/// <param name="locator">The locator.</param>
/// <param name="name">The name.</param>
void RegisterWithServiceLocator<T>(Lazy<TIService> service, IServiceLocator locator, string name)
where T : class, TIService;
/// <summary>
/// Registers the with service locator.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="locator">The locator.</param>
/// <param name="name">The name.</param>
void RegisterWithServiceLocator(Lazy<TIService> service, IServiceLocator locator, string name);
/// <summary>
/// Gets the actions.
/// </summary>
IEnumerable<TServiceSetupAction> Actions { get; }
}
/// <summary>
/// LazySetupDescriptor
/// </summary>
protected class SetupDescriptor : ISetupDescriptor
{
private List<TServiceSetupAction> _actions = new List<TServiceSetupAction>();
private ServiceRegistration _registration;
private Action<ISetupDescriptor> _postAction;
/// <summary>
/// Initializes a new instance of the <see cref="ServiceManagerBase<TIService, TServiceSetupAction, TDebuggerFlags>.SetupDescriptor"/> class.
/// </summary>
/// <param name="registration">The registration.</param>
/// <param name="postAction">The post action.</param>
public SetupDescriptor(ServiceRegistration registration, Action<ISetupDescriptor> postAction)
{
if (registration == null)
throw new ArgumentNullException("registration", "Please ensure EnsureRegistration() has been called");
_registration = registration;
_postAction = postAction;
}
[DebuggerStepThroughAttribute]
void ISetupDescriptor.Do(Action<TIService> action)
{
_actions.Add(_registration.MakeAction(action));
if (_postAction != null)
_postAction(this);
}
[DebuggerStepThroughAttribute]
void ISetupDescriptor.Do(TServiceSetupAction action)
{
if (action == null)
throw new ArgumentNullException("action");
_actions.Add(action);
if (_postAction != null)
_postAction(this);
}
[DebuggerStepThroughAttribute]
void ISetupDescriptor.RegisterWithServiceLocator<T>(Lazy<TIService> service, Lazy<IServiceLocator> locator, string name)
{
if (service == null)
throw new ArgumentNullException("service");
if (locator == null)
throw new ArgumentNullException("locator", "Unable to locate ServiceLocator, please ensure this is defined first.");
if (!locator.IsValueCreated)
{
var descriptor = ServiceLocatorManager.GetSetupDescriptor(locator);
if (descriptor == null)
throw new NullReferenceException();
descriptor.Do(l => RegisterInstance<T>((T)service.Value, l, name));
}
else
{
var descriptor = GetSetupDescriptorProtected(service, null);
if (descriptor == null)
throw new NullReferenceException();
descriptor.Do(l => RegisterInstance<T>((T)service.Value, locator.Value, name));
}
}
[DebuggerStepThroughAttribute]
void ISetupDescriptor.RegisterWithServiceLocator(Lazy<TIService> service, Lazy<IServiceLocator> locator, string name)
{
if (service == null)
throw new ArgumentNullException("service");
if (locator == null)
throw new ArgumentNullException("locator", "Unable to locate ServiceLocator, please ensure this is defined first.");
var serviceRegistrar = _registration.DefaultServiceRegistrar;
if (serviceRegistrar == null)
throw new NullReferenceException("registration.ServiceLocatorRegistrar");
if (!locator.IsValueCreated)
{
// question: should this use RegisterWithServiceLocator below?
var descriptor = ServiceLocatorManager.GetSetupDescriptor(locator);
if (descriptor == null)
throw new NullReferenceException();
descriptor.Do(l => serviceRegistrar(service.Value, l, name));
}
else
{
var descriptor = GetSetupDescriptorProtected(service, null);
if (descriptor == null)
throw new NullReferenceException();
descriptor.Do(s => serviceRegistrar(s, locator.Value, name));
}
}
[DebuggerStepThroughAttribute]
void ISetupDescriptor.RegisterWithServiceLocator<T>(Lazy<TIService> service, IServiceLocator locator, string name)
{
if (service == null)
throw new ArgumentNullException("service");
if (locator == null)
throw new ArgumentNullException("locator", "Unable to locate ServiceLocator, please ensure this is defined first.");
RegisterInstance<T>((T)service.Value, locator, name);
}
[DebuggerStepThroughAttribute]
void ISetupDescriptor.RegisterWithServiceLocator(Lazy<TIService> service, IServiceLocator locator, string name)
{
if (service == null)
throw new ArgumentNullException("service");
if (locator == null)
throw new ArgumentNullException("locator", "Unable to locate ServiceLocator, please ensure this is defined first.");
var serviceRegistrar = _registration.DefaultServiceRegistrar;
if (serviceRegistrar == null)
throw new NullReferenceException("registration.ServiceLocatorRegistrar");
serviceRegistrar(service.Value, locator, name);
}
IEnumerable<TServiceSetupAction> ISetupDescriptor.Actions
{
[DebuggerStepThroughAttribute]
get { return _actions; }
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Runtime.Serialization
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Security;
using Microsoft.Xml;
using DataContractDictionary = System.Collections.Generic.Dictionary<Microsoft.Xml.XmlQualifiedName, DataContract>;
#if USE_REFEMIT || NET_NATIVE
public class XmlObjectSerializerContext
#else
internal class XmlObjectSerializerContext
#endif
{
protected XmlObjectSerializer serializer;
protected DataContract rootTypeDataContract;
internal ScopedKnownTypes scopedKnownTypes = new ScopedKnownTypes();
protected DataContractDictionary serializerKnownDataContracts;
private bool _isSerializerKnownDataContractsSetExplicit;
protected IList<Type> serializerKnownTypeList;
private int _itemCount;
private int _maxItemsInObjectGraph;
private StreamingContext _streamingContext;
private bool _ignoreExtensionDataObject;
private DataContractResolver _dataContractResolver;
private KnownTypeDataContractResolver _knownTypeResolver;
internal XmlObjectSerializerContext(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject,
DataContractResolver dataContractResolver)
{
this.serializer = serializer;
_itemCount = 1;
_maxItemsInObjectGraph = maxItemsInObjectGraph;
_streamingContext = streamingContext;
_ignoreExtensionDataObject = ignoreExtensionDataObject;
_dataContractResolver = dataContractResolver;
}
internal XmlObjectSerializerContext(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject)
: this(serializer, maxItemsInObjectGraph, streamingContext, ignoreExtensionDataObject, null)
{
}
internal XmlObjectSerializerContext(DataContractSerializer serializer, DataContract rootTypeDataContract
, DataContractResolver dataContractResolver
)
: this(serializer,
serializer.MaxItemsInObjectGraph,
new StreamingContext(),
serializer.IgnoreExtensionDataObject,
dataContractResolver
)
{
this.rootTypeDataContract = rootTypeDataContract;
this.serializerKnownTypeList = serializer.knownTypeList;
}
internal virtual SerializationMode Mode
{
get { return SerializationMode.SharedContract; }
}
internal virtual bool IsGetOnlyCollection
{
get { return false; }
set { }
}
#if USE_REFEMIT
public StreamingContext GetStreamingContext()
#else
internal StreamingContext GetStreamingContext()
#endif
{
return _streamingContext;
}
#if USE_REFEMIT
public void IncrementItemCount(int count)
#else
internal void IncrementItemCount(int count)
#endif
{
if (count > _maxItemsInObjectGraph - _itemCount)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(string.Format(SRSerialization.ExceededMaxItemsQuota, _maxItemsInObjectGraph)));
_itemCount += count;
}
internal int RemainingItemCount
{
get { return _maxItemsInObjectGraph - _itemCount; }
}
internal bool IgnoreExtensionDataObject
{
get { return _ignoreExtensionDataObject; }
}
protected DataContractResolver DataContractResolver
{
get { return _dataContractResolver; }
}
protected KnownTypeDataContractResolver KnownTypeResolver
{
get
{
if (_knownTypeResolver == null)
{
_knownTypeResolver = new KnownTypeDataContractResolver(this);
}
return _knownTypeResolver;
}
}
internal DataContract GetDataContract(Type type)
{
return GetDataContract(type.TypeHandle, type);
}
internal virtual DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type type)
{
if (IsGetOnlyCollection)
{
return DataContract.GetGetOnlyCollectionDataContract(DataContract.GetId(typeHandle), typeHandle, type, Mode);
}
else
{
return DataContract.GetDataContract(typeHandle, type, Mode);
}
}
internal virtual DataContract GetDataContractSkipValidation(int typeId, RuntimeTypeHandle typeHandle, Type type)
{
if (IsGetOnlyCollection)
{
return DataContract.GetGetOnlyCollectionDataContractSkipValidation(typeId, typeHandle, type);
}
else
{
return DataContract.GetDataContractSkipValidation(typeId, typeHandle, type);
}
}
internal virtual DataContract GetDataContract(int id, RuntimeTypeHandle typeHandle)
{
if (IsGetOnlyCollection)
{
return DataContract.GetGetOnlyCollectionDataContract(id, typeHandle, null /*type*/, Mode);
}
else
{
return DataContract.GetDataContract(id, typeHandle, Mode);
}
}
internal virtual void CheckIfTypeSerializable(Type memberType, bool isMemberTypeSerializable)
{
if (!isMemberTypeSerializable)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(string.Format(SRSerialization.TypeNotSerializable, memberType)));
}
internal virtual Type GetSurrogatedType(Type type)
{
return type;
}
internal virtual DataContractDictionary SerializerKnownDataContracts
{
get
{
// This field must be initialized during construction by serializers using data contracts.
if (!_isSerializerKnownDataContractsSetExplicit)
{
this.serializerKnownDataContracts = serializer.KnownDataContracts;
_isSerializerKnownDataContractsSetExplicit = true;
}
return this.serializerKnownDataContracts;
}
}
private DataContract GetDataContractFromSerializerKnownTypes(XmlQualifiedName qname)
{
DataContractDictionary serializerKnownDataContracts = this.SerializerKnownDataContracts;
if (serializerKnownDataContracts == null)
return null;
DataContract outDataContract;
return serializerKnownDataContracts.TryGetValue(qname, out outDataContract) ? outDataContract : null;
}
internal static DataContractDictionary GetDataContractsForKnownTypes(IList<Type> knownTypeList)
{
if (knownTypeList == null) return null;
DataContractDictionary dataContracts = new DataContractDictionary();
Dictionary<Type, Type> typesChecked = new Dictionary<Type, Type>();
for (int i = 0; i < knownTypeList.Count; i++)
{
Type knownType = knownTypeList[i];
if (knownType == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(string.Format(SRSerialization.NullKnownType, "knownTypes")));
DataContract.CheckAndAdd(knownType, typesChecked, ref dataContracts);
}
return dataContracts;
}
internal bool IsKnownType(DataContract dataContract, DataContractDictionary knownDataContracts, Type declaredType)
{
bool knownTypesAddedInCurrentScope = false;
if (knownDataContracts != null)
{
scopedKnownTypes.Push(knownDataContracts);
knownTypesAddedInCurrentScope = true;
}
bool isKnownType = IsKnownType(dataContract, declaredType);
if (knownTypesAddedInCurrentScope)
{
scopedKnownTypes.Pop();
}
return isKnownType;
}
internal bool IsKnownType(DataContract dataContract, Type declaredType)
{
DataContract knownContract = ResolveDataContractFromKnownTypes(dataContract.StableName.Name, dataContract.StableName.Namespace, null /*memberTypeContract*/ /*, declaredType */);
return knownContract != null && knownContract.UnderlyingType == dataContract.UnderlyingType;
}
internal Type ResolveNameFromKnownTypes(XmlQualifiedName typeName)
{
DataContract dataContract = ResolveDataContractFromKnownTypes(typeName);
return dataContract == null ? null : dataContract.UnderlyingType;
}
private DataContract ResolveDataContractFromKnownTypes(XmlQualifiedName typeName)
{
DataContract dataContract = PrimitiveDataContract.GetPrimitiveDataContract(typeName.Name, typeName.Namespace);
if (dataContract == null)
{
#if NET_NATIVE
if (typeName.Name == Globals.SafeSerializationManagerName && typeName.Namespace == Globals.SafeSerializationManagerNamespace && Globals.TypeOfSafeSerializationManager != null)
{
return GetDataContract(Globals.TypeOfSafeSerializationManager);
}
#endif
dataContract = scopedKnownTypes.GetDataContract(typeName);
if (dataContract == null)
{
dataContract = GetDataContractFromSerializerKnownTypes(typeName);
}
}
return dataContract;
}
protected DataContract ResolveDataContractFromKnownTypes(string typeName, string typeNs, DataContract memberTypeContract)
{
XmlQualifiedName qname = new XmlQualifiedName(typeName, typeNs);
DataContract dataContract;
if (_dataContractResolver == null)
{
dataContract = ResolveDataContractFromKnownTypes(qname);
}
else
{
Type dataContractType = _dataContractResolver.ResolveName(typeName, typeNs, null, KnownTypeResolver);
dataContract = dataContractType == null ? null : GetDataContract(dataContractType);
}
if (dataContract == null)
{
if (memberTypeContract != null
&& !memberTypeContract.UnderlyingType.GetTypeInfo().IsInterface
&& memberTypeContract.StableName == qname)
{
dataContract = memberTypeContract;
}
if (dataContract == null && rootTypeDataContract != null)
{
if (rootTypeDataContract.StableName == qname)
dataContract = rootTypeDataContract;
else
{
CollectionDataContract collectionContract = rootTypeDataContract as CollectionDataContract;
while (collectionContract != null)
{
DataContract itemContract = GetDataContract(GetSurrogatedType(collectionContract.ItemType));
if (itemContract.StableName == qname)
{
dataContract = itemContract;
break;
}
collectionContract = itemContract as CollectionDataContract;
}
}
}
}
return dataContract;
}
internal void PushKnownTypes(DataContract dc)
{
if (dc != null && dc.KnownDataContracts != null)
{
scopedKnownTypes.Push(dc.KnownDataContracts);
}
}
internal void PopKnownTypes(DataContract dc)
{
if (dc != null && dc.KnownDataContracts != null)
{
scopedKnownTypes.Pop();
}
}
}
}
| |
#region using declarations
using System;
using System.ComponentModel;
using System.Configuration;
using System.Drawing;
using System.Globalization;
using System.Windows.Forms;
using DigitallyImported.Components;
using DigitallyImported.Configuration.Properties;
using DigitallyImported.Controls;
using DigitallyImported.Controls.Windows;
using P = DigitallyImported.Resources.Properties;
using SortOrder = DigitallyImported.Components.SortOrder;
#endregion
// using DigitallyImported.Player;
namespace DigitallyImported.Client
{
/// <summary>
/// Summary description for DIAdmin.
/// </summary>
public class AdminForm : BaseForm
{
private ErrorProvider AdminErrorProvider;
private LinkLabel ListenKeyLinkLabel;
private TextBox ListenKeyTextbox;
private TextBox PasswordTextbox;
private TextBox UsernameTextbox;
private Color _color = Color.Black;
private TimeSpan _refreshInterval;
private ToolStrip adminFormToolStrip;
private ColorPicker alternatingChannelColorPicker;
private DomainUpDown calendarFormatValue;
private ColorPicker channelColorPicker;
private ColorButton colorButton;
private IContainer components;
private Label label1;
private Label label10;
private Label label11;
private Label label12;
private Label label13;
private Label label2;
private Label label3;
private Label label4;
private Label label5;
// PLAYERTYPE RADIO BUTTONS
private Label label6;
private Label label7;
private Label label8;
private Label label9;
private Label lable12;
private RadioButton[] playerTypes;
private GroupBox premiumInfoGroupBox;
private Panel previousChannelPanel;
private RefreshCounter refreshCounter1;
private RadioButton rememberNoRadio;
private RadioButton rememberYesRadio;
private ColorPicker selectedChannelColorPicker;
private CheckedListBox serviceLevelValues;
private Panel showToastPanel;
private DomainUpDown sortByValue;
private DomainUpDown sortOrderValue;
private RadioButton toastNoRadio;
private RadioButton toastYesRadio;
private ToolStripButton toolStripLoadDefaults;
private ToolStripButton toolStripSave;
private ToolStripLabel toolStripStatusLabel;
private Label trackBarValue;
private TrackBar transparencyTrackBar;
/// <summary>
/// </summary>
public AdminForm()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
Icon = P.Resources.DIIconNew;
CenterToScreen();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
private void saveButton_Click(object sender, EventArgs e)
{
bool serviceLevelChanged = false;
if (!ValidateChildren()) return;
Settings.Default.PlaylistRefreshInterval = refreshCounter1.CountdownTimer.Value.TimeOfDay;
Settings.Default.SelectedChannelBackground = selectedChannelColorPicker.Color;
Settings.Default.AlternatingChannelBackground = alternatingChannelColorPicker.Color;
Settings.Default.ChannelBackground = channelColorPicker.Color;
Settings.Default.ShowUserToast = toastYesRadio.Checked;
Settings.Default.RememberPreviousChannel = rememberYesRadio.Checked;
Settings.Default.ChannelSortOrder = sortOrderValue.Text;
Settings.Default.ChannelSortBy = sortByValue.Text;
Settings.Default.CalendarFormat = calendarFormatValue.Text;
Settings.Default.FormOpacityValue = ((double) transparencyTrackBar.Value/100);
foreach (var item in serviceLevelValues.CheckedItems)
{
if (
!Settings.Default.SubscriptionType.Equals(item.ToString(),
StringComparison.CurrentCultureIgnoreCase))
serviceLevelChanged = true;
Settings.Default.SubscriptionType = item.ToString();
break; // only get the first one selected.
}
Settings.Default.Username = UsernameTextbox.Text;
Settings.Default.Password = PasswordTextbox.Text;
Settings.Default.ListenKey = ListenKeyTextbox.Text;
Settings.Default.Save();
if (serviceLevelChanged)
{
switch (
MessageBox.Show(this,
string.Format(P.Resources.ServiceLevelChangedMessage, Environment.NewLine,
P.Resources.RestartApplicationMessage)
, P.Resources.RestartApplicationMessage
, MessageBoxButtons.YesNo
, MessageBoxIcon.Question
, MessageBoxDefaultButton.Button1))
{
case DialogResult.Yes:
Application.Restart();
break;
case DialogResult.No:
DialogResult = DialogResult.OK;
break;
}
}
DialogResult = DialogResult.OK;
}
private void DIAdmin_Load(object sender, EventArgs e)
{
refreshCounter1.Stop();
bindEnums();
bindControls();
trackBarValue.Text = transparencyTrackBar.Value.ToString(CultureInfo.InvariantCulture);
Settings.Default.SettingChanging += Default_SettingChanging;
Settings.Default.SettingsSaving += Default_SettingsSaving;
//int[] colorInts = new int[colors.Length];
// for (int i = 0; i < colors.Length; i++)
// {
// colorInts[i] = Math.Abs(colors[i].ToArgb());
// }
// this.channelColorPicker.Color = Settings.Default.ChannelBackground;
// this.alternatingChannelColorPicker.Color = Settings.Default.AlternatingChannelBackground;
// this.selectedChannelColorPicker.Color = Settings.Default.SelectedChannelBackground;
}
private void colorButton_Click(object sender, EventArgs e)
{
var callingButton = (ColorButton) sender;
var p = new Point(callingButton.Left, callingButton.Top + callingButton.Height);
p = PointToScreen(p);
var clDlg = new ColorPaletteDialog(p.X, p.Y);
clDlg.ShowDialog();
if (clDlg.DialogResult == DialogResult.OK)
_color = clDlg.Color;
callingButton.CenterColor = _color;
Invalidate();
clDlg.Dispose();
}
private void Default_SettingChanging(object sender, SettingChangingEventArgs e)
{
// this.txtPlaylistRefresh.Text = e.SettingName + (int)e.NewValue;
}
private void Default_SettingsSaving(object sender, CancelEventArgs e)
{
// PERFORM VALIDATION HERE!
}
private void ChannelButton_Click(object sender, EventArgs e)
{
}
private void selectedChannelButton_Click(object sender, EventArgs e)
{
// this.selectedChannelColor.ShowDialog();
}
private void alternatingChannelButton_Click(object sender, EventArgs e)
{
// this.alternatingChannelColor.ShowDialog();
}
private void reloadDefaultsButton_Click(object sender, EventArgs e)
{
Settings.Default.Reset();
bindControls();
}
private void bindControls()
{
refreshCounter1.CountdownTimer.Value = new DateTime(2000, 1, 1).Add(Settings.Default.PlaylistRefreshInterval);
selectedChannelColorPicker.Color = Settings.Default.SelectedChannelBackground;
alternatingChannelColorPicker.Color = Settings.Default.AlternatingChannelBackground;
channelColorPicker.Color = Settings.Default.ChannelBackground;
// set selected values
sortOrderValue.Text = Settings.Default.ChannelSortOrder;
sortByValue.Text = Settings.Default.ChannelSortBy;
transparencyTrackBar.Value = ((int) (Settings.Default.FormOpacityValue*100));
calendarFormatValue.Text = Settings.Default.CalendarFormat;
serviceLevelValues.ClearSelected();
serviceLevelValues.SetItemChecked(serviceLevelValues.FindStringExact(Settings.Default.SubscriptionType),
true);
UsernameTextbox.Text = Settings.Default.Username;
PasswordTextbox.Text = Settings.Default.Password;
ListenKeyTextbox.Text = Settings.Default.ListenKey;
// set the Listen Key link here
//LinkLabel.Link link = new LinkLabel.Link();
//link.LinkData = P.Resources.ListenKeyLinkData;
ListenKeyLinkLabel.Links[0].LinkData = P.Resources.ListenKeyLinkData;
// radio buttons
if (!Settings.Default.RememberPreviousChannel) rememberNoRadio.PerformClick();
if (!Settings.Default.ShowUserToast) toastNoRadio.PerformClick();
togglePremiumTextboxes(serviceLevelValues.SelectedIndex);
}
private void bindEnums()
{
// bind to enums
sortOrderValue.Items.AddRange(Enum.GetNames(typeof (SortOrder)));
sortByValue.Items.AddRange(Enum.GetNames(typeof (SortBy)));
serviceLevelValues.Items.AddRange(Enum.GetNames(typeof (SubscriptionLevel)));
calendarFormatValue.Items.AddRange(Enum.GetNames(typeof (CalendarFormat)));
}
private void txtPlaylistRefresh_Validated(object sender, EventArgs e)
{
AdminErrorProvider.SetError((Control) sender, string.Empty);
toolStripSave.Enabled = true;
}
private void txtPlaylistRefresh_Validating(object sender, CancelEventArgs e)
{
string errorMessage;
//if (!ValidRefreshInterval(refreshCounter1, out errorMessage))
//{
// e.Cancel = true;
//}
}
private void transparencyTrackBar_Scroll(object sender, EventArgs e)
{
trackBarValue.Text = (transparencyTrackBar.Value).ToString(CultureInfo.InvariantCulture);
}
private void ListenKeyLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
ListenKeyLinkLabel.Links[ListenKeyLinkLabel.Links.IndexOf(e.Link)].Visited = true;
var target = e.Link.LinkData as string;
if (!string.IsNullOrEmpty(target))
{
Components.Utilities.StartProcess(e.Link.LinkData as string);
}
}
private void serviceLevelValues_SelectedIndexChanged(object sender, EventArgs e)
{
{
//{
// if (selected == 0)
// {
// this.UsernameTextbox.Enabled = false;
// this.PasswordTextbox.Enabled = false;
// this.ListenKeyTextbox.Enabled = false;
// }
// else
// {
// this.UsernameTextbox.Enabled = true;
// this.PasswordTextbox.Enabled = true;
// this.ListenKeyTextbox.Enabled = true;
// }
//}
// togglePremiumTextboxes(serviceLevelValues.SelectedIndex;);
}
}
private void togglePremiumTextboxes(int selected)
{
if (selected >= 0)
{
foreach (Control c in premiumInfoGroupBox.Controls)
{
if (c is TextBox)
{
c.Enabled = Convert.ToBoolean(selected);
}
}
}
}
private void serviceLevelValues_ItemCheck(object sender, ItemCheckEventArgs e)
{
togglePremiumTextboxes(e.Index);
}
#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();
var resources = new System.ComponentModel.ComponentResourceManager(typeof (AdminForm));
this.showToastPanel = new System.Windows.Forms.Panel();
this.toastNoRadio = new System.Windows.Forms.RadioButton();
this.toastYesRadio = new System.Windows.Forms.RadioButton();
this.label11 = new System.Windows.Forms.Label();
this.premiumInfoGroupBox = new System.Windows.Forms.GroupBox();
this.ListenKeyLinkLabel = new System.Windows.Forms.LinkLabel();
this.ListenKeyTextbox = new System.Windows.Forms.TextBox();
this.label12 = new System.Windows.Forms.Label();
this.serviceLevelValues = new System.Windows.Forms.CheckedListBox();
this.label5 = new System.Windows.Forms.Label();
this.label10 = new System.Windows.Forms.Label();
this.PasswordTextbox = new System.Windows.Forms.TextBox();
this.UsernameTextbox = new System.Windows.Forms.TextBox();
this.label9 = new System.Windows.Forms.Label();
this.lable12 = new System.Windows.Forms.Label();
this.label8 = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.trackBarValue = new System.Windows.Forms.Label();
this.transparencyTrackBar = new System.Windows.Forms.TrackBar();
this.label4 = new System.Windows.Forms.Label();
this.sortByValue = new System.Windows.Forms.DomainUpDown();
this.adminFormToolStrip = new System.Windows.Forms.ToolStrip();
this.toolStripStatusLabel = new System.Windows.Forms.ToolStripLabel();
this.toolStripSave = new System.Windows.Forms.ToolStripButton();
this.toolStripLoadDefaults = new System.Windows.Forms.ToolStripButton();
this.label3 = new System.Windows.Forms.Label();
this.sortOrderValue = new System.Windows.Forms.DomainUpDown();
this.previousChannelPanel = new System.Windows.Forms.Panel();
this.rememberNoRadio = new System.Windows.Forms.RadioButton();
this.rememberYesRadio = new System.Windows.Forms.RadioButton();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.AdminErrorProvider = new System.Windows.Forms.ErrorProvider(this.components);
this.refreshCounter1 = new RefreshCounter();
this.channelColorPicker = new ColorPicker();
this.alternatingChannelColorPicker = new ColorPicker();
this.selectedChannelColorPicker = new ColorPicker();
this.label13 = new System.Windows.Forms.Label();
this.calendarFormatValue = new System.Windows.Forms.DomainUpDown();
this.showToastPanel.SuspendLayout();
this.premiumInfoGroupBox.SuspendLayout();
((System.ComponentModel.ISupportInitialize) (this.transparencyTrackBar)).BeginInit();
this.adminFormToolStrip.SuspendLayout();
this.previousChannelPanel.SuspendLayout();
((System.ComponentModel.ISupportInitialize) (this.AdminErrorProvider)).BeginInit();
this.SuspendLayout();
//
// showToastPanel
//
this.showToastPanel.Controls.Add(this.toastNoRadio);
this.showToastPanel.Controls.Add(this.toastYesRadio);
this.showToastPanel.Controls.Add(this.label11);
this.showToastPanel.Location = new System.Drawing.Point(8, 189);
this.showToastPanel.Name = "showToastPanel";
this.showToastPanel.Size = new System.Drawing.Size(218, 23);
this.showToastPanel.TabIndex = 28;
//
// toastNoRadio
//
this.toastNoRadio.AutoSize = true;
this.toastNoRadio.Location = new System.Drawing.Point(173, 1);
this.toastNoRadio.Name = "toastNoRadio";
this.toastNoRadio.Size = new System.Drawing.Size(39, 17);
this.toastNoRadio.TabIndex = 2;
this.toastNoRadio.Text = "No";
this.toastNoRadio.UseVisualStyleBackColor = true;
//
// toastYesRadio
//
this.toastYesRadio.AutoSize = true;
this.toastYesRadio.Checked = true;
this.toastYesRadio.Location = new System.Drawing.Point(126, 1);
this.toastYesRadio.Name = "toastYesRadio";
this.toastYesRadio.Size = new System.Drawing.Size(43, 17);
this.toastYesRadio.TabIndex = 1;
this.toastYesRadio.TabStop = true;
this.toastYesRadio.Text = "Yes";
this.toastYesRadio.UseVisualStyleBackColor = true;
//
// label11
//
this.label11.AutoSize = true;
this.label11.Location = new System.Drawing.Point(-3, 1);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(91, 13);
this.label11.TabIndex = 0;
this.label11.Text = "Show Info Toast?";
//
// premiumInfoGroupBox
//
this.premiumInfoGroupBox.Controls.Add(this.ListenKeyLinkLabel);
this.premiumInfoGroupBox.Controls.Add(this.ListenKeyTextbox);
this.premiumInfoGroupBox.Controls.Add(this.label12);
this.premiumInfoGroupBox.Controls.Add(this.serviceLevelValues);
this.premiumInfoGroupBox.Controls.Add(this.label5);
this.premiumInfoGroupBox.Controls.Add(this.label10);
this.premiumInfoGroupBox.Controls.Add(this.PasswordTextbox);
this.premiumInfoGroupBox.Controls.Add(this.UsernameTextbox);
this.premiumInfoGroupBox.Controls.Add(this.label9);
this.premiumInfoGroupBox.Controls.Add(this.lable12);
this.premiumInfoGroupBox.Location = new System.Drawing.Point(8, 302);
this.premiumInfoGroupBox.Name = "premiumInfoGroupBox";
this.premiumInfoGroupBox.Size = new System.Drawing.Size(218, 173);
this.premiumInfoGroupBox.TabIndex = 25;
this.premiumInfoGroupBox.TabStop = false;
this.premiumInfoGroupBox.Text = "Premium Info";
//
// ListenKeyLinkLabel
//
this.ListenKeyLinkLabel.AutoSize = true;
this.ListenKeyLinkLabel.Cursor = System.Windows.Forms.Cursors.Hand;
this.ListenKeyLinkLabel.DisabledLinkColor = System.Drawing.Color.Red;
this.ListenKeyLinkLabel.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline;
this.ListenKeyLinkLabel.LinkColor = System.Drawing.Color.Navy;
this.ListenKeyLinkLabel.Location = new System.Drawing.Point(67, 131);
this.ListenKeyLinkLabel.Name = "ListenKeyLinkLabel";
this.ListenKeyLinkLabel.Size = new System.Drawing.Size(112, 13);
this.ListenKeyLinkLabel.TabIndex = 30;
this.ListenKeyLinkLabel.TabStop = true;
this.ListenKeyLinkLabel.Text = "What is my listen key?";
this.ListenKeyLinkLabel.VisitedLinkColor = System.Drawing.Color.Blue;
this.ListenKeyLinkLabel.LinkClicked +=
new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.ListenKeyLinkLabel_LinkClicked);
//
// ListenKeyTextbox
//
this.ListenKeyTextbox.Enabled = false;
this.ListenKeyTextbox.Location = new System.Drawing.Point(70, 108);
this.ListenKeyTextbox.Name = "ListenKeyTextbox";
this.ListenKeyTextbox.Size = new System.Drawing.Size(142, 20);
this.ListenKeyTextbox.TabIndex = 29;
//
// label12
//
this.label12.AutoSize = true;
this.label12.Location = new System.Drawing.Point(6, 110);
this.label12.Name = "label12";
this.label12.Size = new System.Drawing.Size(59, 13);
this.label12.TabIndex = 28;
this.label12.Text = "Listen Key:";
//
// serviceLevelValues
//
this.serviceLevelValues.CheckOnClick = true;
this.serviceLevelValues.FormattingEnabled = true;
this.serviceLevelValues.Location = new System.Drawing.Point(90, 16);
this.serviceLevelValues.Name = "serviceLevelValues";
this.serviceLevelValues.Size = new System.Drawing.Size(122, 34);
this.serviceLevelValues.TabIndex = 6;
this.serviceLevelValues.ThreeDCheckBoxes = true;
this.serviceLevelValues.ItemCheck +=
new System.Windows.Forms.ItemCheckEventHandler(this.serviceLevelValues_ItemCheck);
this.serviceLevelValues.SelectedIndexChanged +=
new System.EventHandler(this.serviceLevelValues_SelectedIndexChanged);
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(6, 147);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(98, 13);
this.label5.TabIndex = 27;
this.label5.Text = "Form Transparency";
//
// label10
//
this.label10.AutoSize = true;
this.label10.Location = new System.Drawing.Point(6, 16);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(75, 13);
this.label10.TabIndex = 5;
this.label10.Text = "Service Level:";
//
// PasswordTextbox
//
this.PasswordTextbox.Enabled = false;
this.PasswordTextbox.Location = new System.Drawing.Point(70, 82);
this.PasswordTextbox.Name = "PasswordTextbox";
this.PasswordTextbox.Size = new System.Drawing.Size(142, 20);
this.PasswordTextbox.TabIndex = 4;
this.PasswordTextbox.UseSystemPasswordChar = true;
//
// UsernameTextbox
//
this.UsernameTextbox.Enabled = false;
this.UsernameTextbox.Location = new System.Drawing.Point(70, 56);
this.UsernameTextbox.Name = "UsernameTextbox";
this.UsernameTextbox.Size = new System.Drawing.Size(142, 20);
this.UsernameTextbox.TabIndex = 3;
//
// label9
//
this.label9.AutoSize = true;
this.label9.Location = new System.Drawing.Point(6, 85);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(56, 13);
this.label9.TabIndex = 2;
this.label9.Text = "Password:";
//
// lable12
//
this.lable12.AutoSize = true;
this.lable12.Location = new System.Drawing.Point(6, 59);
this.lable12.Name = "lable12";
this.lable12.Size = new System.Drawing.Size(58, 13);
this.lable12.TabIndex = 1;
this.lable12.Text = "Username:";
this.lable12.TextAlign = System.Drawing.ContentAlignment.TopCenter;
//
// label8
//
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(59, 119);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(118, 13);
this.label8.TabIndex = 24;
this.label8.Text = "Selected Channel Color";
this.label8.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(59, 77);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(126, 13);
this.label7.TabIndex = 23;
this.label7.Text = "Alternating Channel Color";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(81, 35);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(73, 13);
this.label6.TabIndex = 22;
this.label6.Text = "Channel Color";
//
// trackBarValue
//
this.trackBarValue.AutoSize = true;
this.trackBarValue.Location = new System.Drawing.Point(127, 385);
this.trackBarValue.Name = "trackBarValue";
this.trackBarValue.Size = new System.Drawing.Size(98, 13);
this.trackBarValue.TabIndex = 17;
this.trackBarValue.Text = "Form Transparency";
//
// transparencyTrackBar
//
this.transparencyTrackBar.Location = new System.Drawing.Point(8, 481);
this.transparencyTrackBar.Maximum = 100;
this.transparencyTrackBar.Name = "transparencyTrackBar";
this.transparencyTrackBar.Size = new System.Drawing.Size(219, 45);
this.transparencyTrackBar.SmallChange = 5;
this.transparencyTrackBar.TabIndex = 16;
this.transparencyTrackBar.TickFrequency = 10;
this.transparencyTrackBar.Scroll += new System.EventHandler(this.transparencyTrackBar_Scroll);
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(4, 242);
this.label4.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(89, 13);
this.label4.TabIndex = 12;
this.label4.Text = "Channel Sort By: ";
//
// sortByValue
//
this.sortByValue.Location = new System.Drawing.Point(119, 240);
this.sortByValue.Margin = new System.Windows.Forms.Padding(2);
this.sortByValue.Name = "sortByValue";
this.sortByValue.Size = new System.Drawing.Size(105, 20);
this.sortByValue.Sorted = true;
this.sortByValue.TabIndex = 11;
this.sortByValue.Wrap = true;
//
// adminFormToolStrip
//
this.adminFormToolStrip.Dock = System.Windows.Forms.DockStyle.Bottom;
this.adminFormToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[]
{
this.toolStripStatusLabel,
this.toolStripSave,
this.toolStripLoadDefaults
});
this.adminFormToolStrip.Location = new System.Drawing.Point(0, 521);
this.adminFormToolStrip.Name = "adminFormToolStrip";
this.adminFormToolStrip.Size = new System.Drawing.Size(234, 25);
this.adminFormToolStrip.TabIndex = 9;
this.adminFormToolStrip.Text = "toolStrip1";
//
// toolStripStatusLabel
//
this.toolStripStatusLabel.Name = "toolStripStatusLabel";
this.toolStripStatusLabel.Size = new System.Drawing.Size(39, 22);
this.toolStripStatusLabel.Text = "Ready";
//
// toolStripSave
//
this.toolStripSave.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
this.toolStripSave.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.toolStripSave.Image = ((System.Drawing.Image) (resources.GetObject("toolStripSave.Image")));
this.toolStripSave.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripSave.Name = "toolStripSave";
this.toolStripSave.Size = new System.Drawing.Size(35, 22);
this.toolStripSave.Text = "S&ave";
this.toolStripSave.Click += new System.EventHandler(this.saveButton_Click);
//
// toolStripLoadDefaults
//
this.toolStripLoadDefaults.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
this.toolStripLoadDefaults.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.toolStripLoadDefaults.Image =
((System.Drawing.Image) (resources.GetObject("toolStripLoadDefaults.Image")));
this.toolStripLoadDefaults.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripLoadDefaults.Name = "toolStripLoadDefaults";
this.toolStripLoadDefaults.Size = new System.Drawing.Size(83, 22);
this.toolStripLoadDefaults.Text = "Load &Defaults";
this.toolStripLoadDefaults.Click += new System.EventHandler(this.reloadDefaultsButton_Click);
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(4, 219);
this.label3.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(103, 13);
this.label3.TabIndex = 8;
this.label3.Text = "Channel Sort Order: ";
//
// sortOrderValue
//
this.sortOrderValue.Location = new System.Drawing.Point(119, 217);
this.sortOrderValue.Margin = new System.Windows.Forms.Padding(2);
this.sortOrderValue.Name = "sortOrderValue";
this.sortOrderValue.Size = new System.Drawing.Size(105, 20);
this.sortOrderValue.Sorted = true;
this.sortOrderValue.TabIndex = 4;
this.sortOrderValue.Wrap = true;
//
// previousChannelPanel
//
this.previousChannelPanel.Controls.Add(this.rememberNoRadio);
this.previousChannelPanel.Controls.Add(this.rememberYesRadio);
this.previousChannelPanel.Controls.Add(this.label2);
this.previousChannelPanel.Location = new System.Drawing.Point(8, 163);
this.previousChannelPanel.Margin = new System.Windows.Forms.Padding(2);
this.previousChannelPanel.Name = "previousChannelPanel";
this.previousChannelPanel.Size = new System.Drawing.Size(217, 21);
this.previousChannelPanel.TabIndex = 3;
//
// rememberNoRadio
//
this.rememberNoRadio.AutoSize = true;
this.rememberNoRadio.Location = new System.Drawing.Point(173, 2);
this.rememberNoRadio.Margin = new System.Windows.Forms.Padding(2);
this.rememberNoRadio.Name = "rememberNoRadio";
this.rememberNoRadio.Size = new System.Drawing.Size(39, 17);
this.rememberNoRadio.TabIndex = 2;
this.rememberNoRadio.Text = "&No";
this.rememberNoRadio.UseVisualStyleBackColor = true;
//
// rememberYesRadio
//
this.rememberYesRadio.AutoSize = true;
this.rememberYesRadio.Checked = true;
this.rememberYesRadio.Location = new System.Drawing.Point(126, 2);
this.rememberYesRadio.Margin = new System.Windows.Forms.Padding(2);
this.rememberYesRadio.Name = "rememberYesRadio";
this.rememberYesRadio.Size = new System.Drawing.Size(43, 17);
this.rememberYesRadio.TabIndex = 1;
this.rememberYesRadio.TabStop = true;
this.rememberYesRadio.Text = "&Yes";
this.rememberYesRadio.UseVisualStyleBackColor = true;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(-3, 2);
this.label2.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(119, 13);
this.label2.TabIndex = 0;
this.label2.Text = "Play Previous Channel?";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(5, 10);
this.label1.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(117, 13);
this.label1.TabIndex = 4;
this.label1.Text = "Playlist Refresh Interval";
//
// AdminErrorProvider
//
this.AdminErrorProvider.ContainerControl = this;
//
// refreshCounter1
//
this.refreshCounter1.Location = new System.Drawing.Point(164, 5);
this.refreshCounter1.Margin = new System.Windows.Forms.Padding(2);
this.refreshCounter1.Name = "refreshCounter1";
this.refreshCounter1.Size = new System.Drawing.Size(56, 18);
this.refreshCounter1.TabIndex = 26;
this.refreshCounter1.Value = "02:11";
//
// channelColorPicker
//
this.channelColorPicker.Color = System.Drawing.Color.Gainsboro;
this.channelColorPicker.Location = new System.Drawing.Point(8, 51);
this.channelColorPicker.Name = "channelColorPicker";
this.channelColorPicker.Size = new System.Drawing.Size(218, 23);
this.channelColorPicker.TabIndex = 21;
//
// alternatingChannelColorPicker
//
this.alternatingChannelColorPicker.Color = System.Drawing.Color.WhiteSmoke;
this.alternatingChannelColorPicker.Location = new System.Drawing.Point(8, 93);
this.alternatingChannelColorPicker.Name = "alternatingChannelColorPicker";
this.alternatingChannelColorPicker.Size = new System.Drawing.Size(218, 23);
this.alternatingChannelColorPicker.TabIndex = 20;
//
// selectedChannelColorPicker
//
this.selectedChannelColorPicker.Color = System.Drawing.Color.Beige;
this.selectedChannelColorPicker.Location = new System.Drawing.Point(8, 135);
this.selectedChannelColorPicker.Name = "selectedChannelColorPicker";
this.selectedChannelColorPicker.Size = new System.Drawing.Size(218, 23);
this.selectedChannelColorPicker.TabIndex = 19;
//
// label13
//
this.label13.AutoSize = true;
this.label13.Location = new System.Drawing.Point(4, 267);
this.label13.Name = "label13";
this.label13.Size = new System.Drawing.Size(87, 13);
this.label13.TabIndex = 29;
this.label13.Text = "Calendar Format:";
//
// calendarFormatValue
//
this.calendarFormatValue.Location = new System.Drawing.Point(119, 265);
this.calendarFormatValue.Name = "calendarFormatValue";
this.calendarFormatValue.Size = new System.Drawing.Size(105, 20);
this.calendarFormatValue.TabIndex = 30;
//
// AdminForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.ClientSize = new System.Drawing.Size(234, 546);
this.Controls.Add(this.calendarFormatValue);
this.Controls.Add(this.label13);
this.Controls.Add(this.showToastPanel);
this.Controls.Add(this.refreshCounter1);
this.Controls.Add(this.premiumInfoGroupBox);
this.Controls.Add(this.label8);
this.Controls.Add(this.label7);
this.Controls.Add(this.label6);
this.Controls.Add(this.channelColorPicker);
this.Controls.Add(this.alternatingChannelColorPicker);
this.Controls.Add(this.selectedChannelColorPicker);
this.Controls.Add(this.trackBarValue);
this.Controls.Add(this.transparencyTrackBar);
this.Controls.Add(this.label4);
this.Controls.Add(this.sortByValue);
this.Controls.Add(this.adminFormToolStrip);
this.Controls.Add(this.label3);
this.Controls.Add(this.sortOrderValue);
this.Controls.Add(this.previousChannelPanel);
this.Controls.Add(this.label1);
this.DoubleBuffered = true;
this.Icon = ((System.Drawing.Icon) (resources.GetObject("$this.Icon")));
this.Margin = new System.Windows.Forms.Padding(2);
this.Name = "AdminForm";
this.ShowInTaskbar = false;
this.Text = "Digitally Imported Radio :: Options";
this.Load += new System.EventHandler(this.DIAdmin_Load);
this.showToastPanel.ResumeLayout(false);
this.showToastPanel.PerformLayout();
this.premiumInfoGroupBox.ResumeLayout(false);
this.premiumInfoGroupBox.PerformLayout();
((System.ComponentModel.ISupportInitialize) (this.transparencyTrackBar)).EndInit();
this.adminFormToolStrip.ResumeLayout(false);
this.adminFormToolStrip.PerformLayout();
this.previousChannelPanel.ResumeLayout(false);
this.previousChannelPanel.PerformLayout();
((System.ComponentModel.ISupportInitialize) (this.AdminErrorProvider)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using OpenCVBridge;
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Windows.Graphics.Imaging;
using Windows.Media.Capture;
using Windows.Media.Capture.Frames;
using Windows.Media.MediaProperties;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace SDKTemplate
{
/// <summary>
/// Scenario that illustrates using OpenCV along with camera frames.
/// </summary>
public sealed partial class Scenario1_ExampleOperations : Page
{
private MainPage rootPage;
private MediaCapture _mediaCapture = null;
private MediaFrameReader _reader = null;
private FrameRenderer _previewRenderer = null;
private FrameRenderer _outputRenderer = null;
private int _frameCount = 0;
private const int IMAGE_ROWS = 480;
private const int IMAGE_COLS = 640;
private OpenCVHelper _helper;
private DispatcherTimer _FPSTimer = null;
enum OperationType
{
Blur = 0,
HoughLines,
Contours,
Histogram,
MotionDetector
}
OperationType currentOperation;
public Scenario1_ExampleOperations()
{
this.InitializeComponent();
_previewRenderer = new FrameRenderer(PreviewImage);
_outputRenderer = new FrameRenderer(OutputImage);
_helper = new OpenCVHelper();
_FPSTimer = new DispatcherTimer()
{
Interval = TimeSpan.FromSeconds(1)
};
_FPSTimer.Tick += UpdateFPS;
}
/// <summary>
/// Initializes the MediaCapture object with the given source group.
/// </summary>
/// <param name="sourceGroup">SourceGroup with which to initialize.</param>
private async Task InitializeMediaCaptureAsync(MediaFrameSourceGroup sourceGroup)
{
if (_mediaCapture != null)
{
return;
}
_mediaCapture = new MediaCapture();
var settings = new MediaCaptureInitializationSettings()
{
SourceGroup = sourceGroup,
SharingMode = MediaCaptureSharingMode.ExclusiveControl,
StreamingCaptureMode = StreamingCaptureMode.Video,
MemoryPreference = MediaCaptureMemoryPreference.Cpu
};
await _mediaCapture.InitializeAsync(settings);
}
/// <summary>
/// Unregisters FrameArrived event handlers, stops and disposes frame readers
/// and disposes the MediaCapture object.
/// </summary>
private async Task CleanupMediaCaptureAsync()
{
if (_mediaCapture != null)
{
await _reader.StopAsync();
_reader.FrameArrived -= ColorFrameReader_FrameArrivedAsync;
_reader.Dispose();
_mediaCapture = null;
}
}
private void UpdateFPS(object sender, object e)
{
var frameCount = Interlocked.Exchange(ref _frameCount, 0);
this.FPSMonitor.Text = "FPS: " + frameCount;
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
rootPage = MainPage.Current;
// setting up the combobox, and default operation
OperationComboBox.ItemsSource = Enum.GetValues(typeof(OperationType));
OperationComboBox.SelectedIndex = 0;
currentOperation = OperationType.Blur;
// Find the sources
var allGroups = await MediaFrameSourceGroup.FindAllAsync();
var sourceGroups = allGroups.Select(g => new
{
Group = g,
SourceInfo = g.SourceInfos.FirstOrDefault(i => i.SourceKind == MediaFrameSourceKind.Color)
}).Where(g => g.SourceInfo != null).ToList();
if (sourceGroups.Count == 0)
{
// No camera sources found
return;
}
var selectedSource = sourceGroups.FirstOrDefault();
// Initialize MediaCapture
try
{
await InitializeMediaCaptureAsync(selectedSource.Group);
}
catch (Exception exception)
{
Debug.WriteLine("MediaCapture initialization error: " + exception.Message);
await CleanupMediaCaptureAsync();
return;
}
// Create the frame reader
MediaFrameSource frameSource = _mediaCapture.FrameSources[selectedSource.SourceInfo.Id];
BitmapSize size = new BitmapSize() // Choose a lower resolution to make the image processing more performant
{
Height = IMAGE_ROWS,
Width = IMAGE_COLS
};
_reader = await _mediaCapture.CreateFrameReaderAsync(frameSource, MediaEncodingSubtypes.Bgra8, size);
_reader.FrameArrived += ColorFrameReader_FrameArrivedAsync;
await _reader.StartAsync();
_FPSTimer.Start();
}
protected override async void OnNavigatedFrom(NavigationEventArgs args)
{
_FPSTimer.Stop();
await CleanupMediaCaptureAsync();
}
/// <summary>
/// Handles a frame arrived event and renders the frame to the screen.
/// </summary>
private void ColorFrameReader_FrameArrivedAsync(MediaFrameReader sender, MediaFrameArrivedEventArgs args)
{
var frame = sender.TryAcquireLatestFrame();
if (frame != null)
{
SoftwareBitmap originalBitmap = null;
var inputBitmap = frame.VideoMediaFrame?.SoftwareBitmap;
if (inputBitmap != null)
{
// The XAML Image control can only display images in BRGA8 format with premultiplied or no alpha
// The frame reader as configured in this sample gives BGRA8 with straight alpha, so need to convert it
originalBitmap = SoftwareBitmap.Convert(inputBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);
SoftwareBitmap outputBitmap = new SoftwareBitmap(BitmapPixelFormat.Bgra8, originalBitmap.PixelWidth, originalBitmap.PixelHeight, BitmapAlphaMode.Premultiplied);
// Operate on the image in the manner chosen by the user.
if (currentOperation == OperationType.Blur)
{
_helper.Blur(originalBitmap, outputBitmap);
}
else if (currentOperation == OperationType.HoughLines)
{
_helper.HoughLines(originalBitmap, outputBitmap);
}
else if (currentOperation == OperationType.Contours)
{
_helper.Contours(originalBitmap, outputBitmap);
}
else if (currentOperation == OperationType.Histogram)
{
_helper.Histogram(originalBitmap, outputBitmap);
}
else if (currentOperation == OperationType.MotionDetector)
{
_helper.MotionDetector(originalBitmap, outputBitmap);
}
// Display both the original bitmap and the processed bitmap.
_previewRenderer.RenderFrame(originalBitmap);
_outputRenderer.RenderFrame(outputBitmap);
}
Interlocked.Increment(ref _frameCount);
}
}
private void OperationComboBox_SelectionChanged(object sender, RoutedEventArgs e)
{
currentOperation = (OperationType)((sender as ComboBox).SelectedItem);
if (OperationType.Blur == currentOperation)
{
this.CurrentOperationTextBlock.Text = "Current: Blur";
}
else if (OperationType.Contours == currentOperation)
{
this.CurrentOperationTextBlock.Text = "Current: Contours";
}
else if (OperationType.Histogram == currentOperation)
{
this.CurrentOperationTextBlock.Text = "Current: Histogram of RGB channels";
}
else if (OperationType.HoughLines == currentOperation)
{
this.CurrentOperationTextBlock.Text = "Current: Line detection";
}
else if (OperationType.MotionDetector == currentOperation)
{
this.CurrentOperationTextBlock.Text = "Current: Motion detection";
}
else
{
this.CurrentOperationTextBlock.Text = string.Empty;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Globalization;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Xml;
namespace Microsoft.PowerShell.Commands.Internal.Format
{
/// <summary>
/// Class to load the XML document into data structures.
/// It encapsulates the file format specific code.
/// </summary>
internal sealed partial class TypeInfoDataBaseLoader : XmlLoaderBase
{
private void LoadViewDefinitions(TypeInfoDataBase db, XmlNode viewDefinitionsNode)
{
using (this.StackFrame(viewDefinitionsNode))
{
int index = 0;
foreach (XmlNode n in viewDefinitionsNode.ChildNodes)
{
if (MatchNodeName(n, XmlTags.ViewNode))
{
ViewDefinition view = LoadView(n, index++);
if (view != null)
{
ReportTrace(string.Format(CultureInfo.InvariantCulture,
"{0} view {1} is loaded from file {2}",
ControlBase.GetControlShapeName(view.mainControl),
view.name, view.loadingInfo.filePath));
// we are fine, add the view to the list
db.viewDefinitionsSection.viewDefinitionList.Add(view);
}
}
else
{
ProcessUnknownNode(n);
}
}
}
}
private ViewDefinition LoadView(XmlNode viewNode, int index)
{
using (this.StackFrame(viewNode, index))
{
// load the common data
ViewDefinition view = new ViewDefinition();
List<XmlNode> unprocessedNodes = new List<XmlNode>();
bool success = LoadCommonViewData(viewNode, view, unprocessedNodes);
if (!success)
{
// Error at XPath {0} in file {1}: View cannot be loaded.
this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.ViewNotLoaded, ComputeCurrentXPath(), FilePath));
return null; // fatal error
}
// add the main control constituting the view
// only one control can exist, and it can be
// of the various types: Table, List, etc.
string[] controlNodeTags = new string[]
{
XmlTags.TableControlNode,
XmlTags.ListControlNode,
XmlTags.WideControlNode,
XmlTags.ComplexControlNode
};
List<XmlNode> secondPassUnprocessedNodes = new List<XmlNode>();
bool mainControlFound = false; // cardinality 1
foreach (XmlNode n in unprocessedNodes)
{
if (MatchNodeName(n, XmlTags.TableControlNode))
{
if (mainControlFound)
{
ProcessDuplicateNode(n);
return null;
}
mainControlFound = true;
view.mainControl = LoadTableControl(n);
}
else if (MatchNodeName(n, XmlTags.ListControlNode))
{
if (mainControlFound)
{
ProcessDuplicateNode(n);
return null;
}
mainControlFound = true;
view.mainControl = LoadListControl(n);
}
else if (MatchNodeName(n, XmlTags.WideControlNode))
{
if (mainControlFound)
{
ProcessDuplicateNode(n);
return null;
}
mainControlFound = true;
view.mainControl = LoadWideControl(n);
}
else if (MatchNodeName(n, XmlTags.ComplexControlNode))
{
if (mainControlFound)
{
ProcessDuplicateNode(n);
return null;
}
mainControlFound = true;
view.mainControl = LoadComplexControl(n);
}
else
{
secondPassUnprocessedNodes.Add(n);
}
}
if (view.mainControl == null)
{
this.ReportMissingNodes(controlNodeTags);
return null; // fatal
}
if (!LoadMainControlDependentData(secondPassUnprocessedNodes, view))
{
return null; // fatal
}
if (view.outOfBand && (view.groupBy != null))
{
// we cannot have grouping and out of band at the same time
// Error at XPath {0} in file {1}: An Out Of Band view cannot have GroupBy.
this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.OutOfBandGroupByConflict, ComputeCurrentXPath(), FilePath));
return null; // fatal
}
return view;
}
}
private bool LoadMainControlDependentData(List<XmlNode> unprocessedNodes, ViewDefinition view)
{
foreach (XmlNode n in unprocessedNodes)
{
bool outOfBandNodeFound = false; // cardinality 0..1
bool controlDefinitionsFound = false; // cardinality 0..1
if (MatchNodeName(n, XmlTags.OutOfBandNode))
{
if (outOfBandNodeFound)
{
this.ProcessDuplicateNode(n);
return false;
}
outOfBandNodeFound = true;
if (!this.ReadBooleanNode(n, out view.outOfBand))
{
return false;
}
if (view.mainControl is not ComplexControlBody && view.mainControl is not ListControlBody)
{
// Error at XPath {0} in file {1}: Out Of Band views can only have CustomControl or ListControl.
ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.InvalidControlForOutOfBandView, ComputeCurrentXPath(), FilePath));
return false;
}
}
else if (MatchNodeName(n, XmlTags.ControlsNode))
{
if (controlDefinitionsFound)
{
this.ProcessDuplicateNode(n);
return false;
}
controlDefinitionsFound = true;
LoadControlDefinitions(n, view.formatControlDefinitionHolder.controlDefinitionList);
}
else
{
ProcessUnknownNode(n);
}
}
return true;
}
private bool LoadCommonViewData(XmlNode viewNode, ViewDefinition view, List<XmlNode> unprocessedNodes)
{
if (viewNode == null)
throw PSTraceSource.NewArgumentNullException(nameof(viewNode));
if (view == null)
throw PSTraceSource.NewArgumentNullException(nameof(view));
// set loading information
view.loadingInfo = this.LoadingInfo;
view.loadingInfo.xPath = this.ComputeCurrentXPath();
// start the loading process
bool nameNodeFound = false; // cardinality 1
bool appliesToNodeFound = false; // cardinality 1
bool groupByFound = false; // cardinality 0..1
foreach (XmlNode n in viewNode.ChildNodes)
{
if (MatchNodeName(n, XmlTags.NameNode))
{
if (nameNodeFound)
{
this.ProcessDuplicateNode(n);
return false;
}
nameNodeFound = true;
view.name = GetMandatoryInnerText(n);
if (view.name == null)
{
return false;
}
}
else if (MatchNodeName(n, XmlTags.ViewSelectedByNode))
{
if (appliesToNodeFound)
{
this.ProcessDuplicateNode(n);
return false;
}
appliesToNodeFound = true;
// if null, we invalidate the view
view.appliesTo = LoadAppliesToSection(n, false);
if (view.appliesTo == null)
{
return false;
}
}
else if (MatchNodeName(n, XmlTags.GroupByNode))
{
if (groupByFound)
{
this.ProcessDuplicateNode(n);
return false;
}
groupByFound = true;
view.groupBy = LoadGroupBySection(n);
if (view.groupBy == null)
{
return false;
}
}
else
{
// save for further processing
unprocessedNodes.Add(n);
}
}
if (!nameNodeFound)
{
this.ReportMissingNode(XmlTags.NameNode);
return false;
}
if (!appliesToNodeFound)
{
this.ReportMissingNode(XmlTags.ViewSelectedByNode);
return false;
}
return true;
}
private void LoadControlDefinitions(XmlNode definitionsNode, List<ControlDefinition> controlDefinitionList)
{
using (this.StackFrame(definitionsNode))
{
int controlDefinitionIndex = 0;
foreach (XmlNode n in definitionsNode.ChildNodes)
{
if (MatchNodeName(n, XmlTags.ControlNode))
{
ControlDefinition def = LoadControlDefinition(n, controlDefinitionIndex++);
if (def != null)
{
controlDefinitionList.Add(def);
}
}
else
{
ProcessUnknownNode(n);
}
}
}
}
private ControlDefinition LoadControlDefinition(XmlNode controlDefinitionNode, int index)
{
using (this.StackFrame(controlDefinitionNode, index))
{
bool nameNodeFound = false; // cardinality 1
bool controlNodeFound = false; // cardinality 1
ControlDefinition def = new ControlDefinition();
foreach (XmlNode n in controlDefinitionNode.ChildNodes)
{
if (MatchNodeName(n, XmlTags.NameNode))
{
if (nameNodeFound)
{
this.ProcessDuplicateNode(n);
continue;
}
nameNodeFound = true;
def.name = GetMandatoryInnerText(n);
if (def.name == null)
{
// Error at XPath {0} in file {1}: Control cannot have a null Name.
this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.NullControlName, ComputeCurrentXPath(), FilePath));
return null; // fatal error
}
}
else if (MatchNodeName(n, XmlTags.ComplexControlNode))
{
// NOTE: for the time being we allow only complex control definitions to be loaded
if (controlNodeFound)
{
this.ProcessDuplicateNode(n);
return null; // fatal
}
controlNodeFound = true;
def.controlBody = LoadComplexControl(n);
if (def.controlBody == null)
{
return null; // fatal error
}
}
else
{
this.ProcessUnknownNode(n);
}
}
if (def.name == null)
{
this.ReportMissingNode(XmlTags.NameNode);
return null; // fatal
}
if (def.controlBody == null)
{
this.ReportMissingNode(XmlTags.ComplexControlNode);
return null; // fatal
}
return def;
}
}
}
}
| |
// 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.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DevTestLabs
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for ArtifactsOperations.
/// </summary>
public static partial class ArtifactsOperationsExtensions
{
/// <summary>
/// List artifacts in a given artifact source.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='artifactSourceName'>
/// The name of the artifact source.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
public static IPage<Artifact> List(this IArtifactsOperations operations, string labName, string artifactSourceName, ODataQuery<Artifact> odataQuery = default(ODataQuery<Artifact>))
{
return Task.Factory.StartNew(s => ((IArtifactsOperations)s).ListAsync(labName, artifactSourceName, odataQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// List artifacts in a given artifact source.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='artifactSourceName'>
/// The name of the artifact source.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Artifact>> ListAsync(this IArtifactsOperations operations, string labName, string artifactSourceName, ODataQuery<Artifact> odataQuery = default(ODataQuery<Artifact>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(labName, artifactSourceName, odataQuery, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get artifact.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='artifactSourceName'>
/// The name of the artifact source.
/// </param>
/// <param name='name'>
/// The name of the artifact.
/// </param>
/// <param name='expand'>
/// Specify the $expand query. Example: 'properties($select=title)'
/// </param>
public static Artifact Get(this IArtifactsOperations operations, string labName, string artifactSourceName, string name, string expand = default(string))
{
return Task.Factory.StartNew(s => ((IArtifactsOperations)s).GetAsync(labName, artifactSourceName, name, expand), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get artifact.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='artifactSourceName'>
/// The name of the artifact source.
/// </param>
/// <param name='name'>
/// The name of the artifact.
/// </param>
/// <param name='expand'>
/// Specify the $expand query. Example: 'properties($select=title)'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Artifact> GetAsync(this IArtifactsOperations operations, string labName, string artifactSourceName, string name, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(labName, artifactSourceName, name, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Generates an ARM template for the given artifact, uploads the required
/// files to a storage account, and validates the generated artifact.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='artifactSourceName'>
/// The name of the artifact source.
/// </param>
/// <param name='name'>
/// The name of the artifact.
/// </param>
/// <param name='generateArmTemplateRequest'>
/// Parameters for generating an ARM template for deploying artifacts.
/// </param>
public static ArmTemplateInfo GenerateArmTemplate(this IArtifactsOperations operations, string labName, string artifactSourceName, string name, GenerateArmTemplateRequest generateArmTemplateRequest)
{
return Task.Factory.StartNew(s => ((IArtifactsOperations)s).GenerateArmTemplateAsync(labName, artifactSourceName, name, generateArmTemplateRequest), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Generates an ARM template for the given artifact, uploads the required
/// files to a storage account, and validates the generated artifact.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='artifactSourceName'>
/// The name of the artifact source.
/// </param>
/// <param name='name'>
/// The name of the artifact.
/// </param>
/// <param name='generateArmTemplateRequest'>
/// Parameters for generating an ARM template for deploying artifacts.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ArmTemplateInfo> GenerateArmTemplateAsync(this IArtifactsOperations operations, string labName, string artifactSourceName, string name, GenerateArmTemplateRequest generateArmTemplateRequest, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GenerateArmTemplateWithHttpMessagesAsync(labName, artifactSourceName, name, generateArmTemplateRequest, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// List artifacts in a given artifact source.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Artifact> ListNext(this IArtifactsOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IArtifactsOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// List artifacts in a given artifact source.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Artifact>> ListNextAsync(this IArtifactsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace Core.OnPrem.S2S.WindowsCertStoreWeb
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificateSerialNumber = WebConfigurationManager.AppSettings.Get("ClientSigningCertificateSerialNumber");
private static readonly X509SigningCredentials SigningCredentials = GetSigningCredentials(GetCertificateFromStore());
#endregion
#region private methods
private static X509SigningCredentials GetSigningCredentials(X509Certificate2 cert)
{
return (cert == null) ? null : new X509SigningCredentials(cert, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
}
private static X509Certificate2 GetCertificateFromStore()
{
X509Certificate2 storedCert;
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
try
{
// Open for read-only access
store.Open(OpenFlags.ReadOnly);
// Find the cert
storedCert = store.Certificates.Find(X509FindType.FindBySerialNumber, ClientSigningCertificateSerialNumber, false)
.OfType<X509Certificate2>()
.SingleOrDefault();
}
finally
{
store.Close();
}
return storedCert;
}
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void CarrylessMultiplyUInt6417()
{
var test = new PclmulqdqOpTest__CarrylessMultiplyUInt6417();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Pclmulqdq.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Pclmulqdq.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Pclmulqdq.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class PclmulqdqOpTest__CarrylessMultiplyUInt6417
{
private struct TestStruct
{
public Vector128<UInt64> _fld1;
public Vector128<UInt64> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
return testStruct;
}
public void RunStructFldScenario(PclmulqdqOpTest__CarrylessMultiplyUInt6417 testClass)
{
var result = Pclmulqdq.CarrylessMultiply(_fld1, _fld2, 17);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static UInt64[] _data1 = new UInt64[2] {2, 20};
private static UInt64[] _data2 = new UInt64[2] {25, 95};
private static UInt64[] _expectedRet = new UInt64[2] {1164, 0};
private static Vector128<UInt64> _clsVar1;
private static Vector128<UInt64> _clsVar2;
private Vector128<UInt64> _fld1;
private Vector128<UInt64> _fld2;
private SimpleBinaryOpTest__DataTable<UInt64, UInt64, UInt64> _dataTable;
static PclmulqdqOpTest__CarrylessMultiplyUInt6417()
{
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
}
public PclmulqdqOpTest__CarrylessMultiplyUInt6417()
{
Succeeded = true;
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
_dataTable = new SimpleBinaryOpTest__DataTable<UInt64, UInt64, UInt64>(_data1, _data2, new UInt64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Pclmulqdq.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Pclmulqdq.CarrylessMultiply(
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr),
17
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Pclmulqdq.CarrylessMultiply(
Pclmulqdq.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
Pclmulqdq.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)),
17
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Pclmulqdq.CarrylessMultiply(
Pclmulqdq.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)),
Pclmulqdq.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr)),
17
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Pclmulqdq).GetMethod(nameof(Pclmulqdq.CarrylessMultiply), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr),
(byte)17
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Pclmulqdq).GetMethod(nameof(Pclmulqdq.CarrylessMultiply), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
Pclmulqdq.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
Pclmulqdq.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)),
(byte)17
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Pclmulqdq).GetMethod(nameof(Pclmulqdq.CarrylessMultiply), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
Pclmulqdq.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)),
Pclmulqdq.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr)),
(byte)17
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Pclmulqdq.CarrylessMultiply(
_clsVar1,
_clsVar2,
17
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var left = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr);
var result = Pclmulqdq.CarrylessMultiply(left, right, 17);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var left = Pclmulqdq.LoadVector128((UInt64*)(_dataTable.inArray1Ptr));
var right = Pclmulqdq.LoadVector128((UInt64*)(_dataTable.inArray2Ptr));
var result = Pclmulqdq.CarrylessMultiply(left, right, 17);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var left = Pclmulqdq.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr));
var right = Pclmulqdq.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr));
var result = Pclmulqdq.CarrylessMultiply(left, right, 17);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new PclmulqdqOpTest__CarrylessMultiplyUInt6417();
var result = Pclmulqdq.CarrylessMultiply(test._fld1, test._fld2, 17);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Pclmulqdq.CarrylessMultiply(_fld1, _fld2, 17);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Pclmulqdq.CarrylessMultiply(test._fld1, test._fld2, 17);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(void* result, [CallerMemberName] string method = "")
{
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
ValidateResult(outArray, method);
}
private void ValidateResult(UInt64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (int i = 0; i < result.Length; i++)
{
if (result[i] != _expectedRet[i] )
{
succeeded = false;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Pclmulqdq)}.{nameof(Pclmulqdq.CarrylessMultiply)}<UInt64>(Vector128<UInt64>, 17): {method} failed:");
TestLibrary.TestFramework.LogInformation($" expectedRet: ({string.Join(", ", _expectedRet)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) GHI Electronics, LLC.
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Presentation.Media;
using GHI.Glide.Display;
using GHI.Glide.Geom;
namespace GHI.Glide.UI
{
/// <summary>
/// The DataGrid component is a list-based component that provides a grid of rows and columns.
/// </summary>
public class DataGrid : DisplayObject
{
private ArrayList _columns = new ArrayList();
private ArrayList _rows = new ArrayList();
private Bitmap _headers;
private Bitmap _items;
private Bitmap _DataGridIcon_Asc = Resources.GetBitmap(Resources.BitmapResources.DataGridIcon_Asc);
private Bitmap _DataGridIcon_Desc = Resources.GetBitmap(Resources.BitmapResources.DataGridIcon_Desc);
private bool _renderHeaders;
private bool _renderItems;
private int _scrollIndex;
private bool _pressed = false;
private bool _moving = false;
private int _selectedIndex = -1;
private DataGridItem _selectedItem;
private int _selectedDataGridColumnIndex;
private int _listY;
private int _listMaxY;
private int _lastListY;
private int _lastTouchY;
private int _ignoredTouchMoves;
private int _maxIgnoredTouchMoves;
private bool _showHeaders;
private int _rowCount;
private int _scrollbarHeight;
private int _scrollbarTick;
private DataGridItemComparer _comparer = new DataGridItemComparer();
private Order _order;
/// <summary>
/// Creates a new DataGrid component.
/// </summary>
/// <param name="name">name</param>
/// <param name="alpha">alpha</param>
/// <param name="x">x</param>
/// <param name="y">y</param>
/// <param name="width">width</param>
/// <param name="rowHeight">rowHeight</param>
/// <param name="rowCount">rowCount</param>
public DataGrid(string name, ushort alpha, int x, int y, int width, int rowHeight, int rowCount)
{
Name = name;
Alpha = 255;
X = x;
Y = y;
Width = width;
RowHeight = rowHeight;
// Setting the RowCount changes the Height.
RowCount = rowCount;
// Show headers is on by default.
// When the headers are shown the row count is decreased by one.
ShowHeaders = true;
_headers = new Bitmap(Width, RowHeight);
Clear();
}
// Events
/// <summary>
/// Tap grid event.
/// </summary>
public event OnTapCell TapCellEvent;
/// <summary>
/// Triggers a tap cell event.
/// </summary>
/// <param name="sender">Object associated with this event.</param>
/// <param name="args">Tap cell event arguments.</param>
public void TriggerTapCellEvent(object sender, TapCellEventArgs args)
{
if (TapCellEvent != null)
TapCellEvent(sender, args);
}
private void RenderHeaders()
{
int x = 0;
_headers.DrawRectangle(0, 0, x, 0, Width, _headers.Height, 0, 0, HeadersBackColor, 0, 0, 0, 0, 0, 255);
DataGridColumn dataGridColumn;
for (int j = 0; j < _columns.Count; j++)
{
dataGridColumn = (DataGridColumn)_columns[j];
// Draw text
_headers.DrawTextInRect(dataGridColumn.Label, x + 5, (_headers.Height - Font.Height) / 2, dataGridColumn.Width, _headers.Height, 0, HeadersFontColor, Font);
// If we're on the selected column draw the icon.
if (j == _selectedDataGridColumnIndex)
{
int width = 0, height = 0;
Font.ComputeExtent(dataGridColumn.Label, out width, out height);
if (dataGridColumn.Order == Order.ASC)
_headers.DrawImage(x + 10 + width, 5, _DataGridIcon_Asc, 0, 0, _DataGridIcon_Asc.Width, _DataGridIcon_Asc.Height);
else
_headers.DrawImage(x + 10 + width, 5, _DataGridIcon_Desc, 0, 0, _DataGridIcon_Desc.Width, _DataGridIcon_Desc.Height);
}
x += dataGridColumn.Width;
}
}
private void UpdateItem(int index, bool clear)
{
if (clear)
RenderItemClear(index);
if (index == _selectedIndex)
RenderItem(_selectedIndex, ((DataGridItem)_rows[index]).Data, SelectedItemBackColor, SelectedItemFontColor);
else
{
if (index % 2 == 0)
RenderItem(index, ((DataGridItem)_rows[index]).Data, ItemsBackColor, ItemsFontColor);
else
RenderItem(index, ((DataGridItem)_rows[index]).Data, ItemsAltBackColor, ItemsFontColor);
}
}
private void RenderItem(int index, object[] data, Color backColor, Color fontColor)
{
int x = 0;
int y = index * RowHeight;
_items.DrawRectangle(0, 0, x, y, Width, RowHeight, 0, 0, backColor, 0, 0, 0, 0, 0, 255);
DataGridColumn dataGridColumn;
for (int i = 0; i < _columns.Count; i++)
{
dataGridColumn = (DataGridColumn)_columns[i];
_items.DrawTextInRect(data[i].ToString(), x + 5, y + (RowHeight - Font.Height) / 2, dataGridColumn.Width, RowHeight, 0, fontColor, Font);
_items.DrawLine(GridColor, 1, x, y, x, y + RowHeight);
x += dataGridColumn.Width;
}
}
private void RenderItemClear(int index)
{
// HACK: This is done to prevent image/color retention.
_items.DrawRectangle(0, 0, 0, index * RowHeight, Width, RowHeight, 0, 0, 0, 0, 0, 0, 0, 0, 255);
}
private void RenderEmpty()
{
_items.DrawRectangle(0, 0, 0, 0, _items.Width, _items.Height, 0, 0, ItemsBackColor, 0, 0, 0, 0, 0, 255);
int x = 0;
for (int i = 0; i < _columns.Count; i++)
{
_items.DrawLine(GridColor, 1, x, 0, x, _items.Height);
x += ((DataGridColumn)_columns[i]).Width;
}
}
/// <summary>
/// Renders the DataGrid onto it's parent container's graphics.
/// </summary>
public override void Render()
{
if (ShowHeaders && _renderHeaders)
{
_renderHeaders = false;
RenderHeaders();
}
if (_renderItems)
{
_renderItems = false;
// Only recreate the items Bitmap if necessary
if (_items == null || _items.Height != _rows.Count * RowHeight)
{
if (_items != null)
_items.Dispose();
if (_rows.Count < _rowCount)
{
_items = new Bitmap(Width, _rowCount * RowHeight);
RenderEmpty();
}
else
_items = new Bitmap(Width, _rows.Count * RowHeight);
}
else
_items.DrawRectangle(0, 0, 0, 0, Width, _items.Height, 0, 0, 0, 0, 0, 0, 0, 0, 255);
if (_rows.Count > 0)
{
for (int i = 0; i < _rows.Count; i++)
UpdateItem(i, false);
}
}
int x = Parent.X + X;
int y = Parent.Y + Y;
if (_showHeaders)
{
Parent.Graphics.DrawImage(x, y, _headers, 0, 0, Width, RowHeight);
y += RowHeight;
}
Parent.Graphics.DrawImage(x, y, _items, 0, _listY, Width, _rowCount * RowHeight);
if (ShowScrollbar)
{
_scrollbarHeight = RowHeight;
int travel = Height - _scrollbarHeight;
if (_rows.Count > 0)
_scrollbarTick = (int)System.Math.Round((double)(travel / _rows.Count));
else
_scrollbarTick = 0;
_scrollbarHeight = Height - ((_rows.Count - _rowCount) * _scrollbarTick);
x += Width - ScrollbarWidth;
y = Parent.Y + Y;
Parent.Graphics.DrawRectangle(0, 0, x, y, ScrollbarWidth, Height, 0, 0, ScrollbarBackColor, 0, 0, 0, 0, 0, 255);
// Only show the scrollbar scrubber if it's smaller than the Height
if (_scrollbarHeight < Height)
Parent.Graphics.DrawRectangle(0, 0, x, y + (_scrollIndex * _scrollbarTick), ScrollbarWidth, _scrollbarHeight, 0, 0, ScrollbarScrubberColor, 0, 0, 0, 0, 0, 255);
}
}
/// <summary>
/// Handles the touch down event.
/// </summary>
/// <param name="e">Touch event arguments.</param>
/// <returns>Touch event arguments.</returns>
public override TouchEventArgs OnTouchDown(TouchEventArgs e)
{
if (Rect.Contains(e.Point) && _rows.Count > 0)
{
_pressed = true;
_lastTouchY = e.Point.Y;
_lastListY = _listY;
e.StopPropagation();
}
return e;
}
/// <summary>
/// Handles the touch up event.
/// </summary>
/// <param name="e">Touch event arguments.</param>
/// <returns>Touch event arguments.</returns>
public override TouchEventArgs OnTouchUp(TouchEventArgs e)
{
if (!_pressed)
return e;
if (!_moving && Rect.Contains(e.Point))
{
int x = Parent.X + X;
int y = Parent.Y + Y;
int index = ((_listY + e.Point.Y) - y) / RowHeight;
int rowIndex = index;
// If headers are present the rowIndex needs to be offset
if (ShowHeaders)
rowIndex--;
int columnIndex = 0;
DataGridColumn dataGridColumn;
Rectangle rect;
for (int i = 0; i < _columns.Count; i++)
{
dataGridColumn = (DataGridColumn)_columns[i];
rect = new Rectangle(x, y, dataGridColumn.Width, Height);
if (rect.Contains(e.Point))
{
columnIndex = i;
break;
}
x += dataGridColumn.Width;
}
if (index == 0 && ShowHeaders && SortableHeaders)
{
Sort(columnIndex);
Invalidate();
}
else
{
if (TappableCells)
{
SelectedIndex = rowIndex;
TriggerTapCellEvent(this, new TapCellEventArgs(columnIndex, rowIndex));
}
}
}
_pressed = false;
_moving = false;
_ignoredTouchMoves = 0;
return e;
}
/// <summary>
/// Handles the touch move event.
/// </summary>
/// <param name="e">Touch event arguments.</param>
/// <returns>Touch event arguments.</returns>
public override TouchEventArgs OnTouchMove(TouchEventArgs e)
{
if (!Draggable || !_pressed || _rows.Count <= RowCount)
return e;
if (!_moving)
{
if (_ignoredTouchMoves < _maxIgnoredTouchMoves)
_ignoredTouchMoves++;
else
{
_ignoredTouchMoves = 0;
_moving = true;
}
}
else
{
_listY = _lastListY - (e.Point.Y - _lastTouchY);
_listY = GlideUtils.Math.MinMax(_listY, 0, _listMaxY);
_scrollIndex = (int)System.Math.Ceiling(_listY / RowHeight);
Invalidate();
e.StopPropagation();
}
return e;
}
/// <summary>
/// Disposes all disposable objects in this object.
/// </summary>
public override void Dispose()
{
if (_headers != null)
_headers.Dispose();
if (_items != null)
_items.Dispose();
_DataGridIcon_Asc.Dispose();
_DataGridIcon_Desc.Dispose();
}
private bool RowIndexIsValid(int index)
{
return (_rows.Count > 0 && index > -1 && index < _rows.Count);
}
private bool ColumnIndexIsValid(int index)
{
return (_columns.Count > 0 && index > -1 && index < _columns.Count);
}
/// <summary>
/// Adds a column.
/// </summary>
/// <param name="dataGridColumn">dataGridColumn</param>
public void AddColumn(DataGridColumn dataGridColumn)
{
AddColumnAt(-1, dataGridColumn);
}
/// <summary>
/// Adds a column at a specified index.
/// </summary>
/// <param name="index">index</param>
/// <param name="dataGridColumn">dataGridColumn</param>
public void AddColumnAt(int index, DataGridColumn dataGridColumn)
{
if (_columns.Count == 0 || index == -1 || index > _columns.Count - 1)
_columns.Add(dataGridColumn);
else
_columns.Insert(index, dataGridColumn);
// A new column was added so we must re-render the headers.
_renderHeaders = true;
}
/// <summary>
/// Removes a column.
/// </summary>
/// <param name="dataGridColumn">dataGridColumn</param>
public void RemoveColumn(DataGridColumn dataGridColumn)
{
int index = _columns.IndexOf(dataGridColumn);
if (index > -1)
RemoveColumnAt(index);
}
/// <summary>
/// Removes a column at a specified index.
/// </summary>
/// <param name="index">index</param>
public void RemoveColumnAt(int index)
{
if (ColumnIndexIsValid(index))
{
_columns.RemoveAt(index);
_renderHeaders = true;
}
}
/// <summary>
/// Adds an item.
/// </summary>
/// <param name="dataGridItem">dataGridItem</param>
public void AddItem(DataGridItem dataGridItem)
{
AddItemAt(-1, dataGridItem);
}
/// <summary>
/// Adds an item at a specified index.
/// </summary>
/// <param name="index">index</param>
/// <param name="dataGridItem">dataGridItem</param>
public void AddItemAt(int index, DataGridItem dataGridItem)
{
if (dataGridItem.Data.Length != _columns.Count)
throw new ArgumentException("The DataGridRow data length does not match the DataGrid's column count.", "dataGridRow");
if (_rows.Count == 0 || index == -1 || index > _rows.Count - 1)
_rows.Add(dataGridItem);
else
_rows.Insert(index, dataGridItem);
// A new row was added so we must re-render the items.
_renderItems = true;
// Calculate the max list Y position
_listMaxY = _rows.Count * RowHeight;
if (ShowHeaders) _listMaxY += RowHeight;
_listMaxY -= Height;
}
/// <summary>
/// Removes an item.
/// </summary>
/// <param name="dataGridItem">dataGridItem</param>
public void RemoveItem(DataGridItem dataGridItem)
{
int index = _rows.IndexOf(dataGridItem);
if (index > -1)
RemoveItemAt(index);
}
/// <summary>
/// Removes an item a specified index.
/// </summary>
/// <param name="index">index</param>
public void RemoveItemAt(int index)
{
if (RowIndexIsValid(index))
{
_rows.RemoveAt(index);
// A row was removed so we must re-render the items.
_renderItems = true;
// If the rows fall below the selected index
// default to no selection
if (_rows.Count - 1 < SelectedIndex)
SelectedIndex = -1;
// If the index removed was the selected index
// revert to no selection
if (SelectedIndex == index)
SelectedIndex = -1;
}
}
/// <summary>
/// Scroll the rows up by a specified amount.
/// </summary>
/// <param name="amount">amount</param>
public void ScrollUp(int amount)
{
if (_rows.Count == 0)
return;
if (_scrollIndex - amount >= 0)
_scrollIndex -= amount;
else
_scrollIndex = 0;
_listY = _scrollIndex * RowHeight;
}
/// <summary>
/// Scroll the rows down by a specified amount.
/// </summary>
/// <param name="amount">amount</param>
public void ScrollDown(int amount)
{
if (_rows.Count == 0)
return;
if (_scrollIndex + amount < _rows.Count - _rowCount)
_scrollIndex += amount;
else
_scrollIndex = _rows.Count - _rowCount;
_listY = _scrollIndex * RowHeight;
}
/// <summary>
/// Scroll the rows to a specified index.
/// </summary>
/// <param name="index">index</param>
public void ScrollTo(int index)
{
if (RowIndexIsValid(index))
{
_scrollIndex = index;
_listY = _scrollIndex * RowHeight;
}
}
/// <summary>
/// Sets new row data.
/// </summary>
/// <param name="index">index</param>
/// <param name="data">Data object array.</param>
public void SetRowData(int index, object[] data)
{
if (RowIndexIsValid(index))
{
if (data.Length != _columns.Count)
throw new ArgumentException("The data length does not match the DataGrid's column count.", "data");
((DataGridItem)_rows[index]).Data = data;
UpdateItem(index, true);
}
}
/// <summary>
/// Gets row data.
/// </summary>
/// <param name="index">index</param>
/// <returns>Data object array.</returns>
public object[] GetRowData(int index)
{
if (RowIndexIsValid(index))
return ((DataGridItem)_rows[index]).Data;
else
return null;
}
/// <summary>
/// Sets a cell's data.
/// </summary>
/// <param name="columnIndex">columnIndex</param>
/// <param name="rowIndex">rowIndex</param>
/// <param name="data">data</param>
public void SetCellData(int columnIndex, int rowIndex, object data)
{
if (ColumnIndexIsValid(columnIndex) && RowIndexIsValid(rowIndex))
{
((DataGridItem)_rows[rowIndex]).Data[columnIndex] = data;
UpdateItem(rowIndex, true);
}
}
/// <summary>
/// Get a cell's data.
/// </summary>
/// <param name="columnIndex">columnIndex</param>
/// <param name="rowIndex">rowIndex</param>
public object GetCellData(int columnIndex, int rowIndex)
{
if (ColumnIndexIsValid(columnIndex) && RowIndexIsValid(rowIndex))
return ((DataGridItem)_rows[rowIndex]).Data[columnIndex];
else
return null;
}
private void PerformSort()
{
int order = (_order == Order.DESC) ? -1 : 1;
object item;
int i, j;
for (i = 0; i < _rows.Count; i++)
{
item = _rows[i];
j = i;
while ((j > 0) && ((_comparer.Compare(_rows[j - 1], item) * order) > 0))
{
_rows[j] = _rows[j - 1];
j--;
}
_rows[j] = item;
}
_renderHeaders = true;
_renderItems = true;
}
/// <summary>
/// Sorts the items on a specified column index.
/// </summary>
/// <param name="columnIndex"></param>
public void Sort(int columnIndex)
{
_selectedDataGridColumnIndex = columnIndex;
DataGridColumn dataGridColumn = (DataGridColumn)_columns[columnIndex];
dataGridColumn.ToggleOrder();
_order = dataGridColumn.Order;
_comparer.ColumnIndex = columnIndex;
PerformSort();
for (int i = 0; i < _rows.Count; i++)
{
if ((DataGridItem)_rows[i] == _selectedItem)
{
RenderItemClear(_selectedIndex);
_selectedIndex = i;
}
}
}
/// <summary>
/// Clears all items including their data and resets the data grid.
/// </summary>
public void Clear()
{
_rows.Clear();
_renderHeaders = true;
_renderItems = true;
_scrollIndex = 0;
_pressed = false;
_moving = false;
_listY = 0;
_listMaxY = 0;
_ignoredTouchMoves = 0;
_maxIgnoredTouchMoves = 1;
SelectedIndex = -1;
_selectedDataGridColumnIndex = -1;
}
/// <summary>
/// Number of rows displayed.
/// </summary>
public int RowCount
{
get { return _rowCount; }
set
{
if (value != _rowCount)
{
_rowCount = value;
Height = _rowCount * RowHeight;
}
}
}
/// <summary>
/// Font used by the text.
/// </summary>
public Font Font = Resources.GetFont(Resources.FontResources.droid_reg12);
/// <summary>
/// Row height.
/// </summary>
public int RowHeight = 20;
/// <summary>
/// The currently selected index.
/// </summary>
public int SelectedIndex
{
get { return _selectedIndex; }
set
{
if (value != _selectedIndex && (value >= -1 && value < _rows.Count))
{
// If a previous selection exists -- clear it
if (_selectedIndex > -1 && _selectedIndex < _rows.Count)
{
int oldSelectedIndex = _selectedIndex;
_selectedIndex = -1;
UpdateItem(oldSelectedIndex, true);
}
_selectedIndex = value;
if (_selectedIndex > -1)
{
_selectedItem = (DataGridItem)_rows[_selectedIndex];
RenderItem(_selectedIndex, ((DataGridItem)_rows[_selectedIndex]).Data, SelectedItemBackColor, SelectedItemFontColor);
}
else
_selectedItem = null;
// Scroll as selected index gets out of view.
int rowCount = RowCount - 1;
if (_selectedIndex <= _scrollIndex)
ScrollTo(_selectedIndex);
else if (_selectedIndex > _scrollIndex + rowCount)
ScrollTo(_selectedIndex - rowCount);
Invalidate();
}
}
}
/// <summary>
/// Number of items in the DataGrid.
/// </summary>
public int NumItems
{
get { return _rows.Count; }
}
/// <summary>
/// Indicates whether items trigger cell tap events or not.
/// </summary>
public bool TappableCells = true;
/// <summary>
/// Indicates whether or not the item list can be dragged up and down.
/// </summary>
public bool Draggable = true;
/// <summary>
/// Indicates whether the headers are shown.
/// </summary>
public bool ShowHeaders
{
get { return _showHeaders; }
set
{
if (value != _showHeaders)
{
_showHeaders = value;
if (_showHeaders)
_rowCount--;
else
_rowCount++;
_renderHeaders = true;
_renderItems = true;
}
}
}
/// <summary>
/// Indicates whether the headers are sortable.
/// </summary>
public bool SortableHeaders = true;
/// <summary>
/// Headers background color.
/// </summary>
public Color HeadersBackColor = Colors.Black;
/// <summary>
/// Headers font color.
/// </summary>
public Color HeadersFontColor = Colors.White;
/// <summary>
/// Items background color.
/// </summary>
public Color ItemsBackColor = Colors.White;
/// <summary>
/// Items alternate background color.
/// </summary>
public Color ItemsAltBackColor = GlideUtils.Convert.ToColor("F0F0F0");
/// <summary>
/// Items font color.
/// </summary>
public Color ItemsFontColor = Colors.Black;
/// <summary>
/// Selected item background color.
/// </summary>
public Color SelectedItemBackColor = GlideUtils.Convert.ToColor("FFF299");
/// <summary>
/// Selected item font color.
/// </summary>
public Color SelectedItemFontColor = Colors.Black;
/// <summary>
/// Grid color.
/// </summary>
public Color GridColor = Colors.Gray;
/// <summary>
/// Indicates whether the scrollbar is shown.
/// </summary>
public bool ShowScrollbar = true;
/// <summary>
/// Scrollbar width.
/// </summary>
public int ScrollbarWidth = 4;
/// <summary>
/// Scrollbar background color.
/// </summary>
public Color ScrollbarBackColor = GlideUtils.Convert.ToColor("C0C0C0");
/// <summary>
/// Scrollbar scrubber color.
/// </summary>
public Color ScrollbarScrubberColor = Colors.Black;
/// <summary>
/// The order in which rows are sorted.
/// </summary>
/// <remarks>ASC stands for ascending ex: 1 to 10 or A to Z. DESC stands for descending ex: 10 to 1 or Z to A.</remarks>
public enum Order
{
/// <summary>
/// Ascending
/// </summary>
ASC,
/// <summary>
/// Descending
/// </summary>
DESC
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Net.Http.Headers;
using Xunit;
namespace System.Net.Http.Tests
{
public class ContentRangeHeaderValueTest
{
[Fact]
public void Ctor_LengthOnlyOverloadUseInvalidValues_Throw()
{
Assert.Throws<ArgumentOutOfRangeException>(() => { ContentRangeHeaderValue v = new ContentRangeHeaderValue(-1); });
}
[Fact]
public void Ctor_LengthOnlyOverloadValidValues_ValuesCorrectlySet()
{
ContentRangeHeaderValue range = new ContentRangeHeaderValue(5);
Assert.False(range.HasRange);
Assert.True(range.HasLength);
Assert.Equal("bytes", range.Unit);
Assert.Null(range.From);
Assert.Null(range.To);
Assert.Equal(5, range.Length);
}
[Fact]
public void Ctor_FromAndToOverloadUseInvalidValues_Throw()
{
Assert.Throws<ArgumentOutOfRangeException>(() => { new ContentRangeHeaderValue(-1, 1); }); // "Negative 'from'"
Assert.Throws<ArgumentOutOfRangeException>(() => { new ContentRangeHeaderValue(0, -1); }); // "Negative 'to'"
Assert.Throws<ArgumentOutOfRangeException>(() => { new ContentRangeHeaderValue(2, 1); }); // "'from' > 'to'"
}
[Fact]
public void Ctor_FromAndToOverloadValidValues_ValuesCorrectlySet()
{
ContentRangeHeaderValue range = new ContentRangeHeaderValue(0, 1);
Assert.True(range.HasRange);
Assert.False(range.HasLength);
Assert.Equal("bytes", range.Unit);
Assert.Equal(0, range.From);
Assert.Equal(1, range.To);
Assert.Null(range.Length);
}
[Fact]
public void Ctor_FromToAndLengthOverloadUseInvalidValues_Throw()
{
Assert.Throws<ArgumentOutOfRangeException>(() => { new ContentRangeHeaderValue(-1, 1, 2); }); // "Negative 'from'"
Assert.Throws<ArgumentOutOfRangeException>(() => { new ContentRangeHeaderValue(0, -1, 2); }); // "Negative 'to'"
Assert.Throws<ArgumentOutOfRangeException>(() => { new ContentRangeHeaderValue(0, 1, -1); }); // "Negative 'length'"
Assert.Throws<ArgumentOutOfRangeException>(() => { new ContentRangeHeaderValue(2, 1, 3); }); // "'from' > 'to'"
Assert.Throws<ArgumentOutOfRangeException>(() => { new ContentRangeHeaderValue(1, 2, 1); }); // "'to' > 'length'"
}
[Fact]
public void Ctor_FromToAndLengthOverloadValidValues_ValuesCorrectlySet()
{
ContentRangeHeaderValue range = new ContentRangeHeaderValue(0, 1, 2);
Assert.True(range.HasRange);
Assert.True(range.HasLength);
Assert.Equal("bytes", range.Unit);
Assert.Equal(0, range.From);
Assert.Equal(1, range.To);
Assert.Equal(2, range.Length);
}
[Fact]
public void Unit_GetAndSetValidAndInvalidValues_MatchExpectation()
{
ContentRangeHeaderValue range = new ContentRangeHeaderValue(0);
range.Unit = "myunit";
Assert.Equal("myunit", range.Unit); // "Unit (custom value)"
AssertExtensions.Throws<ArgumentException>("value", () => { range.Unit = null; }); // "<null>"
AssertExtensions.Throws<ArgumentException>("value", () => { range.Unit = ""; }); // "empty string"
Assert.Throws<FormatException>(() => { range.Unit = " x"; }); // "leading space"
Assert.Throws<FormatException>(() => { range.Unit = "x "; }); // "trailing space"
Assert.Throws<FormatException>(() => { range.Unit = "x y"; }); // "invalid token"
}
[Fact]
public void ToString_UseDifferentRanges_AllSerializedCorrectly()
{
ContentRangeHeaderValue range = new ContentRangeHeaderValue(1, 2, 3);
range.Unit = "myunit";
Assert.Equal("myunit 1-2/3", range.ToString()); // "Range with all fields set"
range = new ContentRangeHeaderValue(123456789012345678, 123456789012345679);
Assert.Equal("bytes 123456789012345678-123456789012345679/*", range.ToString()); // "Only range, no length"
range = new ContentRangeHeaderValue(150);
Assert.Equal("bytes */150", range.ToString()); // "Only length, no range"
}
[Fact]
public void GetHashCode_UseSameAndDifferentRanges_SameOrDifferentHashCodes()
{
ContentRangeHeaderValue range1 = new ContentRangeHeaderValue(1, 2, 5);
ContentRangeHeaderValue range2 = new ContentRangeHeaderValue(1, 2);
ContentRangeHeaderValue range3 = new ContentRangeHeaderValue(5);
ContentRangeHeaderValue range4 = new ContentRangeHeaderValue(1, 2, 5);
range4.Unit = "BYTES";
ContentRangeHeaderValue range5 = new ContentRangeHeaderValue(1, 2, 5);
range5.Unit = "myunit";
Assert.NotEqual(range1.GetHashCode(), range2.GetHashCode()); // "bytes 1-2/5 vs. bytes 1-2/*"
Assert.NotEqual(range1.GetHashCode(), range3.GetHashCode()); // "bytes 1-2/5 vs. bytes */5"
Assert.NotEqual(range2.GetHashCode(), range3.GetHashCode()); // "bytes 1-2/* vs. bytes */5"
Assert.Equal(range1.GetHashCode(), range4.GetHashCode()); // "bytes 1-2/5 vs. BYTES 1-2/5"
Assert.NotEqual(range1.GetHashCode(), range5.GetHashCode()); // "bytes 1-2/5 vs. myunit 1-2/5"
}
[Fact]
public void Equals_UseSameAndDifferentRanges_EqualOrNotEqualNoExceptions()
{
ContentRangeHeaderValue range1 = new ContentRangeHeaderValue(1, 2, 5);
ContentRangeHeaderValue range2 = new ContentRangeHeaderValue(1, 2);
ContentRangeHeaderValue range3 = new ContentRangeHeaderValue(5);
ContentRangeHeaderValue range4 = new ContentRangeHeaderValue(1, 2, 5);
range4.Unit = "BYTES";
ContentRangeHeaderValue range5 = new ContentRangeHeaderValue(1, 2, 5);
range5.Unit = "myunit";
ContentRangeHeaderValue range6 = new ContentRangeHeaderValue(1, 3, 5);
ContentRangeHeaderValue range7 = new ContentRangeHeaderValue(2, 2, 5);
ContentRangeHeaderValue range8 = new ContentRangeHeaderValue(1, 2, 6);
Assert.False(range1.Equals(null)); // "bytes 1-2/5 vs. <null>"
Assert.False(range1.Equals(range2)); // "bytes 1-2/5 vs. bytes 1-2/*"
Assert.False(range1.Equals(range3)); // "bytes 1-2/5 vs. bytes */5"
Assert.False(range2.Equals(range3)); // "bytes 1-2/* vs. bytes */5"
Assert.True(range1.Equals(range4)); // "bytes 1-2/5 vs. BYTES 1-2/5"
Assert.True(range4.Equals(range1)); // "BYTES 1-2/5 vs. bytes 1-2/5"
Assert.False(range1.Equals(range5)); // "bytes 1-2/5 vs. myunit 1-2/5"
Assert.False(range1.Equals(range6)); // "bytes 1-2/5 vs. bytes 1-3/5"
Assert.False(range1.Equals(range7)); // "bytes 1-2/5 vs. bytes 2-2/5"
Assert.False(range1.Equals(range8)); // "bytes 1-2/5 vs. bytes 1-2/6"
}
[Fact]
public void Clone_Call_CloneFieldsMatchSourceFields()
{
ContentRangeHeaderValue source = new ContentRangeHeaderValue(1, 2, 5);
source.Unit = "custom";
ContentRangeHeaderValue clone = (ContentRangeHeaderValue)((ICloneable)source).Clone();
Assert.Equal(source.Unit, clone.Unit);
Assert.Equal(source.From, clone.From);
Assert.Equal(source.To, clone.To);
Assert.Equal(source.Length, clone.Length);
}
[Fact]
public void GetContentRangeLength_DifferentValidScenarios_AllReturnNonZero()
{
ContentRangeHeaderValue result = null;
CallGetContentRangeLength("bytes 1-2/3", 0, 11, out result);
Assert.Equal("bytes", result.Unit);
Assert.Equal(1, result.From);
Assert.Equal(2, result.To);
Assert.Equal(3, result.Length);
Assert.True(result.HasRange);
Assert.True(result.HasLength);
CallGetContentRangeLength(" custom 1234567890123456789-1234567890123456799/*", 1, 48, out result);
Assert.Equal("custom", result.Unit);
Assert.Equal(1234567890123456789, result.From);
Assert.Equal(1234567890123456799, result.To);
Assert.Null(result.Length);
Assert.True(result.HasRange);
Assert.False(result.HasLength);
// Note that the final space should be skipped by GetContentRangeLength() and be considered by the returned
// value.
CallGetContentRangeLength(" custom * / 123 ", 1, 15, out result);
Assert.Equal("custom", result.Unit);
Assert.Null(result.From);
Assert.Null(result.To);
Assert.Equal(123, result.Length);
Assert.False(result.HasRange);
Assert.True(result.HasLength);
// Note that we don't have a public constructor for value 'bytes */*' since the RFC doesn't mention a
// scenario for it. However, if a server returns this value, we're flexible and accept it.
CallGetContentRangeLength("bytes */*", 0, 9, out result);
Assert.Equal("bytes", result.Unit);
Assert.Null(result.From);
Assert.Null(result.To);
Assert.Null(result.Length);
Assert.False(result.HasRange);
Assert.False(result.HasLength);
}
[Fact]
public void GetContentRangeLength_DifferentInvalidScenarios_AllReturnZero()
{
CheckInvalidGetContentRangeLength(" bytes 1-2/3", 0);
CheckInvalidGetContentRangeLength("bytes 3-2/5", 0);
CheckInvalidGetContentRangeLength("bytes 6-6/5", 0);
CheckInvalidGetContentRangeLength("bytes 1-6/5", 0);
CheckInvalidGetContentRangeLength("bytes 1-2/", 0);
CheckInvalidGetContentRangeLength("bytes 1-2", 0);
CheckInvalidGetContentRangeLength("bytes 1-/", 0);
CheckInvalidGetContentRangeLength("bytes 1-", 0);
CheckInvalidGetContentRangeLength("bytes 1", 0);
CheckInvalidGetContentRangeLength("bytes ", 0);
CheckInvalidGetContentRangeLength("bytes a-2/3", 0);
CheckInvalidGetContentRangeLength("bytes 1-b/3", 0);
CheckInvalidGetContentRangeLength("bytes 1-2/c", 0);
CheckInvalidGetContentRangeLength("bytes1-2/3", 0);
// More than 19 digits >>Int64.MaxValue
CheckInvalidGetContentRangeLength("bytes 1-12345678901234567890/3", 0);
CheckInvalidGetContentRangeLength("bytes 12345678901234567890-3/3", 0);
CheckInvalidGetContentRangeLength("bytes 1-2/12345678901234567890", 0);
// Exceed Int64.MaxValue, but use 19 digits
CheckInvalidGetContentRangeLength("bytes 1-9999999999999999999/3", 0);
CheckInvalidGetContentRangeLength("bytes 9999999999999999999-3/3", 0);
CheckInvalidGetContentRangeLength("bytes 1-2/9999999999999999999", 0);
CheckInvalidGetContentRangeLength(string.Empty, 0);
CheckInvalidGetContentRangeLength(null, 0);
}
[Fact]
public void Parse_SetOfValidValueStrings_ParsedCorrectly()
{
// Only verify parser functionality (i.e. ContentRangeHeaderParser.TryParse()). We don't need to validate
// all possible range values (verification done by tests for ContentRangeHeaderValue.GetContentRangeLength()).
CheckValidParse(" bytes 1-2/3 ", new ContentRangeHeaderValue(1, 2, 3));
CheckValidParse("bytes * / 3", new ContentRangeHeaderValue(3));
}
[Fact]
public void Parse_SetOfInvalidValueStrings_Throws()
{
CheckInvalidParse("bytes 1-2/3,"); // no character after 'length' allowed
CheckInvalidParse("x bytes 1-2/3");
CheckInvalidParse("bytes 1-2/3.4");
CheckInvalidParse(null);
CheckInvalidParse(string.Empty);
}
[Fact]
public void TryParse_SetOfValidValueStrings_ParsedCorrectly()
{
// Only verify parser functionality (i.e. ContentRangeHeaderParser.TryParse()). We don't need to validate
// all possible range values (verification done by tests for ContentRangeHeaderValue.GetContentRangeLength()).
CheckValidTryParse(" bytes 1-2/3 ", new ContentRangeHeaderValue(1, 2, 3));
CheckValidTryParse("bytes * / 3", new ContentRangeHeaderValue(3));
}
[Fact]
public void TryParse_SetOfInvalidValueStrings_ReturnsFalse()
{
CheckInvalidTryParse("bytes 1-2/3,"); // no character after 'length' allowed
CheckInvalidTryParse("x bytes 1-2/3");
CheckInvalidTryParse("bytes 1-2/3.4");
CheckInvalidTryParse(null);
CheckInvalidTryParse(string.Empty);
}
#region Helper methods
private void CheckValidParse(string input, ContentRangeHeaderValue expectedResult)
{
ContentRangeHeaderValue result = ContentRangeHeaderValue.Parse(input);
Assert.Equal(expectedResult, result);
}
private void CheckInvalidParse(string input)
{
Assert.Throws<FormatException>(() => { ContentRangeHeaderValue.Parse(input); });
}
private void CheckValidTryParse(string input, ContentRangeHeaderValue expectedResult)
{
ContentRangeHeaderValue result = null;
Assert.True(ContentRangeHeaderValue.TryParse(input, out result));
Assert.Equal(expectedResult, result);
}
private void CheckInvalidTryParse(string input)
{
ContentRangeHeaderValue result = null;
Assert.False(ContentRangeHeaderValue.TryParse(input, out result));
Assert.Null(result);
}
private static void CallGetContentRangeLength(string input, int startIndex, int expectedLength,
out ContentRangeHeaderValue result)
{
object temp = null;
Assert.Equal(expectedLength, ContentRangeHeaderValue.GetContentRangeLength(input, startIndex, out temp));
result = temp as ContentRangeHeaderValue;
}
private static void CheckInvalidGetContentRangeLength(string input, int startIndex)
{
object result = null;
Assert.Equal(0, ContentRangeHeaderValue.GetContentRangeLength(input, startIndex, out result));
Assert.Null(result);
}
#endregion
}
}
| |
using Nito.AsyncEx;
using System;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.Crypto.Randomness;
using WalletWasabi.Helpers;
using WalletWasabi.Logging;
using WalletWasabi.Tor.Socks5.Exceptions;
using WalletWasabi.Tor.Socks5.Models.Bases;
using WalletWasabi.Tor.Socks5.Models.Fields.ByteArrayFields;
using WalletWasabi.Tor.Socks5.Models.Fields.OctetFields;
using WalletWasabi.Tor.Socks5.Models.Messages;
namespace WalletWasabi.Tor.Socks5
{
/// <summary>
/// Create an instance with the TorSocks5Manager
/// </summary>
public class TorSocks5Client : IDisposable
{
private volatile bool _disposedValue = false; // To detect redundant calls
/// <param name="endPoint">Valid Tor end point.</param>
public TorSocks5Client(EndPoint endPoint)
{
TorSocks5EndPoint = endPoint;
TcpClient = new TcpClient(endPoint.AddressFamily);
AsyncLock = new AsyncLock();
}
#region PropertiesAndMembers
/// <summary>TCP connection to Tor's SOCKS5 server.</summary>
private TcpClient TcpClient { get; set; }
private EndPoint TorSocks5EndPoint { get; }
/// <summary>Transport stream for sending HTTP/HTTPS requests through Tor's SOCKS5 server.</summary>
/// <remarks>This stream is not to be used to send commands to Tor's SOCKS5 server.</remarks>
private Stream Stream { get; set; }
private EndPoint RemoteEndPoint { get; set; }
public bool IsConnected => TcpClient?.Connected is true;
internal AsyncLock AsyncLock { get; }
#endregion PropertiesAndMembers
#region Initializers
/// <summary>
/// Establishes TCP connection with Tor SOCKS5 endpoint.
/// </summary>
/// <exception cref="ArgumentException">This should never happen.</exception>
/// <exception cref="TorException">When connection to Tor SOCKS5 endpoint fails.</exception>
public async Task ConnectAsync(CancellationToken cancellationToken = default)
{
using (await AsyncLock.LockAsync(cancellationToken).ConfigureAwait(false))
{
if (!TorSocks5EndPoint.TryGetHostAndPort(out string? host, out int? port))
{
throw new ArgumentException("Endpoint type is not supported.", nameof(TorSocks5EndPoint));
}
try
{
await TcpClient.ConnectAsync(host, port.Value, cancellationToken).ConfigureAwait(false);
}
catch (SocketException ex) when (ex.ErrorCode is 10061 or 111 or 61)
{
// 10061 ~ "No connection could be made because the target machine actively refused it" on Windows.
// 111 ~ "Connection refused" on Linux.
// 61 ~ "Connection refused" on macOS.
throw new TorConnectionException($"Could not connect to Tor SOCKSPort at '{host}:{port}'. Is Tor running?", ex);
}
Stream = TcpClient.GetStream();
RemoteEndPoint = TcpClient.Client.RemoteEndPoint;
}
}
/// <summary>
/// Checks whether communication can be established with Tor over <see cref="TorSocks5EndPoint"/> endpoint.
/// </summary>
/// <returns></returns>
public async Task<bool> IsTorRunningAsync()
{
try
{
// Internal TCP client may close, so we need a new instance here.
using var client = new TorSocks5Client(TorSocks5EndPoint);
await client.ConnectAsync().ConfigureAwait(false);
await client.HandshakeAsync().ConfigureAwait(false);
return true;
}
catch (TorConnectionException)
{
return false;
}
}
/// <summary>
/// Do the authentication part of Tor's SOCKS5 protocol.
/// </summary>
/// <param name="isolateStream">Whether random username/password should be used for authentication and thus effectively create a new Tor circuit.</param>
/// <remarks>Tor process must be started with enabled <c>IsolateSOCKSAuth</c> option. It's ON by default.</remarks>
/// <seealso href="https://www.torproject.org/docs/tor-manual.html.en"/>
/// <seealso href="https://linux.die.net/man/1/tor">For <c>IsolateSOCKSAuth</c> option explanation.</seealso>
/// <seealso href="https://gitweb.torproject.org/torspec.git/tree/socks-extensions.txt#n35"/>
public async Task HandshakeAsync(bool isolateStream = false, CancellationToken cancellationToken = default)
{
Logger.LogDebug($"> {nameof(isolateStream)}={isolateStream}");
// https://github.com/torproject/torspec/blob/master/socks-extensions.txt
// The "NO AUTHENTICATION REQUIRED" (SOCKS5) authentication method [00] is
// supported; and as of Tor 0.2.3.2 - alpha, the "USERNAME/PASSWORD"(SOCKS5)
// authentication method[02] is supported too, and used as a method to
// implement stream isolation.As an extension to support some broken clients,
// we allow clients to pass "USERNAME/PASSWORD" authentication message to us
// even if no authentication was selected.Furthermore, we allow
// username / password fields of this message to be empty. This technically
// violates RFC1929[4], but ensures interoperability with somewhat broken
// SOCKS5 client implementations.
var methods = new MethodsField(isolateStream ? MethodField.UsernamePassword : MethodField.NoAuthenticationRequired);
byte[] receiveBuffer = await SendRequestAsync(new VersionMethodRequest(methods), cancellationToken).ConfigureAwait(false);
var methodSelection = new MethodSelectionResponse(receiveBuffer);
if (methodSelection.Ver != VerField.Socks5)
{
throw new NotSupportedException($"SOCKS{methodSelection.Ver.Value} not supported. Only SOCKS5 is supported.");
}
else if (methodSelection.Method == MethodField.NoAcceptableMethods)
{
// https://www.ietf.org/rfc/rfc1928.txt
// If the selected METHOD is X'FF', none of the methods listed by the
// client are acceptable, and the client MUST close the connection.
DisposeTcpClient();
throw new NotSupportedException("Tor's SOCKS5 proxy does not support any of the client's authentication methods.");
}
else if (methodSelection.Method == MethodField.UsernamePassword)
{
// https://tools.ietf.org/html/rfc1929#section-2
// Once the SOCKS V5 server has started, and the client has selected the
// Username / Password Authentication protocol, the Username / Password
// sub-negotiation begins. This begins with the client producing a
// Username / Password request:
var identity = RandomString.CapitalAlphaNumeric(21);
var uName = new UNameField(uName: identity);
var passwd = new PasswdField(password: identity);
var usernamePasswordRequest = new UsernamePasswordRequest(uName, passwd);
receiveBuffer = await SendRequestAsync(usernamePasswordRequest, cancellationToken).ConfigureAwait(false);
var userNamePasswordResponse = new UsernamePasswordResponse(receiveBuffer);
if (userNamePasswordResponse.Ver != usernamePasswordRequest.Ver)
{
throw new NotSupportedException($"Authentication version {userNamePasswordResponse.Ver.Value} not supported. Only version {usernamePasswordRequest.Ver} is supported.");
}
if (!userNamePasswordResponse.Status.IsSuccess()) // Tor authentication is different, this will never happen;
{
// https://tools.ietf.org/html/rfc1929#section-2
// A STATUS field of X'00' indicates success. If the server returns a
// `failure' (STATUS value other than X'00') status, it MUST close the
// connection.
DisposeTcpClient();
throw new InvalidOperationException("Wrong username and/or password.");
}
}
Logger.LogDebug("<");
}
public async Task UpgradeToSslAsync(string host)
{
SslStream sslStream = new SslStream(TcpClient.GetStream(), leaveInnerStreamOpen: true);
await sslStream.AuthenticateAsClientAsync(host, new X509CertificateCollection(), true).ConfigureAwait(false);
Stream = sslStream;
}
/// <summary>
/// Stream to transport HTTP(S) request.
/// </summary>
/// <remarks>Either <see cref="TcpClient.GetStream"/> or <see cref="SslStream"/> over <see cref="TcpClient.GetStream"/>.</remarks>
public Stream GetTransportStream()
{
return Stream;
}
/// <summary>
/// Sends <see cref="CmdField.Connect"/> command to SOCKS5 server to instruct it to connect to
/// <paramref name="host"/>:<paramref name="port"/> on behalf of this client.
/// </summary>
/// <param name="host">IPv4 or domain of the destination.</param>
/// <param name="port">Port number of the destination.</param>
/// <seealso href="https://tools.ietf.org/html/rfc1928">Section 3. Procedure for TCP-based clients</seealso>
public async Task ConnectToDestinationAsync(string host, int port, CancellationToken cancellationToken = default)
{
Logger.LogDebug($"> {nameof(host)}='{host}', {nameof(port)}={port}");
host = Guard.NotNullOrEmptyOrWhitespace(nameof(host), host, true);
Guard.MinimumAndNotNull(nameof(port), port, 0);
try
{
TorSocks5Request connectRequest = new(cmd: CmdField.Connect, new AddrField(host), new PortField(port));
byte[] receiveBuffer = await SendRequestAsync(connectRequest, cancellationToken).ConfigureAwait(false);
var connectionResponse = new TorSocks5Response(receiveBuffer);
if (connectionResponse.Rep != RepField.Succeeded)
{
// https://www.ietf.org/rfc/rfc1928.txt
// When a reply (REP value other than X'00') indicates a failure, the
// SOCKS server MUST terminate the TCP connection shortly after sending
// the reply. This must be no more than 10 seconds after detecting the
// condition that caused a failure.
DisposeTcpClient();
Logger.LogWarning($"Connection response indicates a failure. Actual response is: '{connectionResponse.Rep}'. Request: '{host}:{port}'.");
throw new TorConnectCommandFailedException(connectionResponse.Rep);
}
// Do not check the Bnd. Address and Bnd. Port. because Tor does not seem to return any, ever. It returns zeros instead.
// Generally also do not check anything but the success response, according to Socks5 RFC
// If the reply code(REP value of X'00') indicates a success, and the
// request was either a BIND or a CONNECT, the client may now start
// passing data. If the selected authentication method supports
// encapsulation for the purposes of integrity, authentication and / or
// confidentiality, the data are encapsulated using the method-dependent
// encapsulation.Similarly, when data arrives at the SOCKS server for
// the client, the server MUST encapsulate the data as appropriate for
// the authentication method in use.
}
catch (OperationCanceledException)
{
Logger.LogTrace($"Connecting to destination '{host}:{port}' was canceled.");
throw;
}
catch (Exception e)
{
Logger.LogError($"Exception was thrown when connecting to destination '{host}:{port}'.", e);
throw;
}
finally
{
Logger.LogDebug("<");
}
}
#endregion Initializers
#region Methods
/// <summary>
/// Sends a request to the Tor SOCKS5 connection and returns a byte response.
/// </summary>
/// <param name="request">Request to send.</param>
/// <param name="cancellationToken">Cancellation token to cancel sending.</param>
/// <returns>Reply</returns>
/// <exception cref="ArgumentException">When <paramref name="request"/> is not supported.</exception>
/// <exception cref="TorConnectionException">When we receive no response from Tor or the response is invalid.</exception>
private async Task<byte[]> SendRequestAsync(ByteArraySerializableBase request, CancellationToken cancellationToken = default)
{
try
{
using (await AsyncLock.LockAsync(cancellationToken).ConfigureAwait(false))
{
var stream = TcpClient.GetStream();
byte[] dataToSend = request.ToBytes();
// Write data to the stream.
await stream.WriteAsync(dataToSend.AsMemory(0, dataToSend.Length), cancellationToken).ConfigureAwait(false);
await stream.FlushAsync(cancellationToken).ConfigureAwait(false);
if (request is VersionMethodRequest or UsernamePasswordRequest)
{
return await ReadTwoByteResponseAsync(stream, cancellationToken).ConfigureAwait(false);
}
else if (request is TorSocks5Request)
{
return await ReadRequestResponseAsync(stream, cancellationToken).ConfigureAwait(false);
}
else
{
throw new ArgumentException("Not supported request type.", nameof(request));
}
}
}
catch (OperationCanceledException)
{
Logger.LogTrace("Send operation was canceled.");
throw;
}
catch (IOException ex)
{
throw new TorConnectionException($"{nameof(TorSocks5Client)} is not connected to {RemoteEndPoint}.", ex);
}
}
/// <summary>
/// Reads response for <see cref="TorSocks5Request"/>.
/// </summary>
private static async Task<byte[]> ReadRequestResponseAsync(NetworkStream stream, CancellationToken cancellationToken)
{
ByteArrayBuilder builder = new(capacity: 1024);
// Read: VER, CMD, RSV and ATYP values.
int byteResult = -1;
for (int i = 0; i < 4; i++)
{
byteResult = await stream.ReadByteAsync(cancellationToken).ConfigureAwait(false);
if (byteResult == -1)
{
throw new TorConnectionException("Failed to read first four bytes from the SOCKS5 response.");
}
builder.Append((byte)byteResult);
}
// Process last read byte which is ATYP.
byte addrType = (byte)byteResult;
int dstAddrLength = addrType switch
{
// IPv4.
0x01 => 4,
// Fully-qualified domain name.
0x03 => await stream.ReadByteAsync(cancellationToken).ConfigureAwait(false),
// IPv6.
0x04 => 16,
_ => throw new TorConnectionException("Received unsupported ATYP value.")
};
if (dstAddrLength == -1)
{
throw new TorConnectionException("Failed to read the length of DST.ADDR from the SOCKS5 response.");
}
// Read DST.ADDR.
for (int i = 0; i < dstAddrLength; i++)
{
byteResult = await stream.ReadByteAsync(cancellationToken).ConfigureAwait(false);
if (byteResult == -1)
{
throw new TorConnectionException("Failed to read DST.ADDR from the SOCKS5 response.");
}
builder.Append((byte)byteResult);
}
// Read DST.PORT.
for (int i = 0; i < 2; i++)
{
byteResult = await stream.ReadByteAsync(cancellationToken).ConfigureAwait(false);
if (byteResult == -1)
{
throw new TorConnectionException("Failed to read DST.PORT from the SOCKS5 response.");
}
builder.Append((byte)byteResult);
}
return builder.ToArray();
}
private static async Task<byte[]> ReadTwoByteResponseAsync(NetworkStream stream, CancellationToken cancellationToken)
{
// Read exactly "receiveBufferSize" bytes.
int receiveBufferSize = 2;
byte[] receiveBuffer = new byte[receiveBufferSize];
int unreadBytes = await stream.ReadBlockAsync(receiveBuffer, receiveBufferSize, cancellationToken).ConfigureAwait(false);
if (unreadBytes == receiveBufferSize)
{
return receiveBuffer;
}
throw new TorConnectionException($"Failed to read {receiveBufferSize} bytes as expected from Tor SOCKS5.");
}
#endregion Methods
#region IDisposable Support
protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
DisposeTcpClient();
}
_disposedValue = true;
}
}
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
// GC.SuppressFinalize(this);
}
private void DisposeTcpClient()
{
try
{
if (TcpClient is { } tcpClient)
{
if (tcpClient.Connected)
{
Stream?.Dispose();
}
tcpClient.Dispose();
}
}
catch (Exception ex)
{
Logger.LogWarning(ex);
}
finally
{
TcpClient = null; // needs to be called, .net bug
}
}
#endregion IDisposable Support
}
}
| |
#region Copyright (c) 2002-2005, Bas Geertsema, Xih Solutions (http://www.xihsolutions.net)
/*
Copyright (c) 2002-2005, Bas Geertsema, Xih Solutions (http://www.xihsolutions.net)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the names of Bas Geertsema or Xih Solutions nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE. */
#endregion
using System;
using System.IO;
using System.Collections;
using XihSolutions.DotMSN;
using XihSolutions.DotMSN.DataTransfer;
namespace XihSolutions.DotMSN.Core
{
/// <summary>
/// Buffers the incoming data from the notification server (NS).
/// </summary>
/// <remarks>
/// The main purpose of this class is to ensure that MSG, IPG and NOT payload commands are processed
/// only when they are complete. Payload commands can be quite large and may be larger
/// than the socket buffer. This pool
/// will buffer the data and release the messages, or commands, when they are
/// fully retrieved from the server.
/// </remarks>
public class NSMessagePool : MessagePool
{
/// <summary>
/// Constructor to instantiate a NSMessagePool object.
/// </summary>
public NSMessagePool()
{
CreateNewBuffer();
}
/// <summary>
/// Contains all messages waiting to be released
/// </summary>
protected Queue MessageQueue
{
get { return messageQueue; }
}
/// <summary>
/// </summary>
private Queue messageQueue = new Queue(8, 1.25f);
/// <summary>
/// This points to the current message we are writing to
/// </summary>
protected MemoryStream BufferStream
{
get { return bufferStream; }
set { bufferStream = value;}
}
/// <summary>
/// </summary>
private MemoryStream bufferStream = null;
/// <summary>
/// This is the interface to the bufferStream
/// </summary>
protected BinaryWriter BufferWriter
{
get { return bufferWriter; }
set { bufferWriter = value;}
}
/// <summary>
/// </summary>
private BinaryWriter bufferWriter = null;
/// <summary>
/// Indicates the number of bytes remaining for the current payload command
/// </summary>
private int remainingBuffer = 0;
/// <summary>
/// Creates a new memorystream to server as the buffer.
/// </summary>
private void CreateNewBuffer()
{
bufferStream = new MemoryStream(64);
bufferWriter = new BinaryWriter(bufferStream);
}
/// <summary>
/// Enques the current buffer memorystem when a message is completely retrieved.
/// </summary>
private void EnqueueCurrentBuffer()
{
messageQueue.Enqueue(bufferStream);
}
/// <summary>
/// Is true when there are message available to retrieve.
/// </summary>
public override bool MessageAvailable
{
get
{
return messageQueue.Count > 0;
}
}
/// <summary>
/// Get the next message as a byte array.
/// The returned data includes all newlines which seperate the commands ("\r\n")
/// </summary>
/// <returns>Returns the raw message data</returns>
public override byte[] GetNextMessageData()
{
MemoryStream memStream = (MemoryStream)messageQueue.Dequeue();
return memStream.ToArray();
}
/// <summary>
/// Stores the raw data in a buffer. When a full message is detected it is inserted on the internal stack.
/// You can retrieve these messages bij calling GetNextMessageData().
/// </summary>
/// <param name="reader"></param>
public override void BufferData(BinaryReader reader)
{
int length = (int)(reader.BaseStream.Length - reader.BaseStream.Position);
// there is nothing in the bufferstream so we expect a command right away
while(length > 0)
{
// should we buffer the current message
if(remainingBuffer > 0)
{
// read as much as possible in the current message stream
int readLength = Math.Min(remainingBuffer, length);
byte[] msgBuffer = reader.ReadBytes(readLength);
bufferStream.Write(msgBuffer, 0, msgBuffer.Length);
// subtract what we have read from the total length
remainingBuffer -= readLength;
length = (int)(reader.BaseStream.Length - reader.BaseStream.Position);
// when we have read everything we can start a new message
if(remainingBuffer == 0)
{
EnqueueCurrentBuffer();
CreateNewBuffer();
}
}
else
{
// read until we come across a newline
byte val = reader.ReadByte();
if(val != '\n')
bufferWriter.Write(val);
else
{
// write the last newline
bufferWriter.Write(val);
// check if it's a payload command
bufferStream.Position = 0;
byte[] cmd = new byte[3];
cmd[0] = (byte)bufferStream.ReadByte();
cmd[1] = (byte)bufferStream.ReadByte();
cmd[2] = (byte)bufferStream.ReadByte();
if((cmd[0] == 'M' && cmd[1] == 'S' && cmd[2] == 'G') || // MSG payload command
(cmd[0] == 'I' && cmd[1] == 'P' && cmd[2] == 'G') || // IPG pager command
(cmd[0] == 'N' && cmd[1] == 'O' && cmd[2] == 'T')) // NOT notification command
{
bufferStream.Seek(-3, SeekOrigin.End);
// calculate the length by reading backwards from the end
remainingBuffer = 0;
int size = 0;
int iter = 0;
while((size = bufferStream.ReadByte())>0 && size >= '0' && size <= '9')
{
remainingBuffer += (int)((size-'0') * Math.Pow(10, iter));
bufferStream.Seek(-2, SeekOrigin.Current);
iter++;
}
// move to the end of the stream before we are going to write
bufferStream.Seek(0, SeekOrigin.End);
if(remainingBuffer == 0)
{
// something went wrong while getting the message size
throw new DotMSNException("While parsing incoming messages from the NS session an invalid payload size was encountered");
}
}
else
{
// it was just a plain command start a new message
EnqueueCurrentBuffer();
CreateNewBuffer();
}
}
length--;
}
}
}
}
}
| |
/*
* Copyright (C) Sony Computer Entertainment America LLC.
* All Rights Reserved.
*/
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Windows.Forms;
using Sce.Atf.Adaptation;
using Sce.Atf.Applications;
using Sce.Atf.Controls;
using Sce.Atf.Dom;
using Sce.Sled.Resources;
using Sce.Sled.Shared.Controls;
using Sce.Sled.Shared.Dom;
using Sce.Sled.Shared.Plugin;
using Sce.Sled.Shared.Services;
namespace Sce.Sled
{
[Export(typeof(SledSyntaxErrorsEditor))]
[PartCreationPolicy(CreationPolicy.Shared)]
class SledSyntaxErrorsEditor : SledTreeListViewEditor
{
[ImportingConstructor]
public SledSyntaxErrorsEditor()
: base(
Localization.SledSyntaxErrorsTitle,
null,
SledSyntaxErrorType.TheColumnNames,
TreeListView.Style.List,
StandardControlGroup.Right)
{
}
#region IInitializable Interface
public override void Initialize()
{
base.Initialize();
m_projectService = SledServiceInstance.Get<ISledProjectService>();
m_projectService.Created += ProjectServiceCreated;
m_projectService.Opened += ProjectServiceOpened;
m_projectService.Closed += ProjectServiceClosed;
m_syntaxCheckerService = SledServiceInstance.Get<ISledSyntaxCheckerService>();
m_syntaxCheckerService.FilesCheckFinished += SyntaxCheckerServiceFilesCheckFinished;
MouseDoubleClick += ControlMouseDoubleClick;
}
#endregion
#region ISledSyntaxCheckerService interface
private void SyntaxCheckerServiceFilesCheckFinished(object sender, SledSyntaxCheckFilesEventArgs e)
{
try
{
View = null;
if (m_syntaxErrorsCollection == null)
return;
var fixedErrors = new List<SledSyntaxErrorType>();
var newErrors = new List<SledSyntaxCheckerEntry>();
var existingErrors = new List<SledSyntaxCheckerEntry>();
foreach (var domError in m_syntaxErrorsCollection.Errors)
{
List<SledSyntaxCheckerEntry> items;
// check if the file was syntax checked this time
if (!e.FilesAndErrors.TryGetValue(domError.File, out items))
continue;
// check if the file previously had errors but now doesn't
if (items.Count == 0)
{
fixedErrors.Add(domError);
continue;
}
// check if this error is already present on the GUI
var scee = FindCorrespondingSyntaxCheckerEntryError(domError, items);
if (scee == null)
fixedErrors.Add(domError);
else
existingErrors.Add(scee);
}
// remove errors that have been fixed
foreach (var error in fixedErrors)
m_syntaxErrorsCollection.Errors.Remove(error);
// add remaining new errors
foreach (var kv in e.FilesAndErrors)
{
foreach (var syntaxCheckerEntry in kv.Value)
{
if (existingErrors.Contains(syntaxCheckerEntry))
continue;
newErrors.Add(syntaxCheckerEntry);
}
}
// Convert items
foreach (var syntaxCheckerEntry in newErrors)
{
var domError =
new DomNode(SledSchema.SledSyntaxErrorType.Type)
.As<SledSyntaxErrorType>();
domError.File = syntaxCheckerEntry.File;
domError.Language = syntaxCheckerEntry.Language;
domError.Line = syntaxCheckerEntry.Line;
domError.Error = syntaxCheckerEntry.Error;
m_syntaxErrorsCollection.Errors.Add(domError);
}
}
finally
{
View = m_syntaxErrorsCollection;
}
}
#endregion
#region ISledProjectService Events
private void ProjectServiceCreated(object sender, SledProjectServiceProjectEventArgs e)
{
CreateSyntaxErrorsCollection();
}
private void ProjectServiceOpened(object sender, SledProjectServiceProjectEventArgs e)
{
CreateSyntaxErrorsCollection();
}
private void ProjectServiceClosed(object sender, SledProjectServiceProjectEventArgs e)
{
DestroySyntaxErrorsCollection();
}
#endregion
#region Member Methods
private void CreateSyntaxErrorsCollection()
{
var root =
new DomNode(
SledSchema.SledSyntaxErrorListType.Type,
SledSchema.SledSyntaxErrorsRootElement);
m_syntaxErrorsCollection =
root.As<SledSyntaxErrorListType>();
m_syntaxErrorsCollection.Name =
string.Format(
"{0}{1}{2}",
m_projectService.ProjectName,
Resource.Space,
Resource.SyntaxErrorsTitle);
}
private void DestroySyntaxErrorsCollection()
{
// Clear GUI
View = null;
if (m_syntaxErrorsCollection == null)
return;
m_syntaxErrorsCollection.Errors.Clear();
m_syntaxErrorsCollection = null;
}
private void ControlMouseDoubleClick(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Left)
return;
var lastHit = LastHit;
if (lastHit == null)
return;
var error = lastHit.As<SledSyntaxErrorType>();
if (error == null)
return;
if (error.File == null)
return;
if (!File.Exists(error.File.AbsolutePath))
return;
m_gotoService.Get.GotoLine(error.File.AbsolutePath, error.Line, false);
}
private static SledSyntaxCheckerEntry FindCorrespondingSyntaxCheckerEntryError(SledSyntaxErrorType domError, IEnumerable<SledSyntaxCheckerEntry> syntaxErrors)
{
foreach (var syntaxError in syntaxErrors)
{
if (domError.Language != syntaxError.Language)
continue;
if (domError.File != syntaxError.File)
continue;
if (domError.Line != syntaxError.Line)
continue;
if (string.Compare(domError.Error, syntaxError.Error) != 0)
continue;
return syntaxError;
}
return null;
}
#endregion
private SledSyntaxErrorListType m_syntaxErrorsCollection;
private ISledProjectService m_projectService;
private ISledSyntaxCheckerService m_syntaxCheckerService;
private readonly SledServiceReference<ISledGotoService> m_gotoService =
new SledServiceReference<ISledGotoService>();
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
using System.Web;
using bv.common.Configuration;
using bv.common.Diagnostics;
namespace bv.common.Core
{
public class Utils
{
public const long SEARCH_MODE_ID = -2;
/// -----------------------------------------------------------------------------
/// <summary>
/// Returns safe string representation of object.
/// </summary>
/// <param name="o"> object that should be converted to string </param>
/// <returns>
/// Returns string representation of passed object. If passed object is <b>Nothing</b> or <b>DBNull.Value</b> the
/// method returns empty string.
/// </returns>
/// <history>[Mike] 03.04.2006 Created</history>
/// -----------------------------------------------------------------------------
public static string Str(object o)
{
return Str(o, "");
}
public static string Str(object o, string defaultString)
{
if (o == null || o == DBNull.Value)
{
return defaultString;
}
return o.ToString();
}
public static double Dbl(object o)
{
if (o == null || o == DBNull.Value)
{
return 0.0;
}
try
{
return Convert.ToDouble(o);
}
catch (Exception)
{
return 0.0;
}
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Checks if the passed object represents the valid typed object.
/// </summary>
/// <param name="o"> object to check </param>
/// <returns>
/// False if passed object is <b>Nothing</b> or <b>DBNull.Value</b> or its string representation is empty string
/// and True in other case.
/// </returns>
/// <history>[Mike] 03.04.2006 Created</history>
/// -----------------------------------------------------------------------------
public static bool IsEmpty(object o)
{
if (o == null || o == DBNull.Value)
{
return true;
}
if (string.IsNullOrWhiteSpace(o.ToString()))
{
return true;
}
return false;
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Appends the default string with other separating them with some separator
/// </summary>
/// <param name="s"> default string to append </param>
/// <param name="val"> string that should be appended </param>
/// <param name="separator"> string that should separate default and appended strings </param>
/// <remarks>
/// method inserts the separator between strings only if default string is not empty.
/// </remarks>
/// <history>[Mike] 03.04.2006 Created</history>
/// -----------------------------------------------------------------------------
public static void AppendLine(ref string s, object val, string separator)
{
if (val == DBNull.Value || val.ToString().Trim().Length == 0)
{
return;
}
if (s.Length == 0)
{
s += val.ToString();
}
else
{
s += separator + val;
}
}
public static string InsertSeparator(string separator, object val)
{
if (IsEmpty(val))
{
return string.Empty;
}
if (string.IsNullOrEmpty(separator))
{
return separator;
}
return string.Concat(separator, val.ToString());
}
public static string Join(string separator, IEnumerable collection)
{
var result = new StringBuilder();
object item;
foreach (object tempLoopVarItem in collection)
{
item = tempLoopVarItem;
if (item == null || string.IsNullOrWhiteSpace(item.ToString()))
{
continue;
}
if (result.Length > 0)
{
result.Append(separator);
}
result.Append(item.ToString());
}
return result.ToString();
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Checks if directory exists and creates it if it is absent
/// </summary>
/// <param name="dir"> directory to check </param>
/// <returns>
/// Returns <b>True</b> if requested directory exists or was created successfully and <b>False</b> if requested
/// directory can't be created
/// </returns>
/// <history>[Mike] 03.04.2006 Created</history>
/// -----------------------------------------------------------------------------
public static bool ForceDirectories(string dir)
{
int pos = 0;
try
{
do
{
pos = dir.IndexOf(Path.DirectorySeparatorChar, pos);
if (pos < 0)
{
break;
}
string dirName = dir.Substring(0, pos);
if (!Directory.Exists(dirName))
{
Directory.CreateDirectory(dirName);
}
pos++;
} while (true);
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
return Directory.Exists(dir);
}
catch
{
return false;
}
}
public static Bitmap LoadBitmapFromResource(string resName, Type aType)
{
//open the executing assembly
Assembly oAssembly = Assembly.GetAssembly(aType);
//create stream for image (icon) in assembly
Stream oStream = oAssembly.GetManifestResourceStream(resName);
//create new bitmap from stream
if (oStream != null)
{
var oBitmap = (Bitmap) (Image.FromStream(oStream));
return oBitmap;
}
return null;
}
public static bool IsGuid(object g)
{
string s = Str(g);
if (s.Length != 36)
{
return false;
}
try
{
new Guid(s);
return true;
}
catch (Exception)
{
return false;
}
}
/*
public static bool IsEIDSS
{
get
{
return (ApplicationContext.ApplicationName.ToLowerInvariant() == "eidss");
}
}
public static bool IsPACS
{
get
{
return (ApplicationContext.ApplicationName.ToLowerInvariant() == "pacs_main");
}
}
*/
public static T CheckNotNull<T>(T param, string paramName)
{
if (ReferenceEquals(param, null))
{
throw (new ArgumentNullException(paramName));
}
return param;
}
public static string CheckNotNullOrEmpty(string param, string paramName)
{
if (CheckNotNull(param, paramName) == string.Empty)
{
throw (new ArgumentException(paramName + " cannot be empty string"));
}
return param;
}
public static string GetParentDirectoryPath(string dirName)
{
string appLocation = GetExecutingPath();
dirName = dirName.ToLowerInvariant();
var dir = new DirectoryInfo(Path.GetDirectoryName(appLocation));
while (dir != null && dir.Name.ToLowerInvariant() != dirName)
{
foreach (DirectoryInfo subDir in dir.GetDirectories())
{
if (subDir.Name.ToLower(CultureInfo.InvariantCulture) == dirName)
{
return subDir.FullName + "\\";
}
}
dir = dir.Parent;
}
if (dir != null)
{
return string.Format("{0}\\", dir.FullName);
}
return null;
}
//It is assumed that assembly is placed in the project that is located in solution directory;
public static string GetSolutionPath()
{
string binPath = GetParentDirectoryPath("bin");
var dir = new DirectoryInfo(Path.GetDirectoryName(binPath));
return string.Format("{0}\\", dir.Parent.Parent.FullName);
}
public static string GetDesktopExecutingPath()
{
DirectoryInfo appDir;
Assembly asm = Assembly.GetExecutingAssembly();
if (!asm.GetName().Name.StartsWith("nunit"))
{
appDir = new DirectoryInfo(Path.GetDirectoryName(GetAssemblyLocation(asm)));
return string.Format("{0}\\", appDir.FullName);
}
asm = Assembly.GetCallingAssembly();
appDir = new DirectoryInfo(Path.GetDirectoryName(GetAssemblyLocation(asm)));
return string.Format("{0}\\", appDir.FullName);
}
public static string GetExecutingPath()
{
DirectoryInfo appDir;
if (HttpContext.Current != null)
{
try
{
appDir = new DirectoryInfo(HttpContext.Current.Request.PhysicalApplicationPath);
if (Directory.Exists(appDir.FullName))
{
return string.Format("{0}", appDir.FullName);
}
}
catch
{
}
}
return GetDesktopExecutingPath();
}
public static string GetExecutingPathBin()
{
DirectoryInfo appDir;
if (HttpContext.Current != null)
{
try
{
appDir = new DirectoryInfo(HttpContext.Current.Request.PhysicalApplicationPath);
if (Directory.Exists(appDir.FullName))
{
return string.Format("{0}\\bin\\", appDir.FullName);
}
}
catch
{
}
}
return GetDesktopExecutingPath();
}
public static string GetAssemblyLocation(Assembly asm)
{
if (asm.CodeBase.StartsWith("file:///"))
{
return asm.CodeBase.Substring(8).Replace("/", "\\");
}
return asm.Location;
}
public static string GetFilePathNearAssembly(Assembly asm, string fileName)
{
string location = ConvertFileName(asm.Location);
string locationFileName = string.Format(@"{0}\{1}", Path.GetDirectoryName(location), fileName);
if (File.Exists(locationFileName))
{
return locationFileName;
}
string codeBase = ConvertFileName(asm.CodeBase);
string codeBaseFileName = string.Format(@"{0}\{1}", Path.GetDirectoryName(codeBase), fileName);
if (File.Exists(codeBaseFileName))
{
return codeBaseFileName;
}
throw new FileNotFoundException(
string.Format("Could not find file placed neither {0} nor {1}", locationFileName, codeBaseFileName), fileName);
}
public static string ConvertFileName(string fileName)
{
if (fileName.StartsWith("file:///"))
{
return fileName.Substring(8).Replace("/", "\\");
}
return fileName;
}
public static string GetConfigFileName()
{
if (HttpContext.Current != null)
{
return "Web.config";
}
Assembly asm = Assembly.GetEntryAssembly();
if (asm != null)
{
return Path.GetFileName(asm.Location) + ".config";
}
return "";
}
public static long? ToNullableLong(object val)
{
if (IsEmpty(val))
{
return null;
}
long res;
if (long.TryParse(val.ToString(), out res))
return res;
return null;
}
public static int? ToNullableInt(object val)
{
if (IsEmpty(val))
{
return null;
}
int res;
if (int.TryParse(val.ToString(), out res))
return res;
return null;
}
public static bool IsCalledFromUnitTest()
{
var stack = new StackTrace();
int frameCount = stack.FrameCount - 1;
for (int frame = 0; frame <= frameCount; frame++)
{
StackFrame stackFrame = stack.GetFrame(frame);
if (stackFrame != null)
{
MethodBase method = stackFrame.GetMethod();
if (method != null)
{
string moduleName = method.Module.Name;
if (moduleName.Contains("tests"))
{
return true;
}
}
}
}
return false;
}
private static string GetAssemblyCodeBaseLocation(Assembly asm)
{
if (asm.CodeBase.StartsWith("file:///"))
{
return asm.CodeBase.Substring(8).Replace("/", "\\");
}
return asm.Location;
}
public static string GetExecutingAssembly()
{
string app;
if (HttpContext.Current != null)
{
return HttpContext.Current.Request.PhysicalApplicationPath;
}
Assembly asm = Assembly.GetEntryAssembly();
if (asm == null)
{
asm = Assembly.GetExecutingAssembly();
}
if (!asm.GetName().Name.StartsWith("nunit"))
{
app = GetAssemblyCodeBaseLocation(asm);
if (app != null)
{
return app;
}
}
asm = Assembly.GetCallingAssembly();
app = GetAssemblyCodeBaseLocation(asm);
if (app != null)
{
return app;
}
return null;
}
public static object ToDbValue(object val)
{
if (val == null)
{
return DBNull.Value;
}
return val;
}
public static long ToLong(object o, long defValue = 0)
{
if (o == null || o == DBNull.Value)
{
return defValue;
}
try
{
return Convert.ToInt64(o);
}
catch (Exception)
{
return defValue;
}
}
public static int ToInt(object o, int defValue = 0)
{
if (o == null || o == DBNull.Value)
{
return defValue;
}
try
{
return Convert.ToInt32(o);
}
catch (Exception)
{
return defValue;
}
}
public static string GetCurrentMethodName()
{
return GetMethodName(2);
}
public static string GetPreviousMethodName()
{
return GetMethodName(3);
}
private static string GetMethodName(int index)
{
var stackTrace = new StackTrace();
StackFrame stackFrame = stackTrace.GetFrame(index);
string name = stackFrame != null
? stackFrame.GetMethod().Name
: "CANNOT_GET_METHOD_NAME";
return name;
}
public static object SafeDate(object date)
{
return IsEmpty(date) ? "..." : date;
}
public static DateTime? ToDateNullable(string date)
{
if(IsEmpty(date))
return null;
DateTime res;
if (DateTime.TryParse(date, out res))
return res;
return null;
}
public static List<string> m_UsedResources = new List<string>();
public static void CollectUsedResource(string key)
{
if (BaseSettings.CollectUsedXtraResources && !m_UsedResources.Contains(key))
m_UsedResources.Add(key);
}
public static void SaveUsedXtraResource()
{
if (!BaseSettings.CollectUsedXtraResources)
return;
try
{
string fileName = Utils.GetExecutingPath() + "UsedXtraResources.txt";
if (HttpContext.Current != null)
{
fileName = HttpContext.Current.Server.MapPath("~/App_Data/UsedXtraResources.txt");
}
string[] existingKeys = null;
if (File.Exists(fileName))
existingKeys = File.ReadAllLines(fileName);
if (existingKeys != null)
foreach (var key in existingKeys)
{
if (!m_UsedResources.Contains(key))
m_UsedResources.Add(key);
}
if (!File.Exists(fileName))
{
var f = File.Create(fileName);
f.Close();
}
FileAttributes attr = File.GetAttributes(fileName);
if ((attr & FileAttributes.ReadOnly) != 0)
{
attr = attr & ~FileAttributes.ReadOnly;
File.SetAttributes(fileName, attr);
}
var file = new StreamWriter(fileName);
m_UsedResources.Sort();
foreach (var key in m_UsedResources)
{
file.WriteLine(key);
}
file.Flush();
file.Close();
}
catch (Exception e)
{
Dbg.WriteLine("error during writing used xtra resources:{0}", e);
}
}
}
}
| |
using System;
using System.IO.Ports;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
// FonaDevice implementation for NETMF
namespace Molarity.Hardare.AdafruitFona
{
/// <summary>
/// A delegate for handling notifications of a change in the power state of the Fona board.
/// </summary>
/// <param name="sender">The FonaDevice class that is sending this notification</param>
/// <param name="args">The arguments describing the new power state.</param>
public delegate void PowerStateEventHandler(object sender, PowerStateEventArgs args);
public partial class FonaDevice
{
private bool _fSuppressPowerStateDetection = false;
private OutputPort _onOffKeyPin;
/// <summary>
/// An output port that is connected to the Key pin on the Fona board.
/// </summary>
public OutputPort OnOffKeyPin
{
get { return _onOffKeyPin; }
set { _onOffKeyPin = value; }
}
/// <summary>
/// The current power state of the Fona device. True if it is powered on. False otherwise.
/// You must provide a value for PowerStatePin to detect the power state. You must provide
/// a value for both PowerStatePin and OnOffKeyPin to change the power state of the Fona device.
/// </summary>
public bool PowerState
{
get
{
if (PowerStatePin==null)
throw new InvalidOperationException("You cannot detect the power state if you have not provided a value for PowerStatePin");
return this.PowerStatePin.Read();
}
set
{
if (PowerStatePin == null)
throw new InvalidOperationException("You cannot change the power state if you have not provided a value for PowerStatePin");
if (this.OnOffKeyPin == null)
throw new InvalidOperationException("You cannot change the power state if you have not provided a value for the OnOffKeyPin");
if (value)
{
// Turn the fona on
if (this.PowerState)
return; // We are already on
TogglePowerState();
}
else
{
// Turn the Fona off
if (!this.PowerState)
return; // We are already off
TogglePowerState();
}
}
}
private void TogglePowerState()
{
if (this.OnOffKeyPin == null)
throw new InvalidOperationException("You cannot change the power state if you have not provided a value for the OnOffKeyPin");
this.OnOffKeyPin.Write(false);
Thread.Sleep(2000);
this.OnOffKeyPin.Write(true);
}
private OutputPort _resetPin;
/// <summary>
/// An output port that can be used to force a hardware reset of the Fona device.
/// This port should be connected to the RST pin on the Fona board.
/// You do not have to provide a value for the reset pin, although the Reset member
/// of this class will be less able to restore the board to a working state without
/// a value for the reset pin.
/// </summary>
public OutputPort ResetPin
{
get { return _resetPin; }
set
{
_resetPin = value;
_resetPin.Write(true);
}
}
private InterruptPort _ringIndicatorPin;
/// <summary>
/// This pin will be used for hardware-level detection of incoming calls and texts.
/// The FonaDevice class can still detect incoming calls without this pin, but it
/// does so by detecting the string "RING" sent by the board, which is less reliable
/// and may result in multiple notifications for a single incoming call.
/// Using the hardware pin is more accurate than depending on detection of the RING string.
/// This port should be connected to the RI port on the Fona board.
/// This port should be configured with InterruptEdgeLow.
/// </summary>
public InterruptPort RingIndicatorPin
{
get { return _ringIndicatorPin; }
set
{
if (_ringIndicatorPin != null)
{
_ringIndicatorPin.OnInterrupt -= RingIndicatorPinOnInterrupt;
}
_ringIndicatorPin = value;
if (_ringIndicatorPin != null)
{
_ringIndicatorPin.OnInterrupt += RingIndicatorPinOnInterrupt;
_ringIndicatorPin.EnableInterrupt();
}
}
}
private void RingIndicatorPinOnInterrupt(uint data1, uint data2, DateTime time)
{
if (this.PowerStatePin != null)
{
if (!this.PowerStatePin.Read())
{
// The phone cannot be ringing if the power is off, and this pin will
// transition low during power-down.
return;
}
}
if (this.Ringing != null)
{
Ringing(this, new RingingEventArgs(time));
}
}
private bool HardwareRingIndicationEnabled
{
get { return this.RingIndicatorPin != null; }
}
private InputPort _powerStatePin;
/// <summary>
/// This pin is used to detect the current power state of the Fona board.
/// You do not have to provide a value for this pin, but you will not be
/// able to detect or control the power state of the Fona device without it.
/// This pin works together with the OnOffKeyPin to control the power state
/// of the Fona board. The PoweStatePin detects the power state and the OnOffKeyPin
/// is used to change the power state. The pin should be configured with InterruptEdgeBoth.
/// </summary>
public InputPort PowerStatePin
{
get { return _powerStatePin; }
set
{
if (_powerStatePin != null)
{
_powerStatePin.OnInterrupt -= PowerStatePinOnInterrupt;
}
_powerStatePin = value;
if (_powerStatePin != null)
{
_powerStatePin.OnInterrupt += PowerStatePinOnInterrupt;
_powerStatePin.EnableInterrupt();
}
}
}
/// <summary>
/// This event is raised when the current power state of the Fona board changes.
/// If the board is turned on or off either via the 'Key' button on the Fona board
/// or via the OnOffKeyPin, this event will be raised to indicate the change of
/// power state.
/// </summary>
public event PowerStateEventHandler PowerStateChanged;
private void PowerStatePinOnInterrupt(uint data1, uint data2, DateTime time)
{
// The power state will change briefly during a hardware reset
if (_fSuppressPowerStateDetection)
return;
if (this.PowerStateChanged!=null)
{
PowerStateChanged(this, new PowerStateEventArgs(time, data2 != 0));
}
}
private void DoHardwareReset()
{
if (ResetPin != null)
{
try
{
_fSuppressPowerStateDetection = true;
// Drive reset pin low for 100ms.
// Initial 10ms delay is to ensure that the device is ready to be reset as it may not be, right after startup.
Thread.Sleep(10);
ResetPin.Write(false);
Thread.Sleep(100);
ResetPin.Write(true);
// Wait 3s for a reboot
Thread.Sleep(3000);
}
finally
{
_fSuppressPowerStateDetection = false;
}
}
}
}
}
| |
// Generated by UblXml2CSharp
using System.Xml;
using UblLarsen.Ubl2;
using UblLarsen.Ubl2.Cac;
using UblLarsen.Ubl2.Ext;
using UblLarsen.Ubl2.Udt;
namespace UblLarsen.Test.UblClass
{
internal class UBLRequestForQuotation20Example
{
public static RequestForQuotationType Create()
{
var doc = new RequestForQuotationType
{
UBLVersionID = "2.0",
CustomizationID = "urn:oasis:names:specification:ubl:xpath:RequestForQuotation-2.0:sbs-1.0-draft",
ProfileID = "bpid:urn:oasis:names:draft:bpss:ubl-2-sbs-request-for-quotation-draft",
ID = "G867B",
CopyIndicator = false,
UUID = "8D076867-AE6D-439F-8281-5AAFC7F4E3B1",
IssueDate = "2005-06-19",
IssueTime = "11:32:26.0Z",
Note = new TextType[]
{
new TextType
{
Value = "sample"
}
},
CatalogueDocumentReference = new DocumentReferenceType
{
ID = "2005-9A",
IssueDate = "2005-11-03"
},
OriginatorCustomerParty = new CustomerPartyType
{
Party = new PartyType
{
PartyName = new PartyNameType[]
{
new PartyNameType
{
Name = "The Terminus"
}
},
PostalAddress = new AddressType
{
StreetName = "Avon Way",
BuildingName = "Thereabouts",
BuildingNumber = "56A",
CityName = "Bridgtow",
PostalZone = "ZZ99 1ZZ",
CountrySubentity = "Avon",
AddressLine = new AddressLineType[]
{
new AddressLineType
{
Line = "3rd Floor, Room 5"
}
},
Country = new CountryType
{
IdentificationCode = "GB"
}
},
PartyTaxScheme = new PartyTaxSchemeType[]
{
new PartyTaxSchemeType
{
RegistrationName = "Bridgtow District Council",
CompanyID = "12356478",
ExemptionReason = new TextType[]
{
new TextType
{
Value = "Local Authority"
}
},
TaxScheme = new TaxSchemeType
{
ID = "UK VAT",
TaxTypeCode = "VAT"
}
}
},
Contact = new ContactType
{
Name = "S Massiah",
Telephone = "0127 98876545",
Telefax = "0127 98876546",
ElectronicMail = "[email protected]"
}
}
},
SellerSupplierParty = new SupplierPartyType
{
CustomerAssignedAccountID = "CO001",
Party = new PartyType
{
PartyName = new PartyNameType[]
{
new PartyNameType
{
Name = "Consortial"
}
},
PostalAddress = new AddressType
{
StreetName = "Busy Street",
BuildingName = "Thereabouts",
BuildingNumber = "56A",
CityName = "Farthing",
PostalZone = "AA99 1BB",
CountrySubentity = "Heremouthshire",
AddressLine = new AddressLineType[]
{
new AddressLineType
{
Line = "The Roundabout"
}
},
Country = new CountryType
{
IdentificationCode = "GB"
}
},
PartyTaxScheme = new PartyTaxSchemeType[]
{
new PartyTaxSchemeType
{
RegistrationName = "Farthing Purchasing Consortium",
CompanyID = "175 269 2355",
ExemptionReason = new TextType[]
{
new TextType
{
Value = "N/A"
}
},
TaxScheme = new TaxSchemeType
{
ID = "VAT",
TaxTypeCode = "VAT"
}
}
},
Contact = new ContactType
{
Name = "Mrs Bouquet",
Telephone = "0158 1233714",
Telefax = "0158 1233856",
ElectronicMail = "[email protected]"
}
}
},
Delivery = new DeliveryType[]
{
new DeliveryType
{
DeliveryAddress = new AddressType
{
StreetName = "Avon Way",
BuildingName = "Thereabouts",
BuildingNumber = "56A",
CityName = "Bridgtow",
PostalZone = "ZZ99 1ZZ",
CountrySubentity = "Avon",
AddressLine = new AddressLineType[]
{
new AddressLineType
{
Line = "3rd Floor, Room 5"
}
},
Country = new CountryType
{
IdentificationCode = "GB"
}
},
RequestedDeliveryPeriod = new PeriodType
{
StartDate = "2005-06-29",
StartTime = "09:30:47.0Z",
EndDate = "2005-06-29",
EndTime = "09:30:47.0Z"
}
}
},
DeliveryTerms = new DeliveryTermsType[]
{
new DeliveryTermsType
{
SpecialTerms = new TextType[]
{
new TextType
{
Value = "1% deduction for late delivery as per contract"
}
}
}
},
DestinationCountry = new CountryType
{
IdentificationCode = "GB",
Name = "Great Britain"
},
Contract = new ContractType[]
{
new ContractType
{
ContractDocumentReference = new DocumentReferenceType[]
{
new DocumentReferenceType
{
ID = "GHJ76849",
IssueDate = "2002-08-13"
}
}
}
},
RequestForQuotationLine = new RequestForQuotationLineType[]
{
new RequestForQuotationLineType
{
ID = "1",
Note = new TextType[]
{
new TextType
{
Value = "sample"
}
},
LineItem = new LineItemType
{
ID = "1",
Quantity = new QuantityType
{
unitCode = "KGM",
Value = 100M
},
Item = new ItemType
{
Description = new TextType[]
{
new TextType
{
Value = "Acme beeswax"
}
},
Name = "beeswax",
BuyersItemIdentification = new ItemIdentificationType
{
ID = "6578489"
},
SellersItemIdentification = new ItemIdentificationType
{
ID = "17589683"
}
}
}
}
}
};
doc.Xmlns = new System.Xml.Serialization.XmlSerializerNamespaces(new[]
{
new XmlQualifiedName("cac","urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2"),
new XmlQualifiedName("cbc","urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2"),
});
return doc;
}
}
}
| |
//
// Copyright (c) 2014 .NET Foundation
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
// Copyright (c) 2014 Couchbase, 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 System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using Apache.Http;
using Apache.Http.Client;
using Apache.Http.Client.Methods;
using Apache.Http.Conn;
using Apache.Http.Entity;
using Apache.Http.Impl;
using Apache.Http.Message;
using Apache.Http.Params;
using Apache.Http.Protocol;
using Couchbase.Lite;
using Couchbase.Lite.Replicator;
using Couchbase.Lite.Util;
using Sharpen;
namespace Couchbase.Lite.Replicator
{
public class CustomizableMockHttpClient : HttpClient
{
private IDictionary<string, CustomizableMockHttpClient.Responder> responders;
private IList<HttpWebRequest> capturedRequests = new CopyOnWriteArrayList<HttpWebRequest
>();
private long responseDelayMilliseconds;
private int numberOfEntityConsumeCallbacks;
private IList<CustomizableMockHttpClient.ResponseListener> responseListeners;
public CustomizableMockHttpClient()
{
// tests can register custom responders per url. the key is the URL pattern to match,
// the value is the responder that should handle that request.
// capture all request so that the test can verify expected requests were received.
// if this is set, it will delay responses by this number of milliseconds
// track the number of times consumeContent is called on HttpEntity returned in response (detect resource leaks)
// users of this class can subscribe to activity by adding themselves as a response listener
responders = new Dictionary<string, CustomizableMockHttpClient.Responder>();
responseListeners = new AList<CustomizableMockHttpClient.ResponseListener>();
AddDefaultResponders();
}
public virtual void SetResponder(string urlPattern, CustomizableMockHttpClient.Responder
responder)
{
responders.Put(urlPattern, responder);
}
public virtual void AddResponseListener(CustomizableMockHttpClient.ResponseListener
listener)
{
responseListeners.AddItem(listener);
}
public virtual void RemoveResponseListener(CustomizableMockHttpClient.ResponseListener
listener)
{
responseListeners.Remove(listener);
}
public virtual void SetResponseDelayMilliseconds(long responseDelayMilliseconds)
{
this.responseDelayMilliseconds = responseDelayMilliseconds;
}
public virtual void AddDefaultResponders()
{
AddResponderRevDiffsAllMissing();
AddResponderFakeBulkDocs();
AddResponderFakeLocalDocumentUpdateIOException();
}
public virtual void AddResponderFailAllRequests(int statusCode)
{
SetResponder("*", new _Responder_84(statusCode));
}
private sealed class _Responder_84 : CustomizableMockHttpClient.Responder
{
public _Responder_84(int statusCode)
{
this.statusCode = statusCode;
}
/// <exception cref="System.IO.IOException"></exception>
public HttpResponse Execute(HttpRequestMessage httpUriRequest)
{
return Couchbase.Lite.Replicator.CustomizableMockHttpClient.EmptyResponseWithStatusCode
(statusCode);
}
private readonly int statusCode;
}
public virtual void AddResponderThrowExceptionAllRequests()
{
SetResponder("*", new _Responder_93());
}
private sealed class _Responder_93 : CustomizableMockHttpClient.Responder
{
public _Responder_93()
{
}
/// <exception cref="System.IO.IOException"></exception>
public HttpResponse Execute(HttpRequestMessage httpUriRequest)
{
throw new IOException("Test IOException");
}
}
public virtual void AddResponderFakeLocalDocumentUpdate401()
{
responders.Put("_local", GetFakeLocalDocumentUpdate401());
}
public virtual CustomizableMockHttpClient.Responder GetFakeLocalDocumentUpdate401
()
{
return new _Responder_106();
}
private sealed class _Responder_106 : CustomizableMockHttpClient.Responder
{
public _Responder_106()
{
}
/// <exception cref="System.IO.IOException"></exception>
public HttpResponse Execute(HttpRequestMessage httpUriRequest)
{
string json = "{\"error\":\"Unauthorized\",\"reason\":\"Login required\"}";
return Couchbase.Lite.Replicator.CustomizableMockHttpClient.GenerateHttpResponseObject
(401, "Unauthorized", json);
}
}
public virtual void AddResponderFakeLocalDocumentUpdate404()
{
responders.Put("_local", GetFakeLocalDocumentUpdate404());
}
public virtual CustomizableMockHttpClient.Responder GetFakeLocalDocumentUpdate404
()
{
return new _Responder_120();
}
private sealed class _Responder_120 : CustomizableMockHttpClient.Responder
{
public _Responder_120()
{
}
/// <exception cref="System.IO.IOException"></exception>
public HttpResponse Execute(HttpRequestMessage httpUriRequest)
{
string json = "{\"error\":\"not_found\",\"reason\":\"missing\"}";
return Couchbase.Lite.Replicator.CustomizableMockHttpClient.GenerateHttpResponseObject
(404, "NOT FOUND", json);
}
}
public virtual void AddResponderFakeLocalDocumentUpdateIOException()
{
responders.Put("_local", new _Responder_130());
}
private sealed class _Responder_130 : CustomizableMockHttpClient.Responder
{
public _Responder_130()
{
}
/// <exception cref="System.IO.IOException"></exception>
public HttpResponse Execute(HttpRequestMessage httpUriRequest)
{
return Couchbase.Lite.Replicator.CustomizableMockHttpClient.FakeLocalDocumentUpdateIOException
(httpUriRequest);
}
}
public virtual void AddResponderFakeBulkDocs()
{
responders.Put("_bulk_docs", FakeBulkDocsResponder());
}
public static CustomizableMockHttpClient.Responder FakeBulkDocsResponder()
{
return new _Responder_143();
}
private sealed class _Responder_143 : CustomizableMockHttpClient.Responder
{
public _Responder_143()
{
}
/// <exception cref="System.IO.IOException"></exception>
public HttpResponse Execute(HttpRequestMessage httpUriRequest)
{
return Couchbase.Lite.Replicator.CustomizableMockHttpClient.FakeBulkDocs(httpUriRequest
);
}
}
public static CustomizableMockHttpClient.Responder TransientErrorResponder(int statusCode
, string statusMsg)
{
return new _Responder_152(statusCode, statusMsg);
}
private sealed class _Responder_152 : CustomizableMockHttpClient.Responder
{
public _Responder_152(int statusCode, string statusMsg)
{
this.statusCode = statusCode;
this.statusMsg = statusMsg;
}
/// <exception cref="System.IO.IOException"></exception>
public HttpResponse Execute(HttpRequestMessage httpUriRequest)
{
if (statusCode == -1)
{
throw new IOException("Fake IO Exception from transientErrorResponder");
}
else
{
return Couchbase.Lite.Replicator.CustomizableMockHttpClient.GenerateHttpResponseObject
(statusCode, statusMsg, null);
}
}
private readonly int statusCode;
private readonly string statusMsg;
}
public virtual void AddResponderRevDiffsAllMissing()
{
responders.Put("_revs_diff", new _Responder_166());
}
private sealed class _Responder_166 : CustomizableMockHttpClient.Responder
{
public _Responder_166()
{
}
/// <exception cref="System.IO.IOException"></exception>
public HttpResponse Execute(HttpRequestMessage httpUriRequest)
{
return Couchbase.Lite.Replicator.CustomizableMockHttpClient.FakeRevsDiff(httpUriRequest
);
}
}
public virtual void AddResponderRevDiffsSmartResponder()
{
CustomizableMockHttpClient.SmartRevsDiffResponder smartRevsDiffResponder = new CustomizableMockHttpClient.SmartRevsDiffResponder
();
this.AddResponseListener(smartRevsDiffResponder);
responders.Put("_revs_diff", smartRevsDiffResponder);
}
public virtual void AddResponderReturnInvalidChangesFeedJson()
{
SetResponder("_changes", new _Responder_183());
}
private sealed class _Responder_183 : CustomizableMockHttpClient.Responder
{
public _Responder_183()
{
}
/// <exception cref="System.IO.IOException"></exception>
public HttpResponse Execute(HttpRequestMessage httpUriRequest)
{
string json = "{\"results\":[";
return Couchbase.Lite.Replicator.CustomizableMockHttpClient.GenerateHttpResponseObject
(json);
}
}
public virtual void ClearResponders()
{
responders = new Dictionary<string, CustomizableMockHttpClient.Responder>();
}
public virtual void AddResponderReturnEmptyChangesFeed()
{
SetResponder("_changes", new _Responder_197());
}
private sealed class _Responder_197 : CustomizableMockHttpClient.Responder
{
public _Responder_197()
{
}
/// <exception cref="System.IO.IOException"></exception>
public HttpResponse Execute(HttpRequestMessage httpUriRequest)
{
string json = "{\"results\":[]}";
return Couchbase.Lite.Replicator.CustomizableMockHttpClient.GenerateHttpResponseObject
(json);
}
}
public virtual IList<HttpWebRequest> GetCapturedRequests()
{
return capturedRequests;
}
public virtual void ClearCapturedRequests()
{
capturedRequests.Clear();
}
public virtual void RecordEntityConsumeCallback()
{
numberOfEntityConsumeCallbacks += 1;
}
public virtual int GetNumberOfEntityConsumeCallbacks()
{
return numberOfEntityConsumeCallbacks;
}
public virtual HttpParams GetParams()
{
return null;
}
public virtual ClientConnectionManager GetConnectionManager()
{
return null;
}
/// <exception cref="System.IO.IOException"></exception>
public virtual HttpResponse Execute(HttpRequestMessage httpUriRequest)
{
DelayResponseIfNeeded();
Log.D(Database.Tag, "execute() called with request: " + httpUriRequest.GetURI().GetPath
());
capturedRequests.AddItem(httpUriRequest);
foreach (string urlPattern in responders.Keys)
{
if (urlPattern.Equals("*") || httpUriRequest.GetURI().GetPath().Contains(urlPattern
))
{
CustomizableMockHttpClient.Responder responder = responders.Get(urlPattern);
HttpResponse response = responder.Execute(httpUriRequest);
NotifyResponseListeners(httpUriRequest, response);
return response;
}
}
throw new RuntimeException("No responders matched for url pattern: " + httpUriRequest
.GetURI().GetPath());
}
/// <exception cref="System.IO.IOException"></exception>
/// <exception cref="Apache.Http.Client.ClientProtocolException"></exception>
public static HttpResponse FakeLocalDocumentUpdateIOException(HttpRequestMessage
httpUriRequest)
{
throw new IOException("Throw exception on purpose for purposes of testSaveRemoteCheckpointNoResponse()"
);
}
/// <exception cref="System.IO.IOException"></exception>
/// <exception cref="Apache.Http.Client.ClientProtocolException"></exception>
public static HttpResponse FakeBulkDocs(HttpRequestMessage httpUriRequest)
{
Log.D(Database.Tag, "fakeBulkDocs() called");
IDictionary<string, object> jsonMap = GetJsonMapFromRequest((HttpPost)httpUriRequest
);
IList<IDictionary<string, object>> responseList = new AList<IDictionary<string, object
>>();
AList<IDictionary<string, object>> docs = (ArrayList)jsonMap.Get("docs");
foreach (IDictionary<string, object> doc in docs)
{
IDictionary<string, object> responseListItem = new Dictionary<string, object>();
responseListItem.Put("id", doc.Get("_id"));
responseListItem.Put("rev", doc.Get("_rev"));
Log.D(Database.Tag, "id: " + doc.Get("_id"));
Log.D(Database.Tag, "rev: " + doc.Get("_rev"));
responseList.AddItem(responseListItem);
}
HttpResponse response = GenerateHttpResponseObject(responseList);
return response;
}
/// <exception cref="System.IO.IOException"></exception>
public static HttpResponse FakeRevsDiff(HttpRequestMessage httpUriRequest)
{
IDictionary<string, object> jsonMap = GetJsonMapFromRequest((HttpPost)httpUriRequest
);
IDictionary<string, object> responseMap = new Dictionary<string, object>();
foreach (string key in jsonMap.Keys)
{
ArrayList value = (ArrayList)jsonMap.Get(key);
IDictionary<string, object> missingMap = new Dictionary<string, object>();
missingMap.Put("missing", value);
responseMap.Put(key, missingMap);
}
HttpResponse response = GenerateHttpResponseObject(responseMap);
return response;
}
/// <exception cref="System.IO.IOException"></exception>
public static HttpResponse GenerateHttpResponseObject(object o)
{
DefaultHttpResponseFactory responseFactory = new DefaultHttpResponseFactory();
BasicStatusLine statusLine = new BasicStatusLine(HttpVersion.Http11, 200, "OK");
HttpResponse response = responseFactory.NewHttpResponse(statusLine, null);
byte[] responseBytes = Manager.GetObjectMapper().WriteValueAsBytes(o);
response.SetEntity(new ByteArrayEntity(responseBytes));
return response;
}
/// <exception cref="System.IO.IOException"></exception>
public static HttpResponse GenerateHttpResponseObject(string responseJson)
{
return GenerateHttpResponseObject(200, "OK", responseJson);
}
/// <exception cref="System.IO.IOException"></exception>
public static HttpResponse GenerateHttpResponseObject(int statusCode, string statusString
, string responseJson)
{
DefaultHttpResponseFactory responseFactory = new DefaultHttpResponseFactory();
BasicStatusLine statusLine = new BasicStatusLine(HttpVersion.Http11, statusCode,
statusString);
HttpResponse response = responseFactory.NewHttpResponse(statusLine, null);
if (responseJson != null)
{
byte[] responseBytes = Sharpen.Runtime.GetBytesForString(responseJson);
response.SetEntity(new ByteArrayEntity(responseBytes));
}
return response;
}
/// <exception cref="System.IO.IOException"></exception>
public static HttpResponse GenerateHttpResponseObject(HttpEntity responseEntity)
{
DefaultHttpResponseFactory responseFactory = new DefaultHttpResponseFactory();
BasicStatusLine statusLine = new BasicStatusLine(HttpVersion.Http11, 200, "OK");
HttpResponse response = responseFactory.NewHttpResponse(statusLine, null);
response.SetEntity(responseEntity);
return response;
}
public static HttpResponse EmptyResponseWithStatusCode(int statusCode)
{
DefaultHttpResponseFactory responseFactory = new DefaultHttpResponseFactory();
BasicStatusLine statusLine = new BasicStatusLine(HttpVersion.Http11, statusCode,
string.Empty);
HttpResponse response = responseFactory.NewHttpResponse(statusLine, null);
return response;
}
/// <exception cref="System.IO.IOException"></exception>
public static IDictionary<string, object> GetJsonMapFromRequest(HttpPost httpUriRequest
)
{
HttpPost post = (HttpPost)httpUriRequest;
InputStream @is = post.GetEntity().GetContent();
return Manager.GetObjectMapper().ReadValue<IDictionary>(@is);
}
private void DelayResponseIfNeeded()
{
if (responseDelayMilliseconds > 0)
{
try
{
Sharpen.Thread.Sleep(responseDelayMilliseconds);
}
catch (Exception e)
{
Sharpen.Runtime.PrintStackTrace(e);
}
}
}
private void NotifyResponseListeners(HttpRequestMessage httpUriRequest, HttpResponse
response)
{
foreach (CustomizableMockHttpClient.ResponseListener listener in responseListeners)
{
listener.ResponseSent(httpUriRequest, response);
}
}
/// <exception cref="System.IO.IOException"></exception>
public virtual HttpResponse Execute(HttpRequestMessage httpUriRequest, HttpContext
httpContext)
{
throw new RuntimeException("Mock Http Client does not know how to handle this request. It should be fixed"
);
}
/// <exception cref="System.IO.IOException"></exception>
public virtual HttpResponse Execute(HttpHost httpHost, HttpWebRequest httpRequest
)
{
throw new RuntimeException("Mock Http Client does not know how to handle this request. It should be fixed"
);
}
/// <exception cref="System.IO.IOException"></exception>
public virtual HttpResponse Execute(HttpHost httpHost, HttpWebRequest httpRequest
, HttpContext httpContext)
{
throw new RuntimeException("Mock Http Client does not know how to handle this request. It should be fixed"
);
}
/// <exception cref="System.IO.IOException"></exception>
public virtual T Execute<T, _T1>(HttpRequestMessage httpUriRequest, ResponseHandler
<_T1> responseHandler) where _T1:T
{
throw new RuntimeException("Mock Http Client does not know how to handle this request. It should be fixed"
);
}
/// <exception cref="System.IO.IOException"></exception>
public virtual T Execute<T, _T1>(HttpRequestMessage httpUriRequest, ResponseHandler
<_T1> responseHandler, HttpContext httpContext) where _T1:T
{
throw new RuntimeException("Mock Http Client does not know how to handle this request. It should be fixed"
);
}
/// <exception cref="System.IO.IOException"></exception>
public virtual T Execute<T, _T1>(HttpHost httpHost, HttpWebRequest httpRequest, ResponseHandler
<_T1> responseHandler) where _T1:T
{
throw new RuntimeException("Mock Http Client does not know how to handle this request. It should be fixed"
);
}
/// <exception cref="System.IO.IOException"></exception>
public virtual T Execute<T, _T1>(HttpHost httpHost, HttpWebRequest httpRequest, ResponseHandler
<_T1> responseHandler, HttpContext httpContext) where _T1:T
{
throw new RuntimeException("Mock Http Client does not know how to handle this request. It should be fixed"
);
}
internal interface Responder
{
/// <exception cref="System.IO.IOException"></exception>
HttpResponse Execute(HttpRequestMessage httpUriRequest);
}
internal interface ResponseListener
{
void ResponseSent(HttpRequestMessage httpUriRequest, HttpResponse response);
}
public static ArrayList ExtractDocsFromBulkDocsPost(HttpWebRequest capturedRequest
)
{
try
{
if (capturedRequest is HttpPost)
{
HttpPost capturedPostRequest = (HttpPost)capturedRequest;
if (capturedPostRequest.GetURI().GetPath().EndsWith("_bulk_docs"))
{
ByteArrayEntity entity = (ByteArrayEntity)capturedPostRequest.GetEntity();
InputStream contentStream = entity.GetContent();
IDictionary<string, object> body = Manager.GetObjectMapper().ReadValue<IDictionary
>(contentStream);
ArrayList docs = (ArrayList)body.Get("docs");
return docs;
}
}
}
catch (IOException e)
{
throw new RuntimeException(e);
}
return null;
}
internal class SmartRevsDiffResponder : CustomizableMockHttpClient.Responder, CustomizableMockHttpClient.ResponseListener
{
private IList<string> docIdsSeen = new AList<string>();
public virtual void ResponseSent(HttpRequestMessage httpUriRequest, HttpResponse
response)
{
if (httpUriRequest is HttpPost)
{
HttpPost capturedPostRequest = (HttpPost)httpUriRequest;
if (capturedPostRequest.GetURI().GetPath().EndsWith("_bulk_docs"))
{
ArrayList docs = ExtractDocsFromBulkDocsPost(capturedPostRequest);
foreach (object docObject in docs)
{
IDictionary<string, object> doc = (IDictionary)docObject;
docIdsSeen.AddItem((string)doc.Get("_id"));
}
}
}
}
/// <summary>Fake _revs_diff responder</summary>
/// <exception cref="System.IO.IOException"></exception>
public virtual HttpResponse Execute(HttpRequestMessage httpUriRequest)
{
IDictionary<string, object> jsonMap = GetJsonMapFromRequest((HttpPost)httpUriRequest
);
IDictionary<string, object> responseMap = new Dictionary<string, object>();
foreach (string key in jsonMap.Keys)
{
if (docIdsSeen.Contains(key))
{
// we were previously pushed this document, so lets not consider it missing
// TODO: this only takes into account document id's, not rev-ids.
Log.D(Database.Tag, "already saw " + key);
continue;
}
ArrayList value = (ArrayList)jsonMap.Get(key);
IDictionary<string, object> missingMap = new Dictionary<string, object>();
missingMap.Put("missing", value);
responseMap.Put(key, missingMap);
}
HttpResponse response = GenerateHttpResponseObject(responseMap);
return response;
}
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Algo.Storages.Algo
File: StorageRegistry.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Algo.Storages
{
using System;
using Ecng.Collections;
using Ecng.Common;
using StockSharp.Algo.Candles;
using StockSharp.Algo.Storages.Binary;
using StockSharp.Algo.Storages.Csv;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
using StockSharp.Localization;
/// <summary>
/// The storage of market data.
/// </summary>
public class StorageRegistry : Disposable, IStorageRegistry
{
private readonly SynchronizedDictionary<Tuple<SecurityId, IMarketDataStorageDrive>, IMarketDataStorage<QuoteChangeMessage>> _depthStorages = new();
private readonly SynchronizedDictionary<Tuple<SecurityId, IMarketDataStorageDrive>, IMarketDataStorage<Level1ChangeMessage>> _level1Storages = new();
private readonly SynchronizedDictionary<Tuple<SecurityId, IMarketDataStorageDrive>, IMarketDataStorage<PositionChangeMessage>> _positionStorages = new();
private readonly SynchronizedDictionary<Tuple<SecurityId, IMarketDataStorageDrive>, IMarketDataStorage<CandleMessage>> _candleStorages = new();
private readonly SynchronizedDictionary<Tuple<SecurityId, ExecutionTypes, IMarketDataStorageDrive>, IMarketDataStorage<ExecutionMessage>> _executionStorages = new();
private readonly SynchronizedDictionary<IMarketDataStorageDrive, IMarketDataStorage<NewsMessage>> _newsStorages = new();
private readonly SynchronizedDictionary<IMarketDataStorageDrive, IMarketDataStorage<BoardStateMessage>> _boardStateStorages = new();
//private readonly SynchronizedDictionary<IMarketDataDrive, ISecurityStorage> _securityStorages = new SynchronizedDictionary<IMarketDataDrive, ISecurityStorage>();
/// <summary>
/// Initializes a new instance of the <see cref="StorageRegistry"/>.
/// </summary>
public StorageRegistry()
: this(new InMemoryExchangeInfoProvider())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="StorageRegistry"/>.
/// </summary>
/// <param name="exchangeInfoProvider">Exchanges and trading boards provider.</param>
public StorageRegistry(IExchangeInfoProvider exchangeInfoProvider)
{
ExchangeInfoProvider = exchangeInfoProvider ?? throw new ArgumentNullException(nameof(exchangeInfoProvider));
}
/// <summary>
/// Release resources.
/// </summary>
protected override void DisposeManaged()
{
DefaultDrive.Dispose();
base.DisposeManaged();
}
private IMarketDataDrive _defaultDrive = new LocalMarketDataDrive();
/// <inheritdoc />
public virtual IMarketDataDrive DefaultDrive
{
get => _defaultDrive;
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value == _defaultDrive)
return;
_defaultDrive.Dispose();
_defaultDrive = value;
}
}
/// <inheritdoc />
public IExchangeInfoProvider ExchangeInfoProvider { get; }
/// <inheritdoc />
public void RegisterTradeStorage(IMarketDataStorage<ExecutionMessage> storage)
{
RegisterStorage(_executionStorages, ExecutionTypes.Tick, storage);
}
/// <inheritdoc />
public void RegisterMarketDepthStorage(IMarketDataStorage<QuoteChangeMessage> storage)
{
RegisterStorage(_depthStorages, storage);
}
/// <inheritdoc />
public void RegisterOrderLogStorage(IMarketDataStorage<ExecutionMessage> storage)
{
RegisterStorage(_executionStorages, ExecutionTypes.OrderLog, storage);
}
/// <inheritdoc />
public void RegisterLevel1Storage(IMarketDataStorage<Level1ChangeMessage> storage)
{
RegisterStorage(_level1Storages, storage);
}
/// <inheritdoc />
public void RegisterPositionStorage(IMarketDataStorage<PositionChangeMessage> storage)
{
RegisterStorage(_positionStorages, storage);
}
/// <inheritdoc />
public void RegisterCandleStorage(IMarketDataStorage<CandleMessage> storage)
{
if (storage == null)
throw new ArgumentNullException(nameof(storage));
_candleStorages.Add(Tuple.Create(storage.SecurityId, storage.Drive), storage);
}
private static void RegisterStorage<T>(SynchronizedDictionary<Tuple<SecurityId, IMarketDataStorageDrive>, IMarketDataStorage<T>> storages, IMarketDataStorage<T> storage)
where T : Message
{
if (storages == null)
throw new ArgumentNullException(nameof(storages));
if (storage == null)
throw new ArgumentNullException(nameof(storage));
storages.Add(Tuple.Create(storage.SecurityId, storage.Drive), storage);
}
private static void RegisterStorage<T>(SynchronizedDictionary<Tuple<SecurityId, ExecutionTypes, IMarketDataStorageDrive>, IMarketDataStorage<T>> storages, ExecutionTypes type, IMarketDataStorage<T> storage)
where T : Message
{
if (storages == null)
throw new ArgumentNullException(nameof(storages));
if (storage == null)
throw new ArgumentNullException(nameof(storage));
storages.Add(Tuple.Create(storage.SecurityId, type, storage.Drive), storage);
}
/// <inheritdoc />
public IEntityMarketDataStorage<Trade, ExecutionMessage> GetTradeStorage(Security security, IMarketDataDrive drive = null, StorageFormats format = StorageFormats.Binary)
{
return GetTickMessageStorage(security.ToSecurityId(), drive, format).ToEntityStorage<ExecutionMessage, Trade>(security, ExchangeInfoProvider);
}
/// <inheritdoc />
public IEntityMarketDataStorage<MarketDepth, QuoteChangeMessage> GetMarketDepthStorage(Security security, IMarketDataDrive drive = null, StorageFormats format = StorageFormats.Binary)
{
return GetQuoteMessageStorage(security.ToSecurityId(), drive, format).ToEntityStorage<QuoteChangeMessage, MarketDepth>(security, ExchangeInfoProvider);
}
/// <inheritdoc />
public IEntityMarketDataStorage<OrderLogItem, ExecutionMessage> GetOrderLogStorage(Security security, IMarketDataDrive drive = null, StorageFormats format = StorageFormats.Binary)
{
return GetOrderLogMessageStorage(security.ToSecurityId(), drive, format).ToEntityStorage<ExecutionMessage, OrderLogItem>(security, ExchangeInfoProvider);
}
/// <inheritdoc />
public IEntityMarketDataStorage<Candle, CandleMessage> GetCandleStorage(Type candleType, Security security, object arg, IMarketDataDrive drive = null, StorageFormats format = StorageFormats.Binary)
{
return GetCandleMessageStorage(candleType.ToCandleMessageType(), security.ToSecurityId(), arg, drive, format).ToEntityStorage<CandleMessage, Candle>(security, ExchangeInfoProvider);
}
/// <inheritdoc />
public IEntityMarketDataStorage<News, NewsMessage> GetNewsStorage(IMarketDataDrive drive = null, StorageFormats format = StorageFormats.Binary)
{
return GetNewsMessageStorage(drive, format).ToEntityStorage<NewsMessage, News>(null, ExchangeInfoProvider);
}
/// <inheritdoc />
public IMarketDataStorage GetStorage(Security security, Type dataType, object arg, IMarketDataDrive drive = null, StorageFormats format = StorageFormats.Binary)
{
return GetStorage(security.ToSecurityId(), dataType, arg, drive, format);
}
/// <inheritdoc />
public IMarketDataStorage<ExecutionMessage> GetTickMessageStorage(SecurityId securityId, IMarketDataDrive drive = null, StorageFormats format = StorageFormats.Binary)
{
return GetExecutionMessageStorage(securityId, ExecutionTypes.Tick, drive, format);
}
/// <inheritdoc />
public IMarketDataStorage<QuoteChangeMessage> GetQuoteMessageStorage(SecurityId securityId, IMarketDataDrive drive = null, StorageFormats format = StorageFormats.Binary)
{
if (securityId == default)
throw new ArgumentNullException(nameof(securityId));
return _depthStorages.SafeAdd(Tuple.Create(securityId, (drive ?? DefaultDrive).GetStorageDrive(securityId, DataType.MarketDepth, format)), key =>
{
IMarketDataSerializer<QuoteChangeMessage> serializer;
switch (format)
{
case StorageFormats.Binary:
serializer = new QuoteBinarySerializer(key.Item1, ExchangeInfoProvider);
break;
case StorageFormats.Csv:
serializer = new MarketDepthCsvSerializer(key.Item1);
break;
default:
throw new ArgumentOutOfRangeException(nameof(format), format, LocalizedStrings.Str1219);
}
return new MarketDepthStorage(securityId, key.Item2, serializer);
});
}
/// <inheritdoc />
public IMarketDataStorage<ExecutionMessage> GetOrderLogMessageStorage(SecurityId securityId, IMarketDataDrive drive = null, StorageFormats format = StorageFormats.Binary)
{
return GetExecutionMessageStorage(securityId, ExecutionTypes.OrderLog, drive, format);
}
/// <inheritdoc />
public IMarketDataStorage<ExecutionMessage> GetTransactionStorage(SecurityId securityId, IMarketDataDrive drive = null, StorageFormats format = StorageFormats.Binary)
{
return GetExecutionMessageStorage(securityId, ExecutionTypes.Transaction, drive, format);
}
/// <inheritdoc />
public IMarketDataStorage<Level1ChangeMessage> GetLevel1MessageStorage(SecurityId securityId, IMarketDataDrive drive = null, StorageFormats format = StorageFormats.Binary)
{
if (securityId == default)
throw new ArgumentNullException(nameof(securityId));
return _level1Storages.SafeAdd(Tuple.Create(securityId, (drive ?? DefaultDrive).GetStorageDrive(securityId, DataType.Level1, format)), key =>
{
//if (security.Board == ExchangeBoard.Associated)
// return new AllSecurityMarketDataStorage<Level1ChangeMessage>(security, null, md => md.ServerTime, md => ToSecurity(md.SecurityId), (s, d) => GetLevel1MessageStorage(s, d, format), key.Item2, ExchangeInfoProvider);
IMarketDataSerializer<Level1ChangeMessage> serializer;
switch (format)
{
case StorageFormats.Binary:
serializer = new Level1BinarySerializer(key.Item1, ExchangeInfoProvider);
break;
case StorageFormats.Csv:
serializer = new Level1CsvSerializer(key.Item1);
break;
default:
throw new ArgumentOutOfRangeException(nameof(format), format, LocalizedStrings.Str1219);
}
return new Level1Storage(securityId, key.Item2, serializer);
});
}
/// <inheritdoc />
public IMarketDataStorage<PositionChangeMessage> GetPositionMessageStorage(SecurityId securityId, IMarketDataDrive drive = null, StorageFormats format = StorageFormats.Binary)
{
if (securityId == default)
throw new ArgumentNullException(nameof(securityId));
return _positionStorages.SafeAdd(Tuple.Create(securityId, (drive ?? DefaultDrive).GetStorageDrive(securityId, DataType.PositionChanges, format)), key =>
{
//if (security.Board == ExchangeBoard.Associated)
// return new AllSecurityMarketDataStorage<Level1ChangeMessage>(security, null, md => md.ServerTime, md => ToSecurity(md.SecurityId), (s, d) => GetLevel1MessageStorage(s, d, format), key.Item2, ExchangeInfoProvider);
IMarketDataSerializer<PositionChangeMessage> serializer;
switch (format)
{
case StorageFormats.Binary:
serializer = new PositionBinarySerializer(key.Item1, ExchangeInfoProvider);
break;
case StorageFormats.Csv:
serializer = new PositionCsvSerializer(key.Item1);
break;
default:
throw new ArgumentOutOfRangeException(nameof(format), format, LocalizedStrings.Str1219);
}
return new PositionChangeStorage(securityId, key.Item2, serializer);
});
}
/// <inheritdoc />
public IMarketDataStorage<CandleMessage> GetCandleMessageStorage(Type candleMessageType, SecurityId securityId, object arg, IMarketDataDrive drive = null, StorageFormats format = StorageFormats.Binary)
{
if (candleMessageType == null)
throw new ArgumentNullException(nameof(candleMessageType));
if (!candleMessageType.IsCandleMessage())
throw new ArgumentOutOfRangeException(nameof(candleMessageType), candleMessageType, LocalizedStrings.WrongCandleType);
if (securityId == default)
throw new ArgumentNullException(nameof(securityId));
if (arg.IsNull(true))
throw new ArgumentNullException(nameof(arg), LocalizedStrings.EmptyCandleArg);
return _candleStorages.SafeAdd(Tuple.Create(securityId, (drive ?? DefaultDrive).GetStorageDrive(securityId, DataType.Create(candleMessageType, arg), format)), key =>
{
IMarketDataSerializer serializer;
switch (format)
{
case StorageFormats.Binary:
serializer = typeof(CandleBinarySerializer<>).Make(candleMessageType).CreateInstance<IMarketDataSerializer>(key.Item1, arg, ExchangeInfoProvider);
break;
case StorageFormats.Csv:
serializer = typeof(CandleCsvSerializer<>).Make(candleMessageType).CreateInstance<IMarketDataSerializer>(key.Item1, arg, null);
break;
default:
throw new ArgumentOutOfRangeException(nameof(format), format, LocalizedStrings.Str1219);
}
return typeof(CandleStorage<>).Make(candleMessageType).CreateInstance<IMarketDataStorage<CandleMessage>>(key.Item1, arg, key.Item2, serializer);
});
}
/// <inheritdoc />
public IMarketDataStorage<ExecutionMessage> GetExecutionMessageStorage(SecurityId securityId, ExecutionTypes type, IMarketDataDrive drive = null, StorageFormats format = StorageFormats.Binary)
{
if (securityId == default)
throw new ArgumentNullException(nameof(securityId));
return _executionStorages.SafeAdd(Tuple.Create(securityId, type, (drive ?? DefaultDrive).GetStorageDrive(securityId, DataType.Create(typeof(ExecutionMessage), type), format)), key =>
{
var secId = key.Item1;
var mdDrive = key.Item3;
switch (type)
{
case ExecutionTypes.Tick:
{
IMarketDataSerializer<ExecutionMessage> serializer;
switch (format)
{
case StorageFormats.Binary:
serializer = new TickBinarySerializer(key.Item1, ExchangeInfoProvider);
break;
case StorageFormats.Csv:
serializer = new TickCsvSerializer(key.Item1);
break;
default:
throw new ArgumentOutOfRangeException(nameof(format), format, LocalizedStrings.Str1219);
}
return new TradeStorage(securityId, mdDrive, serializer);
}
case ExecutionTypes.Transaction:
{
IMarketDataSerializer<ExecutionMessage> serializer;
switch (format)
{
case StorageFormats.Binary:
serializer = new TransactionBinarySerializer(secId, ExchangeInfoProvider);
break;
case StorageFormats.Csv:
serializer = new TransactionCsvSerializer(secId);
break;
default:
throw new ArgumentOutOfRangeException(nameof(format), format, LocalizedStrings.Str1219);
}
return new TransactionStorage(securityId, mdDrive, serializer);
}
case ExecutionTypes.OrderLog:
{
IMarketDataSerializer<ExecutionMessage> serializer;
switch (format)
{
case StorageFormats.Binary:
serializer = new OrderLogBinarySerializer(secId, ExchangeInfoProvider);
break;
case StorageFormats.Csv:
serializer = new OrderLogCsvSerializer(secId);
break;
default:
throw new ArgumentOutOfRangeException(nameof(format), format, LocalizedStrings.Str1219);
}
return new OrderLogStorage(securityId, mdDrive, serializer);
}
default:
throw new ArgumentOutOfRangeException(nameof(type), type, LocalizedStrings.Str1219);
}
});
}
/// <inheritdoc />
public IMarketDataStorage GetStorage(SecurityId securityId, Type dataType, object arg, IMarketDataDrive drive = null, StorageFormats format = StorageFormats.Binary)
{
if (dataType == null)
throw new ArgumentNullException(nameof(dataType));
if (!dataType.IsSubclassOf(typeof(Message)))
dataType = dataType.ToMessageType(ref arg);
if (dataType == typeof(ExecutionMessage))
{
if (arg == null)
throw new ArgumentNullException(nameof(arg));
return GetExecutionMessageStorage(securityId, (ExecutionTypes)arg, drive, format);
}
else if (dataType == typeof(Level1ChangeMessage))
return GetLevel1MessageStorage(securityId, drive, format);
else if (dataType == typeof(PositionChangeMessage))
return GetPositionMessageStorage(securityId, drive, format);
else if (dataType == typeof(QuoteChangeMessage))
return GetQuoteMessageStorage(securityId, drive, format);
else if (dataType == typeof(NewsMessage))
return GetNewsMessageStorage(drive, format);
else if (dataType == typeof(BoardStateMessage))
return GetBoardStateMessageStorage(drive, format);
else if (dataType.IsCandleMessage())
return GetCandleMessageStorage(dataType, securityId, arg, drive, format);
else
throw new ArgumentOutOfRangeException(nameof(dataType), dataType, LocalizedStrings.Str1018);
}
/// <inheritdoc />
public IMarketDataStorage<NewsMessage> GetNewsMessageStorage(IMarketDataDrive drive = null, StorageFormats format = StorageFormats.Binary)
{
var securityId = SecurityId.News;
return _newsStorages.SafeAdd((drive ?? DefaultDrive).GetStorageDrive(securityId, DataType.News, format), key =>
{
IMarketDataSerializer<NewsMessage> serializer;
switch (format)
{
case StorageFormats.Binary:
serializer = new NewsBinarySerializer(ExchangeInfoProvider);
break;
case StorageFormats.Csv:
serializer = new NewsCsvSerializer();
break;
default:
throw new ArgumentOutOfRangeException(nameof(format), format, LocalizedStrings.Str1219);
}
return new NewsStorage(securityId, serializer, key);
});
}
/// <inheritdoc />
public IMarketDataStorage<BoardStateMessage> GetBoardStateMessageStorage(IMarketDataDrive drive = null, StorageFormats format = StorageFormats.Binary)
{
return _boardStateStorages.SafeAdd((drive ?? DefaultDrive).GetStorageDrive(default, DataType.BoardState, format), key =>
{
IMarketDataSerializer<BoardStateMessage> serializer;
switch (format)
{
case StorageFormats.Binary:
serializer = new BoardStateBinarySerializer(ExchangeInfoProvider);
break;
case StorageFormats.Csv:
serializer = new BoardStateCsvSerializer();
break;
default:
throw new ArgumentOutOfRangeException(nameof(format), format, LocalizedStrings.Str1219);
}
return new BoardStateStorage(default, serializer, key);
});
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class LiftedComparisonGreaterThanNullableTests
{
#region Test methods
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedComparisonGreaterThanNullableByteTest(bool useInterpreter)
{
byte?[] values = new byte?[] { null, 0, 1, byte.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanNullableByte(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedComparisonGreaterThanNullableCharTest(bool useInterpreter)
{
char?[] values = new char?[] { null, '\0', '\b', 'A', '\uffff' };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanNullableChar(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedComparisonGreaterThanNullableDecimalTest(bool useInterpreter)
{
decimal?[] values = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanNullableDecimal(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedComparisonGreaterThanNullableDoubleTest(bool useInterpreter)
{
double?[] values = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanNullableDouble(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedComparisonGreaterThanNullableFloatTest(bool useInterpreter)
{
float?[] values = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanNullableFloat(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedComparisonGreaterThanNullableIntTest(bool useInterpreter)
{
int?[] values = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanNullableInt(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedComparisonGreaterThanNullableLongTest(bool useInterpreter)
{
long?[] values = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanNullableLong(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedComparisonGreaterThanNullableSByteTest(bool useInterpreter)
{
sbyte?[] values = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanNullableSByte(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedComparisonGreaterThanNullableShortTest(bool useInterpreter)
{
short?[] values = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanNullableShort(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedComparisonGreaterThanNullableUIntTest(bool useInterpreter)
{
uint?[] values = new uint?[] { null, 0, 1, uint.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanNullableUInt(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedComparisonGreaterThanNullableULongTest(bool useInterpreter)
{
ulong?[] values = new ulong?[] { null, 0, 1, ulong.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanNullableULong(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedComparisonGreaterThanNullableUShortTest(bool useInterpreter)
{
ushort?[] values = new ushort?[] { null, 0, 1, ushort.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanNullableUShort(values[i], values[j], useInterpreter);
}
}
}
#endregion
#region Test verifiers
private static void VerifyComparisonGreaterThanNullableByte(byte? a, byte? b, bool useInterpreter)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.GreaterThan(
Expression.Constant(a, typeof(byte?)),
Expression.Constant(b, typeof(byte?)),
true,
null));
Func<bool?> f = e.Compile(useInterpreter);
bool? expected = a > b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonGreaterThanNullableChar(char? a, char? b, bool useInterpreter)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.GreaterThan(
Expression.Constant(a, typeof(char?)),
Expression.Constant(b, typeof(char?)),
true,
null));
Func<bool?> f = e.Compile(useInterpreter);
bool? expected = a > b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonGreaterThanNullableDecimal(decimal? a, decimal? b, bool useInterpreter)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.GreaterThan(
Expression.Constant(a, typeof(decimal?)),
Expression.Constant(b, typeof(decimal?)),
true,
null));
Func<bool?> f = e.Compile(useInterpreter);
bool? expected = a > b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonGreaterThanNullableDouble(double? a, double? b, bool useInterpreter)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.GreaterThan(
Expression.Constant(a, typeof(double?)),
Expression.Constant(b, typeof(double?)),
true,
null));
Func<bool?> f = e.Compile(useInterpreter);
bool? expected = a > b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonGreaterThanNullableFloat(float? a, float? b, bool useInterpreter)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.GreaterThan(
Expression.Constant(a, typeof(float?)),
Expression.Constant(b, typeof(float?)),
true,
null));
Func<bool?> f = e.Compile(useInterpreter);
bool? expected = a > b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonGreaterThanNullableInt(int? a, int? b, bool useInterpreter)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.GreaterThan(
Expression.Constant(a, typeof(int?)),
Expression.Constant(b, typeof(int?)),
true,
null));
Func<bool?> f = e.Compile(useInterpreter);
bool? expected = a > b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonGreaterThanNullableLong(long? a, long? b, bool useInterpreter)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.GreaterThan(
Expression.Constant(a, typeof(long?)),
Expression.Constant(b, typeof(long?)),
true,
null));
Func<bool?> f = e.Compile(useInterpreter);
bool? expected = a > b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonGreaterThanNullableSByte(sbyte? a, sbyte? b, bool useInterpreter)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.GreaterThan(
Expression.Constant(a, typeof(sbyte?)),
Expression.Constant(b, typeof(sbyte?)),
true,
null));
Func<bool?> f = e.Compile(useInterpreter);
bool? expected = a > b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonGreaterThanNullableShort(short? a, short? b, bool useInterpreter)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.GreaterThan(
Expression.Constant(a, typeof(short?)),
Expression.Constant(b, typeof(short?)),
true,
null));
Func<bool?> f = e.Compile(useInterpreter);
bool? expected = a > b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonGreaterThanNullableUInt(uint? a, uint? b, bool useInterpreter)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.GreaterThan(
Expression.Constant(a, typeof(uint?)),
Expression.Constant(b, typeof(uint?)),
true,
null));
Func<bool?> f = e.Compile(useInterpreter);
bool? expected = a > b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonGreaterThanNullableULong(ulong? a, ulong? b, bool useInterpreter)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.GreaterThan(
Expression.Constant(a, typeof(ulong?)),
Expression.Constant(b, typeof(ulong?)),
true,
null));
Func<bool?> f = e.Compile(useInterpreter);
bool? expected = a > b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonGreaterThanNullableUShort(ushort? a, ushort? b, bool useInterpreter)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.GreaterThan(
Expression.Constant(a, typeof(ushort?)),
Expression.Constant(b, typeof(ushort?)),
true,
null));
Func<bool?> f = e.Compile(useInterpreter);
bool? expected = a > b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Validation;
using System.Data.Objects;
using System.Linq;
using System.Linq.Expressions;
using DBSystem.Core;
using DBSystem.Core.Data;
namespace DBSystem.Data
{
/// <summary>
/// Entity Framework repository
/// </summary>
public partial class EfRepository<T> : IRepository<T> where T : BaseEntity
{
private readonly IDbContext _context;
private IDbSet<T> _entities;
public EfRepository(IDbContext context)
{
this._context = context;
this.AutoCommitEnabled = false;
}
#region interface members
public virtual IQueryable<T> Table
{
get
{
return this.Entities;
}
}
public T Create()
{
return this.Entities.Create();
}
public T GetById(object id)
{
return this.Entities.Find(id);
}
public void Insert(T entity)
{
if (entity == null)
throw new ArgumentNullException("entity");
this.Entities.Add(entity);
if (this.AutoCommitEnabled)
_context.SaveChanges();
}
public void InsertRange(IEnumerable<T> entities, int batchSize = 100)
{
try
{
if (entities == null)
throw new ArgumentNullException("entities");
if (entities.HasItems())
{
if (batchSize <= 0)
{
// insert all in one step
entities.Each(x => this.Entities.Add(x));
if (this.AutoCommitEnabled)
_context.SaveChanges();
}
else
{
int i = 1;
bool saved = false;
foreach (var entity in entities)
{
this.Entities.Add(entity);
saved = false;
if (i % batchSize == 0)
{
if (this.AutoCommitEnabled)
_context.SaveChanges();
i = 0;
saved = true;
}
i++;
}
if (!saved)
{
if (this.AutoCommitEnabled)
_context.SaveChanges();
}
}
}
}
catch (DbEntityValidationException ex)
{
throw ex;
}
}
public void Update(T entity)
{
if (entity == null)
throw new ArgumentNullException("entity");
if (this.AutoCommitEnabled)
{
_context.SaveChanges();
}
else
{
try
{
this.Entities.Attach(entity);
InternalContext.Entry(entity).State = System.Data.EntityState.Modified;
}
finally { }
}
}
public void Delete(T entity)
{
if (entity == null)
throw new ArgumentNullException("entity");
if (InternalContext.Entry(entity).State == System.Data.EntityState.Detached)
{
this.Entities.Attach(entity);
}
this.Entities.Remove(entity);
if (this.AutoCommitEnabled)
_context.SaveChanges();
}
public IQueryable<T> Include(IQueryable<T> query, string path)
{
//Guard.ArgumentNotNull(query, "query");
//Guard.ArgumentNotEmpty(path, "path");
return query.Include(path);
}
public IQueryable<T> Include<TProperty>(IQueryable<T> query, Expression<Func<T, TProperty>> path)
{
//Guard.ArgumentNotNull(query, "query");
//Guard.ArgumentNotNull(path, "path");
return query.Include(path);
}
public IDictionary<string, object> GetModifiedProperties(T entity)
{
var props = new Dictionary<string, object>();
var ctx = InternalContext;
var entry = ctx.Entry(entity);
var modifiedPropertyNames = from p in entry.CurrentValues.PropertyNames
where entry.Property(p).IsModified
select p;
foreach (var name in modifiedPropertyNames)
{
props.Add(name, entry.Property(name).OriginalValue);
}
return props;
}
public IDbContext Context
{
get { return _context; }
}
public bool AutoCommitEnabled { get; set; }
#endregion
#region Helpers
protected internal ObjectContextBase InternalContext
{
get { return _context as ObjectContextBase; }
}
private DbSet<T> Entities
{
get
{
if (_entities == null)
{
_entities = _context.Set<T>();
}
return _entities as DbSet<T>;
}
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using OpenMetaverse;
namespace Aurora.Framework
{
/// <summary>
/// Implemented by classes which collect up non-viewer statistical information
/// </summary>
public interface IStatsCollector
{
/// <summary>
/// Report back collected statistical information.
/// </summary>
/// <returns></returns>
string Report();
}
public delegate void SendStatResult(SimStats stats);
public class MonitorModuleHelper
{
public static string SimFrameStats = "SimFrameStats";
public static string TimeDilation = "Time Dilation";
public static string TotalFrameTime = "Total Frame Time";
public static string SleepFrameTime = "Sleep Frame Time";
public static string OtherFrameTime = "Other Frame Time";
public static string TotalPhysicsFrameTime = "Total Physics Frame Time";
public static string PhysicsSyncFrameTime = "Physics Sync Frame Time";
public static string PhysicsUpdateFrameTime = "Physics Update Frame Time";
public static string AgentUpdateCount = "Agent Update Count";
public static string NetworkMonitor = "Network Monitor";
public static string ImagesFrameTime = "Images Frame Time";
public static string ScriptFrameTime = "Script Frame Time";
public static string TotalScriptCount = "Total Script Count";
public static string LoginMonitor = "LoginMonitor";
public static string AssetMonitor = "AssetMonitor";
public static string LastCompletedFrameAt = "Last Completed Frame At";
public static string PrimUpdates = "PrimUpdates";
}
public interface IMonitorModule
{
/// <summary>
/// Event that gives others the SimStats class that is being sent out to the client
/// </summary>
event SendStatResult OnSendStatsResult;
/// <summary>
/// Get a monitor module by the RegionID (key parameter, can be "" to get the base monitors) and Name of the monitor
/// </summary>
/// <param name = "Key"></param>
/// <param name = "Name"></param>
/// <returns></returns>
IMonitor GetMonitor(string Key, string Name);
/// <summary>
/// Get the latest stats
/// </summary>
/// <param name = "p">The RegionID of the region</param>
/// <returns></returns>
float[] GetRegionStats(string Key);
}
public interface IMonitor
{
/// <summary>
/// Get the value of this monitor
/// </summary>
/// <returns></returns>
double GetValue();
/// <summary>
/// Get the name of this monitor
/// </summary>
/// <returns></returns>
string GetName();
/// <summary>
/// Get the nice looking value of GetValue()
/// </summary>
/// <returns></returns>
string GetFriendlyValue();
/// <summary>
/// Resets any per stats beat stats that may need done
/// </summary>
void ResetStats();
}
public delegate void Alert(Type reporter, string reason, bool fatal);
public interface IAlert
{
/// <summary>
/// The name of the alert
/// </summary>
/// <returns></returns>
string GetName();
/// <summary>
/// Test the alert
/// </summary>
void Test();
/// <summary>
/// What will happen when the alert is triggered
/// </summary>
event Alert OnTriggerAlert;
}
public interface ITimeMonitor : IMonitor
{
void AddTime(int time);
}
public interface IAssetMonitor
{
/// <summary>
/// Add a failure to ask the asset service
/// </summary>
void AddAssetServiceRequestFailure();
/// <summary>
/// The time that it took to request the asset after it was not found in the cache
/// </summary>
/// <param name = "ts"></param>
void AddAssetRequestTimeAfterCacheMiss(TimeSpan ts);
/// <summary>
/// Add the asset's memory to the memory count
/// </summary>
/// <param name = "asset"></param>
void AddAsset(AssetBase asset);
/// <summary>
/// This asset was removed, take it out of the asset list
/// </summary>
/// <param name = "uuid"></param>
void RemoveAsset(UUID uuid);
/// <summary>
/// Clear the cache for assets
/// </summary>
void ClearAssetCacheStatistics();
/// <summary>
/// Add a missing texture request
/// </summary>
void AddBlockedMissingTextureRequest();
}
public interface INetworkMonitor
{
/// <summary>
/// The number of packets coming in per second
/// </summary>
float InPacketsPerSecond { get; }
/// <summary>
/// The number of packets going out per second
/// </summary>
float OutPacketsPerSecond { get; }
/// <summary>
/// The number of bytes that we have not acked yet (see LLUDPClient for more info)
/// </summary>
float UnackedBytes { get; }
/// <summary>
/// The number of downloads that the client has requested, but has not recieved at this time
/// </summary>
float PendingDownloads { get; }
/// <summary>
/// The number of updates that the client has started, but not finished
/// </summary>
float PendingUploads { get; }
/// <summary>
/// Add the number of packets that are incoming
/// </summary>
/// <param name = "numPackets"></param>
void AddInPackets(int numPackets);
/// <summary>
/// Add the number of outgoing packets
/// </summary>
/// <param name = "numPackets"></param>
void AddOutPackets(int numPackets);
/// <summary>
/// Add the current bytes that are not acked
/// </summary>
/// <param name = "numBytes"></param>
void AddUnackedBytes(int numBytes);
/// <summary>
/// Add new pending downloads
/// </summary>
/// <param name = "count"></param>
void AddPendingDownloads(int count);
/// <summary>
/// Add new pending upload
/// </summary>
/// <param name = "count"></param>
void AddPendingUploads(int count);
}
public interface IScriptCountMonitor : IMonitor
{
/// <summary>
/// The number of active scripts in the region
/// </summary>
int ActiveScripts { get; }
/// <summary>
/// The number of events firing per second in the script engine
/// </summary>
int ScriptEPS { get; }
}
public interface ISetMonitor : IMonitor
{
/// <summary>
/// Set the Value for the monitor
/// </summary>
/// <param name = "value"></param>
void SetValue(int value);
}
public interface ITimeDilationMonitor : IMonitor
{
/// <summary>
/// Set the Value for the monitor
/// </summary>
/// <param name = "value"></param>
void SetPhysicsFPS(float value);
}
public interface IPhysicsFrameMonitor
{
/// <summary>
/// The last reported PhysicsSim FPS
/// </summary>
float LastReportedPhysicsFPS { get; set; }
/// <summary>
/// The 'current' Physics FPS (NOTE: This will NOT be what you expect, you will have to divide by the time since the last check to get the correct average Physics FPS)
/// </summary>
float PhysicsFPS { get; }
/// <summary>
/// Add X frames to the stats
/// </summary>
/// <param name = "frames"></param>
void AddFPS(int frames);
}
public interface ISimFrameMonitor
{
/// <summary>
/// The last reported Sim FPS (for llGetRegionFPS())
/// </summary>
float LastReportedSimFPS { get; set; }
/// <summary>
/// The 'current' Sim FPS (NOTE: This will NOT be what you expect, you will have to divide by the time since the last check to get the correct average Sim FPS)
/// </summary>
float SimFPS { get; }
/// <summary>
/// Add X frames to the stats
/// </summary>
/// <param name = "frames"></param>
void AddFPS(int frames);
}
public interface IImageFrameTimeMonitor
{
/// <summary>
/// Add the time it took to process sending of images to the client
/// </summary>
/// <param name = "time">time in milliseconds</param>
void AddImageTime(int time);
}
public interface ITotalFrameTimeMonitor : IMonitor
{
/// <summary>
/// Add the time it took to process sending of images to the client
/// </summary>
/// <param name = "time">time in milliseconds</param>
void AddFrameTime(int time);
}
public interface IObjectUpdateMonitor
{
/// <summary>
/// The current number of prims that were not sent to the client
/// </summary>
float PrimsLimited { get; }
/// <summary>
/// Add X prims updates that were limited to the stats
/// </summary>
/// <param name = "frames"></param>
void AddLimitedPrims(int prims);
}
public interface IAgentUpdateMonitor
{
/// <summary>
/// The time it takes to update the agent with info
/// </summary>
int AgentFrameTime { get; }
/// <summary>
/// The number of updates sent to the agent
/// </summary>
int AgentUpdates { get; }
/// <summary>
/// Add the agent updates
/// </summary>
/// <param name = "value"></param>
void AddAgentUpdates(int value);
/// <summary>
/// Add the amount of time it took to update the client
/// </summary>
/// <param name = "value"></param>
void AddAgentTime(int value);
}
public interface ILoginMonitor
{
/// <summary>
/// Add a successful login to the stats
/// </summary>
void AddSuccessfulLogin();
/// <summary>
/// Add a successful logout to the stats
/// </summary>
void AddLogout();
/// <summary>
/// Add a terminated client thread to the stats
/// </summary>
void AddAbnormalClientThreadTermination();
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ShiftRightArithmeticInt161()
{
var test = new ImmUnaryOpTest__ShiftRightArithmeticInt161();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmUnaryOpTest__ShiftRightArithmeticInt161
{
private struct TestStruct
{
public Vector256<Int16> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightArithmeticInt161 testClass)
{
var result = Avx2.ShiftRightArithmetic(_fld, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16);
private static Int16[] _data = new Int16[Op1ElementCount];
private static Vector256<Int16> _clsVar;
private Vector256<Int16> _fld;
private SimpleUnaryOpTest__DataTable<Int16, Int16> _dataTable;
static ImmUnaryOpTest__ShiftRightArithmeticInt161()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
}
public ImmUnaryOpTest__ShiftRightArithmeticInt161()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); }
_dataTable = new SimpleUnaryOpTest__DataTable<Int16, Int16>(_data, new Int16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.ShiftRightArithmetic(
Unsafe.Read<Vector256<Int16>>(_dataTable.inArrayPtr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.ShiftRightArithmetic(
Avx.LoadVector256((Int16*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.ShiftRightArithmetic(
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightArithmetic), new Type[] { typeof(Vector256<Int16>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int16>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightArithmetic), new Type[] { typeof(Vector256<Int16>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int16*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightArithmetic), new Type[] { typeof(Vector256<Int16>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.ShiftRightArithmetic(
_clsVar,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector256<Int16>>(_dataTable.inArrayPtr);
var result = Avx2.ShiftRightArithmetic(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Avx.LoadVector256((Int16*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftRightArithmetic(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftRightArithmetic(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__ShiftRightArithmeticInt161();
var result = Avx2.ShiftRightArithmetic(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.ShiftRightArithmetic(_fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.ShiftRightArithmetic(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Int16> firstOp, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray = new Int16[Op1ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray = new Int16[Op1ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Int16[] firstOp, Int16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((short)(firstOp[0] >> 1) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((short)(firstOp[i] >> 1) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.ShiftRightArithmetic)}<Int16>(Vector256<Int16><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
#region License
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Common.Logging;
using Commons.Collections;
using NVelocity.App;
using NVelocity.Exception;
using NVelocity.Runtime;
using NVelocity.Runtime.Resource.Loader;
using Spring.Context.Support;
using Spring.Core.IO;
using Spring.Util;
namespace Spring.Template.Velocity {
/// <summary>
/// Factory that configures a VelocityEngine. Can be used standalone,
/// but typically you will use VelocityEngineFactoryObject
/// for preparing a VelocityEngine as bean reference.
///
/// <br/>
/// The optional "ConfigLocation" property sets the location of the Velocity
/// properties file, within the current application. Velocity properties can be
/// overridden via "VelocityProperties", or even completely specified locally,
/// avoiding the need for an external properties file.
///
/// <br/>
/// The "ResourceLoaderPath" property can be used to specify the Velocity
/// resource loader path via Spring's IResource abstraction, possibly relative
/// to the Spring application context.
///
/// <br/>
/// If "OverrideLogging" is true (the default), the VelocityEngine will be
/// configured to log via Commons Logging, that is, using the Spring-provided
/// CommonsLoggingLogSystem as log system.
///
/// <br/>
/// The simplest way to use this class is to specify a ResourceLoaderPath
/// property. the VelocityEngine typically then does not need any further
/// configuration.
///
/// </summary>
/// <see cref="CommonsLoggingLogSystem" />
/// <see cref="VelocityEngineFactoryObject" />
/// <see cref="CommonsLoggingLogSystem" />
/// <author>Erez Mazor</author>
public class VelocityEngineFactory
{
/// <summary>
/// Shared logger instance.
/// </summary>
protected static readonly ILog log = LogManager.GetLogger(typeof(VelocityEngineFactory));
private IResource configLocation;
private IDictionary<string, object> velocityProperties = new Dictionary<string, object>();
private IList<string> resourceLoaderPaths = new List<string>();
private IResourceLoader resourceLoader = new ConfigurableResourceLoader();
private bool preferFileSystemAccess = true;
private bool overrideLogging = true;
/// <summary>
/// Set the location of the Velocity config file. Alternatively, you can specify all properties locally.
/// </summary>
/// <see cref="VelocityProperties"/>
/// <see cref="ResourceLoaderPath"/>
public IResource ConfigLocation {
set { configLocation = value; }
}
/// <summary>
/// Set local NVelocity properties.
/// </summary>
/// <see cref="VelocityProperties"/>
public IDictionary<string, object> VelocityProperties {
set { velocityProperties = value; }
}
/// <summary>
/// Single ResourceLoaderPath
/// </summary>
/// <see cref="ResourceLoaderPaths"/>
public string ResourceLoaderPath {
set { resourceLoaderPaths.Add(value); }
}
/// <summary>
/// Set the Velocity resource loader path via a Spring resource location.
/// Accepts multiple locations in Velocity's comma-separated path style.
/// <br/>
/// When populated via a String, standard URLs like "file:" and "assembly:"
/// pseudo URLs are supported, as understood by IResourceLoader. Allows for
/// relative paths when running in an ApplicationContext.
/// <br/>
/// Will define a path for the default Velocity resource loader with the name
/// "file". If the specified resource cannot be resolved to a File,
/// a generic SpringResourceLoader will be used under the name "spring", without
/// modification detection.
/// <br/>
/// Take notice that resource caching will be enabled in any case. With the file
/// resource loader, the last-modified timestamp will be checked on access to
/// detect changes. With SpringResourceLoader, the resource will be throughout
/// the life time of the application context (for example for class path resources).
/// <br/>
/// To specify a modification check interval for files, use Velocity's
/// standard "file.resource.loader.modificationCheckInterval" property. By default,
/// the file timestamp is checked on every access (which is surprisingly fast).
/// Of course, this just applies when loading resources from the file system.
/// <br/>
/// To enforce the use of SpringResourceLoader, i.e. to not resolve a path
/// as file system resource in any case, turn off the "preferFileSystemAccess"
/// flag. See the latter's documentation for details.
/// </summary>
/// <see cref="ResourceLoader"/>
/// <see cref="VelocityProperties"/>
/// <see cref="PreferFileSystemAccess"/>
/// <see cref="SpringResourceLoader"/>
/// <see cref="FileResourceLoader"/>
public IList<string> ResourceLoaderPaths
{
set { resourceLoaderPaths = value; }
}
/// <summary>
/// Set the Spring ResourceLoader to use for loading Velocity template files.
/// The default is DefaultResourceLoader. Will get overridden by the
/// ApplicationContext if running in a context.
///
/// </summary>
/// <see cref="ConfigurableResourceLoader"/>
/// <see cref="ContextRegistry"/>
///
public IResourceLoader ResourceLoader {
get { return resourceLoader; }
set { resourceLoader = value; }
}
/// <summary>
/// Set whether to prefer file system access for template loading.
/// File system access enables hot detection of template changes.
/// <br/>
/// If this is enabled, VelocityEngineFactory will try to resolve the
/// specified "resourceLoaderPath" as file system resource.
/// <br/>
/// Default is "true". Turn this off to always load via SpringResourceLoader
/// (i.e. as stream, without hot detection of template changes), which might
/// be necessary if some of your templates reside in a directory while
/// others reside in assembly files.
/// </summary>
/// <see cref="ResourceLoaderPath"/>
public bool PreferFileSystemAccess {
get { return preferFileSystemAccess; }
set { preferFileSystemAccess = value; }
}
/// <summary>
/// Set whether Velocity should log via Commons Logging, i.e. whether Velocity's
/// log system should be set to CommonsLoggingLogSystem. Default value is true
/// </summary>
/// <see cref="CommonsLoggingLogSystem"/>
public bool OverrideLogging {
get { return overrideLogging; }
set { overrideLogging = value; }
}
/// <summary>
/// Create and initialize the VelocityEngine instance and return it
/// </summary>
/// <returns>VelocityEngine</returns>
/// <exception cref="VelocityException" />
/// <see cref="FillProperties" />
/// <see cref="InitVelocityResourceLoader" />
/// <see cref="PostProcessVelocityEngine" />
/// <see cref="VelocityEngine.Init()" />
[CLSCompliant(false)]
public VelocityEngine CreateVelocityEngine()
{
ExtendedProperties extendedProperties = new ExtendedProperties();
VelocityEngine velocityEngine = NewVelocityEngine();
LoadDefaultProperties(extendedProperties);
// Load config file if set.
if (configLocation != null) {
if (log.IsInfoEnabled) {
log.Info(string.Format("Loading Velocity config from [{0}]", configLocation));
}
FillProperties(extendedProperties, configLocation, false);
}
// merge local properties if set.
if (velocityProperties.Count > 0) {
foreach (KeyValuePair<string, object> pair in velocityProperties) {
extendedProperties.SetProperty(pair.Key, pair.Value);
}
}
// Set a resource loader path, if required.
if (!preferFileSystemAccess && resourceLoaderPaths.Count == 0) {
throw new ArgumentException("When using SpringResourceLoader you must provide a path using the ResourceLoaderPath property");
}
if (resourceLoaderPaths.Count > 0) {
InitVelocityResourceLoader(velocityEngine, extendedProperties, resourceLoaderPaths);
}
// Log via Commons Logging?
if (overrideLogging) {
velocityEngine.SetProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM, new CommonsLoggingLogSystem());
}
PostProcessVelocityEngine(velocityEngine);
try {
velocityEngine.Init(extendedProperties);
} catch (Exception ex) {
throw new VelocityException(ex.ToString(), ex);
}
return velocityEngine;
}
/// <summary>
/// This is to overcome an issue with the current NVelocity library, it seems the
/// default runetime properties/directives (nvelocity.properties and directive.properties
/// files) are not being properly located in the library at load time. A jira should
/// be filed but for now we attempt to do this on our own. Particularly our
/// concern here is with several required properties which I don't want
/// to require users to re-defined. e.g.,:
/// <br/>
///
/// Pre-requisites:<br/>
/// resource.manager.class=NVelocity.Runtime.Resource.ResourceManagerImpl <br/>
/// directive.manager=NVelocity.Runtime.Directive.DirectiveManager <br/>
/// runtime.introspector.uberspect=NVelocity.Util.Introspection.UberspectImpl <br/>
/// </summary>
private static void LoadDefaultProperties(ExtendedProperties extendedProperties) {
IResource defaultRuntimeProperties = new AssemblyResource("assembly://NVelocity/NVelocity.Runtime.Defaults/nvelocity.properties");
IResource defaultRuntimeDirectives = new AssemblyResource("assembly://NVelocity/NVelocity.Runtime.Defaults/directive.properties");
FillProperties(extendedProperties, defaultRuntimeProperties, true);
FillProperties(extendedProperties, defaultRuntimeDirectives, true);
}
/// <summary>
/// Return a new VelocityEngine. Subclasses can override this for
/// custom initialization, or for using a mock object for testing. <br/>
/// Called by CreateVelocityEngine()
/// </summary>
/// <returns>VelocityEngine instance (non-configured)</returns>
/// <see cref="CreateVelocityEngine"/>
[CLSCompliant(false)]
protected static VelocityEngine NewVelocityEngine()
{
return new VelocityEngine();
}
/// <summary>
/// Initialize a Velocity resource loader for the given VelocityEngine:
/// either a standard Velocity FileResourceLoader or a SpringResourceLoader.
/// <br/>Called by <code>CreateVelocityEngine()</code>.
/// </summary>
/// <param name="velocityEngine">velocityEngine the VelocityEngine to configure</param>
/// <param name="extendedProperties"></param>
/// <param name="paths">paths the path list to load Velocity resources from</param>
/// <see cref="FileResourceLoader"/>
/// <see cref="SpringResourceLoader"/>
/// <see cref="InitSpringResourceLoader"/>
/// <see cref="CreateVelocityEngine"/>
[CLSCompliant(false)]
protected void InitVelocityResourceLoader(VelocityEngine velocityEngine, ExtendedProperties extendedProperties, IList<string> paths)
{
if (PreferFileSystemAccess) {
// Try to load via the file system, fall back to SpringResourceLoader
// (for hot detection of template changes, if possible).
IList<string> resolvedPaths = new List<string>();
try {
foreach (string path in paths) {
IResource resource = ResourceLoader.GetResource(path);
resolvedPaths.Add(resource.File.FullName);
}
extendedProperties.SetProperty(RuntimeConstants.RESOURCE_LOADER, VelocityConstants.File);
extendedProperties.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH,
StringUtils.CollectionToCommaDelimitedString(resolvedPaths));
} catch (IOException ex) {
if (log.IsDebugEnabled) {
log.Error(string.Format("Cannot resolve resource loader path [{0}] to [File]: using SpringResourceLoader",
StringUtils.CollectionToCommaDelimitedString(resolvedPaths)), ex);
}
InitSpringResourceLoader(velocityEngine, extendedProperties, StringUtils.CollectionToCommaDelimitedString(paths));
}
} else {
// Always load via SpringResourceLoader (without hot detection of template changes).
if (log.IsDebugEnabled) {
log.Debug("File system access not preferred: using SpringResourceLoader");
}
InitSpringResourceLoader(velocityEngine, extendedProperties, StringUtils.CollectionToCommaDelimitedString(paths));
}
}
/// <summary>
/// Initialize a SpringResourceLoader for the given VelocityEngine.
/// <br/>Called by <code>InitVelocityResourceLoader</code>.
///
/// <b>Important</b>: the NVeloctity ResourceLoaderFactory.getLoader
/// method replaces ';' with ',' when attempting to construct our resource
/// loader. The name on the SPRING_RESOURCE_LOADER_CLASS property
/// has to be in the form of "ClassFullName; AssemblyName" in replacement
/// of the tranditional "ClassFullName, AssemblyName" to work.
/// </summary>
/// <param name="velocityEngine">velocityEngine the VelocityEngine to configure</param>
/// <param name="extendedProperties"></param>
/// <param name="resourceLoaderPathString">resourceLoaderPath the path to load Velocity resources from</param>
/// <see cref="SpringResourceLoader"/>
/// <see cref="InitVelocityResourceLoader"/>
[CLSCompliant(false)]
protected void InitSpringResourceLoader(VelocityEngine velocityEngine, ExtendedProperties extendedProperties, string resourceLoaderPathString)
{
extendedProperties.SetProperty(RuntimeConstants.RESOURCE_LOADER, SpringResourceLoader.NAME);
Type springResourceLoaderType = typeof(SpringResourceLoader);
string springResourceLoaderTypeName = springResourceLoaderType.FullName + "; " + springResourceLoaderType.Assembly.GetName().Name;
extendedProperties.SetProperty(SpringResourceLoader.SPRING_RESOURCE_LOADER_CLASS, springResourceLoaderTypeName);
velocityEngine.SetApplicationAttribute(SpringResourceLoader.SPRING_RESOURCE_LOADER, ResourceLoader);
velocityEngine.SetApplicationAttribute(SpringResourceLoader.SPRING_RESOURCE_LOADER_PATH, resourceLoaderPathString);
}
/// <summary>
/// To be implemented by subclasses that want to to perform custom
/// post-processing of the VelocityEngine after this FactoryObject
/// performed its default configuration (but before VelocityEngine.init)
/// <br/>
/// Called by CreateVelocityEngine
/// </summary>
/// <param name="velocityEngine">velocityEngine the current VelocityEngine</param>
/// <exception cref="IOException" />
/// <see cref="CreateVelocityEngine"/>
/// <see cref="VelocityEngine.Init()"/>
[CLSCompliant(false)]
protected virtual void PostProcessVelocityEngine(VelocityEngine velocityEngine)
{
}
/// <summary>
/// Populates the velocity properties from the given resource
/// </summary>
/// <param name="extendedProperties">ExtendedProperties instance to populate</param>
/// <param name="resource">The resource from which to load the properties</param>
/// <param name="append">A flag indicated weather the properties loaded from the resource should be appended or replaced in the extendedProperties</param>
private static void FillProperties(ExtendedProperties extendedProperties, IInputStreamSource resource, bool append) {
try {
if (append) {
extendedProperties.Load(resource.InputStream);
} else {
ExtendedProperties overrides = new ExtendedProperties();
overrides.Load(resource.InputStream);
foreach (DictionaryEntry entry in overrides) {
extendedProperties.SetProperty(Convert.ToString(entry.Key), entry.Value);
}
}
} finally {
resource.InputStream.Close();
}
}
}
}
| |
namespace NAudio.Wave
{
/// <summary>
/// Summary description for WaveFormatEncoding.
/// </summary>
public enum WaveFormatEncoding : ushort
{
/// <summary>WAVE_FORMAT_UNKNOWN, Microsoft Corporation</summary>
Unknown = 0x0000,
/// <summary>WAVE_FORMAT_PCM Microsoft Corporation</summary>
Pcm = 0x0001,
/// <summary>WAVE_FORMAT_ADPCM Microsoft Corporation</summary>
Adpcm = 0x0002,
/// <summary>WAVE_FORMAT_IEEE_FLOAT Microsoft Corporation</summary>
IeeeFloat = 0x0003,
/// <summary>WAVE_FORMAT_VSELP Compaq Computer Corp.</summary>
Vselp = 0x0004,
/// <summary>WAVE_FORMAT_IBM_CVSD IBM Corporation</summary>
IbmCvsd = 0x0005,
/// <summary>WAVE_FORMAT_ALAW Microsoft Corporation</summary>
ALaw = 0x0006,
/// <summary>WAVE_FORMAT_MULAW Microsoft Corporation</summary>
MuLaw = 0x0007,
/// <summary>WAVE_FORMAT_DTS Microsoft Corporation</summary>
Dts = 0x0008,
/// <summary>WAVE_FORMAT_DRM Microsoft Corporation</summary>
Drm = 0x0009,
/// <summary>WAVE_FORMAT_OKI_ADPCM OKI</summary>
OkiAdpcm = 0x0010,
/// <summary>WAVE_FORMAT_DVI_ADPCM Intel Corporation</summary>
DviAdpcm = 0x0011,
/// <summary>WAVE_FORMAT_IMA_ADPCM Intel Corporation</summary>
ImaAdpcm = DviAdpcm,
/// <summary>WAVE_FORMAT_MEDIASPACE_ADPCM Videologic</summary>
MediaspaceAdpcm = 0x0012,
/// <summary>WAVE_FORMAT_SIERRA_ADPCM Sierra Semiconductor Corp </summary>
SierraAdpcm = 0x0013,
/// <summary>WAVE_FORMAT_G723_ADPCM Antex Electronics Corporation </summary>
G723Adpcm = 0x0014,
/// <summary>WAVE_FORMAT_DIGISTD DSP Solutions, Inc.</summary>
DigiStd = 0x0015,
/// <summary>WAVE_FORMAT_DIGIFIX DSP Solutions, Inc.</summary>
DigiFix = 0x0016,
/// <summary>WAVE_FORMAT_DIALOGIC_OKI_ADPCM Dialogic Corporation</summary>
DialogicOkiAdpcm = 0x0017,
/// <summary>WAVE_FORMAT_MEDIAVISION_ADPCM Media Vision, Inc.</summary>
MediaVisionAdpcm = 0x0018,
/// <summary>WAVE_FORMAT_CU_CODEC Hewlett-Packard Company </summary>
CUCodec = 0x0019,
/// <summary>WAVE_FORMAT_YAMAHA_ADPCM Yamaha Corporation of America</summary>
YamahaAdpcm = 0x0020,
/// <summary>WAVE_FORMAT_SONARC Speech Compression</summary>
SonarC = 0x0021,
/// <summary>WAVE_FORMAT_DSPGROUP_TRUESPEECH DSP Group, Inc </summary>
DspGroupTrueSpeech = 0x0022,
/// <summary>WAVE_FORMAT_ECHOSC1 Echo Speech Corporation</summary>
EchoSpeechCorporation1 = 0x0023,
/// <summary>WAVE_FORMAT_AUDIOFILE_AF36, Virtual Music, Inc.</summary>
AudioFileAf36 = 0x0024,
/// <summary>WAVE_FORMAT_APTX Audio Processing Technology</summary>
Aptx = 0x0025,
/// <summary>WAVE_FORMAT_AUDIOFILE_AF10, Virtual Music, Inc.</summary>
AudioFileAf10 = 0x0026,
/// <summary>WAVE_FORMAT_PROSODY_1612, Aculab plc</summary>
Prosody1612 = 0x0027,
/// <summary>WAVE_FORMAT_LRC, Merging Technologies S.A. </summary>
Lrc = 0x0028,
/// <summary>WAVE_FORMAT_DOLBY_AC2, Dolby Laboratories</summary>
DolbyAc2 = 0x0030,
/// <summary>WAVE_FORMAT_GSM610, Microsoft Corporation</summary>
Gsm610 = 0x0031,
/// <summary>WAVE_FORMAT_MSNAUDIO, Microsoft Corporation</summary>
MsnAudio = 0x0032,
/// <summary>WAVE_FORMAT_ANTEX_ADPCME, Antex Electronics Corporation</summary>
AntexAdpcme = 0x0033,
/// <summary>WAVE_FORMAT_CONTROL_RES_VQLPC, Control Resources Limited </summary>
ControlResVqlpc = 0x0034,
/// <summary>WAVE_FORMAT_DIGIREAL, DSP Solutions, Inc. </summary>
DigiReal = 0x0035,
/// <summary>WAVE_FORMAT_DIGIADPCM, DSP Solutions, Inc.</summary>
DigiAdpcm = 0x0036,
/// <summary>WAVE_FORMAT_CONTROL_RES_CR10, Control Resources Limited</summary>
ControlResCr10 = 0x0037,
/// <summary></summary>
WAVE_FORMAT_NMS_VBXADPCM = 0x0038, // Natural MicroSystems
/// <summary></summary>
WAVE_FORMAT_CS_IMAADPCM = 0x0039, // Crystal Semiconductor IMA ADPCM
/// <summary></summary>
WAVE_FORMAT_ECHOSC3 = 0x003A, // Echo Speech Corporation
/// <summary></summary>
WAVE_FORMAT_ROCKWELL_ADPCM = 0x003B, // Rockwell International
/// <summary></summary>
WAVE_FORMAT_ROCKWELL_DIGITALK = 0x003C, // Rockwell International
/// <summary></summary>
WAVE_FORMAT_XEBEC = 0x003D, // Xebec Multimedia Solutions Limited
/// <summary></summary>
WAVE_FORMAT_G721_ADPCM = 0x0040, // Antex Electronics Corporation
/// <summary></summary>
WAVE_FORMAT_G728_CELP = 0x0041, // Antex Electronics Corporation
/// <summary></summary>
WAVE_FORMAT_MSG723 = 0x0042, // Microsoft Corporation
/// <summary></summary>
Mpeg = 0x0050, // WAVE_FORMAT_MPEG, Microsoft Corporation
/// <summary></summary>
WAVE_FORMAT_RT24 = 0x0052, // InSoft, Inc.
/// <summary></summary>
WAVE_FORMAT_PAC = 0x0053, // InSoft, Inc.
/// <summary></summary>
MpegLayer3 = 0x0055, // WAVE_FORMAT_MPEGLAYER3, ISO/MPEG Layer3 Format Tag
/// <summary></summary>
WAVE_FORMAT_LUCENT_G723 = 0x0059, // Lucent Technologies
/// <summary></summary>
WAVE_FORMAT_CIRRUS = 0x0060, // Cirrus Logic
/// <summary></summary>
WAVE_FORMAT_ESPCM = 0x0061, // ESS Technology
/// <summary></summary>
WAVE_FORMAT_VOXWARE = 0x0062, // Voxware Inc
/// <summary></summary>
WAVE_FORMAT_CANOPUS_ATRAC = 0x0063, // Canopus, co., Ltd.
/// <summary></summary>
WAVE_FORMAT_G726_ADPCM = 0x0064, // APICOM
/// <summary></summary>
WAVE_FORMAT_G722_ADPCM = 0x0065, // APICOM
/// <summary></summary>
WAVE_FORMAT_DSAT_DISPLAY = 0x0067, // Microsoft Corporation
/// <summary></summary>
WAVE_FORMAT_VOXWARE_BYTE_ALIGNED = 0x0069, // Voxware Inc
/// <summary></summary>
WAVE_FORMAT_VOXWARE_AC8 = 0x0070, // Voxware Inc
/// <summary></summary>
WAVE_FORMAT_VOXWARE_AC10 = 0x0071, // Voxware Inc
/// <summary></summary>
WAVE_FORMAT_VOXWARE_AC16 = 0x0072, // Voxware Inc
/// <summary></summary>
WAVE_FORMAT_VOXWARE_AC20 = 0x0073, // Voxware Inc
/// <summary></summary>
WAVE_FORMAT_VOXWARE_RT24 = 0x0074, // Voxware Inc
/// <summary></summary>
WAVE_FORMAT_VOXWARE_RT29 = 0x0075, // Voxware Inc
/// <summary></summary>
WAVE_FORMAT_VOXWARE_RT29HW = 0x0076, // Voxware Inc
/// <summary></summary>
WAVE_FORMAT_VOXWARE_VR12 = 0x0077, // Voxware Inc
/// <summary></summary>
WAVE_FORMAT_VOXWARE_VR18 = 0x0078, // Voxware Inc
/// <summary></summary>
WAVE_FORMAT_VOXWARE_TQ40 = 0x0079, // Voxware Inc
/// <summary></summary>
WAVE_FORMAT_SOFTSOUND = 0x0080, // Softsound, Ltd.
/// <summary></summary>
WAVE_FORMAT_VOXWARE_TQ60 = 0x0081, // Voxware Inc
/// <summary></summary>
WAVE_FORMAT_MSRT24 = 0x0082, // Microsoft Corporation
/// <summary></summary>
WAVE_FORMAT_G729A = 0x0083, // AT&T Labs, Inc.
/// <summary></summary>
WAVE_FORMAT_MVI_MVI2 = 0x0084, // Motion Pixels
/// <summary></summary>
WAVE_FORMAT_DF_G726 = 0x0085, // DataFusion Systems (Pty) (Ltd)
/// <summary></summary>
WAVE_FORMAT_DF_GSM610 = 0x0086, // DataFusion Systems (Pty) (Ltd)
/// <summary></summary>
WAVE_FORMAT_ISIAUDIO = 0x0088, // Iterated Systems, Inc.
/// <summary></summary>
WAVE_FORMAT_ONLIVE = 0x0089, // OnLive! Technologies, Inc.
/// <summary></summary>
WAVE_FORMAT_SBC24 = 0x0091, // Siemens Business Communications Sys
/// <summary></summary>
WAVE_FORMAT_DOLBY_AC3_SPDIF = 0x0092, // Sonic Foundry
/// <summary></summary>
WAVE_FORMAT_MEDIASONIC_G723 = 0x0093, // MediaSonic
/// <summary></summary>
WAVE_FORMAT_PROSODY_8KBPS = 0x0094, // Aculab plc
/// <summary></summary>
WAVE_FORMAT_ZYXEL_ADPCM = 0x0097, // ZyXEL Communications, Inc.
/// <summary></summary>
WAVE_FORMAT_PHILIPS_LPCBB = 0x0098, // Philips Speech Processing
/// <summary></summary>
WAVE_FORMAT_PACKED = 0x0099, // Studer Professional Audio AG
/// <summary></summary>
WAVE_FORMAT_MALDEN_PHONYTALK = 0x00A0, // Malden Electronics Ltd.
/// <summary>WAVE_FORMAT_GSM</summary>
Gsm = 0x00A1,
/// <summary>WAVE_FORMAT_G729</summary>
G729 = 0x00A2,
/// <summary>WAVE_FORMAT_G723</summary>
G723 = 0x00A3,
/// <summary>WAVE_FORMAT_ACELP</summary>
Acelp = 0x00A4,
/// <summary></summary>
WAVE_FORMAT_RHETOREX_ADPCM = 0x0100, // Rhetorex Inc.
/// <summary></summary>
WAVE_FORMAT_IRAT = 0x0101, // BeCubed Software Inc.
/// <summary></summary>
WAVE_FORMAT_VIVO_G723 = 0x0111, // Vivo Software
/// <summary></summary>
WAVE_FORMAT_VIVO_SIREN = 0x0112, // Vivo Software
/// <summary></summary>
WAVE_FORMAT_DIGITAL_G723 = 0x0123, // Digital Equipment Corporation
/// <summary></summary>
WAVE_FORMAT_SANYO_LD_ADPCM = 0x0125, // Sanyo Electric Co., Ltd.
/// <summary></summary>
WAVE_FORMAT_SIPROLAB_ACEPLNET = 0x0130, // Sipro Lab Telecom Inc.
/// <summary></summary>
WAVE_FORMAT_SIPROLAB_ACELP4800 = 0x0131, // Sipro Lab Telecom Inc.
/// <summary></summary>
WAVE_FORMAT_SIPROLAB_ACELP8V3 = 0x0132, // Sipro Lab Telecom Inc.
/// <summary></summary>
WAVE_FORMAT_SIPROLAB_G729 = 0x0133, // Sipro Lab Telecom Inc.
/// <summary></summary>
WAVE_FORMAT_SIPROLAB_G729A = 0x0134, // Sipro Lab Telecom Inc.
/// <summary></summary>
WAVE_FORMAT_SIPROLAB_KELVIN = 0x0135, // Sipro Lab Telecom Inc.
/// <summary></summary>
WAVE_FORMAT_G726ADPCM = 0x0140, // Dictaphone Corporation
/// <summary></summary>
WAVE_FORMAT_QUALCOMM_PUREVOICE = 0x0150, // Qualcomm, Inc.
/// <summary></summary>
WAVE_FORMAT_QUALCOMM_HALFRATE = 0x0151, // Qualcomm, Inc.
/// <summary></summary>
WAVE_FORMAT_TUBGSM = 0x0155, // Ring Zero Systems, Inc.
/// <summary></summary>
WAVE_FORMAT_MSAUDIO1 = 0x0160, // Microsoft Corporation
/// <summary>
/// WAVE_FORMAT_WMAUDIO2, Microsoft Corporation
/// </summary>
WAVE_FORMAT_WMAUDIO2 = 0x0161,
/// <summary>
/// WAVE_FORMAT_WMAUDIO3, Microsoft Corporation
/// </summary>
WAVE_FORMAT_WMAUDIO3 = 0x0162,
/// <summary></summary>
WAVE_FORMAT_UNISYS_NAP_ADPCM = 0x0170, // Unisys Corp.
/// <summary></summary>
WAVE_FORMAT_UNISYS_NAP_ULAW = 0x0171, // Unisys Corp.
/// <summary></summary>
WAVE_FORMAT_UNISYS_NAP_ALAW = 0x0172, // Unisys Corp.
/// <summary></summary>
WAVE_FORMAT_UNISYS_NAP_16K = 0x0173, // Unisys Corp.
/// <summary></summary>
WAVE_FORMAT_CREATIVE_ADPCM = 0x0200, // Creative Labs, Inc
/// <summary></summary>
WAVE_FORMAT_CREATIVE_FASTSPEECH8 = 0x0202, // Creative Labs, Inc
/// <summary></summary>
WAVE_FORMAT_CREATIVE_FASTSPEECH10 = 0x0203, // Creative Labs, Inc
/// <summary></summary>
WAVE_FORMAT_UHER_ADPCM = 0x0210, // UHER informatic GmbH
/// <summary></summary>
WAVE_FORMAT_QUARTERDECK = 0x0220, // Quarterdeck Corporation
/// <summary></summary>
WAVE_FORMAT_ILINK_VC = 0x0230, // I-link Worldwide
/// <summary></summary>
WAVE_FORMAT_RAW_SPORT = 0x0240, // Aureal Semiconductor
/// <summary></summary>
WAVE_FORMAT_ESST_AC3 = 0x0241, // ESS Technology, Inc.
/// <summary></summary>
WAVE_FORMAT_IPI_HSX = 0x0250, // Interactive Products, Inc.
/// <summary></summary>
WAVE_FORMAT_IPI_RPELP = 0x0251, // Interactive Products, Inc.
/// <summary></summary>
WAVE_FORMAT_CS2 = 0x0260, // Consistent Software
/// <summary></summary>
WAVE_FORMAT_SONY_SCX = 0x0270, // Sony Corp.
/// <summary></summary>
WAVE_FORMAT_FM_TOWNS_SND = 0x0300, // Fujitsu Corp.
/// <summary></summary>
WAVE_FORMAT_BTV_DIGITAL = 0x0400, // Brooktree Corporation
/// <summary></summary>
WAVE_FORMAT_QDESIGN_MUSIC = 0x0450, // QDesign Corporation
/// <summary></summary>
WAVE_FORMAT_VME_VMPCM = 0x0680, // AT&T Labs, Inc.
/// <summary></summary>
WAVE_FORMAT_TPC = 0x0681, // AT&T Labs, Inc.
/// <summary></summary>
WAVE_FORMAT_OLIGSM = 0x1000, // Ing C. Olivetti & C., S.p.A.
/// <summary></summary>
WAVE_FORMAT_OLIADPCM = 0x1001, // Ing C. Olivetti & C., S.p.A.
/// <summary></summary>
WAVE_FORMAT_OLICELP = 0x1002, // Ing C. Olivetti & C., S.p.A.
/// <summary></summary>
WAVE_FORMAT_OLISBC = 0x1003, // Ing C. Olivetti & C., S.p.A.
/// <summary></summary>
WAVE_FORMAT_OLIOPR = 0x1004, // Ing C. Olivetti & C., S.p.A.
/// <summary></summary>
WAVE_FORMAT_LH_CODEC = 0x1100, // Lernout & Hauspie
/// <summary></summary>
WAVE_FORMAT_NORRIS = 0x1400, // Norris Communications, Inc.
/// <summary></summary>
WAVE_FORMAT_SOUNDSPACE_MUSICOMPRESS = 0x1500, // AT&T Labs, Inc.
/// <summary></summary>
WAVE_FORMAT_DVM = 0x2000, // FAST Multimedia AG
/// <summary>WAVE_FORMAT_EXTENSIBLE</summary>
Extensible = 0xFFFE, // Microsoft
/// <summary></summary>
WAVE_FORMAT_DEVELOPMENT = 0xFFFF,
// others - not from MS headers
/// <summary>WAVE_FORMAT_VORBIS1 "Og" Original stream compatible</summary>
Vorbis1 = 0x674f,
/// <summary>WAVE_FORMAT_VORBIS2 "Pg" Have independent header</summary>
Vorbis2 = 0x6750,
/// <summary>WAVE_FORMAT_VORBIS3 "Qg" Have no codebook header</summary>
Vorbis3 = 0x6751,
/// <summary>WAVE_FORMAT_VORBIS1P "og" Original stream compatible</summary>
Vorbis1P = 0x676f,
/// <summary>WAVE_FORMAT_VORBIS2P "pg" Have independent headere</summary>
Vorbis2P = 0x6770,
/// <summary>WAVE_FORMAT_VORBIS3P "qg" Have no codebook header</summary>
Vorbis3P = 0x6771,
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using Validation;
using Xunit;
namespace System.Collections.Immutable.Tests
{
public abstract class ImmutableDictionaryTestBase : ImmutablesTestBase
{
[Fact]
public virtual void EmptyTest()
{
this.EmptyTestHelper(Empty<int, bool>(), 5);
}
[Fact]
public void EnumeratorTest()
{
this.EnumeratorTestHelper(this.Empty<int, GenericParameterHelper>());
}
[Fact]
public void ContainsTest()
{
this.ContainsTestHelper(Empty<int, string>(), 5, "foo");
}
[Fact]
public void RemoveTest()
{
this.RemoveTestHelper(Empty<int, GenericParameterHelper>(), 5);
}
[Fact]
public void KeysTest()
{
this.KeysTestHelper(Empty<int, bool>(), 5);
}
[Fact]
public void ValuesTest()
{
this.ValuesTestHelper(Empty<int, bool>(), 5);
}
[Fact]
public void AddAscendingTest()
{
this.AddAscendingTestHelper(Empty<int, GenericParameterHelper>());
}
[Fact]
public void AddRangeTest()
{
var map = Empty<int, GenericParameterHelper>();
map = map.AddRange(Enumerable.Range(1, 100).Select(n => new KeyValuePair<int, GenericParameterHelper>(n, new GenericParameterHelper())));
CollectionAssertAreEquivalent(map.Select(kv => kv.Key).ToList(), Enumerable.Range(1, 100).ToList());
this.VerifyAvlTreeState(map);
Assert.Equal(100, map.Count);
// Test optimization for empty map.
var map2 = Empty<int, GenericParameterHelper>();
var jointMap = map2.AddRange(map);
Assert.Same(map, jointMap);
jointMap = map2.AddRange(map.ToReadOnlyDictionary());
Assert.Same(map, jointMap);
jointMap = map2.AddRange(map.ToBuilder());
Assert.Same(map, jointMap);
}
[Fact]
public void AddDescendingTest()
{
this.AddDescendingTestHelper(Empty<int, GenericParameterHelper>());
}
[Fact]
public void AddRemoveRandomDataTest()
{
this.AddRemoveRandomDataTestHelper(Empty<double, GenericParameterHelper>());
}
[Fact]
public void AddRemoveEnumerableTest()
{
this.AddRemoveEnumerableTestHelper(Empty<int, int>());
}
[Fact]
public void SetItemTest()
{
var map = this.Empty<string, int>()
.SetItem("Microsoft", 100)
.SetItem("Corporation", 50);
Assert.Equal(2, map.Count);
map = map.SetItem("Microsoft", 200);
Assert.Equal(2, map.Count);
Assert.Equal(200, map["Microsoft"]);
// Set it to the same thing again and make sure it's all good.
var sameMap = map.SetItem("Microsoft", 200);
Assert.Same(map, sameMap);
}
[Fact]
public void SetItemsTest()
{
var template = new Dictionary<string, int>
{
{ "Microsoft", 100 },
{ "Corporation", 50 },
};
var map = this.Empty<string, int>().SetItems(template);
Assert.Equal(2, map.Count);
var changes = new Dictionary<string, int>
{
{ "Microsoft", 150 },
{ "Dogs", 90 },
};
map = map.SetItems(changes);
Assert.Equal(3, map.Count);
Assert.Equal(150, map["Microsoft"]);
Assert.Equal(50, map["Corporation"]);
Assert.Equal(90, map["Dogs"]);
map = map.SetItems(
new[] {
new KeyValuePair<string, int>("Microsoft", 80),
new KeyValuePair<string, int>("Microsoft", 70),
});
Assert.Equal(3, map.Count);
Assert.Equal(70, map["Microsoft"]);
Assert.Equal(50, map["Corporation"]);
Assert.Equal(90, map["Dogs"]);
map = this.Empty<string, int>().SetItems(new[] { // use an array for code coverage
new KeyValuePair<string, int>("a", 1), new KeyValuePair<string, int>("b", 2),
new KeyValuePair<string, int>("a", 3),
});
Assert.Equal(2, map.Count);
Assert.Equal(3, map["a"]);
Assert.Equal(2, map["b"]);
}
[Fact]
public void ContainsKeyTest()
{
this.ContainsKeyTestHelper(Empty<int, GenericParameterHelper>(), 1, new GenericParameterHelper());
}
[Fact]
public void IndexGetNonExistingKeyThrowsTest()
{
Assert.Throws<KeyNotFoundException>(() => this.Empty<int, int>()[3]);
}
[Fact]
public void IndexGetTest()
{
var map = this.Empty<int, int>().Add(3, 5);
Assert.Equal(5, map[3]);
}
[Fact]
public void DictionaryRemoveThrowsTest()
{
IDictionary<int, int> map = this.Empty<int, int>().Add(5, 3).ToReadOnlyDictionary();
Assert.Throws<NotSupportedException>(() => map.Remove(5));
}
[Fact]
public void DictionaryAddThrowsTest()
{
IDictionary<int, int> map = this.Empty<int, int>().ToReadOnlyDictionary();
Assert.Throws<NotSupportedException>(() => map.Add(5, 3));
}
[Fact]
public void DictionaryIndexSetThrowsTest()
{
IDictionary<int, int> map = this.Empty<int, int>().ToReadOnlyDictionary();
Assert.Throws<NotSupportedException>(() => map[3] = 5);
}
[Fact]
public void EqualsTest()
{
Assert.False(Empty<int, int>().Equals(null));
Assert.False(Empty<int, int>().Equals("hi"));
Assert.True(Empty<int, int>().Equals(Empty<int, int>()));
Assert.False(Empty<int, int>().Add(3, 2).Equals(Empty<int, int>().Add(3, 2)));
Assert.False(Empty<int, int>().Add(3, 2).Equals(Empty<int, int>().Add(3, 1)));
Assert.False(Empty<int, int>().Add(5, 1).Equals(Empty<int, int>().Add(3, 1)));
Assert.False(Empty<int, int>().Add(3, 1).Add(5, 1).Equals(Empty<int, int>().Add(3, 1)));
Assert.False(Empty<int, int>().Add(3, 1).Equals(Empty<int, int>().Add(3, 1).Add(5, 1)));
Assert.True(Empty<int, int>().ToReadOnlyDictionary().Equals(Empty<int, int>()));
Assert.True(Empty<int, int>().Equals(Empty<int, int>().ToReadOnlyDictionary()));
Assert.True(Empty<int, int>().ToReadOnlyDictionary().Equals(Empty<int, int>().ToReadOnlyDictionary()));
Assert.False(Empty<int, int>().Add(3, 1).ToReadOnlyDictionary().Equals(Empty<int, int>()));
Assert.False(Empty<int, int>().Equals(Empty<int, int>().Add(3, 1).ToReadOnlyDictionary()));
Assert.False(Empty<int, int>().ToReadOnlyDictionary().Equals(Empty<int, int>().Add(3, 1).ToReadOnlyDictionary()));
}
/// <summary>
/// Verifies that the GetHashCode method returns the standard one.
/// </summary>
[Fact]
public void GetHashCodeTest()
{
var dictionary = Empty<string, int>();
Assert.Equal(EqualityComparer<object>.Default.GetHashCode(dictionary), dictionary.GetHashCode());
}
[Fact]
public void ICollectionOfKVMembers()
{
var dictionary = (ICollection<KeyValuePair<string, int>>)Empty<string, int>();
Assert.Throws<NotSupportedException>(() => dictionary.Add(new KeyValuePair<string, int>()));
Assert.Throws<NotSupportedException>(() => dictionary.Remove(new KeyValuePair<string, int>()));
Assert.Throws<NotSupportedException>(() => dictionary.Clear());
Assert.True(dictionary.IsReadOnly);
}
[Fact]
public void ICollectionMembers()
{
((ICollection)Empty<string, int>()).CopyTo(new object[0], 0);
var dictionary = (ICollection)Empty<string, int>().Add("a", 1);
Assert.True(dictionary.IsSynchronized);
Assert.NotNull(dictionary.SyncRoot);
Assert.Same(dictionary.SyncRoot, dictionary.SyncRoot);
var array = new object[2];
dictionary.CopyTo(array, 1);
Assert.Null(array[0]);
Assert.Equal(new DictionaryEntry("a", 1), (DictionaryEntry)array[1]);
}
[Fact]
public void IDictionaryOfKVMembers()
{
var dictionary = (IDictionary<string, int>)Empty<string, int>().Add("c", 3);
Assert.Throws<NotSupportedException>(() => dictionary.Add("a", 1));
Assert.Throws<NotSupportedException>(() => dictionary.Remove("a"));
Assert.Throws<NotSupportedException>(() => dictionary["a"] = 2);
Assert.Throws<KeyNotFoundException>(() => dictionary["a"]);
Assert.Equal(3, dictionary["c"]);
}
[Fact]
public void IDictionaryMembers()
{
var dictionary = (IDictionary)Empty<string, int>().Add("c", 3);
Assert.Throws<NotSupportedException>(() => dictionary.Add("a", 1));
Assert.Throws<NotSupportedException>(() => dictionary.Remove("a"));
Assert.Throws<NotSupportedException>(() => dictionary["a"] = 2);
Assert.Throws<NotSupportedException>(() => dictionary.Clear());
Assert.False(dictionary.Contains("a"));
Assert.True(dictionary.Contains("c"));
Assert.Throws<KeyNotFoundException>(() => dictionary["a"]);
Assert.Equal(3, dictionary["c"]);
Assert.True(dictionary.IsFixedSize);
Assert.True(dictionary.IsReadOnly);
Assert.Equal(new[] { "c" }, dictionary.Keys.Cast<string>().ToArray());
Assert.Equal(new[] { 3 }, dictionary.Values.Cast<int>().ToArray());
}
[Fact]
public void IDictionaryEnumerator()
{
var dictionary = (IDictionary)Empty<string, int>().Add("a", 1);
var enumerator = dictionary.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.True(enumerator.MoveNext());
Assert.Equal(enumerator.Entry, enumerator.Current);
Assert.Equal(enumerator.Key, enumerator.Entry.Key);
Assert.Equal(enumerator.Value, enumerator.Entry.Value);
Assert.Equal("a", enumerator.Key);
Assert.Equal(1, enumerator.Value);
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.False(enumerator.MoveNext());
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.True(enumerator.MoveNext());
Assert.Equal(enumerator.Key, ((DictionaryEntry)enumerator.Current).Key);
Assert.Equal(enumerator.Value, ((DictionaryEntry)enumerator.Current).Value);
Assert.Equal("a", enumerator.Key);
Assert.Equal(1, enumerator.Value);
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.False(enumerator.MoveNext());
}
[Fact]
public void TryGetKey()
{
var dictionary = Empty<int>(StringComparer.OrdinalIgnoreCase)
.Add("a", 1);
string actualKey;
Assert.True(dictionary.TryGetKey("a", out actualKey));
Assert.Equal("a", actualKey);
Assert.True(dictionary.TryGetKey("A", out actualKey));
Assert.Equal("a", actualKey);
Assert.False(dictionary.TryGetKey("b", out actualKey));
Assert.Equal("b", actualKey);
}
protected void EmptyTestHelper<K, V>(IImmutableDictionary<K, V> empty, K someKey)
{
Assert.Same(empty, empty.Clear());
Assert.Equal(0, empty.Count);
Assert.Equal(0, empty.Count());
Assert.Equal(0, empty.Keys.Count());
Assert.Equal(0, empty.Values.Count());
Assert.Same(EqualityComparer<V>.Default, GetValueComparer(empty));
Assert.False(empty.ContainsKey(someKey));
Assert.False(empty.Contains(new KeyValuePair<K, V>(someKey, default(V))));
Assert.Equal(default(V), empty.GetValueOrDefault(someKey));
V value;
Assert.False(empty.TryGetValue(someKey, out value));
Assert.Equal(default(V), value);
}
private IImmutableDictionary<TKey, TValue> AddTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value) where TKey : IComparable<TKey>
{
Contract.Requires(map != null);
Contract.Requires(key != null);
IImmutableDictionary<TKey, TValue> addedMap = map.Add(key, value);
Assert.NotSame(map, addedMap);
////Assert.Equal(map.Count + 1, addedMap.Count);
Assert.False(map.ContainsKey(key));
Assert.True(addedMap.ContainsKey(key));
AssertAreSame(value, addedMap.GetValueOrDefault(key));
this.VerifyAvlTreeState(addedMap);
return addedMap;
}
protected void AddAscendingTestHelper(IImmutableDictionary<int, GenericParameterHelper> map)
{
Contract.Requires(map != null);
for (int i = 0; i < 10; i++)
{
map = this.AddTestHelper(map, i, new GenericParameterHelper(i));
}
Assert.Equal(10, map.Count);
for (int i = 0; i < 10; i++)
{
Assert.True(map.ContainsKey(i));
}
}
protected void AddDescendingTestHelper(IImmutableDictionary<int, GenericParameterHelper> map)
{
for (int i = 10; i > 0; i--)
{
map = this.AddTestHelper(map, i, new GenericParameterHelper(i));
}
Assert.Equal(10, map.Count);
for (int i = 10; i > 0; i--)
{
Assert.True(map.ContainsKey(i));
}
}
protected void AddRemoveRandomDataTestHelper(IImmutableDictionary<double, GenericParameterHelper> map)
{
Contract.Requires(map != null);
double[] inputs = GenerateDummyFillData();
for (int i = 0; i < inputs.Length; i++)
{
map = this.AddTestHelper(map, inputs[i], new GenericParameterHelper());
}
Assert.Equal(inputs.Length, map.Count);
for (int i = 0; i < inputs.Length; i++)
{
Assert.True(map.ContainsKey(inputs[i]));
}
for (int i = 0; i < inputs.Length; i++)
{
map = map.Remove(inputs[i]);
this.VerifyAvlTreeState(map);
}
Assert.Equal(0, map.Count);
}
protected void AddRemoveEnumerableTestHelper(IImmutableDictionary<int, int> empty)
{
Contract.Requires(empty != null);
Assert.Same(empty, empty.RemoveRange(Enumerable.Empty<int>()));
Assert.Same(empty, empty.AddRange(Enumerable.Empty<KeyValuePair<int, int>>()));
var list = new List<KeyValuePair<int, int>> { new KeyValuePair<int, int>(3, 5), new KeyValuePair<int, int>(8, 10) };
var nonEmpty = empty.AddRange(list);
this.VerifyAvlTreeState(nonEmpty);
var halfRemoved = nonEmpty.RemoveRange(Enumerable.Range(1, 5));
Assert.Equal(1, halfRemoved.Count);
Assert.True(halfRemoved.ContainsKey(8));
this.VerifyAvlTreeState(halfRemoved);
}
protected void AddExistingKeySameValueTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value1, TValue value2)
{
Contract.Requires(map != null);
Contract.Requires(key != null);
Contract.Requires(GetValueComparer(map).Equals(value1, value2));
map = map.Add(key, value1);
Assert.Same(map, map.Add(key, value2));
Assert.Same(map, map.AddRange(new[] { new KeyValuePair<TKey, TValue>(key, value2) }));
}
/// <summary>
/// Verifies that adding a key-value pair where the key already is in the map but with a different value throws.
/// </summary>
/// <typeparam name="TKey">The type of key in the map.</typeparam>
/// <typeparam name="TValue">The type of value in the map.</typeparam>
/// <param name="map">The map to manipulate.</param>
/// <param name="key">The key to add.</param>
/// <param name="value1">The first value to add.</param>
/// <param name="value2">The second value to add.</param>
/// <remarks>
/// Adding a key-value pair to a map where that key already exists, but with a different value, cannot fit the
/// semantic of "adding", either by just returning or mutating the value on the existing key. Throwing is the only reasonable response.
/// </remarks>
protected void AddExistingKeyDifferentValueTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value1, TValue value2)
{
Contract.Requires(map != null);
Contract.Requires(key != null);
Contract.Requires(!GetValueComparer(map).Equals(value1, value2));
var map1 = map.Add(key, value1);
var map2 = map.Add(key, value2);
Assert.Throws<ArgumentException>(() => map1.Add(key, value2));
Assert.Throws<ArgumentException>(() => map2.Add(key, value1));
}
protected void ContainsKeyTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value)
{
Assert.False(map.ContainsKey(key));
Assert.True(map.Add(key, value).ContainsKey(key));
}
protected void ContainsTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value)
{
Assert.False(map.Contains(new KeyValuePair<TKey, TValue>(key, value)));
Assert.False(map.Contains(key, value));
Assert.True(map.Add(key, value).Contains(new KeyValuePair<TKey, TValue>(key, value)));
Assert.True(map.Add(key, value).Contains(key, value));
}
protected void RemoveTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key)
{
// no-op remove
Assert.Same(map, map.Remove(key));
Assert.Same(map, map.RemoveRange(Enumerable.Empty<TKey>()));
// substantial remove
var addedMap = map.Add(key, default(TValue));
var removedMap = addedMap.Remove(key);
Assert.NotSame(addedMap, removedMap);
Assert.False(removedMap.ContainsKey(key));
}
protected void KeysTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key)
{
Assert.Equal(0, map.Keys.Count());
Assert.Equal(0, map.ToReadOnlyDictionary().Keys.Count());
var nonEmpty = map.Add(key, default(TValue));
Assert.Equal(1, nonEmpty.Keys.Count());
Assert.Equal(1, nonEmpty.ToReadOnlyDictionary().Keys.Count());
KeysOrValuesTestHelper(((IDictionary<TKey, TValue>)nonEmpty).Keys, key);
}
protected void ValuesTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key)
{
Assert.Equal(0, map.Values.Count());
Assert.Equal(0, map.ToReadOnlyDictionary().Values.Count());
var nonEmpty = map.Add(key, default(TValue));
Assert.Equal(1, nonEmpty.Values.Count());
Assert.Equal(1, nonEmpty.ToReadOnlyDictionary().Values.Count());
KeysOrValuesTestHelper(((IDictionary<TKey, TValue>)nonEmpty).Values, default(TValue));
}
protected void EnumeratorTestHelper(IImmutableDictionary<int, GenericParameterHelper> map)
{
for (int i = 0; i < 10; i++)
{
map = this.AddTestHelper(map, i, new GenericParameterHelper(i));
}
int j = 0;
foreach (KeyValuePair<int, GenericParameterHelper> pair in map)
{
Assert.Equal(j, pair.Key);
Assert.Equal(j, pair.Value.Data);
j++;
}
var list = map.ToList();
Assert.Equal<KeyValuePair<int, GenericParameterHelper>>(list, ImmutableSetTest.ToListNonGeneric<KeyValuePair<int, GenericParameterHelper>>(map));
// Apply some less common uses to the enumerator to test its metal.
using (var enumerator = map.GetEnumerator())
{
enumerator.Reset(); // reset isn't usually called before MoveNext
ManuallyEnumerateTest(list, enumerator);
enumerator.Reset();
ManuallyEnumerateTest(list, enumerator);
// this time only partially enumerate
enumerator.Reset();
enumerator.MoveNext();
enumerator.Reset();
ManuallyEnumerateTest(list, enumerator);
}
var manualEnum = map.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => manualEnum.Current);
while (manualEnum.MoveNext()) { }
Assert.False(manualEnum.MoveNext());
Assert.Throws<InvalidOperationException>(() => manualEnum.Current);
}
protected abstract IImmutableDictionary<TKey, TValue> Empty<TKey, TValue>();
protected abstract IImmutableDictionary<string, TValue> Empty<TValue>(StringComparer comparer);
protected abstract IEqualityComparer<TValue> GetValueComparer<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary);
internal abstract IBinaryTree GetRootNode<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary);
private static void KeysOrValuesTestHelper<T>(ICollection<T> collection, T containedValue)
{
Requires.NotNull(collection, "collection");
Assert.True(collection.Contains(containedValue));
Assert.Throws<NotSupportedException>(() => collection.Add(default(T)));
Assert.Throws<NotSupportedException>(() => collection.Clear());
var nonGeneric = (ICollection)collection;
Assert.NotNull(nonGeneric.SyncRoot);
Assert.Same(nonGeneric.SyncRoot, nonGeneric.SyncRoot);
Assert.True(nonGeneric.IsSynchronized);
Assert.True(collection.IsReadOnly);
Assert.Throws<ArgumentNullException>(() => nonGeneric.CopyTo(null, 0));
var array = new T[collection.Count + 1];
nonGeneric.CopyTo(array, 1);
Assert.Equal(default(T), array[0]);
Assert.Equal(array.Skip(1), nonGeneric.Cast<T>().ToArray());
}
private void VerifyAvlTreeState<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary)
{
var rootNode = this.GetRootNode(dictionary);
rootNode.VerifyBalanced();
rootNode.VerifyHeightIsWithinTolerance(dictionary.Count);
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="GeometryDrawing.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.KnownBoxes;
using MS.Internal.Collections;
using MS.Internal.PresentationCore;
using MS.Utility;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.ComponentModel.Design.Serialization;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Effects;
using System.Windows.Media.Media3D;
using System.Windows.Media.Animation;
using System.Windows.Media.Composition;
using System.Windows.Media.Imaging;
using System.Windows.Markup;
using System.Windows.Media.Converters;
using System.Security;
using System.Security.Permissions;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
// These types are aliased to match the unamanaged names used in interop
using BOOL = System.UInt32;
using WORD = System.UInt16;
using Float = System.Single;
namespace System.Windows.Media
{
sealed partial class GeometryDrawing : Drawing
{
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Shadows inherited Clone() with a strongly typed
/// version for convenience.
/// </summary>
public new GeometryDrawing Clone()
{
return (GeometryDrawing)base.Clone();
}
/// <summary>
/// Shadows inherited CloneCurrentValue() with a strongly typed
/// version for convenience.
/// </summary>
public new GeometryDrawing CloneCurrentValue()
{
return (GeometryDrawing)base.CloneCurrentValue();
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
private static void BrushPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// The first change to the default value of a mutable collection property (e.g. GeometryGroup.Children)
// will promote the property value from a default value to a local value. This is technically a sub-property
// change because the collection was changed and not a new collection set (GeometryGroup.Children.
// Add versus GeometryGroup.Children = myNewChildrenCollection). However, we never marshalled
// the default value to the compositor. If the property changes from a default value, the new local value
// needs to be marshalled to the compositor. We detect this scenario with the second condition
// e.OldValueSource != e.NewValueSource. Specifically in this scenario the OldValueSource will be
// Default and the NewValueSource will be Local.
if (e.IsASubPropertyChange &&
(e.OldValueSource == e.NewValueSource))
{
return;
}
GeometryDrawing target = ((GeometryDrawing) d);
Brush oldV = (Brush) e.OldValue;
Brush newV = (Brush) e.NewValue;
System.Windows.Threading.Dispatcher dispatcher = target.Dispatcher;
if (dispatcher != null)
{
DUCE.IResource targetResource = (DUCE.IResource)target;
using (CompositionEngineLock.Acquire())
{
int channelCount = targetResource.GetChannelCount();
for (int channelIndex = 0; channelIndex < channelCount; channelIndex++)
{
DUCE.Channel channel = targetResource.GetChannel(channelIndex);
Debug.Assert(!channel.IsOutOfBandChannel);
Debug.Assert(!targetResource.GetHandle(channel).IsNull);
target.ReleaseResource(oldV,channel);
target.AddRefResource(newV,channel);
}
}
}
target.PropertyChanged(BrushProperty);
}
private static void PenPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// The first change to the default value of a mutable collection property (e.g. GeometryGroup.Children)
// will promote the property value from a default value to a local value. This is technically a sub-property
// change because the collection was changed and not a new collection set (GeometryGroup.Children.
// Add versus GeometryGroup.Children = myNewChildrenCollection). However, we never marshalled
// the default value to the compositor. If the property changes from a default value, the new local value
// needs to be marshalled to the compositor. We detect this scenario with the second condition
// e.OldValueSource != e.NewValueSource. Specifically in this scenario the OldValueSource will be
// Default and the NewValueSource will be Local.
if (e.IsASubPropertyChange &&
(e.OldValueSource == e.NewValueSource))
{
return;
}
GeometryDrawing target = ((GeometryDrawing) d);
Pen oldV = (Pen) e.OldValue;
Pen newV = (Pen) e.NewValue;
System.Windows.Threading.Dispatcher dispatcher = target.Dispatcher;
if (dispatcher != null)
{
DUCE.IResource targetResource = (DUCE.IResource)target;
using (CompositionEngineLock.Acquire())
{
int channelCount = targetResource.GetChannelCount();
for (int channelIndex = 0; channelIndex < channelCount; channelIndex++)
{
DUCE.Channel channel = targetResource.GetChannel(channelIndex);
Debug.Assert(!channel.IsOutOfBandChannel);
Debug.Assert(!targetResource.GetHandle(channel).IsNull);
target.ReleaseResource(oldV,channel);
target.AddRefResource(newV,channel);
}
}
}
target.PropertyChanged(PenProperty);
}
private static void GeometryPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// The first change to the default value of a mutable collection property (e.g. GeometryGroup.Children)
// will promote the property value from a default value to a local value. This is technically a sub-property
// change because the collection was changed and not a new collection set (GeometryGroup.Children.
// Add versus GeometryGroup.Children = myNewChildrenCollection). However, we never marshalled
// the default value to the compositor. If the property changes from a default value, the new local value
// needs to be marshalled to the compositor. We detect this scenario with the second condition
// e.OldValueSource != e.NewValueSource. Specifically in this scenario the OldValueSource will be
// Default and the NewValueSource will be Local.
if (e.IsASubPropertyChange &&
(e.OldValueSource == e.NewValueSource))
{
return;
}
GeometryDrawing target = ((GeometryDrawing) d);
Geometry oldV = (Geometry) e.OldValue;
Geometry newV = (Geometry) e.NewValue;
System.Windows.Threading.Dispatcher dispatcher = target.Dispatcher;
if (dispatcher != null)
{
DUCE.IResource targetResource = (DUCE.IResource)target;
using (CompositionEngineLock.Acquire())
{
int channelCount = targetResource.GetChannelCount();
for (int channelIndex = 0; channelIndex < channelCount; channelIndex++)
{
DUCE.Channel channel = targetResource.GetChannel(channelIndex);
Debug.Assert(!channel.IsOutOfBandChannel);
Debug.Assert(!targetResource.GetHandle(channel).IsNull);
target.ReleaseResource(oldV,channel);
target.AddRefResource(newV,channel);
}
}
}
target.PropertyChanged(GeometryProperty);
}
#region Public Properties
/// <summary>
/// Brush - Brush. Default value is null.
/// </summary>
public Brush Brush
{
get
{
return (Brush) GetValue(BrushProperty);
}
set
{
SetValueInternal(BrushProperty, value);
}
}
/// <summary>
/// Pen - Pen. Default value is null.
/// </summary>
public Pen Pen
{
get
{
return (Pen) GetValue(PenProperty);
}
set
{
SetValueInternal(PenProperty, value);
}
}
/// <summary>
/// Geometry - Geometry. Default value is null.
/// </summary>
public Geometry Geometry
{
get
{
return (Geometry) GetValue(GeometryProperty);
}
set
{
SetValueInternal(GeometryProperty, value);
}
}
#endregion Public Properties
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
#region Protected Methods
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new GeometryDrawing();
}
#endregion ProtectedMethods
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
/// <SecurityNote>
/// Critical: This code calls into an unsafe code block
/// TreatAsSafe: This code does not return any critical data.It is ok to expose
/// Channels are safe to call into and do not go cross domain and cross process
/// </SecurityNote>
[SecurityCritical,SecurityTreatAsSafe]
internal override void UpdateResource(DUCE.Channel channel, bool skipOnChannelCheck)
{
// If we're told we can skip the channel check, then we must be on channel
Debug.Assert(!skipOnChannelCheck || _duceResource.IsOnChannel(channel));
if (skipOnChannelCheck || _duceResource.IsOnChannel(channel))
{
base.UpdateResource(channel, skipOnChannelCheck);
// Read values of properties into local variables
Brush vBrush = Brush;
Pen vPen = Pen;
Geometry vGeometry = Geometry;
// Obtain handles for properties that implement DUCE.IResource
DUCE.ResourceHandle hBrush = vBrush != null ? ((DUCE.IResource)vBrush).GetHandle(channel) : DUCE.ResourceHandle.Null;
DUCE.ResourceHandle hPen = vPen != null ? ((DUCE.IResource)vPen).GetHandle(channel) : DUCE.ResourceHandle.Null;
DUCE.ResourceHandle hGeometry = vGeometry != null ? ((DUCE.IResource)vGeometry).GetHandle(channel) : DUCE.ResourceHandle.Null;
// Pack & send command packet
DUCE.MILCMD_GEOMETRYDRAWING data;
unsafe
{
data.Type = MILCMD.MilCmdGeometryDrawing;
data.Handle = _duceResource.GetHandle(channel);
data.hBrush = hBrush;
data.hPen = hPen;
data.hGeometry = hGeometry;
// Send packed command structure
channel.SendCommand(
(byte*)&data,
sizeof(DUCE.MILCMD_GEOMETRYDRAWING));
}
}
}
internal override DUCE.ResourceHandle AddRefOnChannelCore(DUCE.Channel channel)
{
if (_duceResource.CreateOrAddRefOnChannel(this, channel, System.Windows.Media.Composition.DUCE.ResourceType.TYPE_GEOMETRYDRAWING))
{
Brush vBrush = Brush;
if (vBrush != null) ((DUCE.IResource)vBrush).AddRefOnChannel(channel);
Pen vPen = Pen;
if (vPen != null) ((DUCE.IResource)vPen).AddRefOnChannel(channel);
Geometry vGeometry = Geometry;
if (vGeometry != null) ((DUCE.IResource)vGeometry).AddRefOnChannel(channel);
AddRefOnChannelAnimations(channel);
UpdateResource(channel, true /* skip "on channel" check - we already know that we're on channel */ );
}
return _duceResource.GetHandle(channel);
}
internal override void ReleaseOnChannelCore(DUCE.Channel channel)
{
Debug.Assert(_duceResource.IsOnChannel(channel));
if (_duceResource.ReleaseOnChannel(channel))
{
Brush vBrush = Brush;
if (vBrush != null) ((DUCE.IResource)vBrush).ReleaseOnChannel(channel);
Pen vPen = Pen;
if (vPen != null) ((DUCE.IResource)vPen).ReleaseOnChannel(channel);
Geometry vGeometry = Geometry;
if (vGeometry != null) ((DUCE.IResource)vGeometry).ReleaseOnChannel(channel);
ReleaseOnChannelAnimations(channel);
}
}
internal override DUCE.ResourceHandle GetHandleCore(DUCE.Channel channel)
{
// Note that we are in a lock here already.
return _duceResource.GetHandle(channel);
}
internal override int GetChannelCountCore()
{
// must already be in composition lock here
return _duceResource.GetChannelCount();
}
internal override DUCE.Channel GetChannelCore(int index)
{
// Note that we are in a lock here already.
return _duceResource.GetChannel(index);
}
#endregion Internal Methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
#endregion Internal Properties
//------------------------------------------------------
//
// Dependency Properties
//
//------------------------------------------------------
#region Dependency Properties
/// <summary>
/// The DependencyProperty for the GeometryDrawing.Brush property.
/// </summary>
public static readonly DependencyProperty BrushProperty;
/// <summary>
/// The DependencyProperty for the GeometryDrawing.Pen property.
/// </summary>
public static readonly DependencyProperty PenProperty;
/// <summary>
/// The DependencyProperty for the GeometryDrawing.Geometry property.
/// </summary>
public static readonly DependencyProperty GeometryProperty;
#endregion Dependency Properties
//------------------------------------------------------
//
// Internal Fields
//
//------------------------------------------------------
#region Internal Fields
internal System.Windows.Media.Composition.DUCE.MultiChannelResource _duceResource = new System.Windows.Media.Composition.DUCE.MultiChannelResource();
#endregion Internal Fields
#region Constructors
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
static GeometryDrawing()
{
// We check our static default fields which are of type Freezable
// to make sure that they are not mutable, otherwise we will throw
// if these get touched by more than one thread in the lifetime
// of your app. (Windows OS Bug #947272)
//
// Initializations
Type typeofThis = typeof(GeometryDrawing);
BrushProperty =
RegisterProperty("Brush",
typeof(Brush),
typeofThis,
null,
new PropertyChangedCallback(BrushPropertyChanged),
null,
/* isIndependentlyAnimated = */ false,
/* coerceValueCallback */ null);
PenProperty =
RegisterProperty("Pen",
typeof(Pen),
typeofThis,
null,
new PropertyChangedCallback(PenPropertyChanged),
null,
/* isIndependentlyAnimated = */ false,
/* coerceValueCallback */ null);
GeometryProperty =
RegisterProperty("Geometry",
typeof(Geometry),
typeofThis,
null,
new PropertyChangedCallback(GeometryPropertyChanged),
null,
/* isIndependentlyAnimated = */ false,
/* coerceValueCallback */ null);
}
#endregion Constructors
}
}
| |
#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.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Text;
using Ctrip.Log4.Layout;
using Ctrip.Log4.Core;
using Ctrip.Log4.Util;
namespace Ctrip.Log4.Appender
{
/// <summary>
/// Sends logging events as connectionless UDP datagrams to a remote host or a
/// multicast group using an <see cref="UdpClient" />.
/// </summary>
/// <remarks>
/// <para>
/// UDP guarantees neither that messages arrive, nor that they arrive in the correct order.
/// </para>
/// <para>
/// To view the logging results, a custom application can be developed that listens for logging
/// events.
/// </para>
/// <para>
/// When decoding events send via this appender remember to use the same encoding
/// to decode the events as was used to send the events. See the <see cref="Encoding"/>
/// property to specify the encoding to use.
/// </para>
/// </remarks>
/// <example>
/// This example shows how to log receive logging events that are sent
/// on IP address 244.0.0.1 and port 8080 to the console. The event is
/// encoded in the packet as a unicode string and it is decoded as such.
/// <code lang="C#">
/// IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
/// UdpClient udpClient;
/// byte[] buffer;
/// string loggingEvent;
///
/// try
/// {
/// udpClient = new UdpClient(8080);
///
/// while(true)
/// {
/// buffer = udpClient.Receive(ref remoteEndPoint);
/// loggingEvent = System.Text.Encoding.Unicode.GetString(buffer);
/// Console.WriteLine(loggingEvent);
/// }
/// }
/// catch(Exception e)
/// {
/// Console.WriteLine(e.ToString());
/// }
/// </code>
/// <code lang="Visual Basic">
/// Dim remoteEndPoint as IPEndPoint
/// Dim udpClient as UdpClient
/// Dim buffer as Byte()
/// Dim loggingEvent as String
///
/// Try
/// remoteEndPoint = new IPEndPoint(IPAddress.Any, 0)
/// udpClient = new UdpClient(8080)
///
/// While True
/// buffer = udpClient.Receive(ByRef remoteEndPoint)
/// loggingEvent = System.Text.Encoding.Unicode.GetString(buffer)
/// Console.WriteLine(loggingEvent)
/// Wend
/// Catch e As Exception
/// Console.WriteLine(e.ToString())
/// End Try
/// </code>
/// <para>
/// An example configuration section to log information using this appender to the
/// IP 224.0.0.1 on port 8080:
/// </para>
/// <code lang="XML" escaped="true">
/// <appender name="UdpAppender" type="Ctrip.Log4.Appender.UdpAppender">
/// <remoteAddress value="224.0.0.1" />
/// <remotePort value="8080" />
/// <layout type="Ctrip.Log4.Layout.PatternLayout" value="%-5level %logger [%ndc] - %message%newline" />
/// </appender>
/// </code>
/// </example>
/// <author>Gert Driesen</author>
/// <author>Nicko Cadell</author>
public class UdpAppender : AppenderSkeleton
{
#region Public Instance Constructors
/// <summary>
/// Initializes a new instance of the <see cref="UdpAppender" /> class.
/// </summary>
/// <remarks>
/// The default constructor initializes all fields to their default values.
/// </remarks>
public UdpAppender()
{
}
#endregion Public Instance Constructors
#region Public Instance Properties
/// <summary>
/// Gets or sets the IP address of the remote host or multicast group to which
/// the underlying <see cref="UdpClient" /> should sent the logging event.
/// </summary>
/// <value>
/// The IP address of the remote host or multicast group to which the logging event
/// will be sent.
/// </value>
/// <remarks>
/// <para>
/// Multicast addresses are identified by IP class <b>D</b> addresses (in the range 224.0.0.0 to
/// 239.255.255.255). Multicast packets can pass across different networks through routers, so
/// it is possible to use multicasts in an Internet scenario as long as your network provider
/// supports multicasting.
/// </para>
/// <para>
/// Hosts that want to receive particular multicast messages must register their interest by joining
/// the multicast group. Multicast messages are not sent to networks where no host has joined
/// the multicast group. Class <b>D</b> IP addresses are used for multicast groups, to differentiate
/// them from normal host addresses, allowing nodes to easily detect if a message is of interest.
/// </para>
/// <para>
/// Static multicast addresses that are needed globally are assigned by IANA. A few examples are listed in the table below:
/// </para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>IP Address</term>
/// <description>Description</description>
/// </listheader>
/// <item>
/// <term>224.0.0.1</term>
/// <description>
/// <para>
/// Sends a message to all system on the subnet.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>224.0.0.2</term>
/// <description>
/// <para>
/// Sends a message to all routers on the subnet.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>224.0.0.12</term>
/// <description>
/// <para>
/// The DHCP server answers messages on the IP address 224.0.0.12, but only on a subnet.
/// </para>
/// </description>
/// </item>
/// </list>
/// </para>
/// <para>
/// A complete list of actually reserved multicast addresses and their owners in the ranges
/// defined by RFC 3171 can be found at the <A href="http://www.iana.org/assignments/multicast-addresses">IANA web site</A>.
/// </para>
/// <para>
/// The address range 239.0.0.0 to 239.255.255.255 is reserved for administrative scope-relative
/// addresses. These addresses can be reused with other local groups. Routers are typically
/// configured with filters to prevent multicast traffic in this range from flowing outside
/// of the local network.
/// </para>
/// </remarks>
public IPAddress RemoteAddress
{
get { return m_remoteAddress; }
set { m_remoteAddress = value; }
}
/// <summary>
/// Gets or sets the TCP port number of the remote host or multicast group to which
/// the underlying <see cref="UdpClient" /> should sent the logging event.
/// </summary>
/// <value>
/// An integer value in the range <see cref="IPEndPoint.MinPort" /> to <see cref="IPEndPoint.MaxPort" />
/// indicating the TCP port number of the remote host or multicast group to which the logging event
/// will be sent.
/// </value>
/// <remarks>
/// The underlying <see cref="UdpClient" /> will send messages to this TCP port number
/// on the remote host or multicast group.
/// </remarks>
/// <exception cref="ArgumentOutOfRangeException">The value specified is less than <see cref="IPEndPoint.MinPort" /> or greater than <see cref="IPEndPoint.MaxPort" />.</exception>
public int RemotePort
{
get { return m_remotePort; }
set
{
if (value < IPEndPoint.MinPort || value > IPEndPoint.MaxPort)
{
throw Ctrip.Log4.Util.SystemInfo.CreateArgumentOutOfRangeException("value", (object)value,
"The value specified is less than " +
IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) +
" or greater than " +
IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + ".");
}
else
{
m_remotePort = value;
}
}
}
/// <summary>
/// Gets or sets the TCP port number from which the underlying <see cref="UdpClient" /> will communicate.
/// </summary>
/// <value>
/// An integer value in the range <see cref="IPEndPoint.MinPort" /> to <see cref="IPEndPoint.MaxPort" />
/// indicating the TCP port number from which the underlying <see cref="UdpClient" /> will communicate.
/// </value>
/// <remarks>
/// <para>
/// The underlying <see cref="UdpClient" /> will bind to this port for sending messages.
/// </para>
/// <para>
/// Setting the value to 0 (the default) will cause the udp client not to bind to
/// a local port.
/// </para>
/// </remarks>
/// <exception cref="ArgumentOutOfRangeException">The value specified is less than <see cref="IPEndPoint.MinPort" /> or greater than <see cref="IPEndPoint.MaxPort" />.</exception>
public int LocalPort
{
get { return m_localPort; }
set
{
if (value != 0 && (value < IPEndPoint.MinPort || value > IPEndPoint.MaxPort))
{
throw Ctrip.Log4.Util.SystemInfo.CreateArgumentOutOfRangeException("value", (object)value,
"The value specified is less than " +
IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) +
" or greater than " +
IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + ".");
}
else
{
m_localPort = value;
}
}
}
/// <summary>
/// Gets or sets <see cref="Encoding"/> used to write the packets.
/// </summary>
/// <value>
/// The <see cref="Encoding"/> used to write the packets.
/// </value>
/// <remarks>
/// <para>
/// The <see cref="Encoding"/> used to write the packets.
/// </para>
/// </remarks>
public Encoding Encoding
{
get { return m_encoding; }
set { m_encoding = value; }
}
#endregion Public Instance Properties
#region Protected Instance Properties
/// <summary>
/// Gets or sets the underlying <see cref="UdpClient" />.
/// </summary>
/// <value>
/// The underlying <see cref="UdpClient" />.
/// </value>
/// <remarks>
/// <see cref="UdpAppender" /> creates a <see cref="UdpClient" /> to send logging events
/// over a network. Classes deriving from <see cref="UdpAppender" /> can use this
/// property to get or set this <see cref="UdpClient" />. Use the underlying <see cref="UdpClient" />
/// returned from <see cref="Client" /> if you require access beyond that which
/// <see cref="UdpAppender" /> provides.
/// </remarks>
protected UdpClient Client
{
get { return this.m_client; }
set { this.m_client = value; }
}
/// <summary>
/// Gets or sets the cached remote endpoint to which the logging events should be sent.
/// </summary>
/// <value>
/// The cached remote endpoint to which the logging events will be sent.
/// </value>
/// <remarks>
/// The <see cref="ActivateOptions" /> method will initialize the remote endpoint
/// with the values of the <see cref="RemoteAddress" /> and <see cref="RemotePort"/>
/// properties.
/// </remarks>
protected IPEndPoint RemoteEndPoint
{
get { return this.m_remoteEndPoint; }
set { this.m_remoteEndPoint = value; }
}
#endregion Protected Instance Properties
#region Implementation of IOptionHandler
/// <summary>
/// Initialize the appender based on the options set.
/// </summary>
/// <remarks>
/// <para>
/// This is part of the <see cref="IOptionHandler"/> delayed object
/// activation scheme. The <see cref="ActivateOptions"/> method must
/// be called on this object after the configuration properties have
/// been set. Until <see cref="ActivateOptions"/> is called this
/// object is in an undefined state and must not be used.
/// </para>
/// <para>
/// If any of the configuration properties are modified then
/// <see cref="ActivateOptions"/> must be called again.
/// </para>
/// <para>
/// The appender will be ignored if no <see cref="RemoteAddress" /> was specified or
/// an invalid remote or local TCP port number was specified.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException">The required property <see cref="RemoteAddress" /> was not specified.</exception>
/// <exception cref="ArgumentOutOfRangeException">The TCP port number assigned to <see cref="LocalPort" /> or <see cref="RemotePort" /> is less than <see cref="IPEndPoint.MinPort" /> or greater than <see cref="IPEndPoint.MaxPort" />.</exception>
public override void ActivateOptions()
{
base.ActivateOptions();
if (this.RemoteAddress == null)
{
throw new ArgumentNullException("The required property 'Address' was not specified.");
}
else if (this.RemotePort < IPEndPoint.MinPort || this.RemotePort > IPEndPoint.MaxPort)
{
throw Ctrip.Log4.Util.SystemInfo.CreateArgumentOutOfRangeException("this.RemotePort", (object)this.RemotePort,
"The RemotePort is less than " +
IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) +
" or greater than " +
IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + ".");
}
else if (this.LocalPort != 0 && (this.LocalPort < IPEndPoint.MinPort || this.LocalPort > IPEndPoint.MaxPort))
{
throw Ctrip.Log4.Util.SystemInfo.CreateArgumentOutOfRangeException("this.LocalPort", (object)this.LocalPort,
"The LocalPort is less than " +
IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) +
" or greater than " +
IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + ".");
}
else
{
this.RemoteEndPoint = new IPEndPoint(this.RemoteAddress, this.RemotePort);
this.InitializeClientConnection();
}
}
#endregion
#region Override implementation of AppenderSkeleton
/// <summary>
/// This method is called by the <see cref="M:AppenderSkeleton.DoAppend(LoggingEvent)"/> method.
/// </summary>
/// <param name="loggingEvent">The event to log.</param>
/// <remarks>
/// <para>
/// Sends the event using an UDP datagram.
/// </para>
/// <para>
/// Exceptions are passed to the <see cref="AppenderSkeleton.ErrorHandler"/>.
/// </para>
/// </remarks>
protected override void Append(LoggingEvent loggingEvent)
{
try
{
Byte [] buffer = m_encoding.GetBytes(RenderLoggingEvent(loggingEvent).ToCharArray());
this.Client.Send(buffer, buffer.Length, this.RemoteEndPoint);
}
catch (Exception ex)
{
ErrorHandler.Error(
"Unable to send logging event to remote host " +
this.RemoteAddress.ToString() +
" on port " +
this.RemotePort + ".",
ex,
ErrorCode.WriteFailure);
}
}
/// <summary>
/// This appender requires a <see cref="Layout"/> to be set.
/// </summary>
/// <value><c>true</c></value>
/// <remarks>
/// <para>
/// This appender requires a <see cref="Layout"/> to be set.
/// </para>
/// </remarks>
override protected bool RequiresLayout
{
get { return true; }
}
/// <summary>
/// Closes the UDP connection and releases all resources associated with
/// this <see cref="UdpAppender" /> instance.
/// </summary>
/// <remarks>
/// <para>
/// Disables the underlying <see cref="UdpClient" /> and releases all managed
/// and unmanaged resources associated with the <see cref="UdpAppender" />.
/// </para>
/// </remarks>
override protected void OnClose()
{
base.OnClose();
if (this.Client != null)
{
this.Client.Close();
this.Client = null;
}
}
#endregion Override implementation of AppenderSkeleton
#region Protected Instance Methods
/// <summary>
/// Initializes the underlying <see cref="UdpClient" /> connection.
/// </summary>
/// <remarks>
/// <para>
/// The underlying <see cref="UdpClient"/> is initialized and binds to the
/// port number from which you intend to communicate.
/// </para>
/// <para>
/// Exceptions are passed to the <see cref="AppenderSkeleton.ErrorHandler"/>.
/// </para>
/// </remarks>
protected virtual void InitializeClientConnection()
{
try
{
if (this.LocalPort == 0)
{
#if NETCF || NET_1_0 || SSCLI_1_0 || CLI_1_0
this.Client = new UdpClient();
#else
this.Client = new UdpClient(RemoteAddress.AddressFamily);
#endif
}
else
{
#if NETCF || NET_1_0 || SSCLI_1_0 || CLI_1_0
this.Client = new UdpClient(this.LocalPort);
#else
this.Client = new UdpClient(this.LocalPort, RemoteAddress.AddressFamily);
#endif
}
}
catch (Exception ex)
{
ErrorHandler.Error(
"Could not initialize the UdpClient connection on port " +
this.LocalPort.ToString(NumberFormatInfo.InvariantInfo) + ".",
ex,
ErrorCode.GenericFailure);
this.Client = null;
}
}
#endregion Protected Instance Methods
#region Private Instance Fields
/// <summary>
/// The IP address of the remote host or multicast group to which
/// the logging event will be sent.
/// </summary>
private IPAddress m_remoteAddress;
/// <summary>
/// The TCP port number of the remote host or multicast group to
/// which the logging event will be sent.
/// </summary>
private int m_remotePort;
/// <summary>
/// The cached remote endpoint to which the logging events will be sent.
/// </summary>
private IPEndPoint m_remoteEndPoint;
/// <summary>
/// The TCP port number from which the <see cref="UdpClient" /> will communicate.
/// </summary>
private int m_localPort;
/// <summary>
/// The <see cref="UdpClient" /> instance that will be used for sending the
/// logging events.
/// </summary>
private UdpClient m_client;
/// <summary>
/// The encoding to use for the packet.
/// </summary>
private Encoding m_encoding = Encoding.Default;
#endregion Private Instance Fields
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using CS_threescale;
using System.Net;
using System.IO;
using System.Collections;
namespace CS_threescale
{
public class Api:IApi
{
string provider_key;
string hostURI;
const string contentType = "application/x-www-form-urlencoded";
string version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
public Api()
{
hostURI = "https://su1.3scale.net:443";
}
public Api(string provider_key):this()
{
if (string.IsNullOrEmpty(provider_key))
throw new ApiException("argument error: undefined provider_key");
this.provider_key = provider_key;
}
public Api(string hostURI, string provider_key):this(provider_key)
{
if (string.IsNullOrEmpty(hostURI))
throw new ApiException("argument error: undefined server");
this.hostURI = hostURI;
}
public string HostURI
{
get { return hostURI; }
set { hostURI = value; }
}
/// <summary>
/// Calls Authrep on the 3scale backend to authorize an application and report the associated transaction at the same time.
/// </summary>
/// <param name="parameters">A Hashtable of parameter name value pairs</param>
public AuthorizeResponse authrep(Hashtable parameters)
{
return CallAuthorize("/transactions/authrep.xml", parameters);
}
/// <summary>
/// Calls Authorize on the 3scale backend to:
/// Check an application exists, is active and within limits.
/// Can also be used to authenticate a call using the required authentication parameters
/// </summary>
/// <param name="parameters">A Hashtable of parameter name value pairs</param>
public AuthorizeResponse authorize(Hashtable parameters)
{
return CallAuthorize("/transactions/authorize.xml", parameters);
}
/// <summary>
/// Report the specified transactions to the 3scale backend.
/// </summary>
/// <param name="transactions">A Hashtable containing the transactions to be reported</param>
public void report(Hashtable transactions)
{
if ((transactions == null) || (transactions.Count <= 0))
throw new ApiException("argument error: undefined transactions, must be at least one");
string URL = hostURI + "/transactions.xml";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Headers.Add("X-3scale-User-Agent", "plugin-dotnet-v" + version);
request.ContentType = contentType;
request.Method = "POST";
string content;
//Check we have a service_token or provider_key
if (String.IsNullOrEmpty (provider_key) && !transactions.ContainsKey ("service_token")) {
throw new ApiException ("You need to set either a provider_key or service_token");
} else {
content = String.IsNullOrEmpty (provider_key) ? "" : "provider_key=" + provider_key;
}
AddTransactions(ref content, transactions);
byte [] data = Encoding.UTF8.GetBytes (content);
try{
request.ContentLength = data.Length;
Stream str = request.GetRequestStream ();
str.Write (data, 0, data.Length);
using (var response = request.GetResponse ()) {
switch (((HttpWebResponse)response).StatusCode) {
case HttpStatusCode.OK:
return;
case HttpStatusCode.Accepted:
return;
}
}
}
catch (WebException w){
using (WebResponse response = w.Response) {
using (var streamReader = new StreamReader (response.GetResponseStream ())) {
ApiError err = null;
string err_msg = streamReader.ReadToEnd ();
try
{
err = new ApiError (err_msg);
} catch (Exception) {
err = null;
}
if (err != null)
throw new ApiException (err.code + " : " + err.message);
switch (((HttpWebResponse)w.Response).StatusCode) {
case HttpStatusCode.Forbidden:
throw new ApiException ("Forbidden");
case HttpStatusCode.BadRequest:
throw new ApiException ("Bad request");
case HttpStatusCode.InternalServerError:
throw new ApiException ("Internal server error");
case HttpStatusCode.NotFound:
throw new ApiException ("Request route not found");
default:
throw new ApiException ("Unknown Exception: " + err_msg);
}
}
}
}
return;
}
/// <summary>
/// Calls Authorize on the 3scale backend with the specified parameters using the Oauth authentication pattern.
/// </summary>
/// <param name="parameters">A Hashtable of parameter name value pairs</param>
public AuthorizeResponse oauth_authorize(Hashtable parameters)
{
return CallAuthorize("/transactions/oauth_authorize.xml", parameters);
}
/// <summary>
/// Executes a different Authorize calls on the 3scale backend depending on the endpoint
/// </summary>
/// <returns>An AuthorizeResponse object representing the authorize response</returns>
/// <param name="endPoint">The endpoint to hit</param>
/// <param name="parameters">A Hashtable of parameter name value pairs.</param>
private AuthorizeResponse CallAuthorize(string endPoint, Hashtable parameters)
{
string URL = hostURI + endPoint;
string content = "?provider_key=" + provider_key;
if (!parameters.ContainsKey("usage"))
{
Hashtable usage = new Hashtable();
usage.Add("hits", "1");
parameters.Add("usage", usage);
}
AddParameters(ref content, parameters);
URL += content;
var request = WebRequest.Create(URL);
request.Headers.Add("X-3scale-User-Agent", "plugin-dotnet-v" + version);
try
{
using (var response = request.GetResponse())
{
using (var streamReader = new StreamReader (response.GetResponseStream ())) {
switch (((HttpWebResponse)response).StatusCode) {
case HttpStatusCode.OK:
string msg = streamReader.ReadToEnd ();
AuthorizeResponse auth_response = new AuthorizeResponse (msg);
return auth_response;
}
}
}
}
catch (WebException w)
{
using (WebResponse response = w.Response) {
using (var streamReader = new StreamReader (response.GetResponseStream ())) {
ApiError err = null;
string err_msg = streamReader.ReadToEnd ();
try {
err = new ApiError (err_msg);
} catch (Exception) {
err = null;
}
if (err != null)
throw new ApiException (err.code + " : " + err.message);
switch (((HttpWebResponse)w.Response).StatusCode) {
case HttpStatusCode.Forbidden:
throw new ApiException ("Forbidden");
case HttpStatusCode.BadRequest:
throw new ApiException ("Bad request");
case HttpStatusCode.InternalServerError:
throw new ApiException ("Internal server error");
case HttpStatusCode.NotFound:
throw new ApiException ("Request route not found");
case HttpStatusCode.Conflict:
AuthorizeResponse auth_response = new AuthorizeResponse (err_msg);
return auth_response;
default:
throw new ApiException ("Unknown Exception: " + err_msg);
}
}
}
}
return null;
}
/// <summary>
/// Encodes the parameters in the content part of the URL
/// </summary>
/// <param name="content">A string containing the content part of the URL</param>
/// <param name="parameters">A Hashtable of parameter name value pairs</param>
private void AddParameters(ref string content, Hashtable parameters)
{
foreach (string parameter in parameters.Keys)
{
if (parameter.Equals("usage"))
{
Hashtable usage = (Hashtable)parameters[parameter];
if ((usage == null) || (usage.Count <= 0))
throw new ApiException("argument error: usage is missing");
foreach (string metric in usage.Keys)
{
content += string.Format("&{0}[{1}]={2}", parameter, metric, usage[metric]);
}
}
else
{
content += string.Format("&{0}={1}", parameter, parameters[parameter]);
}
}
}
/// <summary>
/// Encodes the transactions in the content part of the URL
/// </summary>
/// <param name="content">A string containing the content part of the URL</param>
/// <param name="transactions">A Hashtable of transactions</param>
private void AddTransactions(ref string content, Hashtable transactions)
{
foreach (var entry in transactions.Keys)
{
Hashtable transaction = (Hashtable)transactions[entry];
foreach (string parameter in transaction.Keys)
{
if (parameter.Equals("usage"))
{
Hashtable usage = (Hashtable)transaction[parameter];
if ((usage == null) || (usage.Count <= 0))
throw new ApiException("argument error: undefined transaction, usage is missing in one record");
foreach (string metric in usage.Keys)
{
content += string.Format("&transactions[{0}][{1}][{2}]={3}", entry, parameter, metric, usage[metric]);
}
}
else
{
content += string.Format("&transactions[{0}][{1}]={2}", entry, parameter, transaction[parameter]);
}
}
}
}
}
}
| |
// dnlib: See LICENSE.txt for more info
using System;
using System.Collections.Generic;
using System.IO;
namespace dnlib.DotNet.Writer {
/// <summary>
/// Helps <see cref="CustomAttributeWriter"/> write custom attributes
/// </summary>
public interface ICustomAttributeWriterHelper : IWriterError, IFullNameFactoryHelper {
}
/// <summary>
/// Writes <see cref="CustomAttribute"/>s
/// </summary>
public struct CustomAttributeWriter : IDisposable {
readonly ICustomAttributeWriterHelper helper;
RecursionCounter recursionCounter;
readonly MemoryStream outStream;
readonly DataWriter writer;
readonly bool disposeStream;
GenericArguments genericArguments;
/// <summary>
/// Writes a custom attribute
/// </summary>
/// <param name="helper">Helper class</param>
/// <param name="ca">The custom attribute</param>
/// <returns>Custom attribute blob</returns>
public static byte[] Write(ICustomAttributeWriterHelper helper, CustomAttribute ca) {
using (var writer = new CustomAttributeWriter(helper)) {
writer.Write(ca);
return writer.GetResult();
}
}
internal static byte[] Write(ICustomAttributeWriterHelper helper, CustomAttribute ca, DataWriterContext context) {
using (var writer = new CustomAttributeWriter(helper, context)) {
writer.Write(ca);
return writer.GetResult();
}
}
/// <summary>
/// Writes custom attribute named arguments
/// </summary>
/// <param name="helper">Helper class</param>
/// <param name="namedArgs">Named arguments</param>
/// <returns>The named args blob</returns>
internal static byte[] Write(ICustomAttributeWriterHelper helper, IList<CANamedArgument> namedArgs) {
using (var writer = new CustomAttributeWriter(helper)) {
writer.Write(namedArgs);
return writer.GetResult();
}
}
internal static byte[] Write(ICustomAttributeWriterHelper helper, IList<CANamedArgument> namedArgs, DataWriterContext context) {
using (var writer = new CustomAttributeWriter(helper, context)) {
writer.Write(namedArgs);
return writer.GetResult();
}
}
CustomAttributeWriter(ICustomAttributeWriterHelper helper) {
this.helper = helper;
recursionCounter = new RecursionCounter();
outStream = new MemoryStream();
writer = new DataWriter(outStream);
genericArguments = null;
disposeStream = true;
}
CustomAttributeWriter(ICustomAttributeWriterHelper helper, DataWriterContext context) {
this.helper = helper;
recursionCounter = new RecursionCounter();
outStream = context.OutStream;
writer = context.Writer;
genericArguments = null;
disposeStream = false;
outStream.SetLength(0);
outStream.Position = 0;
}
byte[] GetResult() => outStream.ToArray();
void Write(CustomAttribute ca) {
if (ca is null) {
helper.Error("The custom attribute is null");
return;
}
// Check whether it's raw first. If it is, we don't care whether the ctor is
// invalid. Just use the raw data.
if (ca.IsRawBlob) {
if ((ca.ConstructorArguments is not null && ca.ConstructorArguments.Count > 0) || (ca.NamedArguments is not null && ca.NamedArguments.Count > 0))
helper.Error("Raw custom attribute contains arguments and/or named arguments");
writer.WriteBytes(ca.RawData);
return;
}
if (ca.Constructor is null) {
helper.Error("Custom attribute ctor is null");
return;
}
var methodSig = GetMethodSig(ca.Constructor);
if (methodSig is null) {
helper.Error("Custom attribute ctor's method signature is invalid");
return;
}
if (ca.ConstructorArguments.Count != methodSig.Params.Count)
helper.Error("Custom attribute arguments count != method sig arguments count");
if (methodSig.ParamsAfterSentinel is not null && methodSig.ParamsAfterSentinel.Count > 0)
helper.Error("Custom attribute ctor has parameters after the sentinel");
if (ca.NamedArguments.Count > ushort.MaxValue)
helper.Error("Custom attribute has too many named arguments");
if (ca.Constructor is MemberRef mrCtor && mrCtor.Class is TypeSpec owner && owner.TypeSig is GenericInstSig gis) {
genericArguments = new GenericArguments();
genericArguments.PushTypeArgs(gis.GenericArguments);
}
writer.WriteUInt16((ushort)1);
int numArgs = Math.Min(methodSig.Params.Count, ca.ConstructorArguments.Count);
for (int i = 0; i < numArgs; i++)
WriteValue(FixTypeSig(methodSig.Params[i]), ca.ConstructorArguments[i]);
int numNamedArgs = Math.Min((int)ushort.MaxValue, ca.NamedArguments.Count);
writer.WriteUInt16((ushort)numNamedArgs);
for (int i = 0; i < numNamedArgs; i++)
Write(ca.NamedArguments[i]);
}
void Write(IList<CANamedArgument> namedArgs) {
if (namedArgs is null || namedArgs.Count > 0x1FFFFFFF) {
helper.Error("Too many custom attribute named arguments");
namedArgs = Array2.Empty<CANamedArgument>();
}
writer.WriteCompressedUInt32((uint)namedArgs.Count);
for (int i = 0; i < namedArgs.Count; i++)
Write(namedArgs[i]);
}
TypeSig FixTypeSig(TypeSig type) => SubstituteGenericParameter(type.RemoveModifiers()).RemoveModifiers();
TypeSig SubstituteGenericParameter(TypeSig type) {
if (genericArguments is null)
return type;
return genericArguments.Resolve(type);
}
void WriteValue(TypeSig argType, CAArgument value) {
if (argType is null || value.Type is null) {
helper.Error("Custom attribute argument type is null");
return;
}
if (!recursionCounter.Increment()) {
helper.Error("Infinite recursion");
return;
}
if (argType is SZArraySig arrayType) {
var argsArray = value.Value as IList<CAArgument>;
if (argsArray is null && value.Value is not null)
helper.Error("CAArgument.Value is not null or an array");
WriteArrayValue(arrayType, argsArray);
}
else
WriteElem(argType, value);
recursionCounter.Decrement();
}
void WriteArrayValue(SZArraySig arrayType, IList<CAArgument> args) {
if (arrayType is null) {
helper.Error("Custom attribute: Array type is null");
return;
}
if (args is null)
writer.WriteUInt32(uint.MaxValue);
else {
writer.WriteUInt32((uint)args.Count);
var arrayElementType = FixTypeSig(arrayType.Next);
for (int i = 0; i < args.Count; i++)
WriteValue(arrayElementType, args[i]);
}
}
bool VerifyTypeAndValue(CAArgument value, ElementType etype) {
if (!VerifyType(value.Type, etype)) {
helper.Error("Custom attribute arg type != value.Type");
return false;
}
if (!VerifyValue(value.Value, etype)) {
helper.Error("Custom attribute value.Value's type != value.Type");
return false;
}
return true;
}
bool VerifyTypeAndValue(CAArgument value, ElementType etype, Type valueType) {
if (!VerifyType(value.Type, etype)) {
helper.Error("Custom attribute arg type != value.Type");
return false;
}
return value.Value is null || value.Value.GetType() == valueType;
}
static bool VerifyType(TypeSig type, ElementType etype) {
type = type.RemoveModifiers();
// Assume it's an enum if it's a ValueType
return type is not null && (etype == type.ElementType || type.ElementType == ElementType.ValueType);
}
static bool VerifyValue(object o, ElementType etype) {
if (o is null)
return false;
return Type.GetTypeCode(o.GetType()) switch {
TypeCode.Boolean => etype == ElementType.Boolean,
TypeCode.Char => etype == ElementType.Char,
TypeCode.SByte => etype == ElementType.I1,
TypeCode.Byte => etype == ElementType.U1,
TypeCode.Int16 => etype == ElementType.I2,
TypeCode.UInt16 => etype == ElementType.U2,
TypeCode.Int32 => etype == ElementType.I4,
TypeCode.UInt32 => etype == ElementType.U4,
TypeCode.Int64 => etype == ElementType.I8,
TypeCode.UInt64 => etype == ElementType.U8,
TypeCode.Single => etype == ElementType.R4,
TypeCode.Double => etype == ElementType.R8,
_ => false,
};
}
static ulong ToUInt64(object o) {
ToUInt64(o, out ulong result);
return result;
}
static bool ToUInt64(object o, out ulong result) {
if (o is null) {
result = 0;
return false;
}
switch (Type.GetTypeCode(o.GetType())) {
case TypeCode.Boolean:
result = (bool)o ? 1UL : 0UL;
return true;
case TypeCode.Char:
result = (ushort)(char)o;
return true;
case TypeCode.SByte:
result = (ulong)(sbyte)o;
return true;
case TypeCode.Byte:
result = (byte)o;
return true;
case TypeCode.Int16:
result = (ulong)(short)o;
return true;
case TypeCode.UInt16:
result = (ushort)o;
return true;
case TypeCode.Int32:
result = (ulong)(int)o;
return true;
case TypeCode.UInt32:
result = (uint)o;
return true;
case TypeCode.Int64:
result = (ulong)(long)o;
return true;
case TypeCode.UInt64:
result = (ulong)o;
return true;
case TypeCode.Single:
result = (ulong)(float)o;
return true;
case TypeCode.Double:
result = (ulong)(double)o;
return true;
}
result = 0;
return false;
}
static double ToDouble(object o) {
ToDouble(o, out double result);
return result;
}
static bool ToDouble(object o, out double result) {
if (o is null) {
result = double.NaN;
return false;
}
switch (Type.GetTypeCode(o.GetType())) {
case TypeCode.Boolean:
result = (bool)o ? 1 : 0;
return true;
case TypeCode.Char:
result = (ushort)(char)o;
return true;
case TypeCode.SByte:
result = (sbyte)o;
return true;
case TypeCode.Byte:
result = (byte)o;
return true;
case TypeCode.Int16:
result = (short)o;
return true;
case TypeCode.UInt16:
result = (ushort)o;
return true;
case TypeCode.Int32:
result = (int)o;
return true;
case TypeCode.UInt32:
result = (uint)o;
return true;
case TypeCode.Int64:
result = (long)o;
return true;
case TypeCode.UInt64:
result = (ulong)o;
return true;
case TypeCode.Single:
result = (float)o;
return true;
case TypeCode.Double:
result = (double)o;
return true;
}
result = double.NaN;
return false;
}
/// <summary>
/// Write a value
/// </summary>
/// <param name="argType">The ctor arg type, field type, or property type</param>
/// <param name="value">The value to write</param>
void WriteElem(TypeSig argType, CAArgument value) {
if (argType is null) {
helper.Error("Custom attribute: Arg type is null");
argType = value.Type;
if (argType is null)
return;
}
if (!recursionCounter.Increment()) {
helper.Error("Infinite recursion");
return;
}
TypeSig underlyingType;
ITypeDefOrRef tdr;
switch (argType.ElementType) {
case ElementType.Boolean:
if (!VerifyTypeAndValue(value, ElementType.Boolean))
writer.WriteBoolean(ToUInt64(value.Value) != 0);
else
writer.WriteBoolean((bool)value.Value);
break;
case ElementType.Char:
if (!VerifyTypeAndValue(value, ElementType.Char))
writer.WriteUInt16((ushort)ToUInt64(value.Value));
else
writer.WriteUInt16((ushort)(char)value.Value);
break;
case ElementType.I1:
if (!VerifyTypeAndValue(value, ElementType.I1))
writer.WriteSByte((sbyte)ToUInt64(value.Value));
else
writer.WriteSByte((sbyte)value.Value);
break;
case ElementType.U1:
if (!VerifyTypeAndValue(value, ElementType.U1))
writer.WriteByte((byte)ToUInt64(value.Value));
else
writer.WriteByte((byte)value.Value);
break;
case ElementType.I2:
if (!VerifyTypeAndValue(value, ElementType.I2))
writer.WriteInt16((short)ToUInt64(value.Value));
else
writer.WriteInt16((short)value.Value);
break;
case ElementType.U2:
if (!VerifyTypeAndValue(value, ElementType.U2))
writer.WriteUInt16((ushort)ToUInt64(value.Value));
else
writer.WriteUInt16((ushort)value.Value);
break;
case ElementType.I4:
if (!VerifyTypeAndValue(value, ElementType.I4))
writer.WriteInt32((int)ToUInt64(value.Value));
else
writer.WriteInt32((int)value.Value);
break;
case ElementType.U4:
if (!VerifyTypeAndValue(value, ElementType.U4))
writer.WriteUInt32((uint)ToUInt64(value.Value));
else
writer.WriteUInt32((uint)value.Value);
break;
case ElementType.I8:
if (!VerifyTypeAndValue(value, ElementType.I8))
writer.WriteInt64((long)ToUInt64(value.Value));
else
writer.WriteInt64((long)value.Value);
break;
case ElementType.U8:
if (!VerifyTypeAndValue(value, ElementType.U8))
writer.WriteUInt64(ToUInt64(value.Value));
else
writer.WriteUInt64((ulong)value.Value);
break;
case ElementType.R4:
if (!VerifyTypeAndValue(value, ElementType.R4))
writer.WriteSingle((float)ToDouble(value.Value));
else
writer.WriteSingle((float)value.Value);
break;
case ElementType.R8:
if (!VerifyTypeAndValue(value, ElementType.R8))
writer.WriteDouble(ToDouble(value.Value));
else
writer.WriteDouble((double)value.Value);
break;
case ElementType.String:
if (VerifyTypeAndValue(value, ElementType.String, typeof(UTF8String)))
WriteUTF8String((UTF8String)value.Value);
else if (VerifyTypeAndValue(value, ElementType.String, typeof(string)))
WriteUTF8String((string)value.Value);
else
WriteUTF8String(UTF8String.Empty);
break;
case ElementType.ValueType:
tdr = ((TypeDefOrRefSig)argType).TypeDefOrRef;
underlyingType = GetEnumUnderlyingType(argType);
if (underlyingType is not null)
WriteElem(underlyingType, value);
else if (tdr is TypeRef && TryWriteEnumUnderlyingTypeValue(value.Value)) {
// No error. Assume it's an enum that couldn't be resolved.
}
else
helper.Error("Custom attribute value is not an enum");
break;
case ElementType.Class:
tdr = ((TypeDefOrRefSig)argType).TypeDefOrRef;
if (CheckCorLibType(argType, "Type")) {
if (CheckCorLibType(value.Type, "Type")) {
if (value.Value is TypeSig ts)
WriteType(ts);
else if (value.Value is null)
WriteUTF8String(null);
else {
helper.Error("Custom attribute value is not a type");
WriteUTF8String(UTF8String.Empty);
}
}
else {
helper.Error("Custom attribute value type is not System.Type");
WriteUTF8String(UTF8String.Empty);
}
break;
}
else if (tdr is TypeRef && TryWriteEnumUnderlyingTypeValue(value.Value)) {
// No error. Assume it's an enum that couldn't be resolved.
break;
}
goto default;
case ElementType.SZArray:
WriteValue(argType, value);
break;
case ElementType.Object:
WriteFieldOrPropType(value.Type);
WriteElem(value.Type, value);
break;
case ElementType.End:
case ElementType.Void:
case ElementType.Ptr:
case ElementType.ByRef:
case ElementType.Var:
case ElementType.Array:
case ElementType.GenericInst:
case ElementType.TypedByRef:
case ElementType.ValueArray:
case ElementType.I:
case ElementType.U:
case ElementType.R:
case ElementType.FnPtr:
case ElementType.MVar:
case ElementType.CModReqd:
case ElementType.CModOpt:
case ElementType.Internal:
case ElementType.Module:
case ElementType.Sentinel:
case ElementType.Pinned:
default:
helper.Error("Invalid or unsupported element type in custom attribute");
break;
}
recursionCounter.Decrement();
}
bool TryWriteEnumUnderlyingTypeValue(object o) {
if (o is null)
return false;
switch (Type.GetTypeCode(o.GetType())) {
case TypeCode.Boolean: writer.WriteBoolean((bool)o); break;
case TypeCode.Char: writer.WriteUInt16((ushort)(char)o); break;
case TypeCode.SByte: writer.WriteSByte((sbyte)o); break;
case TypeCode.Byte: writer.WriteByte((byte)o); break;
case TypeCode.Int16: writer.WriteInt16((short)o); break;
case TypeCode.UInt16: writer.WriteUInt16((ushort)o); break;
case TypeCode.Int32: writer.WriteInt32((int)o); break;
case TypeCode.UInt32: writer.WriteUInt32((uint)o); break;
case TypeCode.Int64: writer.WriteInt64((long)o); break;
case TypeCode.UInt64: writer.WriteUInt64((ulong)o); break;
default: return false;
}
return true;
}
/// <summary>
/// Gets the enum's underlying type
/// </summary>
/// <param name="type">An enum type</param>
/// <returns>The underlying type or <c>null</c> if we couldn't resolve the type ref</returns>
static TypeSig GetEnumUnderlyingType(TypeSig type) {
var td = GetEnumTypeDef(type);
if (td is null)
return null;
return td.GetEnumUnderlyingType().RemoveModifiers();
}
static TypeDef GetEnumTypeDef(TypeSig type) {
if (type is null)
return null;
var td = GetTypeDef(type);
if (td is null)
return null;
if (!td.IsEnum)
return null;
return td;
}
/// <summary>
/// Converts <paramref name="type"/> to a <see cref="TypeDef"/>, possibly resolving
/// a <see cref="TypeRef"/>
/// </summary>
/// <param name="type">The type</param>
/// <returns>A <see cref="TypeDef"/> or <c>null</c> if we couldn't resolve the
/// <see cref="TypeRef"/> or if <paramref name="type"/> is a type spec</returns>
static TypeDef GetTypeDef(TypeSig type) {
if (type is TypeDefOrRefSig tdr) {
var td = tdr.TypeDef;
if (td is not null)
return td;
var tr = tdr.TypeRef;
if (tr is not null)
return tr.Resolve();
}
return null;
}
void Write(CANamedArgument namedArg) {
if (namedArg is null) {
helper.Error("Custom attribute named arg is null");
return;
}
if (!recursionCounter.Increment()) {
helper.Error("Infinite recursion");
return;
}
if (namedArg.IsProperty)
writer.WriteByte((byte)SerializationType.Property);
else
writer.WriteByte((byte)SerializationType.Field);
WriteFieldOrPropType(namedArg.Type);
WriteUTF8String(namedArg.Name);
WriteValue(namedArg.Type, namedArg.Argument);
recursionCounter.Decrement();
}
void WriteFieldOrPropType(TypeSig type) {
type = type.RemoveModifiers();
if (type is null) {
helper.Error("Custom attribute: Field/property type is null");
return;
}
if (!recursionCounter.Increment()) {
helper.Error("Infinite recursion");
return;
}
ITypeDefOrRef tdr;
switch (type.ElementType) {
case ElementType.Boolean: writer.WriteByte((byte)SerializationType.Boolean); break;
case ElementType.Char: writer.WriteByte((byte)SerializationType.Char); break;
case ElementType.I1: writer.WriteByte((byte)SerializationType.I1); break;
case ElementType.U1: writer.WriteByte((byte)SerializationType.U1); break;
case ElementType.I2: writer.WriteByte((byte)SerializationType.I2); break;
case ElementType.U2: writer.WriteByte((byte)SerializationType.U2); break;
case ElementType.I4: writer.WriteByte((byte)SerializationType.I4); break;
case ElementType.U4: writer.WriteByte((byte)SerializationType.U4); break;
case ElementType.I8: writer.WriteByte((byte)SerializationType.I8); break;
case ElementType.U8: writer.WriteByte((byte)SerializationType.U8); break;
case ElementType.R4: writer.WriteByte((byte)SerializationType.R4); break;
case ElementType.R8: writer.WriteByte((byte)SerializationType.R8); break;
case ElementType.String: writer.WriteByte((byte)SerializationType.String); break;
case ElementType.Object: writer.WriteByte((byte)SerializationType.TaggedObject); break;
case ElementType.SZArray:
writer.WriteByte((byte)SerializationType.SZArray);
WriteFieldOrPropType(type.Next);
break;
case ElementType.Class:
tdr = ((TypeDefOrRefSig)type).TypeDefOrRef;
if (CheckCorLibType(type, "Type"))
writer.WriteByte((byte)SerializationType.Type);
else if (tdr is TypeRef) {
// Could be an enum TypeRef that couldn't be resolved, so the code
// assumed it's a class and created a ClassSig.
writer.WriteByte((byte)SerializationType.Enum);
WriteType(tdr);
}
else
goto default;
break;
case ElementType.ValueType:
tdr = ((TypeDefOrRefSig)type).TypeDefOrRef;
var enumType = GetEnumTypeDef(type);
// If TypeRef => assume it's an enum that couldn't be resolved
if (enumType is not null || tdr is TypeRef) {
writer.WriteByte((byte)SerializationType.Enum);
WriteType(tdr);
}
else {
helper.Error("Custom attribute type doesn't seem to be an enum.");
writer.WriteByte((byte)SerializationType.Enum);
WriteType(tdr);
}
break;
default:
helper.Error("Custom attribute: Invalid type");
writer.WriteByte((byte)0xFF);
break;
}
recursionCounter.Decrement();
}
void WriteType(IType type) {
if (type is null) {
helper.Error("Custom attribute: Type is null");
WriteUTF8String(UTF8String.Empty);
}
else
WriteUTF8String(FullNameFactory.AssemblyQualifiedName(type, helper));
}
static bool CheckCorLibType(TypeSig ts, string name) {
var tdrs = ts as TypeDefOrRefSig;
if (tdrs is null)
return false;
return CheckCorLibType(tdrs.TypeDefOrRef, name);
}
static bool CheckCorLibType(ITypeDefOrRef tdr, string name) {
if (tdr is null)
return false;
if (!tdr.DefinitionAssembly.IsCorLib())
return false;
if (tdr is TypeSpec)
return false;
return tdr.TypeName == name && tdr.Namespace == "System";
}
static MethodSig GetMethodSig(ICustomAttributeType ctor) => ctor?.MethodSig;
void WriteUTF8String(UTF8String s) {
if (s is null || s.Data is null)
writer.WriteByte((byte)0xFF);
else {
writer.WriteCompressedUInt32((uint)s.Data.Length);
writer.WriteBytes(s.Data);
}
}
/// <inheritdoc/>
public void Dispose() {
if (!disposeStream)
return;
if (outStream is not null)
outStream.Dispose();
}
}
}
| |
/*
* Exchange Web Services Managed API
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* MIT License
*
* 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 Microsoft.Exchange.WebServices.Data
{
using System.Collections.Generic;
using System.Xml;
/// <summary>
/// Represents the JobInsightValue.
/// </summary>
public sealed class JobInsightValue : InsightValue
{
private string company;
private string companyDescription;
private string companyTicker;
private string companyLogoUrl;
private string companyWebsiteUrl;
private string companyLinkedInUrl;
private string title;
private long startUtcTicks;
private long endUtcTicks;
/// <summary>
/// Gets the Company
/// </summary>
public string Company
{
get
{
return this.company;
}
set
{
this.SetFieldValue<string>(ref this.company, value);
}
}
/// <summary>
/// Gets the CompanyDescription
/// </summary>
public string CompanyDescription
{
get
{
return this.companyDescription;
}
set
{
this.SetFieldValue<string>(ref this.companyDescription, value);
}
}
/// <summary>
/// Gets the CompanyTicker
/// </summary>
public string CompanyTicker
{
get
{
return this.companyTicker;
}
set
{
this.SetFieldValue<string>(ref this.companyTicker, value);
}
}
/// <summary>
/// Gets the CompanyLogoUrl
/// </summary>
public string CompanyLogoUrl
{
get
{
return this.companyLogoUrl;
}
set
{
this.SetFieldValue<string>(ref this.companyLogoUrl, value);
}
}
/// <summary>
/// Gets the CompanyWebsiteUrl
/// </summary>
public string CompanyWebsiteUrl
{
get
{
return this.companyWebsiteUrl;
}
set
{
this.SetFieldValue<string>(ref this.companyWebsiteUrl, value);
}
}
/// <summary>
/// Gets the CompanyLinkedInUrl
/// </summary>
public string CompanyLinkedInUrl
{
get
{
return this.companyLinkedInUrl;
}
set
{
this.SetFieldValue<string>(ref this.companyLinkedInUrl, value);
}
}
/// <summary>
/// Gets the Title
/// </summary>
public string Title
{
get
{
return this.title;
}
set
{
this.SetFieldValue<string>(ref this.title, value);
}
}
/// <summary>
/// Gets the StartUtcTicks
/// </summary>
public long StartUtcTicks
{
get
{
return this.startUtcTicks;
}
set
{
this.SetFieldValue<long>(ref this.startUtcTicks, value);
}
}
/// <summary>
/// Gets the EndUtcTicks
/// </summary>
public long EndUtcTicks
{
get
{
return this.endUtcTicks;
}
set
{
this.SetFieldValue<long>(ref this.endUtcTicks, value);
}
}
/// <summary>
/// Tries to read element from XML.
/// </summary>
/// <param name="reader">XML reader</param>
/// <returns>Whether the element was read</returns>
internal override bool TryReadElementFromXml(EwsServiceXmlReader reader)
{
switch (reader.LocalName)
{
case XmlElementNames.InsightSource:
this.InsightSource = reader.ReadElementValue<InsightSourceType>();
break;
case XmlElementNames.UpdatedUtcTicks:
this.UpdatedUtcTicks = reader.ReadElementValue<long>();
break;
case XmlElementNames.Company:
this.Company = reader.ReadElementValue();
break;
case XmlElementNames.Title:
this.Title = reader.ReadElementValue();
break;
case XmlElementNames.StartUtcTicks:
this.StartUtcTicks = reader.ReadElementValue<long>();
break;
case XmlElementNames.EndUtcTicks:
this.EndUtcTicks = reader.ReadElementValue<long>();
break;
default:
return false;
}
return true;
}
}
}
| |
/************************************************************************
*
* The MIT License (MIT)
*
* Copyright (c) 2025 - Christian Falch
*
* 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 NControl.Abstractions;
using Xamarin.Forms;
using NControlDemo.FormsApp.Controls;
using NGraphics;
using NControlDemo.Localization;
using System.Threading.Tasks;
using NControlDemo.FormsApp.Views;
using NControlDemo.FormsApp.ViewModels;
using Xamarin.Forms.Maps;
namespace NControlDemo.FormsApp.Views
{
/// <summary>
/// Main view.
/// </summary>
public class MainView: BaseContentsView<MainViewModel>
{
/// <summary>
/// The chrome visible.
/// </summary>
private bool _chromeVisible = false;
/// <summary>
/// The map container.
/// </summary>
private RelativeLayout _mapContainer;
/// <summary>
/// The bottom bar.
/// </summary>
private NControlView _bottomBar;
/// <summary>
/// The top bar.
/// </summary>
private NControlView _navigationBar;
/// <summary>
/// The progress.
/// </summary>
private ProgressControl _progress;
/// <summary>
/// The top background view.
/// </summary>
private NControlView _topBackgroundView;
/// <summary>
/// The bottom background view.
/// </summary>
private NControlView _bottomBackgroundView;
/// <summary>
/// Initializes a new instance of the <see cref="NControlDemo.FormsApp.Views.MainView"/> class.
/// </summary>
public MainView()
{
NavigationPage.SetHasNavigationBar(this, false);
}
/// <summary>
/// Implement to create the layout on the page
/// </summary>
/// <returns>The layout.</returns>
protected override View CreateContents()
{
_topBackgroundView = new NControlView {
DrawingFunction = (canvas, rect) => canvas.FillRectangle(rect, new SolidBrush(new NGraphics.Color("#3498DB")))
};
_bottomBackgroundView = new NControlView {
DrawingFunction = (canvas, rect) => canvas.FillRectangle(rect, new SolidBrush(new NGraphics.Color("#3498DB")))
};
var grid = new Grid();
grid.Children.Add(new StackLayout
{
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.CenterAndExpand,
Padding = 11,
Children =
{
new CircularButtonControl { FAIcon = FontAwesomeLabel.FAPlay },
new CircularButtonControl { FAIcon = FontAwesomeLabel.FAPlus },
new CircularButtonControl { FAIcon = FontAwesomeLabel.FATerminal },
new Button { Text = "Hello" },
}
}, 0, 0);
var buttonOverlay = new NControlView {
DrawingFunction = (canvas, rect) =>
{
rect.Inflate(-10, -10);
canvas.DrawRectangle(rect, Pens.Blue, null);
},
};
buttonOverlay.InputTransparent = true;
grid.Children.Add(buttonOverlay, 0, 0);
_bottomBar = new NControlView
{
BackgroundColor = Xamarin.Forms.Color.FromHex("#EEEEEE"),
DrawingFunction = (ICanvas canvas, Rect rect) =>
canvas.DrawLine(0, 0, rect.Width, 0, NGraphics.Colors.Gray, 0.5)
,
Content = grid
};
// Navigation bar
_navigationBar = new NavigationBarEx { Title = Strings.AppName };
// Progress controll
_progress = new ProgressControl();
// Map
_mapContainer = new RelativeLayout();
// Layout
var layout = new RelativeLayout();
layout.Children.Add(_mapContainer, () => layout.Bounds);
layout.Children.Add(_topBackgroundView, () => new Xamarin.Forms.Rectangle(0, 0, layout.Width, 1 + (layout.Height / 2)));
layout.Children.Add(_bottomBackgroundView, () => new Xamarin.Forms.Rectangle(0, layout.Height / 2, layout.Width, layout.Height / 2));
layout.Children.Add(_bottomBar, () => new Xamarin.Forms.Rectangle(0, layout.Height, layout.Width, 65));
layout.Children.Add(_navigationBar, () => new Xamarin.Forms.Rectangle(0, -80, layout.Width, 80));
layout.Children.Add(_progress, () => new Xamarin.Forms.Rectangle((layout.Width / 2) - (25),
(layout.Height / 2) - 25, 50, 50));
return layout;
}
/// <summary>
/// Startup animations
/// </summary>
protected override async void OnAppearing()
{
base.OnAppearing();
// Start the progress control
_progress.Start();
// Lets pretend we're doing something
await Task.Delay(1500);
// Introduce the navigation bar and toolbar
await ShowChromeAsync();
// Hide the background and remove progressbar
await Task.WhenAll(new[] {
_topBackgroundView.TranslateTo(0, -Height/2, 465, Easing.CubicIn),
_bottomBackgroundView.TranslateTo(0, Height, 465, Easing.CubicIn),
_progress.FadeTo(0, 365, Easing.CubicIn)
});
// Add map
var map = new Map();
var mapOverlay = new NControlView {
BackgroundColor = Xamarin.Forms.Color.Transparent,
};
mapOverlay.OnTouchesBegan += async (sender, e) => await ToggleChromeAsync();
_mapContainer.Children.Add(map, () => _mapContainer.Bounds);
_mapContainer.Children.Add(mapOverlay, () => _mapContainer.Bounds);
}
/// <summary>
/// Toggles the chrome async.
/// </summary>
/// <returns>The chrome async.</returns>
private Task ToggleChromeAsync()
{
if (_chromeVisible)
return HideChromeAsync();
return ShowChromeAsync();
}
/// <summary>
/// Shows the chrome, ie the navigation bar and button bar
/// </summary>
private async Task ShowChromeAsync()
{
_chromeVisible = true;
await Task.WhenAll(new []{
_bottomBar.TranslateTo(0, -_bottomBar.Height, 550, Easing.BounceOut),
_navigationBar.TranslateTo(0, Device.OnPlatform<int>(61, 80, 55), 550, Easing.BounceOut),
});
}
/// <summary>
/// Shows the chrome, ie the navigation bar and button bar
/// </summary>
private async Task HideChromeAsync()
{
_chromeVisible = false;
await Task.WhenAll(new []{
_bottomBar.TranslateTo(0, 0, 550, Easing.CubicIn),
_navigationBar.TranslateTo(0, 0, 550, Easing.CubicIn),
});
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Reflection;
using System.Reflection.Emit;
using Xunit;
namespace System.Reflection.Emit.Tests
{
public class ModuleBuilderDefineUninitializedData
{
private const string DefaultAssemblyName = "ModuleBuilderDefineUninitializedData";
private const AssemblyBuilderAccess DefaultAssemblyBuilderAccess = AssemblyBuilderAccess.Run;
private const string DefaultModuleName = "DynamicModule";
private const int MinStringLength = 8;
private const int MaxStringLength = 256;
private const int ReservedMaskFieldAttribute = 0x9500; // This constant maps to FieldAttributes.ReservedMask that is not available in the contract.
private readonly RandomDataGenerator _generator = new RandomDataGenerator();
private ModuleBuilder GetModuleBuilder()
{
AssemblyName name = new AssemblyName(DefaultAssemblyName);
AssemblyBuilder asmBuilder = AssemblyBuilder.DefineDynamicAssembly(name, DefaultAssemblyBuilderAccess);
return TestLibrary.Utilities.GetModuleBuilder(asmBuilder, DefaultModuleName);
}
[Fact]
public void TestWithValidData()
{
ModuleBuilder builder = GetModuleBuilder();
string fieldName = "PosTest1_";
int size = _generator.GetByte();
if (size == 0)
size++;
FieldAttributes[] attributes = new FieldAttributes[] {
FieldAttributes.Assembly,
FieldAttributes.FamANDAssem,
FieldAttributes.Family,
FieldAttributes.FamORAssem,
FieldAttributes.FieldAccessMask,
FieldAttributes.HasDefault,
FieldAttributes.HasFieldMarshal,
FieldAttributes.HasFieldRVA,
FieldAttributes.InitOnly,
FieldAttributes.Literal,
FieldAttributes.NotSerialized,
FieldAttributes.PinvokeImpl,
FieldAttributes.Private,
FieldAttributes.PrivateScope,
FieldAttributes.Public,
FieldAttributes.RTSpecialName,
FieldAttributes.SpecialName,
FieldAttributes.Static
};
for (int i = 0; i < attributes.Length; ++i)
{
FieldAttributes attribute = attributes[i];
string desiredFieldName = fieldName + i.ToString();
FieldBuilder fb = builder.DefineUninitializedData(desiredFieldName, size, attribute);
int desiredAttribute = ((int)attribute | (int)FieldAttributes.Static) & ~ReservedMaskFieldAttribute;
VerificationHelper(fb, desiredFieldName, (FieldAttributes)desiredAttribute);
}
}
[Fact]
public void TestWithBoundaryData()
{
ModuleBuilder builder = GetModuleBuilder();
string fieldName = "PosTest2_";
int[] sizeValues = new int[] {
1,
0x003f0000 - 1
};
FieldAttributes[] attributes = new FieldAttributes[] {
FieldAttributes.Assembly,
FieldAttributes.FamANDAssem,
FieldAttributes.Family,
FieldAttributes.FamORAssem,
FieldAttributes.FieldAccessMask,
FieldAttributes.HasDefault,
FieldAttributes.HasFieldMarshal,
FieldAttributes.HasFieldRVA,
FieldAttributes.InitOnly,
FieldAttributes.Literal,
FieldAttributes.NotSerialized,
FieldAttributes.PinvokeImpl,
FieldAttributes.Private,
FieldAttributes.PrivateScope,
FieldAttributes.Public,
FieldAttributes.RTSpecialName,
FieldAttributes.SpecialName,
FieldAttributes.Static
};
for (int i = 0; i < sizeValues.Length; ++i)
{
for (int j = 0; j < attributes.Length; ++j)
{
FieldAttributes attribute = attributes[j];
string desiredFieldName = fieldName + i.ToString() + "_" + j.ToString();
FieldBuilder fb = builder.DefineUninitializedData(desiredFieldName, sizeValues[i], attribute);
int desiredAttribute = ((int)attribute | (int)FieldAttributes.Static) & (~ReservedMaskFieldAttribute);
VerificationHelper(fb, desiredFieldName, (FieldAttributes)desiredAttribute);
}
}
}
[Fact]
public void TestThrowsExceptionWithZeroLengthName()
{
ModuleBuilder builder = GetModuleBuilder();
FieldAttributes[] attributes = new FieldAttributes[] {
FieldAttributes.Assembly,
FieldAttributes.FamANDAssem,
FieldAttributes.Family,
FieldAttributes.FamORAssem,
FieldAttributes.FieldAccessMask,
FieldAttributes.HasDefault,
FieldAttributes.HasFieldMarshal,
FieldAttributes.HasFieldRVA,
FieldAttributes.InitOnly,
FieldAttributes.Literal,
FieldAttributes.NotSerialized,
FieldAttributes.PinvokeImpl,
FieldAttributes.Private,
FieldAttributes.PrivateScope,
FieldAttributes.Public,
FieldAttributes.RTSpecialName,
FieldAttributes.SpecialName,
FieldAttributes.Static
};
int size = _generator.GetByte();
for (int i = 0; i < attributes.Length; ++i)
{
VerificationHelper(builder, "", size, attributes[i], typeof(ArgumentException));
}
}
[Fact]
public void TestThrowsExceptionWithInvalidSizeData()
{
int[] sizeValues = new int[] {
0,
-1,
0x003f0000,
0x003f0000 + 1
};
ModuleBuilder builder = GetModuleBuilder();
FieldAttributes[] attributes = new FieldAttributes[] {
FieldAttributes.Assembly,
FieldAttributes.FamANDAssem,
FieldAttributes.Family,
FieldAttributes.FamORAssem,
FieldAttributes.FieldAccessMask,
FieldAttributes.HasDefault,
FieldAttributes.HasFieldMarshal,
FieldAttributes.HasFieldRVA,
FieldAttributes.InitOnly,
FieldAttributes.Literal,
FieldAttributes.NotSerialized,
FieldAttributes.PinvokeImpl,
FieldAttributes.Private,
FieldAttributes.PrivateScope,
FieldAttributes.Public,
FieldAttributes.RTSpecialName,
FieldAttributes.SpecialName,
FieldAttributes.Static
};
for (int i = 0; i < sizeValues.Length; ++i)
{
for (int j = 0; j < attributes.Length; ++j)
{
FieldAttributes attribute = attributes[j];
VerificationHelper(builder, "", sizeValues[i], attribute, typeof(ArgumentException));
}
}
}
[Fact]
public void TestThrowsExceptionWithNullName()
{
ModuleBuilder builder = GetModuleBuilder();
FieldAttributes[] attributes = new FieldAttributes[] {
FieldAttributes.Assembly,
FieldAttributes.FamANDAssem,
FieldAttributes.Family,
FieldAttributes.FamORAssem,
FieldAttributes.FieldAccessMask,
FieldAttributes.HasDefault,
FieldAttributes.HasFieldMarshal,
FieldAttributes.HasFieldRVA,
FieldAttributes.InitOnly,
FieldAttributes.Literal,
FieldAttributes.NotSerialized,
FieldAttributes.PinvokeImpl,
FieldAttributes.Private,
FieldAttributes.PrivateScope,
FieldAttributes.Public,
FieldAttributes.RTSpecialName,
FieldAttributes.SpecialName,
FieldAttributes.Static
};
int size = _generator.GetByte();
for (int i = 0; i < attributes.Length; ++i)
{
VerificationHelper(builder, null, size, attributes[i], typeof(ArgumentNullException));
}
}
[Fact]
public void TestThrowsExceptionOnCreateGlobalFunctionCalledPreviously()
{
FieldAttributes[] attributes = new FieldAttributes[] {
FieldAttributes.Assembly,
FieldAttributes.FamANDAssem,
FieldAttributes.Family,
FieldAttributes.FamORAssem,
FieldAttributes.FieldAccessMask,
FieldAttributes.HasDefault,
FieldAttributes.HasFieldMarshal,
FieldAttributes.HasFieldRVA,
FieldAttributes.InitOnly,
FieldAttributes.Literal,
FieldAttributes.NotSerialized,
FieldAttributes.PinvokeImpl,
FieldAttributes.Private,
FieldAttributes.PrivateScope,
FieldAttributes.Public,
FieldAttributes.RTSpecialName,
FieldAttributes.SpecialName,
FieldAttributes.Static
};
int size = _generator.GetByte();
ModuleBuilder testModuleBuilder = GetModuleBuilder();
testModuleBuilder.CreateGlobalFunctions();
string fieldName = "NegTest4_";
for (int i = 0; i < attributes.Length; ++i)
{
VerificationHelper(testModuleBuilder, fieldName + i.ToString(), size, attributes[i], typeof(InvalidOperationException));
}
}
private void VerificationHelper(FieldBuilder fb, string desiredName, FieldAttributes desiredAttribute)
{
Assert.Equal(desiredName, fb.Name);
Assert.Equal(desiredAttribute, fb.Attributes);
}
private void VerificationHelper(ModuleBuilder builder, string name, int size, FieldAttributes attribute, Type desiredException)
{
Assert.Throws(desiredException, () => { FieldBuilder fieldBuilder = builder.DefineUninitializedData(name, size, attribute); });
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Management.Store;
using Microsoft.WindowsAzure.Management.Store.Models;
namespace Microsoft.WindowsAzure.Management.Store
{
/// <summary>
/// The Windows Azure Store API is a REST API for managing Windows Azure
/// Store add-ins.
/// </summary>
public static partial class AddOnOperationsExtensions
{
/// <summary>
/// The Create Store Item operation creates Windows Azure Store entries
/// in a Windows Azure subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Store.IAddOnOperations.
/// </param>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service to which this store item
/// will be assigned.
/// </param>
/// <param name='resourceName'>
/// Required. The name of this resource.
/// </param>
/// <param name='addOnName'>
/// Required. The add on name.
/// </param>
/// <param name='parameters'>
/// Required. Parameters used to specify how the Create procedure will
/// function.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static OperationStatusResponse BeginCreating(this IAddOnOperations operations, string cloudServiceName, string resourceName, string addOnName, AddOnCreateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IAddOnOperations)s).BeginCreatingAsync(cloudServiceName, resourceName, addOnName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Create Store Item operation creates Windows Azure Store entries
/// in a Windows Azure subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Store.IAddOnOperations.
/// </param>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service to which this store item
/// will be assigned.
/// </param>
/// <param name='resourceName'>
/// Required. The name of this resource.
/// </param>
/// <param name='addOnName'>
/// Required. The add on name.
/// </param>
/// <param name='parameters'>
/// Required. Parameters used to specify how the Create procedure will
/// function.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static Task<OperationStatusResponse> BeginCreatingAsync(this IAddOnOperations operations, string cloudServiceName, string resourceName, string addOnName, AddOnCreateParameters parameters)
{
return operations.BeginCreatingAsync(cloudServiceName, resourceName, addOnName, parameters, CancellationToken.None);
}
/// <summary>
/// The Delete Store Item operation deletes Windows Azure Store entries
/// that re provisioned for a subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Store.IAddOnOperations.
/// </param>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service to which this store item
/// will be assigned.
/// </param>
/// <param name='resourceProviderNamespace'>
/// Required. The namespace in which this store item resides.
/// </param>
/// <param name='resourceProviderType'>
/// Required. The type of store item to be deleted.
/// </param>
/// <param name='resourceProviderName'>
/// Required. The name of this resource provider.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static OperationStatusResponse BeginDeleting(this IAddOnOperations operations, string cloudServiceName, string resourceProviderNamespace, string resourceProviderType, string resourceProviderName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IAddOnOperations)s).BeginDeletingAsync(cloudServiceName, resourceProviderNamespace, resourceProviderType, resourceProviderName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Delete Store Item operation deletes Windows Azure Store entries
/// that re provisioned for a subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Store.IAddOnOperations.
/// </param>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service to which this store item
/// will be assigned.
/// </param>
/// <param name='resourceProviderNamespace'>
/// Required. The namespace in which this store item resides.
/// </param>
/// <param name='resourceProviderType'>
/// Required. The type of store item to be deleted.
/// </param>
/// <param name='resourceProviderName'>
/// Required. The name of this resource provider.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static Task<OperationStatusResponse> BeginDeletingAsync(this IAddOnOperations operations, string cloudServiceName, string resourceProviderNamespace, string resourceProviderType, string resourceProviderName)
{
return operations.BeginDeletingAsync(cloudServiceName, resourceProviderNamespace, resourceProviderType, resourceProviderName, CancellationToken.None);
}
/// <summary>
/// The Create Store Item operation creates Windows Azure Store entries
/// in a Windows Azure subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Store.IAddOnOperations.
/// </param>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service to which this store item
/// will be assigned.
/// </param>
/// <param name='resourceName'>
/// Required. The name of this resource.
/// </param>
/// <param name='addOnName'>
/// Required. The add on name.
/// </param>
/// <param name='parameters'>
/// Required. Parameters used to specify how the Create procedure will
/// function.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static OperationStatusResponse Create(this IAddOnOperations operations, string cloudServiceName, string resourceName, string addOnName, AddOnCreateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IAddOnOperations)s).CreateAsync(cloudServiceName, resourceName, addOnName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Create Store Item operation creates Windows Azure Store entries
/// in a Windows Azure subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Store.IAddOnOperations.
/// </param>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service to which this store item
/// will be assigned.
/// </param>
/// <param name='resourceName'>
/// Required. The name of this resource.
/// </param>
/// <param name='addOnName'>
/// Required. The add on name.
/// </param>
/// <param name='parameters'>
/// Required. Parameters used to specify how the Create procedure will
/// function.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static Task<OperationStatusResponse> CreateAsync(this IAddOnOperations operations, string cloudServiceName, string resourceName, string addOnName, AddOnCreateParameters parameters)
{
return operations.CreateAsync(cloudServiceName, resourceName, addOnName, parameters, CancellationToken.None);
}
/// <summary>
/// The Delete Store Item operation deletes Windows Azure Storeentries
/// that are provisioned for a subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Store.IAddOnOperations.
/// </param>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service to which this store item
/// will be assigned.
/// </param>
/// <param name='resourceProviderNamespace'>
/// Required. The namespace in which this store item resides.
/// </param>
/// <param name='resourceProviderType'>
/// Required. The type of store item to be deleted.
/// </param>
/// <param name='resourceProviderName'>
/// Required. The name of this resource provider.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static OperationStatusResponse Delete(this IAddOnOperations operations, string cloudServiceName, string resourceProviderNamespace, string resourceProviderType, string resourceProviderName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IAddOnOperations)s).DeleteAsync(cloudServiceName, resourceProviderNamespace, resourceProviderType, resourceProviderName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Delete Store Item operation deletes Windows Azure Storeentries
/// that are provisioned for a subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Store.IAddOnOperations.
/// </param>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service to which this store item
/// will be assigned.
/// </param>
/// <param name='resourceProviderNamespace'>
/// Required. The namespace in which this store item resides.
/// </param>
/// <param name='resourceProviderType'>
/// Required. The type of store item to be deleted.
/// </param>
/// <param name='resourceProviderName'>
/// Required. The name of this resource provider.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static Task<OperationStatusResponse> DeleteAsync(this IAddOnOperations operations, string cloudServiceName, string resourceProviderNamespace, string resourceProviderType, string resourceProviderName)
{
return operations.DeleteAsync(cloudServiceName, resourceProviderNamespace, resourceProviderType, resourceProviderName, CancellationToken.None);
}
/// <summary>
/// The Update Store Item operation creates Windows Azure Store entries
/// in a Windows Azure subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Store.IAddOnOperations.
/// </param>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service to which this store item
/// will be assigned.
/// </param>
/// <param name='resourceName'>
/// Required. The name of this resource.
/// </param>
/// <param name='addOnName'>
/// Required. The addon name.
/// </param>
/// <param name='parameters'>
/// Required. Parameters used to specify how the Create procedure will
/// function.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static OperationStatusResponse Update(this IAddOnOperations operations, string cloudServiceName, string resourceName, string addOnName, AddOnUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IAddOnOperations)s).UpdateAsync(cloudServiceName, resourceName, addOnName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Update Store Item operation creates Windows Azure Store entries
/// in a Windows Azure subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Store.IAddOnOperations.
/// </param>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service to which this store item
/// will be assigned.
/// </param>
/// <param name='resourceName'>
/// Required. The name of this resource.
/// </param>
/// <param name='addOnName'>
/// Required. The addon name.
/// </param>
/// <param name='parameters'>
/// Required. Parameters used to specify how the Create procedure will
/// function.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static Task<OperationStatusResponse> UpdateAsync(this IAddOnOperations operations, string cloudServiceName, string resourceName, string addOnName, AddOnUpdateParameters parameters)
{
return operations.UpdateAsync(cloudServiceName, resourceName, addOnName, parameters, CancellationToken.None);
}
}
}
| |
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
using System.Text.RegularExpressions;
#if !(UNITY_5_0 || UNITY_5_1 || UNITY_5_2)
using UnityEditor.SceneManagement;
using UnityEngine.SceneManagement;
#endif
namespace Sabresaurus.SabreCSG
{
public static class EditorHelper
{
// Threshold for raycasting vertex clicks, in screen space (should match half the icon dimensions)
const float CLICK_THRESHOLD = 15;
// Used for offseting mouse position
const int TOOLBAR_HEIGHT = 37;
public static bool HasDelegate (System.Delegate mainDelegate, System.Delegate targetListener)
{
if (mainDelegate != null)
{
if (mainDelegate.GetInvocationList().Contains(targetListener))
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
public static bool SceneViewHasDelegate(SceneView.OnSceneFunc targetDelegate)
{
return HasDelegate(SceneView.onSceneGUIDelegate, targetDelegate);
}
public enum SceneViewCamera { Top, Bottom, Left, Right, Front, Back, Other };
public static SceneViewCamera GetSceneViewCamera(SceneView sceneView)
{
return GetSceneViewCamera(sceneView.camera);
}
public static SceneViewCamera GetSceneViewCamera(Camera camera)
{
Vector3 cameraForward = camera.transform.forward;
if (cameraForward == new Vector3(0, -1, 0))
{
return SceneViewCamera.Top;
}
else if (cameraForward == new Vector3(0, 1, 0))
{
return SceneViewCamera.Bottom;
}
else if (cameraForward == new Vector3(1, 0, 0))
{
return SceneViewCamera.Left;
}
else if (cameraForward == new Vector3(-1, 0, 0))
{
return SceneViewCamera.Right;
}
else if (cameraForward == new Vector3(0, 0, -1))
{
return SceneViewCamera.Front;
}
else if (cameraForward == new Vector3(0, 0, 1))
{
return SceneViewCamera.Back;
}
else
{
return SceneViewCamera.Other;
}
}
/// <summary>
/// Whether the mouse position is within the bounds of the axis snapping gizmo that appears in the top right
/// </summary>
public static bool IsMousePositionNearSceneGizmo(Vector2 mousePosition)
{
float scale = 1;
#if UNITY_5_4_OR_NEWER
mousePosition = EditorGUIUtility.PointsToPixels(mousePosition);
scale = EditorGUIUtility.pixelsPerPoint;
#endif
mousePosition.x = Screen.width - mousePosition.x;
if (mousePosition.x > 14 * scale
&& mousePosition.x < 89 * scale
&& mousePosition.y > 14 * scale
&& mousePosition.y < 105 * scale)
{
return true;
}
else
{
return false;
}
}
public static Vector2 ConvertMousePointPosition(Vector2 sourceMousePosition, bool convertPointsToPixels = true)
{
#if UNITY_5_4_OR_NEWER
if(convertPointsToPixels)
{
sourceMousePosition = EditorGUIUtility.PointsToPixels(sourceMousePosition);
}
// Flip the direction of Y and remove the Scene View top toolbar's height
sourceMousePosition.y = Screen.height - sourceMousePosition.y - (TOOLBAR_HEIGHT * EditorGUIUtility.pixelsPerPoint);
#else
// Flip the direction of Y and remove the Scene View top toolbar's height
sourceMousePosition.y = Screen.height - sourceMousePosition.y - TOOLBAR_HEIGHT;
#endif
return sourceMousePosition;
}
public static Vector2 ConvertMousePixelPosition(Vector2 sourceMousePosition, bool convertPixelsToPoints = true)
{
#if UNITY_5_4_OR_NEWER
if(convertPixelsToPoints)
{
sourceMousePosition = EditorGUIUtility.PixelsToPoints(sourceMousePosition);
}
// Flip the direction of Y and remove the Scene View top toolbar's height
sourceMousePosition.y = (Screen.height / EditorGUIUtility.pixelsPerPoint) - sourceMousePosition.y - (TOOLBAR_HEIGHT);
#else
// Flip the direction of Y and remove the Scene View top toolbar's height
sourceMousePosition.y = Screen.height - sourceMousePosition.y - TOOLBAR_HEIGHT;
#endif
return sourceMousePosition;
}
public static bool IsMousePositionInIMGUIRect(Vector2 mousePosition, Rect rect)
{
// This works in point space, not pixel space
mousePosition += new Vector2(0, EditorStyles.toolbar.fixedHeight);
return rect.Contains(mousePosition);
}
public static bool InClickZone(Vector2 mousePosition, Vector3 worldPosition)
{
mousePosition = ConvertMousePointPosition(mousePosition);
Vector3 targetScreenPosition = Camera.current.WorldToScreenPoint(worldPosition);
if (targetScreenPosition.z < 0)
{
return false;
}
float distance = Vector2.Distance(mousePosition, targetScreenPosition);
float depthDistance = targetScreenPosition.z;
//#if UNITY_5_4_OR_NEWER
// depthDistance *= EditorGUIUtility.pixelsPerPoint;
//#endif
// When z is 6 then click threshold is 15
// when z is 20 then click threshold is 5
float threshold;
// if(CurrentSettings.ReducedHandleThreshold)
// {
// threshold = Mathf.Lerp(5, 2, Mathf.InverseLerp(6,20,depthDistance));
// }
// else
{
threshold = Mathf.Lerp(15, 5, Mathf.InverseLerp(6,20,depthDistance));
}
#if UNITY_5_4_OR_NEWER
threshold *= EditorGUIUtility.pixelsPerPoint;
#endif
if (distance <= threshold)
{
return true;
}
else
{
return false;
}
}
public static bool InClickRect(Vector2 mousePosition, Vector3 worldPosition1, Vector3 worldPosition2)
{
mousePosition = ConvertMousePointPosition(mousePosition);
Vector3 targetScreenPosition1 = Camera.current.WorldToScreenPoint(worldPosition1);
Vector3 targetScreenPosition2 = Camera.current.WorldToScreenPoint(worldPosition2);
if (targetScreenPosition1.z < 0)
{
return false;
}
// When z is 6 then click threshold is 15
// when z is 20 then click threshold is 5
float threshold = Mathf.Lerp(15, 5, Mathf.InverseLerp(6,20,targetScreenPosition1.z));
#if UNITY_5_4_OR_NEWER
threshold *= EditorGUIUtility.pixelsPerPoint;
#endif
Vector3 closestPoint = MathHelper.ProjectPointOnLineSegment(targetScreenPosition1, targetScreenPosition2, mousePosition);
closestPoint.z = 0;
if(Vector3.Distance(closestPoint, mousePosition) < threshold)
// if(mousePosition.y > Mathf.Min(targetScreenPosition1.y, targetScreenPosition2.y - threshold)
// && mousePosition.y < Mathf.Max(targetScreenPosition1.y, targetScreenPosition2.y) + threshold
// && mousePosition.x > Mathf.Min(targetScreenPosition1.x, targetScreenPosition2.x - threshold)
// && mousePosition.x < Mathf.Max(targetScreenPosition1.x, targetScreenPosition2.x) + threshold)
{
return true;
}
else
{
return false;
}
}
public static Vector3 CalculateWorldPoint(SceneView sceneView, Vector3 screenPoint)
{
screenPoint = ConvertMousePointPosition(screenPoint);
return sceneView.camera.ScreenToWorldPoint(screenPoint);
}
// public static string GetCurrentSceneGUID()
// {
// string currentScenePath = EditorApplication.currentScene;
// if(!string.IsNullOrEmpty(currentScenePath))
// {
// return AssetDatabase.AssetPathToGUID(currentScenePath);
// }
// else
// {
// // Scene hasn't been saved
// return null;
// }
// }
public static void SetDirty(Object targetObject)
{
if(!Application.isPlaying)
{
EditorUtility.SetDirty(targetObject);
#if UNITY_5_0 || UNITY_5_1 || UNITY_5_2
// As of Unity 5, SetDirty no longer marks the scene as dirty. Need to use the new call for that.
EditorApplication.MarkSceneDirty();
#else // 5.3 and above introduce multiple scene management via EditorSceneManager
Scene activeScene = EditorSceneManager.GetActiveScene();
EditorSceneManager.MarkSceneDirty(activeScene);
#endif
}
}
public static void IsoAlignSceneView(Vector3 direction)
{
SceneView sceneView = SceneView.lastActiveSceneView;
SceneView.lastActiveSceneView.LookAt(sceneView.pivot, Quaternion.LookRotation(direction));
// Mark the camera as iso (orthographic)
sceneView.orthographic = true;
}
public static void IsoAlignSceneViewToNearest()
{
SceneView sceneView = SceneView.lastActiveSceneView;
Vector3 cameraForward = sceneView.camera.transform.forward;
Vector3 newForward = Vector3.up;
float bestDot = -1;
Vector3 testDirection;
float dot;
// Find out of the six axis directions the closest direction to the camera
for (int i = 0; i < 3; i++)
{
testDirection = Vector3.zero;
testDirection[i] = 1;
dot = Vector3.Dot(testDirection, cameraForward);
if(dot > bestDot)
{
bestDot = dot;
newForward = testDirection;
}
testDirection[i] = -1;
dot = Vector3.Dot(testDirection, cameraForward);
if(dot > bestDot)
{
bestDot = dot;
newForward = testDirection;
}
}
IsoAlignSceneView(newForward);
}
/// <summary>
/// Overrides the built in selection duplication to maintain sibling order of the selection. But only if at least one of the selection is under a CSG Model.
/// </summary>
/// <returns><c>true</c>, if our custom duplication took place (and one of the selection was under a CSG Model), <c>false</c> otherwise in which case the duplication event should not be consumed so that Unity will duplicate for us.</returns>
public static bool DuplicateSelection()
{
List<Transform> selectedTransforms = Selection.transforms.ToList();
// Whether any of the selection objects are under a CSG Model
bool shouldCustomDuplicationOccur = false;
for (int i = 0; i < selectedTransforms.Count; i++)
{
if(selectedTransforms[i].GetComponentInParent<CSGModel>() != null)
{
shouldCustomDuplicationOccur = true;
}
}
if(shouldCustomDuplicationOccur) // Some of the objects are under a CSG Model, so peform our special duplication override
{
// Sort the selected transforms in order of sibling index
selectedTransforms.Sort((x,y) => x.GetSiblingIndex().CompareTo(y.GetSiblingIndex()));
GameObject[] newObjects = new GameObject[Selection.gameObjects.Length];
// Walk through each selected object in the correct order, duplicating them one by one
for (int i = 0; i < selectedTransforms.Count; i++)
{
// Temporarily set the selection to the single entry
Selection.activeGameObject = selectedTransforms[i].gameObject;
// Duplicate the single entry
Unsupported.DuplicateGameObjectsUsingPasteboard();
// Cache the new entry, so when we're done we reselect all new objects
newObjects[i] = Selection.activeGameObject;
}
// Finished duplicating, select all new objects
Selection.objects = newObjects;
}
// Whether custom duplication took place and whether the Duplicate event should be consumed
return shouldCustomDuplicationOccur;
}
public class TransformIndexComparer : IComparer
{
public int Compare(object x, object y)
{
return ((Transform) x).GetSiblingIndex().CompareTo(((Transform) y).GetSiblingIndex());
}
}
}
}
#endif
| |
/****************************************************************************
Tilde
Copyright (c) 2008 Tantalus Media Pty
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Reflection;
namespace Tilde.LuaDebugger
{
public class ThreadedHost : ITarget
{
//private Thread mThread;
private AutoResetEvent mEvent;
private MessageQueue mMessageQueue;
private ITarget mRealHost;
private Thread mThread;
private Form mForm;
public ThreadedHost(Form form)
{
mMessageQueue = new MessageQueue();
mEvent = new AutoResetEvent(false);
mForm = form;
}
public ITarget Client
{
get { return mRealHost; }
set
{
mRealHost = value;
mRealHost.DebugPrint += new DebugPrintEventHandler(realHost_DebugPrint);
mRealHost.ErrorMessage += new ErrorMessageEventHandler(realHost_ErrorMessage);
mRealHost.StatusMessage += new StatusMessageEventHandler(realHost_StatusMessage);
mRealHost.StateUpdate += new StateUpdateEventHandler(realHost_StateUpdate);
mRealHost.CallstackUpdate += new CallstackUpdateEventHandler(realHost_CallstackUpdate);
mRealHost.ThreadUpdate += new ThreadUpdateEventHandler(realHost_ThreadUpdate);
mRealHost.VariableUpdate += new VariableUpdateEventHandler(realHost_VariableUpdate);
mRealHost.BreakpointUpdate += new BreakpointUpdateEventHandler(realHost_BreakpointUpdate);
mRealHost.ValueCached += new ValueCachedEventHandler(realHost_ValueCached);
mRealHost.FileUpload += new FileUploadEventHandler(realHost_FileUpload);
mRealHost.SnippetResult += new SnippetResultEventHandler(realHost_SnippetResult);
mRealHost.AutocompleteOptions += new AutocompleteOptionsEventHandler(realHost_AutocompleteOptions);
}
}
public Form Form
{
get { return mForm; }
}
public MessageQueue MessageQueue
{
get { return mMessageQueue; }
}
public AutoResetEvent Event
{
get { return mEvent; }
}
public Thread Thread
{
get { return mThread; }
set { mThread = value; }
}
public void ProcessEvents()
{
while(!mMessageQueue.Empty)
{
// Retrieve a message from the queue
KeyValuePair<Delegate, object []> message = mMessageQueue.Pop();
// Execute it
Delegate method = message.Key;
object [] args = message.Value;
try
{
method.DynamicInvoke();
}
catch (TargetInvocationException ex)
{
// Re-throw any exceptions
throw ex.InnerException;
}
}
}
private void Invoke(Delegate del)
{
mMessageQueue.Push(del, null);
mEvent.Set();
}
private void realHost_DebugPrint(ITarget sender, DebugPrintEventArgs args)
{
if (mForm != null && mForm.IsHandleCreated)
mForm.BeginInvoke(new MethodInvoker(delegate()
{
if (this.DebugPrint != null)
this.DebugPrint(this, args);
}));
}
private void realHost_ErrorMessage(ITarget sender, ErrorMessageEventArgs args)
{
if (mForm != null && mForm.IsHandleCreated)
mForm.BeginInvoke(new MethodInvoker(delegate()
{
if (this.ErrorMessage != null)
this.ErrorMessage(this, args);
}));
}
private void realHost_StatusMessage(ITarget sender, StatusMessageEventArgs args)
{
if (mForm != null && mForm.IsHandleCreated)
mForm.BeginInvoke(new MethodInvoker(delegate()
{
if (this.StatusMessage != null)
this.StatusMessage(this, args);
}));
}
private void realHost_StateUpdate(ITarget sender, StateUpdateEventArgs args)
{
if (mForm != null && mForm.IsHandleCreated)
mForm.BeginInvoke(new MethodInvoker(delegate()
{
if (this.StateUpdate != null)
this.StateUpdate(this, args);
}));
}
void realHost_CallstackUpdate(ITarget sender, CallstackUpdateEventArgs args)
{
if (mForm != null && mForm.IsHandleCreated)
mForm.BeginInvoke(new MethodInvoker(delegate()
{
if (this.CallstackUpdate != null)
this.CallstackUpdate(this, args);
}));
}
void realHost_ThreadUpdate(ITarget sender, ThreadUpdateEventArgs args)
{
if (mForm != null && mForm.IsHandleCreated)
mForm.BeginInvoke(new MethodInvoker(delegate()
{
if (this.ThreadUpdate != null)
this.ThreadUpdate(this, args);
}));
}
void realHost_VariableUpdate(ITarget sender, VariableUpdateEventArgs args)
{
if (mForm != null && mForm.IsHandleCreated)
mForm.BeginInvoke(new MethodInvoker(delegate()
{
if (this.VariableUpdate != null)
this.VariableUpdate(this, args);
}));
}
void realHost_BreakpointUpdate(ITarget sender, BreakpointUpdateEventArgs args)
{
if (mForm != null && mForm.IsHandleCreated)
mForm.BeginInvoke(new MethodInvoker(delegate()
{
if (this.BreakpointUpdate != null)
this.BreakpointUpdate(this, args);
}));
}
void realHost_ValueCached(ITarget host, ValueCachedEventArgs args)
{
if (mForm != null && mForm.IsHandleCreated)
mForm.BeginInvoke(new MethodInvoker(delegate()
{
if (this.ValueCached != null)
this.ValueCached(this, args);
}));
}
void realHost_FileUpload(ITarget host, FileUploadEventArgs args)
{
if (mForm != null && mForm.IsHandleCreated)
mForm.BeginInvoke(new MethodInvoker(delegate()
{
if (this.FileUpload != null)
this.FileUpload(this, args);
}));
}
void realHost_SnippetResult(ITarget host, SnippetResultEventArgs args)
{
if (mForm != null && mForm.IsHandleCreated)
mForm.BeginInvoke(new MethodInvoker(delegate()
{
if (this.SnippetResult != null)
this.SnippetResult(this, args);
}));
}
void realHost_AutocompleteOptions(ITarget sender, AutocompleteOptionsEventArgs args)
{
if (mForm != null && mForm.IsHandleCreated)
mForm.BeginInvoke(new MethodInvoker(delegate()
{
if (this.AutocompleteOptions != null)
this.AutocompleteOptions(this, args);
}));
}
#region IHost Members
public event DebugPrintEventHandler DebugPrint;
public event ErrorMessageEventHandler ErrorMessage;
public event StatusMessageEventHandler StatusMessage;
public event StateUpdateEventHandler StateUpdate;
public event CallstackUpdateEventHandler CallstackUpdate;
public event ThreadUpdateEventHandler ThreadUpdate;
public event VariableUpdateEventHandler VariableUpdate;
public event BreakpointUpdateEventHandler BreakpointUpdate;
public event ValueCachedEventHandler ValueCached;
public event FileUploadEventHandler FileUpload;
public event SnippetResultEventHandler SnippetResult;
public event AutocompleteOptionsEventHandler AutocompleteOptions;
public void Reset(string fileName)
{
Invoke(new MethodInvoker(delegate() { mRealHost.Reset(fileName); }));
}
public void Attach()
{
Invoke(new MethodInvoker(delegate() { mRealHost.Attach(); }));
}
public void Disconnect()
{
Invoke(new MethodInvoker(delegate() { mRealHost.Disconnect(); }));
}
public void Run(ExecutionMode mode)
{
Invoke(new MethodInvoker(delegate() { mRealHost.Run(mode); }));
}
public void DownloadFile(int fileid, string filename)
{
Invoke(new MethodInvoker(delegate() { mRealHost.DownloadFile(fileid, filename); }));
}
public void ExecuteFile(int fileid)
{
Invoke(new MethodInvoker(delegate() { mRealHost.ExecuteFile(fileid); }));
}
public void DiscardFile(int fileid)
{
Invoke(new MethodInvoker(delegate() { mRealHost.DiscardFile(fileid); }));
}
public void StartProfile()
{
Invoke(new MethodInvoker(delegate() { mRealHost.StartProfile(); }));
}
public void StopProfile()
{
Invoke(new MethodInvoker(delegate() { mRealHost.StopProfile(); }));
}
public TargetInfo HostInfo
{
get { return mRealHost.HostInfo; }
}
public void AddBreakpoint(string fileName, int lineNumber, int bkptid)
{
Invoke(new MethodInvoker(delegate() { mRealHost.AddBreakpoint(fileName, lineNumber, bkptid); }));
}
public void RemoveBreakpoint(int bkptid)
{
Invoke(new MethodInvoker(delegate() { mRealHost.RemoveBreakpoint(bkptid); }));
}
public void ClearBreakpoints()
{
Invoke(new MethodInvoker(delegate() { mRealHost.ClearBreakpoints(); }));
}
public void IgnoreError(string fileName, int lineNumber)
{
Invoke(new MethodInvoker(delegate() { mRealHost.IgnoreError(fileName, lineNumber); }));
}
public void RetrieveStatus(LuaValue thread, int stackFrame)
{
Invoke(new MethodInvoker(delegate() { mRealHost.RetrieveStatus(thread, stackFrame); }));
}
public void RetrieveThreads()
{
Invoke(new MethodInvoker(delegate() { mRealHost.RetrieveThreads(); }));
}
public void RetrieveLocals(LuaValue thread, int stackFrame)
{
Invoke(new MethodInvoker(delegate() { mRealHost.RetrieveLocals(thread, stackFrame); }));
}
public void ExpandLocal(LuaValue[] path)
{
Invoke(new MethodInvoker(delegate() { mRealHost.ExpandLocal(path); }));
}
public void CloseLocal(LuaValue[] path)
{
Invoke(new MethodInvoker(delegate() { mRealHost.CloseLocal(path); }));
}
public void RetrieveWatches(LuaValue thread, int stackFrame)
{
Invoke(new MethodInvoker(delegate() { mRealHost.RetrieveWatches(thread, stackFrame); }));
}
public void AddWatch(string expr, int watchid)
{
Invoke(new MethodInvoker(delegate() { mRealHost.AddWatch(expr, watchid); }));
}
public void RemoveWatch(int watchid)
{
Invoke(new MethodInvoker(delegate() { mRealHost.RemoveWatch(watchid); }));
}
public void ExpandWatch(int watchid, LuaValue[] path)
{
Invoke(new MethodInvoker(delegate() { mRealHost.ExpandWatch(watchid, path); }));
}
public void CloseWatch(int watchid, LuaValue[] path)
{
Invoke(new MethodInvoker(delegate() { mRealHost.CloseWatch(watchid, path); }));
}
public void ClearWatches()
{
Invoke(new MethodInvoker(delegate() { mRealHost.ClearWatches(); }));
}
public void RunSnippet(string snippet, LuaValue thread, int stackFrame)
{
Invoke(new MethodInvoker(delegate() { mRealHost.RunSnippet(snippet, thread, stackFrame); }));
}
public void RetrieveAutocompleteOptions(int seqid, string expression, LuaValue thread, int stackFrame)
{
Invoke(new MethodInvoker(delegate() { mRealHost.RetrieveAutocompleteOptions(seqid, expression, thread, stackFrame); }));
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="SqlDependency.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="true">[....]</owner>
// <owner current="false" primary="false">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Data.SqlClient {
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.ProviderBase;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Remoting;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Net;
using System.Xml;
using System.Runtime.Versioning;
public sealed class SqlDependency {
// ---------------------------------------------------------------------------------------------------------
// Private class encapsulating the user/identity information - either SQL Auth username or Windows identity.
// ---------------------------------------------------------------------------------------------------------
internal class IdentityUserNamePair {
private DbConnectionPoolIdentity _identity;
private string _userName;
internal IdentityUserNamePair(DbConnectionPoolIdentity identity, string userName) {
Debug.Assert( (identity == null && userName != null) ||
(identity != null && userName == null), "Unexpected arguments!");
_identity = identity;
_userName = userName;
}
internal DbConnectionPoolIdentity Identity {
get {
return _identity;
}
}
internal string UserName {
get {
return _userName;
}
}
override public bool Equals(object value) {
IdentityUserNamePair temp = (IdentityUserNamePair) value;
bool result = false;
if (null == temp) { // If passed value null - false.
result = false;
}
else if (this == temp) { // If instances equal - true.
result = true;
}
else {
if (_identity != null) {
if (_identity.Equals(temp._identity)) {
result = true;
}
}
else if (_userName == temp._userName) {
result = true;
}
}
return result;
}
override public int GetHashCode() {
int hashValue = 0;
if (null != _identity) {
hashValue = _identity.GetHashCode();
}
else {
hashValue = _userName.GetHashCode();
}
return hashValue;
}
}
// ----------------------------------------
// END IdentityHashHelper private class.
// ----------------------------------------
// ----------------------------------------------------------------------
// Private class encapsulating the database, service info and hash logic.
// ----------------------------------------------------------------------
private class DatabaseServicePair {
private string _database;
private string _service; // Store the value, but don't use for equality or hashcode!
internal DatabaseServicePair(string database, string service) {
Debug.Assert(database != null, "Unexpected argument!");
_database = database;
_service = service;
}
internal string Database {
get {
return _database;
}
}
internal string Service {
get {
return _service;
}
}
override public bool Equals(object value) {
DatabaseServicePair temp = (DatabaseServicePair) value;
bool result = false;
if (null == temp) { // If passed value null - false.
result = false;
}
else if (this == temp) { // If instances equal - true.
result = true;
}
else if (_database == temp._database) {
result = true;
}
return result;
}
override public int GetHashCode() {
return _database.GetHashCode();
}
}
// ----------------------------------------
// END IdentityHashHelper private class.
// ----------------------------------------
// ----------------------------------------------------------------------------
// Private class encapsulating the event and it's registered execution context.
// ----------------------------------------------------------------------------
internal class EventContextPair {
private OnChangeEventHandler _eventHandler;
private ExecutionContext _context;
private SqlDependency _dependency;
private SqlNotificationEventArgs _args;
static private ContextCallback _contextCallback = new ContextCallback(InvokeCallback);
internal EventContextPair(OnChangeEventHandler eventHandler, SqlDependency dependency) {
Debug.Assert(eventHandler != null && dependency != null, "Unexpected arguments!");
_eventHandler = eventHandler;
_context = ExecutionContext.Capture();
_dependency = dependency;
}
override public bool Equals(object value) {
EventContextPair temp = (EventContextPair) value;
bool result = false;
if (null == temp) { // If passed value null - false.
result = false;
}
else if (this == temp) { // If instances equal - true.
result = true;
}
else {
if (_eventHandler == temp._eventHandler) { // Handler for same delegates are reference equivalent.
result = true;
}
}
return result;
}
override public int GetHashCode() {
return _eventHandler.GetHashCode();
}
internal void Invoke(SqlNotificationEventArgs args) {
_args = args;
ExecutionContext.Run(_context, _contextCallback, this);
}
private static void InvokeCallback(object eventContextPair) {
EventContextPair pair = (EventContextPair) eventContextPair;
pair._eventHandler(pair._dependency, (SqlNotificationEventArgs) pair._args);
}
}
// ----------------------------------------
// END EventContextPair private class.
// ----------------------------------------
// ----------------
// Instance members
// ----------------
// SqlNotificationRequest required state members
// Only used for SqlDependency.Id.
private readonly string _id = Guid.NewGuid().ToString() + ";" + _appDomainKey;
private string _options; // Concat of service & db, in the form "service=x;local database=y".
private int _timeout;
// Various SqlDependency required members
private bool _dependencyFired = false;
// SQL BU DT 382314 - we are required to implement our own event collection to preserve ExecutionContext on callback.
private List<EventContextPair> _eventList = new List<EventContextPair>();
private object _eventHandlerLock = new object(); // Lock for event serialization.
// Track the time that this dependency should time out. If the server didn't send a change
// notification or a time-out before this point then the client will perform a client-side
// timeout.
private DateTime _expirationTime = DateTime.MaxValue;
// Used for invalidation of dependencies based on which servers they rely upon.
// It's possible we will over invalidate if unexpected server failure occurs (but not server down).
private List<string> _serverList = new List<string>();
// --------------
// Static members
// --------------
private static object _startStopLock = new object();
private static readonly string _appDomainKey = Guid.NewGuid().ToString();
// Hashtable containing all information to match from a server, user, database triple to the service started for that
// triple. For each server, there can be N users. For each user, there can be N databases. For each server, user,
// database, there can only be one service.
private static Dictionary<string, Dictionary<IdentityUserNamePair, List<DatabaseServicePair>>> _serverUserHash =
new Dictionary<string, Dictionary<IdentityUserNamePair, List<DatabaseServicePair>>>(StringComparer.OrdinalIgnoreCase);
private static SqlDependencyProcessDispatcher _processDispatcher = null;
// The following two strings are used for AppDomain.CreateInstance.
private static readonly string _assemblyName = (typeof(SqlDependencyProcessDispatcher)).Assembly.FullName;
private static readonly string _typeName = (typeof(SqlDependencyProcessDispatcher)).FullName;
// -----------
// BID members
// -----------
internal const Bid.ApiGroup NotificationsTracePoints = (Bid.ApiGroup)0x2000;
private readonly int _objectID = System.Threading.Interlocked.Increment(ref _objectTypeCount);
private static int _objectTypeCount; // Bid counter
internal int ObjectID {
get {
return _objectID;
}
}
// ------------
// Constructors
// ------------
[System.Security.Permissions.HostProtectionAttribute(ExternalThreading = true)]
public SqlDependency() : this(null, null, SQL.SqlDependencyTimeoutDefault) {
}
[System.Security.Permissions.HostProtectionAttribute(ExternalThreading = true)]
public SqlDependency(SqlCommand command) : this(command, null, SQL.SqlDependencyTimeoutDefault) {
}
[System.Security.Permissions.HostProtectionAttribute(ExternalThreading = true)]
public SqlDependency(SqlCommand command, string options, int timeout) {
IntPtr hscp;
Bid.NotificationsScopeEnter(out hscp, "<sc.SqlDependency|DEP> %d#, options: '%ls', timeout: '%d'", ObjectID, options, timeout);
try {
if (InOutOfProcHelper.InProc) {
throw SQL.SqlDepCannotBeCreatedInProc();
}
if (timeout < 0) {
throw SQL.InvalidSqlDependencyTimeout("timeout");
}
_timeout = timeout;
if (null != options) { // Ignore null value - will force to default.
_options = options;
}
AddCommandInternal(command);
SqlDependencyPerAppDomainDispatcher.SingletonInstance.AddDependencyEntry(this); // Add dep to hashtable with Id.
}
finally {
Bid.ScopeLeave(ref hscp);
}
}
// -----------------
// Public Properties
// -----------------
[
ResCategoryAttribute(Res.DataCategory_Data),
ResDescriptionAttribute(Res.SqlDependency_HasChanges)
]
public bool HasChanges {
get {
return _dependencyFired;
}
}
[
ResCategoryAttribute(Res.DataCategory_Data),
ResDescriptionAttribute(Res.SqlDependency_Id)
]
public string Id {
get {
return _id;
}
}
// -------------------
// Internal Properties
// -------------------
internal static string AppDomainKey {
get {
return _appDomainKey;
}
}
internal DateTime ExpirationTime {
get {
return _expirationTime;
}
}
internal string Options {
get {
string result = null;
if (null != _options) {
result = _options;
}
return result;
}
}
internal static SqlDependencyProcessDispatcher ProcessDispatcher {
get {
return _processDispatcher;
}
}
internal int Timeout {
get {
return _timeout;
}
}
// ------
// Events
// ------
[
ResCategoryAttribute(Res.DataCategory_Data),
ResDescriptionAttribute(Res.SqlDependency_OnChange)
]
public event OnChangeEventHandler OnChange {
// EventHandlers to be fired when dependency is notified.
add {
IntPtr hscp;
Bid.NotificationsScopeEnter(out hscp, "<sc.SqlDependency.OnChange-Add|DEP> %d#", ObjectID);
try {
if (null != value) {
SqlNotificationEventArgs sqlNotificationEvent = null;
lock (_eventHandlerLock) {
if (_dependencyFired) { // If fired, fire the new event immediately.
Bid.NotificationsTrace("<sc.SqlDependency.OnChange-Add|DEP> Dependency already fired, firing new event.\n");
sqlNotificationEvent = new SqlNotificationEventArgs(SqlNotificationType.Subscribe, SqlNotificationInfo.AlreadyChanged, SqlNotificationSource.Client);
}
else {
Bid.NotificationsTrace("<sc.SqlDependency.OnChange-Add|DEP> Dependency has not fired, adding new event.\n");
EventContextPair pair = new EventContextPair(value, this);
if (!_eventList.Contains(pair)) {
_eventList.Add(pair);
}
else {
throw SQL.SqlDependencyEventNoDuplicate(); // SQL BU DT 382314
}
}
}
if (null != sqlNotificationEvent) { // Delay firing the event until outside of lock.
value(this, sqlNotificationEvent);
}
}
}
finally {
Bid.ScopeLeave(ref hscp);
}
}
remove {
IntPtr hscp;
Bid.NotificationsScopeEnter(out hscp, "<sc.SqlDependency.OnChange-Remove|DEP> %d#", ObjectID);
try {
if (null != value) {
EventContextPair pair = new EventContextPair(value, this);
lock (_eventHandlerLock) {
int index = _eventList.IndexOf(pair);
if (0 <= index) {
_eventList.RemoveAt(index);
}
}
}
}
finally {
Bid.ScopeLeave(ref hscp);
}
}
}
// --------------
// Public Methods
// --------------
[
ResCategoryAttribute(Res.DataCategory_Data),
ResDescriptionAttribute(Res.SqlDependency_AddCommandDependency)
]
public void AddCommandDependency(SqlCommand command) {
// Adds command to dependency collection so we automatically create the SqlNotificationsRequest object
// and listen for a notification for the added commands.
IntPtr hscp;
Bid.NotificationsScopeEnter(out hscp, "<sc.SqlDependency.AddCommandDependency|DEP> %d#", ObjectID);
try {
if (command == null) {
throw ADP.ArgumentNull("command");
}
AddCommandInternal(command);
}
finally {
Bid.ScopeLeave(ref hscp);
}
}
[System.Security.Permissions.ReflectionPermission(System.Security.Permissions.SecurityAction.Assert, MemberAccess=true)]
private static ObjectHandle CreateProcessDispatcher(_AppDomain masterDomain) {
return masterDomain.CreateInstance(_assemblyName, _typeName);
}
// ----------------------------------
// Static Methods - public & internal
// ----------------------------------
// Method to obtain AppDomain reference and then obtain the reference to the process wide dispatcher for
// Start() and Stop() method calls on the individual SqlDependency instances.
// SxS: this method retrieves the primary AppDomain stored in native library. Since each System.Data.dll has its own copy of native
// library, this call is safe in SxS
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
private static void ObtainProcessDispatcher() {
byte[] nativeStorage = SNINativeMethodWrapper.GetData();
if (nativeStorage == null) {
Bid.NotificationsTrace("<sc.SqlDependency.ObtainProcessDispatcher|DEP> nativeStorage null, obtaining dispatcher AppDomain and creating ProcessDispatcher.\n");
#if DEBUG // Possibly expensive, limit to debug.
Bid.NotificationsTrace("<sc.SqlDependency.ObtainProcessDispatcher|DEP> AppDomain.CurrentDomain.FriendlyName: %ls\n", AppDomain.CurrentDomain.FriendlyName);
#endif
_AppDomain masterDomain = SNINativeMethodWrapper.GetDefaultAppDomain();
if (null != masterDomain) {
ObjectHandle handle = CreateProcessDispatcher(masterDomain);
if (null != handle) {
SqlDependencyProcessDispatcher dependency = (SqlDependencyProcessDispatcher) handle.Unwrap();
if (null != dependency) {
_processDispatcher = dependency.SingletonProcessDispatcher; // Set to static instance.
// Serialize and set in native.
ObjRef objRef = GetObjRef(_processDispatcher);
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
GetSerializedObject(objRef, formatter, stream);
SNINativeMethodWrapper.SetData(stream.GetBuffer()); // Native will be forced to synchronize and not overwrite.
}
else {
Bid.NotificationsTrace("<sc.SqlDependency.ObtainProcessDispatcher|DEP|ERR> ERROR - ObjectHandle.Unwrap returned null!\n");
throw ADP.InternalError(ADP.InternalErrorCode.SqlDependencyObtainProcessDispatcherFailureObjectHandle);
}
}
else {
Bid.NotificationsTrace("<sc.SqlDependency.ObtainProcessDispatcher|DEP|ERR> ERROR - AppDomain.CreateInstance returned null!\n");
throw ADP.InternalError(ADP.InternalErrorCode.SqlDependencyProcessDispatcherFailureCreateInstance);
}
}
else {
Bid.NotificationsTrace("<sc.SqlDependency.ObtainProcessDispatcher|DEP|ERR> ERROR - unable to obtain default AppDomain!\n");
throw ADP.InternalError(ADP.InternalErrorCode.SqlDependencyProcessDispatcherFailureAppDomain);
}
}
else {
Bid.NotificationsTrace("<sc.SqlDependency.ObtainProcessDispatcher|DEP> nativeStorage not null, obtaining existing dispatcher AppDomain and ProcessDispatcher.\n");
#if DEBUG // Possibly expensive, limit to debug.
Bid.NotificationsTrace("<sc.SqlDependency.ObtainProcessDispatcher|DEP> AppDomain.CurrentDomain.FriendlyName: %ls\n", AppDomain.CurrentDomain.FriendlyName);
#endif
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream(nativeStorage);
_processDispatcher = GetDeserializedObject(formatter, stream); // Deserialize and set for appdomain.
Bid.NotificationsTrace("<sc.SqlDependency.ObtainProcessDispatcher|DEP> processDispatcher obtained, ID: %d\n", _processDispatcher.ObjectID);
}
}
// ---------------------------------------------------------
// Static security asserted methods - limit scope of assert.
// ---------------------------------------------------------
[SecurityPermission(SecurityAction.Assert, Flags=SecurityPermissionFlag.RemotingConfiguration)]
private static ObjRef GetObjRef(SqlDependencyProcessDispatcher _processDispatcher) {
return RemotingServices.Marshal(_processDispatcher);
}
[SecurityPermission(SecurityAction.Assert, Flags=SecurityPermissionFlag.SerializationFormatter)]
private static void GetSerializedObject(ObjRef objRef, BinaryFormatter formatter, MemoryStream stream) {
formatter.Serialize(stream, objRef);
}
[SecurityPermission(SecurityAction.Assert, Flags=SecurityPermissionFlag.SerializationFormatter)]
private static SqlDependencyProcessDispatcher GetDeserializedObject(BinaryFormatter formatter, MemoryStream stream) {
object result = formatter.Deserialize(stream);
Debug.Assert(result.GetType() == typeof(SqlDependencyProcessDispatcher), "Unexpected type stored in native!");
return (SqlDependencyProcessDispatcher) result;
}
// -------------------------
// Static Start/Stop methods
// -------------------------
[System.Security.Permissions.HostProtectionAttribute(ExternalThreading = true)]
public static bool Start(string connectionString) {
return Start(connectionString, null, true);
}
[System.Security.Permissions.HostProtectionAttribute(ExternalThreading = true)]
public static bool Start(string connectionString, string queue) {
return Start(connectionString, queue, false);
}
internal static bool Start(string connectionString, string queue, bool useDefaults) {
IntPtr hscp;
Bid.NotificationsScopeEnter(out hscp, "<sc.SqlDependency.Start|DEP> AppDomainKey: '%ls', queue: '%ls'", AppDomainKey, queue);
try {
// The following code exists in Stop as well. It exists here to demand permissions as high in the stack
// as possible.
if (InOutOfProcHelper.InProc) {
throw SQL.SqlDepCannotBeCreatedInProc();
}
if (ADP.IsEmpty(connectionString)) {
if (null == connectionString) {
throw ADP.ArgumentNull("connectionString");
}
else {
throw ADP.Argument("connectionString");
}
}
if (!useDefaults && ADP.IsEmpty(queue)) { // If specified but null or empty, use defaults.
useDefaults = true;
queue = null; // Force to null - for proper hashtable comparison for default case.
}
// Create new connection options for demand on their connection string. We modify the connection string
// and assert on our modified string when we create the container.
SqlConnectionString connectionStringObject = new SqlConnectionString(connectionString);
connectionStringObject.DemandPermission();
if (connectionStringObject.LocalDBInstance!=null) {
LocalDBAPI.DemandLocalDBPermissions();
}
// End duplicate Start/Stop logic.
bool errorOccurred = false;
bool result = false;
lock (_startStopLock) {
try {
if (null == _processDispatcher) { // Ensure _processDispatcher reference is present - inside lock.
ObtainProcessDispatcher();
}
if (useDefaults) { // Default listener.
string server = null;
DbConnectionPoolIdentity identity = null;
string user = null;
string database = null;
string service = null;
bool appDomainStart = false;
RuntimeHelpers.PrepareConstrainedRegions();
try { // CER to ensure that if Start succeeds we add to hash completing setup.
// Start using process wide default service/queue & database from connection string.
result = _processDispatcher.StartWithDefault( connectionString,
out server,
out identity,
out user,
out database,
ref service,
_appDomainKey,
SqlDependencyPerAppDomainDispatcher.SingletonInstance,
out errorOccurred,
out appDomainStart);
Bid.NotificationsTrace("<sc.SqlDependency.Start|DEP> Start (defaults) returned: '%d', with service: '%ls', server: '%ls', database: '%ls'\n", result, service, server, database);
}
finally {
if (appDomainStart && !errorOccurred) { // If success, add to hashtable.
IdentityUserNamePair identityUser = new IdentityUserNamePair(identity, user);
DatabaseServicePair databaseService = new DatabaseServicePair(database, service);
if (!AddToServerUserHash(server, identityUser, databaseService)) {
try {
Stop(connectionString, queue, useDefaults, true);
}
catch (Exception e) { // Discard stop failure!
if (!ADP.IsCatchableExceptionType(e)) {
throw;
}
ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now.
Bid.NotificationsTrace("<sc.SqlDependency.Start|DEP|ERR> Exception occurred from Stop() after duplicate was found on Start().\n");
}
throw SQL.SqlDependencyDuplicateStart();
}
}
}
}
else { // Start with specified service/queue & database.
result = _processDispatcher.Start(connectionString,
queue,
_appDomainKey,
SqlDependencyPerAppDomainDispatcher.SingletonInstance);
Bid.NotificationsTrace("<sc.SqlDependency.Start|DEP> Start (user provided queue) returned: '%d'\n", result);
// No need to call AddToServerDatabaseHash since if not using default queue user is required
// to provide options themselves.
}
}
catch (Exception e) {
if (!ADP.IsCatchableExceptionType(e)) {
throw;
}
ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now.
Bid.NotificationsTrace("<sc.SqlDependency.Start|DEP|ERR> Exception occurred from _processDispatcher.Start(...), calling Invalidate(...).\n");
throw;
}
}
return result;
}
finally {
Bid.ScopeLeave(ref hscp);
}
}
[System.Security.Permissions.HostProtectionAttribute(ExternalThreading = true)]
public static bool Stop(string connectionString) {
return Stop(connectionString, null, true, false);
}
[System.Security.Permissions.HostProtectionAttribute(ExternalThreading = true)]
public static bool Stop(string connectionString, string queue) {
return Stop(connectionString, queue, false, false);
}
internal static bool Stop(string connectionString, string queue, bool useDefaults, bool startFailed) {
IntPtr hscp;
Bid.NotificationsScopeEnter(out hscp, "<sc.SqlDependency.Stop|DEP> AppDomainKey: '%ls', queue: '%ls'", AppDomainKey, queue);
try {
// The following code exists in Stop as well. It exists here to demand permissions as high in the stack
// as possible.
if (InOutOfProcHelper.InProc) {
throw SQL.SqlDepCannotBeCreatedInProc();
}
if (ADP.IsEmpty(connectionString)) {
if (null == connectionString) {
throw ADP.ArgumentNull("connectionString");
}
else {
throw ADP.Argument("connectionString");
}
}
if (!useDefaults && ADP.IsEmpty(queue)) { // If specified but null or empty, use defaults.
useDefaults = true;
queue = null; // Force to null - for proper hashtable comparison for default case.
}
// Create new connection options for demand on their connection string. We modify the connection string
// and assert on our modified string when we create the container.
SqlConnectionString connectionStringObject = new SqlConnectionString(connectionString);
connectionStringObject.DemandPermission();
if (connectionStringObject.LocalDBInstance!=null) {
LocalDBAPI.DemandLocalDBPermissions();
}
// End duplicate Start/Stop logic.
bool result = false;
lock (_startStopLock) {
if (null != _processDispatcher) { // If _processDispatcher null, no Start has been called.
try {
string server = null;
DbConnectionPoolIdentity identity = null;
string user = null;
string database = null;
string service = null;
if (useDefaults) {
bool appDomainStop = false;
RuntimeHelpers.PrepareConstrainedRegions();
try { // CER to ensure that if Stop succeeds we remove from hash completing teardown.
// Start using process wide default service/queue & database from connection string.
result = _processDispatcher.Stop( connectionString,
out server,
out identity,
out user,
out database,
ref service,
_appDomainKey,
out appDomainStop);
}
finally {
if (appDomainStop && !startFailed) { // If success, remove from hashtable.
Debug.Assert(!ADP.IsEmpty(server) && !ADP.IsEmpty(database), "Server or Database null/Empty upon successfull Stop()!");
IdentityUserNamePair identityUser = new IdentityUserNamePair(identity, user);
DatabaseServicePair databaseService = new DatabaseServicePair(database, service);
RemoveFromServerUserHash(server, identityUser, databaseService);
}
}
}
else {
bool ignored = false;
result = _processDispatcher.Stop( connectionString,
out server,
out identity,
out user,
out database,
ref queue,
_appDomainKey,
out ignored);
// No need to call RemoveFromServerDatabaseHash since if not using default queue user is required
// to provide options themselves.
}
}
catch (Exception e) {
if (!ADP.IsCatchableExceptionType(e)) {
throw;
}
ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now.
}
}
}
return result;
}
finally {
Bid.ScopeLeave(ref hscp);
}
}
// --------------------------------
// General static utility functions
// --------------------------------
private static bool AddToServerUserHash(string server, IdentityUserNamePair identityUser, DatabaseServicePair databaseService) {
IntPtr hscp;
Bid.NotificationsScopeEnter(out hscp, "<sc.SqlDependency.AddToServerUserHash|DEP> server: '%ls', database: '%ls', service: '%ls'", server, databaseService.Database, databaseService.Service);
try {
bool result = false;
lock (_serverUserHash) {
Dictionary<IdentityUserNamePair, List<DatabaseServicePair>> identityDatabaseHash;
if (!_serverUserHash.ContainsKey(server)) {
Bid.NotificationsTrace("<sc.SqlDependency.AddToServerUserHash|DEP> Hash did not contain server, adding.\n");
identityDatabaseHash = new Dictionary<IdentityUserNamePair, List<DatabaseServicePair>>();
_serverUserHash.Add(server, identityDatabaseHash);
}
else {
identityDatabaseHash = _serverUserHash[server];
}
List<DatabaseServicePair> databaseServiceList;
if (!identityDatabaseHash.ContainsKey(identityUser)) {
Bid.NotificationsTrace("<sc.SqlDependency.AddToServerUserHash|DEP> Hash contained server but not user, adding user.\n");
databaseServiceList = new List<DatabaseServicePair>();
identityDatabaseHash.Add(identityUser, databaseServiceList);
}
else {
databaseServiceList = identityDatabaseHash[identityUser];
}
if (!databaseServiceList.Contains(databaseService)) {
Bid.NotificationsTrace("<sc.SqlDependency.AddToServerUserHash|DEP> Adding database.\n");
databaseServiceList.Add(databaseService);
result = true;
}
else {
Bid.NotificationsTrace("<sc.SqlDependency.AddToServerUserHash|DEP|ERR> ERROR - hash already contained server, user, and database - we will throw!.\n");
}
}
return result;
}
finally {
Bid.ScopeLeave(ref hscp);
}
}
private static void RemoveFromServerUserHash(string server, IdentityUserNamePair identityUser, DatabaseServicePair databaseService) {
IntPtr hscp;
Bid.NotificationsScopeEnter(out hscp, "<sc.SqlDependency.RemoveFromServerUserHash|DEP> server: '%ls', database: '%ls', service: '%ls'", server, databaseService.Database, databaseService.Service);
try {
lock (_serverUserHash) {
Dictionary<IdentityUserNamePair, List<DatabaseServicePair>> identityDatabaseHash;
if (_serverUserHash.ContainsKey(server)) {
identityDatabaseHash = _serverUserHash[server];
List<DatabaseServicePair> databaseServiceList;
if (identityDatabaseHash.ContainsKey(identityUser)) {
databaseServiceList = identityDatabaseHash[identityUser];
int index = databaseServiceList.IndexOf(databaseService);
if (index >= 0) {
Bid.NotificationsTrace("<sc.SqlDependency.RemoveFromServerUserHash|DEP> Hash contained server, user, and database - removing database.\n");
databaseServiceList.RemoveAt(index);
if (databaseServiceList.Count == 0) {
Bid.NotificationsTrace("<sc.SqlDependency.RemoveFromServerUserHash|DEP> databaseServiceList count 0, removing the list for this server and user.\n");
identityDatabaseHash.Remove(identityUser);
if (identityDatabaseHash.Count == 0) {
Bid.NotificationsTrace("<sc.SqlDependency.RemoveFromServerUserHash|DEP> identityDatabaseHash count 0, removing the hash for this server.\n");
_serverUserHash.Remove(server);
}
}
}
else {
Bid.NotificationsTrace("<sc.SqlDependency.RemoveFromServerUserHash|DEP|ERR> ERROR - hash contained server and user but not database!\n");
Debug.Assert(false, "Unexpected state - hash did not contain database!");
}
}
else {
Bid.NotificationsTrace("<sc.SqlDependency.RemoveFromServerUserHash|DEP|ERR> ERROR - hash contained server but not user!\n");
Debug.Assert(false, "Unexpected state - hash did not contain user!");
}
}
else {
Bid.NotificationsTrace("<sc.SqlDependency.RemoveFromServerUserHash|DEP|ERR> ERROR - hash did not contain server!\n");
Debug.Assert(false, "Unexpected state - hash did not contain server!");
}
}
}
finally {
Bid.ScopeLeave(ref hscp);
}
}
internal static string GetDefaultComposedOptions(string server, string failoverServer, IdentityUserNamePair identityUser, string database) {
// Server must be an exact match, but user and database only needs to match exactly if there is more than one
// for the given user or database passed. That is ambiguious and we must fail.
IntPtr hscp;
Bid.NotificationsScopeEnter(out hscp, "<sc.SqlDependency.GetDefaultComposedOptions|DEP> server: '%ls', failoverServer: '%ls', database: '%ls'", server, failoverServer, database);
try {
string result;
lock (_serverUserHash) {
if (!_serverUserHash.ContainsKey(server)) {
if (0 == _serverUserHash.Count) { // Special error for no calls to start.
Bid.NotificationsTrace("<sc.SqlDependency.GetDefaultComposedOptions|DEP|ERR> ERROR - no start calls have been made, about to throw.\n");
throw SQL.SqlDepDefaultOptionsButNoStart();
}
else if (!ADP.IsEmpty(failoverServer) && _serverUserHash.ContainsKey(failoverServer)) {
Bid.NotificationsTrace("<sc.SqlDependency.GetDefaultComposedOptions|DEP> using failover server instead\n");
server = failoverServer;
}
else {
Bid.NotificationsTrace("<sc.SqlDependency.GetDefaultComposedOptions|DEP|ERR> ERROR - not listening to this server, about to throw.\n");
throw SQL.SqlDependencyNoMatchingServerStart();
}
}
Dictionary<IdentityUserNamePair, List<DatabaseServicePair>> identityDatabaseHash = _serverUserHash[server];
List<DatabaseServicePair> databaseList = null;
if (!identityDatabaseHash.ContainsKey(identityUser)) {
if (identityDatabaseHash.Count > 1) {
Bid.NotificationsTrace("<sc.SqlDependency.GetDefaultComposedOptions|DEP|ERR> ERROR - not listening for this user, but listening to more than one other user, about to throw.\n");
throw SQL.SqlDependencyNoMatchingServerStart();
}
else {
// Since only one user, - use that.
// Foreach - but only one value present.
foreach (KeyValuePair<IdentityUserNamePair, List<DatabaseServicePair>> entry in identityDatabaseHash) {
databaseList = entry.Value;
break; // Only iterate once.
}
}
}
else {
databaseList = identityDatabaseHash[identityUser];
}
DatabaseServicePair pair = new DatabaseServicePair(database, null);
DatabaseServicePair resultingPair = null;
int index = databaseList.IndexOf(pair);
if (index != -1) { // Exact match found, use it.
resultingPair = databaseList[index];
}
if (null != resultingPair) { // Exact database match.
database = FixupServiceOrDatabaseName(resultingPair.Database); // Fixup in place.
string quotedService = FixupServiceOrDatabaseName(resultingPair.Service);
result = "Service="+quotedService+";Local Database="+database;
}
else { // No exact database match found.
if (databaseList.Count == 1) { // If only one database for this server/user, use it.
object[] temp = databaseList.ToArray(); // Must copy, no other choice but foreach.
resultingPair = (DatabaseServicePair) temp[0];
Debug.Assert(temp.Length == 1, "If databaseList.Count==1, why does copied array have length other than 1?");
string quotedDatabase = FixupServiceOrDatabaseName(resultingPair.Database);
string quotedService = FixupServiceOrDatabaseName(resultingPair.Service);
result = "Service="+quotedService+";Local Database="+quotedDatabase;
}
else { // More than one database for given server, ambiguous - fail the default case!
Bid.NotificationsTrace("<sc.SqlDependency.GetDefaultComposedOptions|DEP|ERR> ERROR - SqlDependency.Start called multiple times for this server/user, but no matching database.\n");
throw SQL.SqlDependencyNoMatchingServerDatabaseStart();
}
}
}
Debug.Assert(!ADP.IsEmpty(result), "GetDefaultComposedOptions should never return null or empty string!");
Bid.NotificationsTrace("<sc.SqlDependency.GetDefaultComposedOptions|DEP> resulting options: '%ls'.\n", result);
return result;
}
finally {
Bid.ScopeLeave(ref hscp);
}
}
// ----------------
// Internal Methods
// ----------------
// Called by SqlCommand upon execution of a SqlNotificationRequest class created by this dependency. We
// use this list for a reverse lookup based on server.
internal void AddToServerList(string server) {
IntPtr hscp;
Bid.NotificationsScopeEnter(out hscp, "<sc.SqlDependency.AddToServerList|DEP> %d#, server: '%ls'", ObjectID, server);
try {
lock (_serverList) {
int index = _serverList.BinarySearch(server, StringComparer.OrdinalIgnoreCase);
if (0 > index) { // If less than 0, item was not found in list.
Bid.NotificationsTrace("<sc.SqlDependency.AddToServerList|DEP> Server not present in hashtable, adding server: '%ls'.\n", server);
index = ~index; // BinarySearch returns the 2's compliment of where the item should be inserted to preserver a sorted list after insertion.
_serverList.Insert(index, server);
}
}
}
finally {
Bid.ScopeLeave(ref hscp);
}
}
internal bool ContainsServer(string server) {
lock (_serverList) {
return _serverList.Contains(server);
}
}
internal string ComputeHashAndAddToDispatcher(SqlCommand command) {
IntPtr hscp;
Bid.NotificationsScopeEnter(out hscp, "<sc.SqlDependency.ComputeHashAndAddToDispatcher|DEP> %d#, SqlCommand: %d#", ObjectID, command.ObjectID);
try {
// Create a string representing the concatenation of the connection string, command text and .ToString on all parameter values.
// This string will then be mapped to unique notification ID (new GUID). We add the guid and the hash to the app domain
// dispatcher to be able to map back to the dependency that needs to be fired for a notification of this
// command.
// VSTS 59821: add Connection string to prevent redundant notifications when same command is running against different databases or SQL servers
//
string commandHash = ComputeCommandHash(command.Connection.ConnectionString, command); // calculate the string representation of command
string idString = SqlDependencyPerAppDomainDispatcher.SingletonInstance.AddCommandEntry(commandHash, this); // Add to map.
Bid.NotificationsTrace("<sc.SqlDependency.ComputeHashAndAddToDispatcher|DEP> computed id string: '%ls'.\n", idString);
return idString;
}
finally {
Bid.ScopeLeave(ref hscp);
}
}
internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, SqlNotificationSource source) {
IntPtr hscp;
Bid.NotificationsScopeEnter(out hscp, "<sc.SqlDependency.Invalidate|DEP> %d#", ObjectID);
try {
List<EventContextPair> eventList = null;
lock (_eventHandlerLock) {
if (_dependencyFired &&
SqlNotificationInfo.AlreadyChanged != info &&
SqlNotificationSource.Client != source) {
if (ExpirationTime < DateTime.UtcNow) {
// There is a small window in which SqlDependencyPerAppDomainDispatcher.TimeoutTimerCallback
// raises Timeout event but before removing this event from the list. If notification is received from
// server in this case, we will hit this code path.
// It is safe to ignore this race condition because no event is sent to user and no leak happens.
Bid.NotificationsTrace("<sc.SqlDependency.Invalidate|DEP> ignore notification received after timeout!");
}
else {
Debug.Assert(false, "Received notification twice - we should never enter this state!");
Bid.NotificationsTrace("<sc.SqlDependency.Invalidate|DEP|ERR> ERROR - notification received twice - we should never enter this state!");
}
}
else {
// It is the invalidators responsibility to remove this dependency from the app domain static hash.
_dependencyFired = true;
eventList = _eventList;
_eventList = new List<EventContextPair>(); // Since we are firing the events, null so we do not fire again.
}
}
if (eventList != null) {
Bid.NotificationsTrace("<sc.SqlDependency.Invalidate|DEP> Firing events.\n");
foreach(EventContextPair pair in eventList) {
pair.Invoke(new SqlNotificationEventArgs(type, info, source));
}
}
}
finally {
Bid.ScopeLeave(ref hscp);
}
}
// This method is used by SqlCommand.
internal void StartTimer(SqlNotificationRequest notificationRequest) {
IntPtr hscp;
Bid.NotificationsScopeEnter(out hscp, "<sc.SqlDependency.StartTimer|DEP> %d#", ObjectID);
try {
if(_expirationTime == DateTime.MaxValue) {
Bid.NotificationsTrace("<sc.SqlDependency.StartTimer|DEP> We've timed out, executing logic.\n");
int seconds = SQL.SqlDependencyServerTimeout;
if (0 != _timeout) {
seconds = _timeout;
}
if (notificationRequest != null && notificationRequest.Timeout < seconds && notificationRequest.Timeout != 0) {
seconds = notificationRequest.Timeout;
}
// VSDD 563926: we use UTC to check if SqlDependency is expired, need to use it here as well.
_expirationTime = DateTime.UtcNow.AddSeconds(seconds);
SqlDependencyPerAppDomainDispatcher.SingletonInstance.StartTimer(this);
}
}
finally {
Bid.ScopeLeave(ref hscp);
}
}
// ---------------
// Private Methods
// ---------------
private void AddCommandInternal(SqlCommand cmd) {
if (cmd != null) { // Don't bother with BID if command null.
IntPtr hscp;
Bid.NotificationsScopeEnter(out hscp, "<sc.SqlDependency.AddCommandInternal|DEP> %d#, SqlCommand: %d#", ObjectID, cmd.ObjectID);
try {
SqlConnection connection = cmd.Connection;
if (cmd.Notification != null) {
// Fail if cmd has notification that is not already associated with this dependency.
if (cmd._sqlDep == null || cmd._sqlDep != this) {
Bid.NotificationsTrace("<sc.SqlDependency.AddCommandInternal|DEP|ERR> ERROR - throwing command has existing SqlNotificationRequest exception.\n");
throw SQL.SqlCommandHasExistingSqlNotificationRequest();
}
}
else {
bool needToInvalidate = false;
lock (_eventHandlerLock) {
if (!_dependencyFired) {
cmd.Notification = new SqlNotificationRequest();
cmd.Notification.Timeout = _timeout;
// Add the command - A dependancy should always map to a set of commands which haven't fired.
if (null != _options) { // Assign options if user provided.
cmd.Notification.Options = _options;
}
cmd._sqlDep = this;
}
else {
// We should never be able to enter this state, since if we've fired our event list is cleared
// and the event method will immediately fire if a new event is added. So, we should never have
// an event to fire in the event list once we've fired.
Debug.Assert(0 == _eventList.Count, "How can we have an event at this point?");
if (0 == _eventList.Count) { // Keep logic just in case.
Bid.NotificationsTrace("<sc.SqlDependency.AddCommandInternal|DEP|ERR> ERROR - firing events, though it is unexpected we have events at this point.\n");
needToInvalidate = true; // Delay invalidation until outside of lock.
}
}
}
if (needToInvalidate) {
Invalidate(SqlNotificationType.Subscribe, SqlNotificationInfo.AlreadyChanged, SqlNotificationSource.Client);
}
}
}
finally {
Bid.ScopeLeave(ref hscp);
}
}
}
private string ComputeCommandHash(string connectionString, SqlCommand command) {
IntPtr hscp;
Bid.NotificationsScopeEnter(out hscp, "<sc.SqlDependency.ComputeCommandHash|DEP> %d#, SqlCommand: %d#", ObjectID, command.ObjectID);
try {
// Create a string representing the concatenation of the connection string, the command text and .ToString on all its parameter values.
// This string will then be mapped to the notification ID.
// All types should properly support a .ToString for the values except
// byte[], char[], and XmlReader.
// NOTE - I hope this doesn't come back to bite us. :(
StringBuilder builder = new StringBuilder();
// add the Connection string and the Command text
builder.AppendFormat("{0};{1}", connectionString, command.CommandText);
// append params
for (int i=0; i<command.Parameters.Count; i++) {
object value = command.Parameters[i].Value;
if (value == null || value == DBNull.Value) {
builder.Append("; NULL");
}
else {
Type type = value.GetType();
if (type == typeof(Byte[])) {
builder.Append(";");
byte[] temp = (byte[]) value;
for (int j=0; j<temp.Length; j++) {
builder.Append(temp[j].ToString("x2", CultureInfo.InvariantCulture));
}
}
else if (type == typeof(Char[])) {
builder.Append((char[]) value);
}
else if (type == typeof(XmlReader)) {
builder.Append(";");
// Cannot .ToString XmlReader - just allocate GUID.
// This means if XmlReader is used, we will not reuse IDs.
builder.Append(Guid.NewGuid().ToString());
}
else {
builder.Append(";");
builder.Append(value.ToString());
}
}
}
string result = builder.ToString();
Bid.NotificationsTrace("<sc.SqlDependency.ComputeCommandHash|DEP> ComputeCommandHash result: '%ls'.\n", result);
return result;
}
finally {
Bid.ScopeLeave(ref hscp);
}
}
// Basic copy of function in SqlConnection.cs for ChangeDatabase and similar functionality. Since this will
// only be used for default service and database provided by server, we do not need to worry about an already
// quoted value.
static internal string FixupServiceOrDatabaseName(string name) {
if (!ADP.IsEmpty(name)) {
return "\"" + name.Replace("\"", "\"\"") + "\"";
}
else {
return name;
}
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using Microsoft.VisualStudio.Services.WebApi;
using Newtonsoft.Json;
namespace Microsoft.VisualStudio.Services.Agent.Util
{
public static class IOUtil
{
private static Lazy<JsonSerializerSettings> s_serializerSettings = new Lazy<JsonSerializerSettings>(() => new VssJsonMediaTypeFormatter().SerializerSettings);
public static string ExeExtension
{
get
{
#if OS_WINDOWS
return ".exe";
#else
return string.Empty;
#endif
}
}
public static String ToString(object obj)
{
return JsonConvert.SerializeObject(obj, Formatting.Indented, s_serializerSettings.Value);
}
public static T FromString<T>(string value)
{
return JsonConvert.DeserializeObject<T>(value, s_serializerSettings.Value);
}
public static void SaveObject(object obj, string path)
{
File.WriteAllText(path, ToString(obj), Encoding.UTF8);
}
public static T LoadObject<T>(string path)
{
string json = File.ReadAllText(path, Encoding.UTF8);
return FromString<T>(json);
}
public static string GetBinPath()
{
return Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
}
public static string GetBinPathHash()
{
string hashString = GetBinPath().ToLowerInvariant();
using (SHA256 sha256hash = SHA256.Create())
{
byte[] data = sha256hash.ComputeHash(Encoding.UTF8.GetBytes(hashString));
StringBuilder sBuilder = new StringBuilder();
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
string hash = sBuilder.ToString();
return hash;
}
}
public static string GetDiagPath()
{
return Path.Combine(
Path.GetDirectoryName(GetBinPath()),
Constants.Path.DiagDirectory);
}
public static string GetExternalsPath()
{
return Path.Combine(
GetRootPath(),
Constants.Path.ExternalsDirectory);
}
public static string GetRootPath()
{
return new DirectoryInfo(GetBinPath()).Parent.FullName;
}
public static string GetConfigFilePath()
{
return Path.Combine(GetRootPath(), ".agent");
}
public static string GetCredFilePath()
{
return Path.Combine(GetRootPath(), ".credentials");
}
public static string GetServiceConfigFilePath()
{
return Path.Combine(GetRootPath(), ".service");
}
public static string GetRSACredFilePath()
{
return Path.Combine(GetRootPath(), ".credentials_rsaparams");
}
public static string GetProxyConfigFilePath()
{
return Path.Combine(GetRootPath(), ".proxy");
}
public static string GetWorkPath(IHostContext hostContext)
{
var configurationStore = hostContext.GetService<IConfigurationStore>();
AgentSettings settings = configurationStore.GetSettings();
return Path.Combine(
Path.GetDirectoryName(GetBinPath()),
settings.WorkFolder);
}
public static string GetTasksPath(IHostContext hostContext)
{
return Path.Combine(
GetWorkPath(hostContext),
Constants.Path.TasksDirectory);
}
public static void Delete(string path, CancellationToken cancellationToken)
{
DeleteDirectory(path, cancellationToken);
DeleteFile(path);
}
public static string GetUpdatePath(IHostContext hostContext)
{
return Path.Combine(
GetWorkPath(hostContext),
Constants.Path.UpdateDirectory);
}
public static void DeleteDirectory(string path, CancellationToken cancellationToken)
{
ArgUtil.NotNullOrEmpty(path, nameof(path));
DirectoryInfo directory = new DirectoryInfo(path);
if (!directory.Exists)
{
return;
}
// Remove the readonly flag.
RemoveReadOnly(directory);
// Check if the directory is a reparse point.
if (directory.Attributes.HasFlag(FileAttributes.ReparsePoint))
{
// Delete the reparse point directory and short-circuit.
directory.Delete();
return;
}
// Initialize a concurrent stack to store the directories. The directories
// cannot be deleted until the files are deleted.
var directories = new ConcurrentStack<DirectoryInfo>();
directories.Push(directory);
// Create a new token source for the parallel query. The parallel query should be
// canceled after the first error is encountered. Otherwise the number of exceptions
// could get out of control for a large directory with access denied on every file.
using (var tokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
{
try
{
// Recursively delete all files and store all subdirectories.
Enumerate(directory, tokenSource)
.AsParallel()
.WithCancellation(tokenSource.Token)
.ForAll((FileSystemInfo item) =>
{
bool success = false;
try
{
// Check if the item is a file.
var file = item as FileInfo;
if (file != null)
{
// Delete the file.
RemoveReadOnly(file);
file.Delete();
success = true;
return;
}
// The item is a directory.
var subdirectory = item as DirectoryInfo;
ArgUtil.NotNull(subdirectory, nameof(subdirectory));
// Remove the readonly attribute and store the subdirectory.
RemoveReadOnly(subdirectory);
directories.Push(subdirectory);
success = true;
}
finally
{
if (!success)
{
tokenSource.Cancel(); // Cancel is thread-safe.
}
}
});
}
catch (Exception)
{
tokenSource.Cancel();
throw;
}
}
// Delete the directories.
foreach (DirectoryInfo dir in directories.OrderByDescending(x => x.FullName.Length))
{
cancellationToken.ThrowIfCancellationRequested();
dir.Delete();
}
}
public static void DeleteFile(string path)
{
ArgUtil.NotNullOrEmpty(path, nameof(path));
var file = new FileInfo(path);
if (file.Exists)
{
RemoveReadOnly(file);
file.Delete();
}
}
/// <summary>
/// Given a path and directory, return the path relative to the directory. If the path is not
/// under the directory the path is returned un modified. Examples:
/// MakeRelative(@"d:\src\project\foo.cpp", @"d:\src") -> @"project\foo.cpp"
/// MakeRelative(@"d:\src\project\foo.cpp", @"d:\specs") -> @"d:\src\project\foo.cpp"
/// MakeRelative(@"d:\src\project\foo.cpp", @"d:\src\proj") -> @"d:\src\project\foo.cpp"
/// </summary>
/// <remarks>Safe for remote paths. Does not access the local disk.</remarks>
/// <param name="path">Path to make relative.</param>
/// <param name="folder">Folder to make it relative to.</param>
/// <returns>Relative path.</returns>
public static string MakeRelative(string path, string folder)
{
ArgUtil.NotNullOrEmpty(path, nameof(path));
ArgUtil.NotNull(folder, nameof(folder));
// Replace all Path.AltDirectorySeparatorChar with Path.DirectorySeparatorChar from both inputs
path = path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
folder = folder.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
// Check if the dir is a prefix of the path (if not, it isn't relative at all).
if (!path.StartsWith(folder, StringComparison.OrdinalIgnoreCase))
{
return path;
}
// Dir is a prefix of the path, if they are the same length then the relative path is empty.
if (path.Length == folder.Length)
{
return string.Empty;
}
// If the dir ended in a '\\' (like d:\) or '/' (like user/bin/) then we have a relative path.
if (folder.Length > 0 && folder[folder.Length - 1] == Path.DirectorySeparatorChar)
{
return path.Substring(folder.Length);
}
// The next character needs to be a '\\' or they aren't really relative.
else if (path[folder.Length] == Path.DirectorySeparatorChar)
{
return path.Substring(folder.Length + 1);
}
else
{
return path;
}
}
public static void CopyDirectory(string sourceDirectory, string targetDirectory, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
DirectoryInfo sourceDir = new DirectoryInfo(sourceDirectory);
// If the source directory does not exist, throw an exception.
if (!sourceDir.Exists)
{
throw new DirectoryNotFoundException($"{sourceDirectory}");
}
Directory.CreateDirectory(targetDirectory);
// Get the file contents of the directory to copy.
foreach (FileInfo file in sourceDir.GetFiles() ?? new FileInfo[0])
{
cancellationToken.ThrowIfCancellationRequested();
// Create the path to the new copy of the file.
string targetFilePath = Path.Combine(targetDirectory, file.Name);
// Copy the file.
file.CopyTo(targetFilePath, true);
}
DirectoryInfo[] subDirs = sourceDir.GetDirectories();
foreach (DirectoryInfo subDir in subDirs ?? new DirectoryInfo[0])
{
// Create the subdirectory.
string targetDirectoryPath = Path.Combine(targetDirectory, subDir.Name);
// Copy the subdirectories.
CopyDirectory(subDir.FullName, targetDirectoryPath, cancellationToken);
}
}
/// <summary>
/// Recursively enumerates a directory without following directory reparse points.
/// </summary>
private static IEnumerable<FileSystemInfo> Enumerate(DirectoryInfo directory, CancellationTokenSource tokenSource)
{
ArgUtil.NotNull(directory, nameof(directory));
ArgUtil.Equal(false, directory.Attributes.HasFlag(FileAttributes.ReparsePoint), nameof(directory.Attributes.HasFlag));
// Push the directory onto the processing stack.
var directories = new Stack<DirectoryInfo>(new[] { directory });
while (directories.Count > 0)
{
// Pop the next directory.
directory = directories.Pop();
foreach (FileSystemInfo item in directory.GetFileSystemInfos())
{
yield return item;
// Push non-reparse-point directories onto the processing stack.
directory = item as DirectoryInfo;
if (directory != null &&
!item.Attributes.HasFlag(FileAttributes.ReparsePoint))
{
directories.Push(directory);
}
}
}
}
private static void RemoveReadOnly(FileSystemInfo item)
{
ArgUtil.NotNull(item, nameof(item));
if (item.Attributes.HasFlag(FileAttributes.ReadOnly))
{
item.Attributes = item.Attributes & ~FileAttributes.ReadOnly;
}
}
}
}
| |
using System;
using System.IO;
using System.Collections;
namespace HtmlHelp.ChmDecoding
{
/// <summary>
/// The class <c>CHMTocidx</c> implements functions to decode the #TOCIDX internal file.
/// </summary>
internal sealed class CHMTocidx : IDisposable
{
/// <summary>
/// Constant specifying the size of the data blocks
/// </summary>
private const int BLOCK_SIZE = 0x1000;
/// <summary>
/// Internal flag specifying if the object is going to be disposed
/// </summary>
private bool disposed = false;
/// <summary>
/// Internal member storing the binary file data
/// </summary>
private byte[] _binaryFileData = null;
/// <summary>
/// Internal memebr storing the offset to the 20/28 byte structs
/// </summary>
private int _offset2028 = 0;
/// <summary>
/// Internal member storing the offset to the 16 byte structs
/// </summary>
private int _offset16structs = 0;
/// <summary>
/// Internal member storing the number of 16 byte structs
/// </summary>
private int _numberOf16structs = 0;
/// <summary>
/// Internal member storing the offset to the topic list
/// </summary>
private int _offsetOftopics = 0;
/// <summary>
/// Internal member storing the toc
/// </summary>
private ArrayList _toc = new ArrayList();
/// <summary>
/// Internal member for offset seeking
/// </summary>
private Hashtable _offsetTable = new Hashtable();
/// <summary>
/// Internal member storing the associated chmfile object
/// </summary>
private CHMFile _associatedFile = null;
/// <summary>
/// Constructor of the class
/// </summary>
/// <param name="binaryFileData">binary file data of the #TOCIDX file</param>
/// <param name="associatedFile">associated chm file</param>
public CHMTocidx(byte[] binaryFileData, CHMFile associatedFile)
{
_binaryFileData = binaryFileData;
_associatedFile = associatedFile;
DecodeData();
// clear internal binary data after extraction
_binaryFileData = null;
}
/// <summary>
/// Decodes the binary file data and fills the internal properties
/// </summary>
/// <returns>true if succeeded</returns>
private bool DecodeData()
{
_toc = new ArrayList();
_offsetTable = new Hashtable();
bool bRet = true;
MemoryStream memStream = new MemoryStream(_binaryFileData);
BinaryReader binReader = new BinaryReader(memStream);
int nCurOffset = 0;
_offset2028 = binReader.ReadInt32();
_offset16structs = binReader.ReadInt32();
_numberOf16structs = binReader.ReadInt32();
_offsetOftopics = binReader.ReadInt32();
binReader.BaseStream.Seek( _offset2028, SeekOrigin.Begin );
if( RecursivelyBuildTree(ref binReader, _offset2028, _toc, null) )
{
binReader.BaseStream.Seek( _offset16structs, SeekOrigin.Begin );
nCurOffset = (int)binReader.BaseStream.Position;
for(int i=0; i < _numberOf16structs; i++)
{
int tocOffset = binReader.ReadInt32();
int sqNr = binReader.ReadInt32();
int topOffset = binReader.ReadInt32();
int hhctopicIdx = binReader.ReadInt32();
nCurOffset = (int)binReader.BaseStream.Position;
int topicIdx = -1;
// if the topic offset is within the range of the stream
// and is >= the offset of the first topic dword
if((topOffset < (binReader.BaseStream.Length - 4)) && (topOffset >= _offsetOftopics))
{
// read the index of the topic for this item
binReader.BaseStream.Seek( topOffset, SeekOrigin.Begin);
topicIdx = binReader.ReadInt32();
binReader.BaseStream.Seek( nCurOffset, SeekOrigin.Begin);
TOCItem item = (TOCItem)_offsetTable[tocOffset.ToString()];
if( item != null)
{
if(( topicIdx < _associatedFile.TopicsFile.TopicTable.Count)&&(topicIdx>=0))
{
TopicEntry te = (TopicEntry) (_associatedFile.TopicsFile.TopicTable[topicIdx]);
if( (te != null) && (item.TopicOffset < 0) )
{
item.TopicOffset = te.EntryOffset;
}
}
}
}
}
}
return bRet;
}
/// <summary>
/// Recursively reads the binary toc tree from the file
/// </summary>
/// <param name="binReader">reference to binary reader</param>
/// <param name="NodeOffset">offset of the first node in the current level</param>
/// <param name="level">arraylist of TOCItems for the current level</param>
/// <param name="parentItem">parent item for the item</param>
/// <returns>Returns true if succeeded</returns>
private bool RecursivelyBuildTree(ref BinaryReader binReader, int NodeOffset, ArrayList level, TOCItem parentItem)
{
bool bRet = true;
int nextOffset=0;
int nReadOffset = (int)binReader.BaseStream.Position;
binReader.BaseStream.Seek(NodeOffset, SeekOrigin.Begin);
do
{
int nCurOffset = (int)binReader.BaseStream.Position;
int unkn1 = binReader.ReadInt16(); // unknown
int unkn2 = binReader.ReadInt16(); // unknown
int flag = binReader.ReadInt32();
int nFolderAdd = 0;
if((_associatedFile != null) && (_associatedFile.ImageTypeFolder))
{
// get the value which should be added, to display folders instead of books
if(HtmlHelpSystem.UseHH2TreePics)
nFolderAdd = 8;
else
nFolderAdd = 4;
}
int nFolderImgIdx = (HtmlHelpSystem.UseHH2TreePics ? (TOCItem.STD_FOLDER_HH2+nFolderAdd) : (TOCItem.STD_FOLDER_HH1+nFolderAdd));
int nFileImgIdx = (HtmlHelpSystem.UseHH2TreePics ? TOCItem.STD_FILE_HH2 : TOCItem.STD_FILE_HH1);
int stdImage = ((flag & 0x4)!=0) ? nFolderImgIdx : nFileImgIdx;
int stringOffset = binReader.ReadInt32();
int ParentOffset = binReader.ReadInt32();
nextOffset = binReader.ReadInt32();
int firstChildOffset = 0;
int unkn3=0;
if( (flag&0x4)!=0 )
{
firstChildOffset = binReader.ReadInt32();
unkn3 = binReader.ReadInt32(); // unknown
}
TOCItem newItem = new TOCItem();
newItem.ImageIndex = stdImage;
newItem.Offset = nCurOffset;
newItem.OffsetNext = nextOffset;
newItem.AssociatedFile = _associatedFile;
newItem.TocMode = DataMode.Binary;
newItem.Parent = parentItem;
if( (flag&0x08) == 0)
{
// toc item doesn't have a local value (=> stringOffset = offset of strings file)
newItem.Name = _associatedFile.StringsFile[stringOffset];
}
else
{
// this item has a topic entry (=> stringOffset = index of topic entry)
if((stringOffset < _associatedFile.TopicsFile.TopicTable.Count) && (stringOffset >= 0))
{
TopicEntry te = (TopicEntry) (_associatedFile.TopicsFile.TopicTable[stringOffset]);
if(te != null)
{
newItem.TopicOffset = te.EntryOffset;
}
}
}
_offsetTable[nCurOffset.ToString()] = newItem;
// if this item has children (firstChildOffset > 0)
if( firstChildOffset > 0)
{
bRet &= RecursivelyBuildTree(ref binReader, firstChildOffset, newItem.Children, newItem);
}
level.Add( newItem );
if(nCurOffset != nextOffset)
binReader.BaseStream.Seek(nextOffset, SeekOrigin.Begin);
}while(nextOffset != 0);
binReader.BaseStream.Seek(nReadOffset, SeekOrigin.Begin);
return bRet;
}
/// <summary>
/// Gets the internal read toc
/// </summary>
internal ArrayList TOC
{
get { return _toc; }
}
/// <summary>
/// Implement IDisposable.
/// </summary>
public void Dispose()
{
Dispose(true);
// This object will be cleaned up by the Dispose method.
// Therefore, you should call GC.SupressFinalize to
// take this object off the finalization queue
// and prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
/// <summary>
/// Dispose(bool disposing) executes in two distinct scenarios.
/// If disposing equals true, the method has been called directly
/// or indirectly by a user's code. Managed and unmanaged resources
/// can be disposed.
/// If disposing equals false, the method has been called by the
/// runtime from inside the finalizer and you should not reference
/// other objects. Only unmanaged resources can be disposed.
/// </summary>
/// <param name="disposing">disposing flag</param>
private void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if(!this.disposed)
{
// If disposing equals true, dispose all managed
// and unmanaged resources.
if(disposing)
{
// Dispose managed resources.
_binaryFileData = null;
_toc = null;
_offsetTable = null;
}
}
disposed = true;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#nullable enable
using System.Diagnostics;
using System.Threading;
namespace System.Net.Http.HPack
{
internal static class Huffman
{
// HPack static huffman code. see: https://httpwg.org/specs/rfc7541.html#huffman.code
// Stored into two tables to optimize its initialization and memory consumption.
private static readonly uint[] s_encodingTableCodes = new uint[257]
{
0b11111111_11000000_00000000_00000000,
0b11111111_11111111_10110000_00000000,
0b11111111_11111111_11111110_00100000,
0b11111111_11111111_11111110_00110000,
0b11111111_11111111_11111110_01000000,
0b11111111_11111111_11111110_01010000,
0b11111111_11111111_11111110_01100000,
0b11111111_11111111_11111110_01110000,
0b11111111_11111111_11111110_10000000,
0b11111111_11111111_11101010_00000000,
0b11111111_11111111_11111111_11110000,
0b11111111_11111111_11111110_10010000,
0b11111111_11111111_11111110_10100000,
0b11111111_11111111_11111111_11110100,
0b11111111_11111111_11111110_10110000,
0b11111111_11111111_11111110_11000000,
0b11111111_11111111_11111110_11010000,
0b11111111_11111111_11111110_11100000,
0b11111111_11111111_11111110_11110000,
0b11111111_11111111_11111111_00000000,
0b11111111_11111111_11111111_00010000,
0b11111111_11111111_11111111_00100000,
0b11111111_11111111_11111111_11111000,
0b11111111_11111111_11111111_00110000,
0b11111111_11111111_11111111_01000000,
0b11111111_11111111_11111111_01010000,
0b11111111_11111111_11111111_01100000,
0b11111111_11111111_11111111_01110000,
0b11111111_11111111_11111111_10000000,
0b11111111_11111111_11111111_10010000,
0b11111111_11111111_11111111_10100000,
0b11111111_11111111_11111111_10110000,
0b01010000_00000000_00000000_00000000,
0b11111110_00000000_00000000_00000000,
0b11111110_01000000_00000000_00000000,
0b11111111_10100000_00000000_00000000,
0b11111111_11001000_00000000_00000000,
0b01010100_00000000_00000000_00000000,
0b11111000_00000000_00000000_00000000,
0b11111111_01000000_00000000_00000000,
0b11111110_10000000_00000000_00000000,
0b11111110_11000000_00000000_00000000,
0b11111001_00000000_00000000_00000000,
0b11111111_01100000_00000000_00000000,
0b11111010_00000000_00000000_00000000,
0b01011000_00000000_00000000_00000000,
0b01011100_00000000_00000000_00000000,
0b01100000_00000000_00000000_00000000,
0b00000000_00000000_00000000_00000000,
0b00001000_00000000_00000000_00000000,
0b00010000_00000000_00000000_00000000,
0b01100100_00000000_00000000_00000000,
0b01101000_00000000_00000000_00000000,
0b01101100_00000000_00000000_00000000,
0b01110000_00000000_00000000_00000000,
0b01110100_00000000_00000000_00000000,
0b01111000_00000000_00000000_00000000,
0b01111100_00000000_00000000_00000000,
0b10111000_00000000_00000000_00000000,
0b11111011_00000000_00000000_00000000,
0b11111111_11111000_00000000_00000000,
0b10000000_00000000_00000000_00000000,
0b11111111_10110000_00000000_00000000,
0b11111111_00000000_00000000_00000000,
0b11111111_11010000_00000000_00000000,
0b10000100_00000000_00000000_00000000,
0b10111010_00000000_00000000_00000000,
0b10111100_00000000_00000000_00000000,
0b10111110_00000000_00000000_00000000,
0b11000000_00000000_00000000_00000000,
0b11000010_00000000_00000000_00000000,
0b11000100_00000000_00000000_00000000,
0b11000110_00000000_00000000_00000000,
0b11001000_00000000_00000000_00000000,
0b11001010_00000000_00000000_00000000,
0b11001100_00000000_00000000_00000000,
0b11001110_00000000_00000000_00000000,
0b11010000_00000000_00000000_00000000,
0b11010010_00000000_00000000_00000000,
0b11010100_00000000_00000000_00000000,
0b11010110_00000000_00000000_00000000,
0b11011000_00000000_00000000_00000000,
0b11011010_00000000_00000000_00000000,
0b11011100_00000000_00000000_00000000,
0b11011110_00000000_00000000_00000000,
0b11100000_00000000_00000000_00000000,
0b11100010_00000000_00000000_00000000,
0b11100100_00000000_00000000_00000000,
0b11111100_00000000_00000000_00000000,
0b11100110_00000000_00000000_00000000,
0b11111101_00000000_00000000_00000000,
0b11111111_11011000_00000000_00000000,
0b11111111_11111110_00000000_00000000,
0b11111111_11100000_00000000_00000000,
0b11111111_11110000_00000000_00000000,
0b10001000_00000000_00000000_00000000,
0b11111111_11111010_00000000_00000000,
0b00011000_00000000_00000000_00000000,
0b10001100_00000000_00000000_00000000,
0b00100000_00000000_00000000_00000000,
0b10010000_00000000_00000000_00000000,
0b00101000_00000000_00000000_00000000,
0b10010100_00000000_00000000_00000000,
0b10011000_00000000_00000000_00000000,
0b10011100_00000000_00000000_00000000,
0b00110000_00000000_00000000_00000000,
0b11101000_00000000_00000000_00000000,
0b11101010_00000000_00000000_00000000,
0b10100000_00000000_00000000_00000000,
0b10100100_00000000_00000000_00000000,
0b10101000_00000000_00000000_00000000,
0b00111000_00000000_00000000_00000000,
0b10101100_00000000_00000000_00000000,
0b11101100_00000000_00000000_00000000,
0b10110000_00000000_00000000_00000000,
0b01000000_00000000_00000000_00000000,
0b01001000_00000000_00000000_00000000,
0b10110100_00000000_00000000_00000000,
0b11101110_00000000_00000000_00000000,
0b11110000_00000000_00000000_00000000,
0b11110010_00000000_00000000_00000000,
0b11110100_00000000_00000000_00000000,
0b11110110_00000000_00000000_00000000,
0b11111111_11111100_00000000_00000000,
0b11111111_10000000_00000000_00000000,
0b11111111_11110100_00000000_00000000,
0b11111111_11101000_00000000_00000000,
0b11111111_11111111_11111111_11000000,
0b11111111_11111110_01100000_00000000,
0b11111111_11111111_01001000_00000000,
0b11111111_11111110_01110000_00000000,
0b11111111_11111110_10000000_00000000,
0b11111111_11111111_01001100_00000000,
0b11111111_11111111_01010000_00000000,
0b11111111_11111111_01010100_00000000,
0b11111111_11111111_10110010_00000000,
0b11111111_11111111_01011000_00000000,
0b11111111_11111111_10110100_00000000,
0b11111111_11111111_10110110_00000000,
0b11111111_11111111_10111000_00000000,
0b11111111_11111111_10111010_00000000,
0b11111111_11111111_10111100_00000000,
0b11111111_11111111_11101011_00000000,
0b11111111_11111111_10111110_00000000,
0b11111111_11111111_11101100_00000000,
0b11111111_11111111_11101101_00000000,
0b11111111_11111111_01011100_00000000,
0b11111111_11111111_11000000_00000000,
0b11111111_11111111_11101110_00000000,
0b11111111_11111111_11000010_00000000,
0b11111111_11111111_11000100_00000000,
0b11111111_11111111_11000110_00000000,
0b11111111_11111111_11001000_00000000,
0b11111111_11111110_11100000_00000000,
0b11111111_11111111_01100000_00000000,
0b11111111_11111111_11001010_00000000,
0b11111111_11111111_01100100_00000000,
0b11111111_11111111_11001100_00000000,
0b11111111_11111111_11001110_00000000,
0b11111111_11111111_11101111_00000000,
0b11111111_11111111_01101000_00000000,
0b11111111_11111110_11101000_00000000,
0b11111111_11111110_10010000_00000000,
0b11111111_11111111_01101100_00000000,
0b11111111_11111111_01110000_00000000,
0b11111111_11111111_11010000_00000000,
0b11111111_11111111_11010010_00000000,
0b11111111_11111110_11110000_00000000,
0b11111111_11111111_11010100_00000000,
0b11111111_11111111_01110100_00000000,
0b11111111_11111111_01111000_00000000,
0b11111111_11111111_11110000_00000000,
0b11111111_11111110_11111000_00000000,
0b11111111_11111111_01111100_00000000,
0b11111111_11111111_11010110_00000000,
0b11111111_11111111_11011000_00000000,
0b11111111_11111111_00000000_00000000,
0b11111111_11111111_00001000_00000000,
0b11111111_11111111_10000000_00000000,
0b11111111_11111111_00010000_00000000,
0b11111111_11111111_11011010_00000000,
0b11111111_11111111_10000100_00000000,
0b11111111_11111111_11011100_00000000,
0b11111111_11111111_11011110_00000000,
0b11111111_11111110_10100000_00000000,
0b11111111_11111111_10001000_00000000,
0b11111111_11111111_10001100_00000000,
0b11111111_11111111_10010000_00000000,
0b11111111_11111111_11100000_00000000,
0b11111111_11111111_10010100_00000000,
0b11111111_11111111_10011000_00000000,
0b11111111_11111111_11100010_00000000,
0b11111111_11111111_11111000_00000000,
0b11111111_11111111_11111000_01000000,
0b11111111_11111110_10110000_00000000,
0b11111111_11111110_00100000_00000000,
0b11111111_11111111_10011100_00000000,
0b11111111_11111111_11100100_00000000,
0b11111111_11111111_10100000_00000000,
0b11111111_11111111_11110110_00000000,
0b11111111_11111111_11111000_10000000,
0b11111111_11111111_11111000_11000000,
0b11111111_11111111_11111001_00000000,
0b11111111_11111111_11111011_11000000,
0b11111111_11111111_11111011_11100000,
0b11111111_11111111_11111001_01000000,
0b11111111_11111111_11110001_00000000,
0b11111111_11111111_11110110_10000000,
0b11111111_11111110_01000000_00000000,
0b11111111_11111111_00011000_00000000,
0b11111111_11111111_11111001_10000000,
0b11111111_11111111_11111100_00000000,
0b11111111_11111111_11111100_00100000,
0b11111111_11111111_11111001_11000000,
0b11111111_11111111_11111100_01000000,
0b11111111_11111111_11110010_00000000,
0b11111111_11111111_00100000_00000000,
0b11111111_11111111_00101000_00000000,
0b11111111_11111111_11111010_00000000,
0b11111111_11111111_11111010_01000000,
0b11111111_11111111_11111111_11010000,
0b11111111_11111111_11111100_01100000,
0b11111111_11111111_11111100_10000000,
0b11111111_11111111_11111100_10100000,
0b11111111_11111110_11000000_00000000,
0b11111111_11111111_11110011_00000000,
0b11111111_11111110_11010000_00000000,
0b11111111_11111111_00110000_00000000,
0b11111111_11111111_10100100_00000000,
0b11111111_11111111_00111000_00000000,
0b11111111_11111111_01000000_00000000,
0b11111111_11111111_11100110_00000000,
0b11111111_11111111_10101000_00000000,
0b11111111_11111111_10101100_00000000,
0b11111111_11111111_11110111_00000000,
0b11111111_11111111_11110111_10000000,
0b11111111_11111111_11110100_00000000,
0b11111111_11111111_11110101_00000000,
0b11111111_11111111_11111010_10000000,
0b11111111_11111111_11101000_00000000,
0b11111111_11111111_11111010_11000000,
0b11111111_11111111_11111100_11000000,
0b11111111_11111111_11111011_00000000,
0b11111111_11111111_11111011_01000000,
0b11111111_11111111_11111100_11100000,
0b11111111_11111111_11111101_00000000,
0b11111111_11111111_11111101_00100000,
0b11111111_11111111_11111101_01000000,
0b11111111_11111111_11111101_01100000,
0b11111111_11111111_11111111_11100000,
0b11111111_11111111_11111101_10000000,
0b11111111_11111111_11111101_10100000,
0b11111111_11111111_11111101_11000000,
0b11111111_11111111_11111101_11100000,
0b11111111_11111111_11111110_00000000,
0b11111111_11111111_11111011_10000000,
0b11111111_11111111_11111111_11111100,
};
private static ReadOnlySpan<byte> EncodingTableBitLengths => new byte[257]
{
13,
23,
28,
28,
28,
28,
28,
28,
28,
24,
30,
28,
28,
30,
28,
28,
28,
28,
28,
28,
28,
28,
30,
28,
28,
28,
28,
28,
28,
28,
28,
28,
6,
10,
10,
12,
13,
6,
8,
11,
10,
10,
8,
11,
8,
6,
6,
6,
5,
5,
5,
6,
6,
6,
6,
6,
6,
6,
7,
8,
15,
6,
12,
10,
13,
6,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
8,
7,
8,
13,
19,
13,
14,
6,
15,
5,
6,
5,
6,
5,
6,
6,
6,
5,
7,
7,
6,
6,
6,
5,
6,
7,
6,
5,
5,
6,
7,
7,
7,
7,
7,
15,
11,
14,
13,
28,
20,
22,
20,
20,
22,
22,
22,
23,
22,
23,
23,
23,
23,
23,
24,
23,
24,
24,
22,
23,
24,
23,
23,
23,
23,
21,
22,
23,
22,
23,
23,
24,
22,
21,
20,
22,
22,
23,
23,
21,
23,
22,
22,
24,
21,
22,
23,
23,
21,
21,
22,
21,
23,
22,
23,
23,
20,
22,
22,
22,
23,
22,
22,
23,
26,
26,
20,
19,
22,
23,
22,
25,
26,
26,
26,
27,
27,
26,
24,
25,
19,
21,
26,
27,
27,
26,
27,
24,
21,
21,
26,
26,
28,
27,
27,
27,
20,
24,
20,
21,
22,
21,
21,
23,
22,
22,
25,
25,
24,
24,
26,
23,
26,
27,
26,
26,
27,
27,
27,
27,
27,
28,
27,
27,
27,
27,
27,
26,
30
};
private static readonly ushort[] s_decodingTree = GenerateDecodingLookupTree();
public static (uint encoded, int bitLength) Encode(int data)
{
return (s_encodingTableCodes[data], EncodingTableBitLengths[data]);
}
private static ushort[] GenerateDecodingLookupTree()
{
// Decoding lookup tree is a tree of 8 bit lookup tables stored in
// one dimensional array of ushort to reduce allocations.
// First 256 ushort is lookup table with index 0, next 256 ushort is lookup table with index 1, etc...
// lookup_value = [(lookup_table_index << 8) + lookup_index]
// lookup_index is next 8 bits of huffman code, if there is less than 8 bits in source.
// lookup_index MUST be aligned to 8 bits with LSB bits set to anything (zeros are recommended).
// Lookup value is encoded in ushort as either.
// -----------------------------------------------------------------
// 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
// +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
// | 1 | next_lookup_table_index | not_used |
// +---+---------------------------+-------------------------------+
// or
// +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
// | 0 | number_of_used_bits | octet |
// +---+---------------------------+-------------------------------+
// Bit 15 unset indicates a leaf value of decoding tree.
// For example value 0x0241 means that we have reached end of huffman code
// with result byte 0x41 'A' and from lookup bits only rightmost 2 bits were used
// and rest of bits are part of next huffman code.
// Bit 15 set indicates that code is not yet decoded and next lookup table index shall be used
// for next n bits of huffman code.
// 0 in 'next lookup table index' is considered as decoding error - invalid huffman code
// Because HPack uses static huffman code defined in RFC https://httpwg.org/specs/rfc7541.html#huffman.code
// it is guaranteed that for this huffman code generated decoding lookup tree MUST consist of exactly 15 lookup tables
var decodingTree = new ushort[15 * 256];
uint[] encodingTableCodes = s_encodingTableCodes;
ReadOnlySpan<byte> encodingTableBitLengths = EncodingTableBitLengths;
int allocatedLookupTableIndex = 0;
// Create traverse path for all 0..256 octets, 256 is EOS, see: http://httpwg.org/specs/rfc7541.html#rfc.section.5.2
for (int octet = 0; octet <= 256; octet++)
{
uint code = encodingTableCodes[octet];
int bitLength = encodingTableBitLengths[octet];
int lookupTableIndex = 0;
int bitsLeft = bitLength;
while (bitsLeft > 0)
{
// read next 8 bits from huffman code
int indexInLookupTable = (int)(code >> (32 - 8));
if (bitsLeft <= 8)
{
// Reached last lookup table for this huffman code.
// Identical lookup value has to be stored for every combination of unused bits,
// For example: 12 bit code could be looked up during decoding as this:
// ---------------------------------
// 7 6 5 4 3 2 1 0
// +---+---+---+---+---+---+---+---+
// |last_code_bits | next_code_bits|
// +-------------------------------+
// next_code_bits are 'random' bits of next huffman code, so in order for lookup
// to work, lookup value has to be stored for all 4 unused bits, in this case for suffix 0..15
int suffixCount = 1 << (8 - bitsLeft);
for (int suffix = 0; suffix < suffixCount; suffix++)
{
if (octet == 256)
{
// EOS (in our case 256) have special meaning in HPack static huffman code
// see: http://httpwg.org/specs/rfc7541.html#rfc.section.5.2
// > A Huffman-encoded string literal containing the EOS symbol MUST be treated as a decoding error.
// To force decoding error we store 0 as 'next lookup table index' which MUST be treated as decoding error.
// Invalid huffman code - EOS
// +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
// | 1 | 0 0 0 0 0 0 0 | 1 1 1 1 1 1 1 1 |
// +---+---------------------------+-------------------------------+
decodingTree[(lookupTableIndex << 8) + (indexInLookupTable | suffix)] = 0x80ff;
}
else
{
// Leaf lookup value
// +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
// | 0 | number_of_used_bits | code |
// +---+---------------------------+-------------------------------+
decodingTree[(lookupTableIndex << 8) + (indexInLookupTable | suffix)] = (ushort)((bitsLeft << 8) | octet);
}
}
}
else
{
// More than 8 bits left in huffman code means that we need to traverse to another lookup table for next 8 bits
ushort lookupValue = decodingTree[(lookupTableIndex << 8) + indexInLookupTable];
// Because next_lookup_table_index can not be 0, as 0 is index of root table, default value of array element
// means that we have not initialized it yet => lookup table MUST be allocated and its index assigned to that lookup value
// +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
// | 1 | next_lookup_table_index | not_used |
// +---+---------------------------+-------------------------------+
if (lookupValue == 0)
{
++allocatedLookupTableIndex;
decodingTree[(lookupTableIndex << 8) + indexInLookupTable] = (ushort)((0x80 | allocatedLookupTableIndex) << 8);
lookupTableIndex = allocatedLookupTableIndex;
}
else
{
lookupTableIndex = (lookupValue & 0x7f00) >> 8;
}
}
bitsLeft -= 8;
code <<= 8;
}
}
return decodingTree;
}
/// <summary>
/// Decodes a Huffman encoded string from a byte array.
/// </summary>
/// <param name="src">The source byte array containing the encoded data.</param>
/// <param name="dstArray">The destination byte array to store the decoded data. This may grow if its size is insufficient.</param>
/// <returns>The number of decoded symbols.</returns>
public static int Decode(ReadOnlySpan<byte> src, ref byte[] dstArray)
{
// The code below implements the decoding logic for an HPack huffman encoded literal values.
// https://httpwg.org/specs/rfc7541.html#string.literal.representation
//
// To decode a symbol, we traverse the decoding lookup table tree by 8 bits for each lookup
// until we found a leaf - which contains decoded symbol (octet)
//
// see comments in GenerateDecodingLookupTree() describing decoding table
Span<byte> dst = dstArray;
Debug.Assert(dst != null && dst.Length > 0);
ushort[] decodingTree = s_decodingTree;
int lookupTableIndex = 0;
int lookupIndex;
uint acc = 0;
int bitsInAcc = 0;
int i = 0;
int j = 0;
while (i < src.Length)
{
// Load next 8 bits into accumulator.
acc <<= 8;
acc |= src[i++];
bitsInAcc += 8;
// Decode bits in accumulator.
do
{
lookupIndex = (byte)(acc >> (bitsInAcc - 8));
int lookupValue = decodingTree[(lookupTableIndex << 8) + lookupIndex];
if (lookupValue < 0x80_00)
{
// Octet found.
// +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
// | 0 | number_of_used_bits | octet |
// +---+---------------------------+-------------------------------+
if (j == dst.Length)
{
Array.Resize(ref dstArray, dst.Length * 2);
dst = dstArray;
}
dst[j++] = (byte)lookupValue;
// Start lookup of next symbol
lookupTableIndex = 0;
bitsInAcc -= lookupValue >> 8;
}
else
{
// Traverse to next lookup table.
// +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
// | 1 | next_lookup_table_index | not_used |
// +---+---------------------------+-------------------------------+
lookupTableIndex = (lookupValue & 0x7f00) >> 8;
if (lookupTableIndex == 0)
{
// No valid symbol could be decoded or EOS was decoded
throw new HuffmanDecodingException(SR.net_http_hpack_huffman_decode_failed);
}
bitsInAcc -= 8;
}
} while (bitsInAcc >= 8);
}
// Finish decoding last < 8 bits of src.
// Processing of the last byte has to handle several corner cases
// so it's extracted outside of the main loop for performance reasons.
while (bitsInAcc > 0)
{
Debug.Assert(bitsInAcc < 8);
// Check for correct EOS, which is padding with ones till end of byte
// when we STARTED new huffman code in last 8 bits (lookupTableIndex was reset to 0 -> root lookup table).
if (lookupTableIndex == 0)
{
// Check if all remaining bits are ones.
uint ones = uint.MaxValue >> (32 - bitsInAcc);
if ((acc & ones) == ones)
{
// Is it a EOS. See: http://httpwg.org/specs/rfc7541.html#rfc.section.5.2
break;
}
}
// Lookup index has to be 8 bits aligned to MSB
lookupIndex = (byte)(acc << (8 - bitsInAcc));
int lookupValue = decodingTree[(lookupTableIndex << 8) + lookupIndex];
if (lookupValue < 0x80_00)
{
// Octet found.
// +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
// | 0 | number_of_used_bits | octet |
// +---+---------------------------+-------------------------------+
bitsInAcc -= lookupValue >> 8;
if (bitsInAcc < 0)
{
// Last looked up code had more bits than was left in accumulator which indicated invalid or incomplete source
throw new HuffmanDecodingException(SR.net_http_hpack_huffman_decode_failed);
}
if (j == dst.Length)
{
Array.Resize(ref dstArray, dst.Length * 2);
dst = dstArray;
}
dst[j++] = (byte)lookupValue;
// Set table index to root - start of new huffman code.
lookupTableIndex = 0;
}
else
{
// Src was depleted in middle of lookup tree or EOS was decoded.
throw new HuffmanDecodingException(SR.net_http_hpack_huffman_decode_failed);
}
}
if (lookupTableIndex != 0)
{
// Finished in middle of traversing - no valid symbol could be decoded
// or too long EOS padding (7 bits plus). See: http://httpwg.org/specs/rfc7541.html#rfc.section.5.2
throw new HuffmanDecodingException(SR.net_http_hpack_huffman_decode_failed);
}
return j;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Diagnostics.RemoveUnnecessaryImports;
using Microsoft.CodeAnalysis.CSharp.Diagnostics.SimplifyTypeNames;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.Squiggles;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text.Adornments;
using Microsoft.VisualStudio.Text.Tagging;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Squiggles
{
public class ErrorSquiggleProducerTests : AbstractSquiggleProducerTests
{
[Fact, Trait(Traits.Feature, Traits.Features.ErrorSquiggles)]
public void ErrorTagGeneratedForError()
{
var spans = GetErrorSpans("class C {");
Assert.Equal(1, spans.Count());
var firstSpan = spans.First();
Assert.Equal(PredefinedErrorTypeNames.SyntaxError, firstSpan.Tag.ErrorType);
}
[Fact, Trait(Traits.Feature, Traits.Features.ErrorSquiggles)]
public void ErrorTagGeneratedForWarning()
{
var spans = GetErrorSpans("class C { long x = 5l; }");
Assert.Equal(1, spans.Count());
Assert.Equal(PredefinedErrorTypeNames.Warning, spans.First().Tag.ErrorType);
}
[Fact, Trait(Traits.Feature, Traits.Features.ErrorSquiggles)]
public void ErrorTagGeneratedForWarningAsError()
{
var workspaceXml =
@"<Workspace>
<Project Language=""C#"" CommonReferences=""true"">
<CompilationOptions ReportDiagnostic = ""Error"" />
<Document FilePath = ""Test.cs"" >
class Program
{
void Test()
{
int a = 5;
}
}
</Document>
</Project>
</Workspace>";
using (var workspace = TestWorkspaceFactory.CreateWorkspace(workspaceXml))
{
var spans = GetErrorSpans(workspace);
Assert.Equal(1, spans.Count());
Assert.Equal(PredefinedErrorTypeNames.SyntaxError, spans.First().Tag.ErrorType);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.ErrorSquiggles)]
public void SuggestionTagsForUnnecessaryCode()
{
var workspaceXml =
@"<Workspace>
<Project Language=""C#"" CommonReferences=""true"">
<Document FilePath = ""Test.cs"" >
// System is used - rest are unused.
using System.Collections;
using System;
using System.Diagnostics;
using System.Collections.Generic;
class Program
{
void Test()
{
Int32 x = 2; // Int32 can be simplified.
x += 1;
}
}
</Document>
</Project>
</Workspace>";
using (var workspace = TestWorkspaceFactory.CreateWorkspace(workspaceXml))
{
var analyzerMap = ImmutableDictionary.CreateBuilder<string, ImmutableArray<DiagnosticAnalyzer>>();
analyzerMap.Add(LanguageNames.CSharp,
ImmutableArray.Create<DiagnosticAnalyzer>(
new CSharpSimplifyTypeNamesDiagnosticAnalyzer(),
new CSharpRemoveUnnecessaryImportsDiagnosticAnalyzer()));
var spans =
GetErrorSpans(workspace, analyzerMap.ToImmutable())
.OrderBy(s => s.Span.Span.Start).ToImmutableArray();
Assert.Equal(3, spans.Length);
var first = spans[0];
var second = spans[1];
var third = spans[2];
Assert.Equal(PredefinedErrorTypeNames.Suggestion, first.Tag.ErrorType);
Assert.Equal(CSharpFeaturesResources.RemoveUnnecessaryUsingsDiagnosticTitle, first.Tag.ToolTipContent);
Assert.Equal(40, first.Span.Start);
Assert.Equal(25, first.Span.Length);
Assert.Equal(PredefinedErrorTypeNames.Suggestion, second.Tag.ErrorType);
Assert.Equal(CSharpFeaturesResources.RemoveUnnecessaryUsingsDiagnosticTitle, second.Tag.ToolTipContent);
Assert.Equal(82, second.Span.Start);
Assert.Equal(60, second.Span.Length);
Assert.Equal(PredefinedErrorTypeNames.Suggestion, third.Tag.ErrorType);
Assert.Equal(WorkspacesResources.NameCanBeSimplified, third.Tag.ToolTipContent);
Assert.Equal(196, third.Span.Start);
Assert.Equal(5, third.Span.Length);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.ErrorSquiggles)]
public void ErrorDoesNotCrashPastEOF()
{
var spans = GetErrorSpans("class C { int x =");
Assert.Equal(3, spans.Count());
}
[Fact, Trait(Traits.Feature, Traits.Features.ErrorSquiggles)]
public void SemanticErrorReported()
{
var spans = GetErrorSpans("class C : Bar { }");
Assert.Equal(1, spans.Count());
var firstSpan = spans.First();
Assert.Equal(PredefinedErrorTypeNames.SyntaxError, firstSpan.Tag.ErrorType);
Assert.Contains("Bar", (string)firstSpan.Tag.ToolTipContent, StringComparison.Ordinal);
}
[Fact, Trait(Traits.Feature, Traits.Features.ErrorSquiggles)]
public void BuildErrorZeroLengthSpan()
{
var workspaceXml =
@"<Workspace>
<Project Language=""C#"" CommonReferences=""true"">
<Document FilePath = ""Test.cs"" >
class Test
{
}
</Document>
</Project>
</Workspace>";
using (var workspace = TestWorkspaceFactory.CreateWorkspace(workspaceXml))
{
var document = workspace.Documents.First();
var updateArgs = new DiagnosticsUpdatedArgs(
new object(), workspace, workspace.CurrentSolution, document.Project.Id, document.Id,
ImmutableArray.Create(
CreateDiagnosticData(workspace, document, new TextSpan(0, 0)),
CreateDiagnosticData(workspace, document, new TextSpan(0, 1))));
var spans = GetErrorsFromUpdateSource(workspace, document, updateArgs);
Assert.Equal(1, spans.Count());
var first = spans.First();
Assert.Equal(1, first.Span.Span.Length);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.ErrorSquiggles)]
public void LiveErrorZeroLengthSpan()
{
var workspaceXml =
@"<Workspace>
<Project Language=""C#"" CommonReferences=""true"">
<Document FilePath = ""Test.cs"" >
class Test
{
}
</Document>
</Project>
</Workspace>";
using (var workspace = TestWorkspaceFactory.CreateWorkspace(workspaceXml))
{
var document = workspace.Documents.First();
var updateArgs = new DiagnosticsUpdatedArgs(
new LiveId(), workspace, workspace.CurrentSolution, document.Project.Id, document.Id,
ImmutableArray.Create(
CreateDiagnosticData(workspace, document, new TextSpan(0, 0)),
CreateDiagnosticData(workspace, document, new TextSpan(0, 1))));
var spans = GetErrorsFromUpdateSource(workspace, document, updateArgs);
Assert.Equal(2, spans.Count());
var first = spans.First();
var second = spans.Last();
Assert.Equal(1, first.Span.Span.Length);
Assert.Equal(1, second.Span.Span.Length);
}
}
private class LiveId : UpdateArgsId
{
// use just a random analyzer
public LiveId() : base(new CSharpSimplifyTypeNamesDiagnosticAnalyzer())
{
}
}
private static IEnumerable<ITagSpan<IErrorTag>> GetErrorSpans(params string[] content)
{
using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(content))
{
return GetErrorSpans(workspace);
}
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmPersonFPReg
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmPersonFPReg() : base()
{
Load += frmPersonFPReg_Load;
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
private System.Windows.Forms.Button withEventsField_cmdExit;
public System.Windows.Forms.Button cmdExit {
get { return withEventsField_cmdExit; }
set {
if (withEventsField_cmdExit != null) {
withEventsField_cmdExit.Click -= cmdExit_Click;
}
withEventsField_cmdExit = value;
if (withEventsField_cmdExit != null) {
withEventsField_cmdExit.Click += cmdExit_Click;
}
}
}
public System.Windows.Forms.Label Label3;
public System.Windows.Forms.Panel picButtons;
private System.Windows.Forms.Button withEventsField_Command1;
public System.Windows.Forms.Button Command1 {
get { return withEventsField_Command1; }
set {
if (withEventsField_Command1 != null) {
withEventsField_Command1.Click -= Command1_Click;
}
withEventsField_Command1 = value;
if (withEventsField_Command1 != null) {
withEventsField_Command1.Click += Command1_Click;
}
}
}
public System.Windows.Forms.TextBox eName;
private System.Windows.Forms.Button withEventsField_start_cmd;
public System.Windows.Forms.Button start_cmd {
get { return withEventsField_start_cmd; }
set {
if (withEventsField_start_cmd != null) {
withEventsField_start_cmd.Click -= start_cmd_Click;
}
withEventsField_start_cmd = value;
if (withEventsField_start_cmd != null) {
withEventsField_start_cmd.Click += start_cmd_Click;
}
}
}
public System.Windows.Forms.PictureBox _picSample_3;
public System.Windows.Forms.PictureBox _picSample_2;
public System.Windows.Forms.PictureBox _picSample_1;
public System.Windows.Forms.PictureBox _picSample_0;
public System.Windows.Forms.Label _Label6_3;
public System.Windows.Forms.Label _Label6_2;
public System.Windows.Forms.Label _Label6_1;
public System.Windows.Forms.Label _Label6_0;
public System.Windows.Forms.Label Label2;
public System.Windows.Forms.Label lblEvents;
public System.Windows.Forms.Label Label1;
public System.Windows.Forms.Label lblQuality;
//Public WithEvents Label6 As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//Public WithEvents picSample As Microsoft.VisualBasic.Compatibility.VB6.PictureBoxArray
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmPersonFPReg));
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(components);
this.picButtons = new System.Windows.Forms.Panel();
this.cmdExit = new System.Windows.Forms.Button();
this.Label3 = new System.Windows.Forms.Label();
this.Command1 = new System.Windows.Forms.Button();
this.eName = new System.Windows.Forms.TextBox();
this.start_cmd = new System.Windows.Forms.Button();
this._picSample_3 = new System.Windows.Forms.PictureBox();
this._picSample_2 = new System.Windows.Forms.PictureBox();
this._picSample_1 = new System.Windows.Forms.PictureBox();
this._picSample_0 = new System.Windows.Forms.PictureBox();
this._Label6_3 = new System.Windows.Forms.Label();
this._Label6_2 = new System.Windows.Forms.Label();
this._Label6_1 = new System.Windows.Forms.Label();
this._Label6_0 = new System.Windows.Forms.Label();
this.Label2 = new System.Windows.Forms.Label();
this.lblEvents = new System.Windows.Forms.Label();
this.Label1 = new System.Windows.Forms.Label();
this.lblQuality = new System.Windows.Forms.Label();
//Me.Label6 = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components)
//Me.picSample = New Microsoft.VisualBasic.Compatibility.VB6.PictureBoxArray(components)
this.picButtons.SuspendLayout();
this.SuspendLayout();
this.ToolTip1.Active = true;
//CType(Me.Label6, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.picSample, System.ComponentModel.ISupportInitialize).BeginInit()
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Text = "Registration Form";
this.ClientSize = new System.Drawing.Size(409, 265);
this.Location = new System.Drawing.Point(3, 19);
this.ControlBox = false;
this.ForeColor = System.Drawing.SystemColors.Desktop;
this.KeyPreview = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Control;
this.Enabled = true;
this.Cursor = System.Windows.Forms.Cursors.Default;
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.ShowInTaskbar = true;
this.HelpButton = false;
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
this.Name = "frmPersonFPReg";
this.picButtons.Dock = System.Windows.Forms.DockStyle.Top;
this.picButtons.BackColor = System.Drawing.Color.Blue;
this.picButtons.Size = new System.Drawing.Size(409, 39);
this.picButtons.Location = new System.Drawing.Point(0, 0);
this.picButtons.TabIndex = 15;
this.picButtons.TabStop = false;
this.picButtons.CausesValidation = true;
this.picButtons.Enabled = true;
this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText;
this.picButtons.Cursor = System.Windows.Forms.Cursors.Default;
this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.picButtons.Visible = true;
this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.picButtons.Name = "picButtons";
this.cmdExit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdExit.Text = "E&xit";
this.cmdExit.Size = new System.Drawing.Size(73, 29);
this.cmdExit.Location = new System.Drawing.Point(328, 3);
this.cmdExit.TabIndex = 16;
this.cmdExit.TabStop = false;
this.cmdExit.BackColor = System.Drawing.SystemColors.Control;
this.cmdExit.CausesValidation = true;
this.cmdExit.Enabled = true;
this.cmdExit.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdExit.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdExit.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdExit.Name = "cmdExit";
this.Label3.Text = "Press Start Button to Start";
this.Label3.ForeColor = System.Drawing.Color.White;
this.Label3.Size = new System.Drawing.Size(313, 25);
this.Label3.Location = new System.Drawing.Point(8, 8);
this.Label3.TabIndex = 17;
this.Label3.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.Label3.BackColor = System.Drawing.Color.Transparent;
this.Label3.Enabled = true;
this.Label3.Cursor = System.Windows.Forms.Cursors.Default;
this.Label3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label3.UseMnemonic = true;
this.Label3.Visible = true;
this.Label3.AutoSize = false;
this.Label3.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.Label3.Name = "Label3";
this.Command1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.Command1.Text = "Verify";
this.Command1.Size = new System.Drawing.Size(65, 25);
this.Command1.Location = new System.Drawing.Point(168, 232);
this.Command1.TabIndex = 14;
this.Command1.BackColor = System.Drawing.SystemColors.Control;
this.Command1.CausesValidation = true;
this.Command1.Enabled = true;
this.Command1.ForeColor = System.Drawing.SystemColors.ControlText;
this.Command1.Cursor = System.Windows.Forms.Cursors.Default;
this.Command1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Command1.TabStop = true;
this.Command1.Name = "Command1";
this.eName.AutoSize = false;
this.eName.BackColor = System.Drawing.Color.Blue;
this.eName.ForeColor = System.Drawing.Color.White;
this.eName.Size = new System.Drawing.Size(377, 17);
this.eName.Location = new System.Drawing.Point(16, 48);
this.eName.ReadOnly = true;
this.eName.TabIndex = 13;
this.eName.Text = "name";
this.eName.AcceptsReturn = true;
this.eName.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
this.eName.CausesValidation = true;
this.eName.Enabled = true;
this.eName.HideSelection = true;
this.eName.MaxLength = 0;
this.eName.Cursor = System.Windows.Forms.Cursors.IBeam;
this.eName.Multiline = false;
this.eName.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.eName.ScrollBars = System.Windows.Forms.ScrollBars.None;
this.eName.TabStop = true;
this.eName.Visible = true;
this.eName.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.eName.Name = "eName";
this.start_cmd.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.start_cmd.Text = "Start";
this.start_cmd.Size = new System.Drawing.Size(65, 25);
this.start_cmd.Location = new System.Drawing.Point(168, 200);
this.start_cmd.TabIndex = 12;
this.start_cmd.BackColor = System.Drawing.SystemColors.Control;
this.start_cmd.CausesValidation = true;
this.start_cmd.Enabled = true;
this.start_cmd.ForeColor = System.Drawing.SystemColors.ControlText;
this.start_cmd.Cursor = System.Windows.Forms.Cursors.Default;
this.start_cmd.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.start_cmd.TabStop = true;
this.start_cmd.Name = "start_cmd";
this._picSample_3.Size = new System.Drawing.Size(85, 109);
this._picSample_3.Location = new System.Drawing.Point(304, 80);
this._picSample_3.TabIndex = 7;
this._picSample_3.Dock = System.Windows.Forms.DockStyle.None;
this._picSample_3.BackColor = System.Drawing.SystemColors.Control;
this._picSample_3.CausesValidation = true;
this._picSample_3.Enabled = true;
this._picSample_3.ForeColor = System.Drawing.SystemColors.ControlText;
this._picSample_3.Cursor = System.Windows.Forms.Cursors.Default;
this._picSample_3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._picSample_3.TabStop = true;
this._picSample_3.Visible = true;
this._picSample_3.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Normal;
this._picSample_3.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this._picSample_3.Name = "_picSample_3";
this._picSample_2.Size = new System.Drawing.Size(85, 109);
this._picSample_2.Location = new System.Drawing.Point(208, 80);
this._picSample_2.TabIndex = 6;
this._picSample_2.Dock = System.Windows.Forms.DockStyle.None;
this._picSample_2.BackColor = System.Drawing.SystemColors.Control;
this._picSample_2.CausesValidation = true;
this._picSample_2.Enabled = true;
this._picSample_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._picSample_2.Cursor = System.Windows.Forms.Cursors.Default;
this._picSample_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._picSample_2.TabStop = true;
this._picSample_2.Visible = true;
this._picSample_2.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Normal;
this._picSample_2.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this._picSample_2.Name = "_picSample_2";
this._picSample_1.Size = new System.Drawing.Size(85, 109);
this._picSample_1.Location = new System.Drawing.Point(112, 80);
this._picSample_1.TabIndex = 5;
this._picSample_1.Dock = System.Windows.Forms.DockStyle.None;
this._picSample_1.BackColor = System.Drawing.SystemColors.Control;
this._picSample_1.CausesValidation = true;
this._picSample_1.Enabled = true;
this._picSample_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._picSample_1.Cursor = System.Windows.Forms.Cursors.Default;
this._picSample_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._picSample_1.TabStop = true;
this._picSample_1.Visible = true;
this._picSample_1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Normal;
this._picSample_1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this._picSample_1.Name = "_picSample_1";
this._picSample_0.Size = new System.Drawing.Size(85, 109);
this._picSample_0.Location = new System.Drawing.Point(16, 80);
this._picSample_0.TabIndex = 0;
this._picSample_0.Dock = System.Windows.Forms.DockStyle.None;
this._picSample_0.BackColor = System.Drawing.SystemColors.Control;
this._picSample_0.CausesValidation = true;
this._picSample_0.Enabled = true;
this._picSample_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._picSample_0.Cursor = System.Windows.Forms.Cursors.Default;
this._picSample_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._picSample_0.TabStop = true;
this._picSample_0.Visible = true;
this._picSample_0.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Normal;
this._picSample_0.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this._picSample_0.Name = "_picSample_0";
this._Label6_3.BackColor = System.Drawing.Color.FromArgb(255, 255, 192);
this._Label6_3.Size = new System.Drawing.Size(89, 113);
this._Label6_3.Location = new System.Drawing.Point(304, 76);
this._Label6_3.TabIndex = 11;
this._Label6_3.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._Label6_3.Enabled = true;
this._Label6_3.ForeColor = System.Drawing.SystemColors.ControlText;
this._Label6_3.Cursor = System.Windows.Forms.Cursors.Default;
this._Label6_3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Label6_3.UseMnemonic = true;
this._Label6_3.Visible = true;
this._Label6_3.AutoSize = false;
this._Label6_3.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._Label6_3.Name = "_Label6_3";
this._Label6_2.BackColor = System.Drawing.Color.FromArgb(255, 255, 192);
this._Label6_2.Size = new System.Drawing.Size(89, 113);
this._Label6_2.Location = new System.Drawing.Point(208, 76);
this._Label6_2.TabIndex = 10;
this._Label6_2.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._Label6_2.Enabled = true;
this._Label6_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._Label6_2.Cursor = System.Windows.Forms.Cursors.Default;
this._Label6_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Label6_2.UseMnemonic = true;
this._Label6_2.Visible = true;
this._Label6_2.AutoSize = false;
this._Label6_2.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._Label6_2.Name = "_Label6_2";
this._Label6_1.BackColor = System.Drawing.Color.FromArgb(255, 255, 192);
this._Label6_1.Size = new System.Drawing.Size(89, 113);
this._Label6_1.Location = new System.Drawing.Point(112, 76);
this._Label6_1.TabIndex = 9;
this._Label6_1.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._Label6_1.Enabled = true;
this._Label6_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._Label6_1.Cursor = System.Windows.Forms.Cursors.Default;
this._Label6_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Label6_1.UseMnemonic = true;
this._Label6_1.Visible = true;
this._Label6_1.AutoSize = false;
this._Label6_1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._Label6_1.Name = "_Label6_1";
this._Label6_0.BackColor = System.Drawing.Color.FromArgb(255, 255, 192);
this._Label6_0.Size = new System.Drawing.Size(89, 113);
this._Label6_0.Location = new System.Drawing.Point(16, 76);
this._Label6_0.TabIndex = 8;
this._Label6_0.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._Label6_0.Enabled = true;
this._Label6_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._Label6_0.Cursor = System.Windows.Forms.Cursors.Default;
this._Label6_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Label6_0.UseMnemonic = true;
this._Label6_0.Visible = true;
this._Label6_0.AutoSize = false;
this._Label6_0.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._Label6_0.Name = "_Label6_0";
this.Label2.Text = "Events";
this.Label2.Font = new System.Drawing.Font("Arial", 9.75f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.Label2.Size = new System.Drawing.Size(41, 16);
this.Label2.Location = new System.Drawing.Point(248, 200);
this.Label2.TabIndex = 4;
this.Label2.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.Label2.BackColor = System.Drawing.SystemColors.Control;
this.Label2.Enabled = true;
this.Label2.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label2.Cursor = System.Windows.Forms.Cursors.Default;
this.Label2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label2.UseMnemonic = true;
this.Label2.Visible = true;
this.Label2.AutoSize = true;
this.Label2.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.Label2.Name = "Label2";
this.lblEvents.Font = new System.Drawing.Font("Arial", 9.75f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.lblEvents.Size = new System.Drawing.Size(145, 25);
this.lblEvents.Location = new System.Drawing.Point(248, 216);
this.lblEvents.TabIndex = 3;
this.lblEvents.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.lblEvents.BackColor = System.Drawing.SystemColors.Control;
this.lblEvents.Enabled = true;
this.lblEvents.ForeColor = System.Drawing.SystemColors.ControlText;
this.lblEvents.Cursor = System.Windows.Forms.Cursors.Default;
this.lblEvents.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblEvents.UseMnemonic = true;
this.lblEvents.Visible = true;
this.lblEvents.AutoSize = false;
this.lblEvents.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lblEvents.Name = "lblEvents";
this.Label1.Text = "Quality";
this.Label1.Font = new System.Drawing.Font("Arial", 9.75f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.Label1.Size = new System.Drawing.Size(42, 16);
this.Label1.Location = new System.Drawing.Point(16, 200);
this.Label1.TabIndex = 2;
this.Label1.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.Label1.BackColor = System.Drawing.SystemColors.Control;
this.Label1.Enabled = true;
this.Label1.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label1.Cursor = System.Windows.Forms.Cursors.Default;
this.Label1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label1.UseMnemonic = true;
this.Label1.Visible = true;
this.Label1.AutoSize = true;
this.Label1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.Label1.Name = "Label1";
this.lblQuality.Font = new System.Drawing.Font("Arial", 9.75f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.lblQuality.Size = new System.Drawing.Size(137, 25);
this.lblQuality.Location = new System.Drawing.Point(16, 216);
this.lblQuality.TabIndex = 1;
this.lblQuality.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.lblQuality.BackColor = System.Drawing.SystemColors.Control;
this.lblQuality.Enabled = true;
this.lblQuality.ForeColor = System.Drawing.SystemColors.ControlText;
this.lblQuality.Cursor = System.Windows.Forms.Cursors.Default;
this.lblQuality.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblQuality.UseMnemonic = true;
this.lblQuality.Visible = true;
this.lblQuality.AutoSize = false;
this.lblQuality.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lblQuality.Name = "lblQuality";
this.Controls.Add(picButtons);
this.Controls.Add(Command1);
this.Controls.Add(eName);
this.Controls.Add(start_cmd);
this.Controls.Add(_picSample_3);
this.Controls.Add(_picSample_2);
this.Controls.Add(_picSample_1);
this.Controls.Add(_picSample_0);
this.Controls.Add(_Label6_3);
this.Controls.Add(_Label6_2);
this.Controls.Add(_Label6_1);
this.Controls.Add(_Label6_0);
this.Controls.Add(Label2);
this.Controls.Add(lblEvents);
this.Controls.Add(Label1);
this.Controls.Add(lblQuality);
this.picButtons.Controls.Add(cmdExit);
this.picButtons.Controls.Add(Label3);
//Me.Label6.SetIndex(_Label6_3, CType(3, Short))
//Me.Label6.SetIndex(_Label6_2, CType(2, Short))
//Me.Label6.SetIndex(_Label6_1, CType(1, Short))
//Me.Label6.SetIndex(_Label6_0, CType(0, Short))
//Me.picSample.SetIndex(_picSample_3, CType(3, Short))
//Me.picSample.SetIndex(_picSample_2, CType(2, Short))
//Me.picSample.SetIndex(_picSample_1, CType(1, Short))
//Me.picSample.SetIndex(_picSample_0, CType(0, Short))
//CType(Me.picSample, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.Label6, System.ComponentModel.ISupportInitialize).EndInit()
this.picButtons.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
| |
using System;
using BACnet.Types;
using BACnet.Types.Schemas;
namespace BACnet.Ashrae
{
public abstract partial class ExtendedParameter
{
public abstract Tags Tag { get; }
public bool IsNull { get { return this.Tag == Tags.Null; } }
public Null AsNull { get { return ((NullWrapper)this).Item; } }
public static ExtendedParameter NewNull(Null @null)
{
return new NullWrapper(@null);
}
public bool IsReal { get { return this.Tag == Tags.Real; } }
public float AsReal { get { return ((RealWrapper)this).Item; } }
public static ExtendedParameter NewReal(float real)
{
return new RealWrapper(real);
}
public bool IsInteger { get { return this.Tag == Tags.Integer; } }
public uint AsInteger { get { return ((IntegerWrapper)this).Item; } }
public static ExtendedParameter NewInteger(uint integer)
{
return new IntegerWrapper(integer);
}
public bool IsBoolean { get { return this.Tag == Tags.Boolean; } }
public bool AsBoolean { get { return ((BooleanWrapper)this).Item; } }
public static ExtendedParameter NewBoolean(bool boolean)
{
return new BooleanWrapper(boolean);
}
public bool IsDouble { get { return this.Tag == Tags.Double; } }
public double AsDouble { get { return ((DoubleWrapper)this).Item; } }
public static ExtendedParameter NewDouble(double @double)
{
return new DoubleWrapper(@double);
}
public bool IsOctet { get { return this.Tag == Tags.Octet; } }
public byte[] AsOctet { get { return ((OctetWrapper)this).Item; } }
public static ExtendedParameter NewOctet(byte[] octet)
{
return new OctetWrapper(octet);
}
public bool IsBitstring { get { return this.Tag == Tags.Bitstring; } }
public BitString56 AsBitstring { get { return ((BitstringWrapper)this).Item; } }
public static ExtendedParameter NewBitstring(BitString56 bitstring)
{
return new BitstringWrapper(bitstring);
}
public bool IsEnum { get { return this.Tag == Tags.Enum; } }
public Enumerated AsEnum { get { return ((EnumWrapper)this).Item; } }
public static ExtendedParameter NewEnum(Enumerated @enum)
{
return new EnumWrapper(@enum);
}
public bool IsReference { get { return this.Tag == Tags.Reference; } }
public DeviceObjectPropertyReference AsReference { get { return ((ReferenceWrapper)this).Item; } }
public static ExtendedParameter NewReference(DeviceObjectPropertyReference reference)
{
return new ReferenceWrapper(reference);
}
public static readonly ISchema Schema = new ChoiceSchema(false,
new FieldSchema("Null", 255, Value<Null>.Schema),
new FieldSchema("Real", 255, Value<float>.Schema),
new FieldSchema("Integer", 255, Value<uint>.Schema),
new FieldSchema("Boolean", 255, Value<bool>.Schema),
new FieldSchema("Double", 255, Value<double>.Schema),
new FieldSchema("Octet", 255, Value<byte[]>.Schema),
new FieldSchema("Bitstring", 255, Value<BitString56>.Schema),
new FieldSchema("Enum", 255, Value<Enumerated>.Schema),
new FieldSchema("Reference", 0, Value<DeviceObjectPropertyReference>.Schema));
public static ExtendedParameter Load(IValueStream stream)
{
ExtendedParameter ret = null;
Tags tag = (Tags)stream.EnterChoice();
switch(tag)
{
case Tags.Null:
ret = Value<NullWrapper>.Load(stream);
break;
case Tags.Real:
ret = Value<RealWrapper>.Load(stream);
break;
case Tags.Integer:
ret = Value<IntegerWrapper>.Load(stream);
break;
case Tags.Boolean:
ret = Value<BooleanWrapper>.Load(stream);
break;
case Tags.Double:
ret = Value<DoubleWrapper>.Load(stream);
break;
case Tags.Octet:
ret = Value<OctetWrapper>.Load(stream);
break;
case Tags.Bitstring:
ret = Value<BitstringWrapper>.Load(stream);
break;
case Tags.Enum:
ret = Value<EnumWrapper>.Load(stream);
break;
case Tags.Reference:
ret = Value<ReferenceWrapper>.Load(stream);
break;
default:
throw new Exception();
}
stream.LeaveChoice();
return ret;
}
public static void Save(IValueSink sink, ExtendedParameter value)
{
sink.EnterChoice((byte)value.Tag);
switch(value.Tag)
{
case Tags.Null:
Value<NullWrapper>.Save(sink, (NullWrapper)value);
break;
case Tags.Real:
Value<RealWrapper>.Save(sink, (RealWrapper)value);
break;
case Tags.Integer:
Value<IntegerWrapper>.Save(sink, (IntegerWrapper)value);
break;
case Tags.Boolean:
Value<BooleanWrapper>.Save(sink, (BooleanWrapper)value);
break;
case Tags.Double:
Value<DoubleWrapper>.Save(sink, (DoubleWrapper)value);
break;
case Tags.Octet:
Value<OctetWrapper>.Save(sink, (OctetWrapper)value);
break;
case Tags.Bitstring:
Value<BitstringWrapper>.Save(sink, (BitstringWrapper)value);
break;
case Tags.Enum:
Value<EnumWrapper>.Save(sink, (EnumWrapper)value);
break;
case Tags.Reference:
Value<ReferenceWrapper>.Save(sink, (ReferenceWrapper)value);
break;
default:
throw new Exception();
}
sink.LeaveChoice();
}
public enum Tags : byte
{
Null = 0,
Real = 1,
Integer = 2,
Boolean = 3,
Double = 4,
Octet = 5,
Bitstring = 6,
Enum = 7,
Reference = 8
}
public partial class NullWrapper : ExtendedParameter
{
public override Tags Tag { get { return Tags.Null; } }
public Null Item { get; private set; }
public NullWrapper(Null item)
{
this.Item = item;
}
public static readonly new ISchema Schema = Value<Null>.Schema;
public static new NullWrapper Load(IValueStream stream)
{
var temp = Value<Null>.Load(stream);
return new NullWrapper(temp);
}
public static void Save(IValueSink sink, NullWrapper value)
{
Value<Null>.Save(sink, value.Item);
}
}
public partial class RealWrapper : ExtendedParameter
{
public override Tags Tag { get { return Tags.Real; } }
public float Item { get; private set; }
public RealWrapper(float item)
{
this.Item = item;
}
public static readonly new ISchema Schema = Value<float>.Schema;
public static new RealWrapper Load(IValueStream stream)
{
var temp = Value<float>.Load(stream);
return new RealWrapper(temp);
}
public static void Save(IValueSink sink, RealWrapper value)
{
Value<float>.Save(sink, value.Item);
}
}
public partial class IntegerWrapper : ExtendedParameter
{
public override Tags Tag { get { return Tags.Integer; } }
public uint Item { get; private set; }
public IntegerWrapper(uint item)
{
this.Item = item;
}
public static readonly new ISchema Schema = Value<uint>.Schema;
public static new IntegerWrapper Load(IValueStream stream)
{
var temp = Value<uint>.Load(stream);
return new IntegerWrapper(temp);
}
public static void Save(IValueSink sink, IntegerWrapper value)
{
Value<uint>.Save(sink, value.Item);
}
}
public partial class BooleanWrapper : ExtendedParameter
{
public override Tags Tag { get { return Tags.Boolean; } }
public bool Item { get; private set; }
public BooleanWrapper(bool item)
{
this.Item = item;
}
public static readonly new ISchema Schema = Value<bool>.Schema;
public static new BooleanWrapper Load(IValueStream stream)
{
var temp = Value<bool>.Load(stream);
return new BooleanWrapper(temp);
}
public static void Save(IValueSink sink, BooleanWrapper value)
{
Value<bool>.Save(sink, value.Item);
}
}
public partial class DoubleWrapper : ExtendedParameter
{
public override Tags Tag { get { return Tags.Double; } }
public double Item { get; private set; }
public DoubleWrapper(double item)
{
this.Item = item;
}
public static readonly new ISchema Schema = Value<double>.Schema;
public static new DoubleWrapper Load(IValueStream stream)
{
var temp = Value<double>.Load(stream);
return new DoubleWrapper(temp);
}
public static void Save(IValueSink sink, DoubleWrapper value)
{
Value<double>.Save(sink, value.Item);
}
}
public partial class OctetWrapper : ExtendedParameter
{
public override Tags Tag { get { return Tags.Octet; } }
public byte[] Item { get; private set; }
public OctetWrapper(byte[] item)
{
this.Item = item;
}
public static readonly new ISchema Schema = Value<byte[]>.Schema;
public static new OctetWrapper Load(IValueStream stream)
{
var temp = Value<byte[]>.Load(stream);
return new OctetWrapper(temp);
}
public static void Save(IValueSink sink, OctetWrapper value)
{
Value<byte[]>.Save(sink, value.Item);
}
}
public partial class BitstringWrapper : ExtendedParameter
{
public override Tags Tag { get { return Tags.Bitstring; } }
public BitString56 Item { get; private set; }
public BitstringWrapper(BitString56 item)
{
this.Item = item;
}
public static readonly new ISchema Schema = Value<BitString56>.Schema;
public static new BitstringWrapper Load(IValueStream stream)
{
var temp = Value<BitString56>.Load(stream);
return new BitstringWrapper(temp);
}
public static void Save(IValueSink sink, BitstringWrapper value)
{
Value<BitString56>.Save(sink, value.Item);
}
}
public partial class EnumWrapper : ExtendedParameter
{
public override Tags Tag { get { return Tags.Enum; } }
public Enumerated Item { get; private set; }
public EnumWrapper(Enumerated item)
{
this.Item = item;
}
public static readonly new ISchema Schema = Value<Enumerated>.Schema;
public static new EnumWrapper Load(IValueStream stream)
{
var temp = Value<Enumerated>.Load(stream);
return new EnumWrapper(temp);
}
public static void Save(IValueSink sink, EnumWrapper value)
{
Value<Enumerated>.Save(sink, value.Item);
}
}
public partial class ReferenceWrapper : ExtendedParameter
{
public override Tags Tag { get { return Tags.Reference; } }
public DeviceObjectPropertyReference Item { get; private set; }
public ReferenceWrapper(DeviceObjectPropertyReference item)
{
this.Item = item;
}
public static readonly new ISchema Schema = Value<DeviceObjectPropertyReference>.Schema;
public static new ReferenceWrapper Load(IValueStream stream)
{
var temp = Value<DeviceObjectPropertyReference>.Load(stream);
return new ReferenceWrapper(temp);
}
public static void Save(IValueSink sink, ReferenceWrapper value)
{
Value<DeviceObjectPropertyReference>.Save(sink, value.Item);
}
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// 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.Diagnostics.Contracts;
namespace System.Xml.Schema
{
// Summary:
// An in-memory representation of an XML Schema as specified in the World Wide
// Web Consortium (W3C) XML Schema Part 1: Structures and XML Schema Part 2:
// Datatypes specifications.
//// [XmlRoot("schema", Namespace = "http://www.w3.org/2001/XMLSchema")]
public class XmlSchema
{
#if SILVERLIGHT
private
#else
public
#endif
XmlSchema() { }
#if !SILVERLIGHT
// Summary:
// The XML schema instance namespace. This field is constant.
public const string InstanceNamespace = "http://www.w3.org/2001/XMLSchema-instance";
//
// Summary:
// The XML schema namespace. This field is constant.
public const string Namespace = "http://www.w3.org/2001/XMLSchema";
#endif
// Summary:
// Initializes a new instance of the System.Xml.Schema.XmlSchema class.
//public XmlSchema();
// Summary:
// Gets or sets the form for attributes declared in the target namespace of
// the schema.
//
// Returns:
// The System.Xml.Schema.XmlSchemaForm value that indicates if attributes from
// the target namespace are required to be qualified with the namespace prefix.
// The default is System.Xml.Schema.XmlSchemaForm.None.
//// [XmlAttribute("attributeFormDefault")]
//public XmlSchemaForm AttributeFormDefault { get; set; }
//
// Summary:
// Gets the post-schema-compilation value of all the global attribute groups
// in the schema.
//
// Returns:
// An System.Xml.Schema.XmlSchemaObjectTable collection of all the global attribute
// groups in the schema.
// [XmlIgnore]
#if !SILVERLIGHT
public XmlSchemaObjectTable AttributeGroups
{
get
{
Contract.Ensures(Contract.Result<XmlSchemaObjectTable>() != null);
return default(XmlSchemaObjectTable);
}
}
#endif
//
// Summary:
// Gets the post-schema-compilation value for all the attributes in the schema.
//
// Returns:
// An System.Xml.Schema.XmlSchemaObjectTable collection of all the attributes
// in the schema.
// [XmlIgnore]
#if !SILVERLIGHT
public XmlSchemaObjectTable Attributes
{
get
{
Contract.Ensures(Contract.Result<XmlSchemaObjectTable>() != null);
return default(XmlSchemaObjectTable);
}
}
#endif
//
// Summary:
// Gets or sets the blockDefault attribute which sets the default value of the
// block attribute on element and complex types in the targetNamespace of the
// schema.
//
// Returns:
// An System.Xml.Schema.XmlSchemaDerivationMethod value representing the different
// methods for preventing derivation. The default value is XmlSchemaDerivationMethod.None.
// [XmlAttribute("blockDefault")]
//public XmlSchemaDerivationMethod BlockDefault { get; set; }
//
// Summary:
// Gets or sets the form for elements declared in the target namespace of the
// schema.
//
// Returns:
// The System.Xml.Schema.XmlSchemaForm value that indicates if elements from
// the target namespace are required to be qualified with the namespace prefix.
// The default is System.Xml.Schema.XmlSchemaForm.None.
// [XmlAttribute("elementFormDefault")]
//public XmlSchemaForm ElementFormDefault { get; set; }
//
// Summary:
// Gets the post-schema-compilation value for all the elements in the schema.
//
// Returns:
// An System.Xml.Schema.XmlSchemaObjectTable collection of all the elements
// in the schema.
// [XmlIgnore]
#if !SILVERLIGHT
public XmlSchemaObjectTable Elements
{
get
{
Contract.Ensures(Contract.Result<XmlSchemaObjectTable>() != null);
return default(XmlSchemaObjectTable);
}
}
#endif
//
// Summary:
// Gets or sets the finalDefault attribute which sets the default value of the
// final attribute on elements and complex types in the target namespace of
// the schema.
//
// Returns:
// An System.Xml.Schema.XmlSchemaDerivationMethod value representing the different
// methods for preventing derivation. The default value is XmlSchemaDerivationMethod.None.
// [XmlAttribute("finalDefault")]
//public XmlSchemaDerivationMethod FinalDefault { get; set; }
//
// Summary:
// Gets the post-schema-compilation value of all the groups in the schema.
//
// Returns:
// An System.Xml.Schema.XmlSchemaObjectTable collection of all the groups in
// the schema.
// [XmlIgnore]
//public XmlSchemaObjectTable Groups { get; }
//
// Summary:
// Gets or sets the string ID.
//
// Returns:
// The ID of the string. The default value is String.Empty.
// [XmlAttribute("id", DataType = "ID")]
//public string Id { get; set; }
//
// Summary:
// Gets the collection of included and imported schemas.
//
// Returns:
// An System.Xml.Schema.XmlSchemaObjectCollection of the included and imported
// schemas.
// [XmlElement("redefine", typeof(XmlSchemaRedefine))]
// [XmlElement("include", typeof(XmlSchemaInclude))]
// [XmlElement("import", typeof(XmlSchemaImport))]
//public XmlSchemaObjectCollection Includes { get; }
//
// Summary:
// Indicates if the schema has been compiled.
//
// Returns:
// true if schema has been compiled, otherwise, false. The default value is
// false.
// [XmlIgnore]
//public bool IsCompiled { get; }
//
// Summary:
// Gets the collection of schema elements in the schema and is used to add new
// element types at the schema element level.
//
// Returns:
// An System.Xml.Schema.XmlSchemaObjectCollection of schema elements in the
// schema.
// [XmlElement("notation", typeof(XmlSchemaNotation))]
// [XmlElement("group", typeof(XmlSchemaGroup))]
// [XmlElement("annotation", typeof(XmlSchemaAnnotation))]
// [XmlElement("attributeGroup", typeof(XmlSchemaAttributeGroup))]
// [XmlElement("attribute", typeof(XmlSchemaAttribute))]
// [XmlElement("complexType", typeof(XmlSchemaComplexType))]
// [XmlElement("simpleType", typeof(XmlSchemaSimpleType))]
// [XmlElement("element", typeof(XmlSchemaElement))]
#if !SILVERLIGHT
public XmlSchemaObjectCollection Items
{
get
{
Contract.Ensures(Contract.Result<XmlSchemaObjectCollection>() != null);
return default(XmlSchemaObjectCollection);
}
}
#endif
//
// Summary:
// Gets the post-schema-compilation value for all notations in the schema.
//
// Returns:
// An System.Xml.Schema.XmlSchemaObjectTable collection of all notations in
// the schema.
// [XmlIgnore]
//public XmlSchemaObjectTable Notations { get; }
//
// Summary:
// Gets the post-schema-compilation value of all schema types in the schema.
//
// Returns:
// An System.Xml.Schema.XmlSchemaObjectCollection of all schema types in the
// schema.
// [XmlIgnore]
#if !SILVERLIGHT
public XmlSchemaObjectTable SchemaTypes
{
get
{
Contract.Ensures(Contract.Result<XmlSchemaObjectTable>() != null);
return default(XmlSchemaObjectTable);
}
}
#endif
//
// Summary:
// Gets or sets the Uniform Resource Identifier (URI) of the schema target namespace.
//
// Returns:
// The schema target namespace.
// [XmlAttribute("targetNamespace", DataType = "anyURI")]
//public string TargetNamespace { get; set; }
//
// Summary:
// Gets and sets the qualified attributes which do not belong to the schema
// target namespace.
//
// Returns:
// An array of qualified System.Xml.XmlAttribute objects that do not belong
// to the schema target namespace.
// [XmlAnyAttribute]
//public XmlAttribute [] UnhandledAttributes { get; set; }
//
// Summary:
// Gets or sets the version of the schema.
//
// Returns:
// The version of the schema. The default value is String.Empty.
// [XmlAttribute("version", DataType = "token")]
//public string Version { get; set; }
// Summary:
// Compiles the XML Schema Object Model (SOM) into schema information for validation.
// Used to check the syntactic and semantic structure of the programmatically
// built SOM. Semantic validation checking is performed during compilation.
//
// Parameters:
// validationEventHandler:
// The validation event handler that receives information about XML Schema validation
// errors.
// [Obsolete("Use System.Xml.Schema.XmlSchemaSet for schema compilation and validation. http://go.microsoft.com/fwlink/?linkid=14202")]
//public void Compile(ValidationEventHandler validationEventHandler);
//
// Summary:
// Compiles the XML Schema Object Model (SOM) into schema information for validation.
// Used to check the syntactic and semantic structure of the programmatically
// built SOM. Semantic validation checking is performed during compilation.
//
// Parameters:
// validationEventHandler:
// The validation event handler that receives information about the XML Schema
// validation errors.
//
// resolver:
// The XmlResolver used to resolve namespaces referenced in include and import
// elements.
// [Obsolete("Use System.Xml.Schema.XmlSchemaSet for schema compilation and validation. http://go.microsoft.com/fwlink/?linkid=14202")]
//public void Compile(ValidationEventHandler validationEventHandler, XmlResolver resolver);
//
// Summary:
// Reads an XML Schema from the supplied stream.
//
// Parameters:
// stream:
// The supplied data stream.
//
// validationEventHandler:
// The validation event handler that receives information about XML Schema syntax
// errors.
//
// Returns:
// The System.Xml.Schema.XmlSchema object representing the XML Schema.
//
// Exceptions:
// System.Xml.Schema.XmlSchemaException:
// An System.Xml.Schema.XmlSchemaException is raised if no System.Xml.Schema.ValidationEventHandler
// is specified.
//public static XmlSchema Read(Stream stream, ValidationEventHandler validationEventHandler);
//
// Summary:
// Reads an XML Schema from the supplied System.IO.TextReader.
//
// Parameters:
// reader:
// The TextReader containing the XML Schema to read.
//
// validationEventHandler:
// The validation event handler that receives information about the XML Schema
// syntax errors.
//
// Returns:
// The System.Xml.Schema.XmlSchema object representing the XML Schema.
//
// Exceptions:
// System.Xml.Schema.XmlSchemaException:
// An System.Xml.Schema.XmlSchemaException is raised if no System.Xml.Schema.ValidationEventHandler
// is specified.
//public static XmlSchema Read(TextReader reader, ValidationEventHandler validationEventHandler);
//
// Summary:
// Reads an XML Schema from the supplied System.Xml.XmlReader.
//
// Parameters:
// reader:
// The XmlReader containing the XML Schema to read.
//
// validationEventHandler:
// The validation event handler that receives information about the XML Schema
// syntax errors.
//
// Returns:
// The System.Xml.Schema.XmlSchema object representing the XML Schema.
//
// Exceptions:
// System.Xml.Schema.XmlSchemaException:
// An System.Xml.Schema.XmlSchemaException is raised if no System.Xml.Schema.ValidationEventHandler
// is specified.
//public static XmlSchema Read(XmlReader reader, ValidationEventHandler validationEventHandler);
//
// Summary:
// Writes the XML Schema to the supplied data stream.
//
// Parameters:
// stream:
// The supplied data stream.
//public void Write(Stream stream);
//
// Summary:
// Writes the XML Schema to the supplied System.IO.TextWriter.
//
// Parameters:
// writer:
// The System.IO.TextWriter to write to.
//public void Write(TextWriter writer);
//
// Summary:
// Writes the XML Schema to the supplied System.Xml.XmlWriter.
//
// Parameters:
// writer:
// The System.Xml.XmlWriter to write to.
//
// Exceptions:
// System.ArgumentNullException:
// The writer parameter is null.
#if !SILVERLIGHT
public void Write(XmlWriter writer)
{
Contract.Requires(writer != null);
}
#endif
//
// Summary:
// Writes the XML Schema to the supplied System.IO.Stream using the System.Xml.XmlNamespaceManager
// specified.
//
// Parameters:
// stream:
// The supplied data stream.
//
// namespaceManager:
// The System.Xml.XmlNamespaceManager.
//public void Write(Stream stream, XmlNamespaceManager namespaceManager);
//
// Summary:
// Writes the XML Schema to the supplied System.IO.TextWriter.
//
// Parameters:
// writer:
// The System.IO.TextWriter to write to.
//
// namespaceManager:
// The System.Xml.XmlNamespaceManager.
//public void Write(TextWriter writer, XmlNamespaceManager namespaceManager);
//
// Summary:
// Writes the XML Schema to the supplied System.Xml.XmlWriter.
//
// Parameters:
// writer:
// The System.Xml.XmlWriter to write to.
//
// namespaceManager:
// The System.Xml.XmlNamespaceManager.
//public void Write(XmlWriter writer, XmlNamespaceManager namespaceManager);
}
}
| |
/*
Copyright (c) 2004-2006 Tomas Matousek.
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger distribution. By using this software
in any fashion, you are agreeing to be bound by the terms of this license.
You must not remove this notice from this software.
*/
using System;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Globalization;
using System.Collections;
using System.Reflection;
using System.Collections.Generic;
using PHP.Core;
using PHP.Core.Emit;
using PHP.Core.Reflection;
#if SILVERLIGHT
using PHP.CoreCLR;
#endif
namespace PHP.Core
{
#region Enumerations
public partial class PhpTypeCodeEnum
{
/// <summary>
/// Retrieves <see cref="Type"/> from a specified <see cref="PhpTypeCode"/>.
/// </summary>
public static Type ToType(PhpTypeCode code)
{
switch (code)
{
case PhpTypeCode.String: return Types.String[0];
case PhpTypeCode.Integer: return Types.Int[0];
case PhpTypeCode.LongInteger: return Types.LongInt[0];
case PhpTypeCode.Boolean: return Types.Bool[0];
case PhpTypeCode.Double: return Types.Double[0];
case PhpTypeCode.Object: return Types.Object[0];
case PhpTypeCode.PhpReference: return Types.PhpReference[0];
case PhpTypeCode.PhpArray: return Types.PhpArray[0];
case PhpTypeCode.DObject: return Types.DObject[0];
case PhpTypeCode.PhpResource: return typeof(PhpResource);
case PhpTypeCode.PhpBytes: return typeof(PhpBytes);
case PhpTypeCode.PhpString: return typeof(PhpString);
case PhpTypeCode.Void: return Types.Void;
default: return null;
}
}
/// <summary>
/// Retrieves <see cref="PhpTypeCode"/> from a specified <see cref="Type"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The code.</returns>
internal static PhpTypeCode FromType(Type type)
{
if (type == Types.Object[0]) return PhpTypeCode.Object;
if (type == Types.Double[0]) return PhpTypeCode.Double;
if (type == Types.Int[0]) return PhpTypeCode.Integer;
if (type == Types.LongInt[0]) return PhpTypeCode.LongInteger;
if (type == Types.String[0]) return PhpTypeCode.String;
if (type == Types.Bool[0]) return PhpTypeCode.Boolean;
if (type == Types.Void) return PhpTypeCode.Void;
if (type == typeof(PhpReference)) return PhpTypeCode.PhpReference;
if (type == Types.PhpArray[0]) return PhpTypeCode.PhpArray;
if (typeof(Reflection.DObject).IsAssignableFrom(type)) return PhpTypeCode.DObject;
if (type == typeof(PhpResource)) return PhpTypeCode.PhpResource;
if (type == typeof(PhpBytes)) return PhpTypeCode.PhpBytes;
if (type == typeof(PhpString)) return PhpTypeCode.PhpString;
Debug.Fail("GetCodeFromType used on a method with a return type unknown for Phalanger");
return PhpTypeCode.Invalid;
}
/// <summary>
/// Retrieves <see cref="PhpTypeCode"/> from a specified <paramref name="value"/> instance.
/// </summary>
internal static PhpTypeCode FromObject(object value)
{
if (value == null) return PhpTypeCode.Object;
return FromType(value.GetType());
}
/// <summary>
/// <c>True</c> iff given <paramref name="code"/> represents value that can be copied (is IPhpCloneable and implements some logic in Copy method).
/// </summary>
/// <param name="code"><see cref="PhpTypeCode"/>.</param>
/// <returns>Wheter given <paramref name="code"/> represents value that can be copied.</returns>
internal static bool IsDeeplyCopied(PhpTypeCode code)
{
return
code != PhpTypeCode.Void &&
code != PhpTypeCode.String &&
code != PhpTypeCode.Boolean &&
code != PhpTypeCode.Double &&
code != PhpTypeCode.Integer &&
code != PhpTypeCode.LongInteger &&
code != PhpTypeCode.PhpResource;
}
}
/// <summary>
/// Reason why a variable should be copied.
/// </summary>
public enum CopyReason
{
/// <summary>
/// Used when copied by operator =.
/// </summary>
Assigned,
/// <summary>
/// If <see cref="PhpDeepCopyAttribute"/> has been used on argument compiler generates deep-copy call
/// with this copy reason.
/// </summary>
PassedByCopy,
/// <summary>
/// If <see cref="PhpDeepCopyAttribute"/> has been used on return value compiler generates deep-copy call
/// with this copy reason.
/// </summary>
ReturnedByCopy,
/// <summary>
/// The reason is unknown.
/// </summary>
Unknown
}
#endregion
#region Interfaces: IPhpVariable, IPhpCloneable, IPhpPrintable, IPhpObjectGraphNode, IPhpEnumerator, IPhpEnumerable
/// <summary>
/// The set of interfaces which each type used in PHP language should implement.
/// </summary>
public interface IPhpVariable : IPhpConvertible, IPhpPrintable, IPhpCloneable, IPhpComparable
{
/// <summary>
/// Defines emptiness on implementor.
/// </summary>
/// <returns>Whether the variable is empty.</returns>
bool IsEmpty();
/// <summary>
/// Defines whether implementor is a scalar.
/// </summary>
/// <returns>Whether the variable is a scalar.</returns>
bool IsScalar();
/// <summary>
/// Defines a PHP name of implementor.
/// </summary>
/// <returns>The string identification of the type.</returns>
string GetTypeName();
}
/// <summary>
/// Supports cloning, which creates a deep copy of an existing instance.
/// </summary>
public interface IPhpCloneable
{
/// <summary>
/// Creates a deep copy of this instance.
/// </summary>
/// <returns>The deep copy of this instance.</returns>
object DeepCopy();
/// <summary>
/// Creates a copy of this instance.
/// </summary>
/// <param name="reason">The reason why the copy is being made.</param>
/// <returns>
/// The copy which should contain data independent of the image ones. This often means that a deep copy
/// is made, although an inplace deep copy optimization can also be used as well as other methods of copying.
/// Whatever copy method takes place any changes to the image data should not cause
/// a change in the result which may be identified by its user.
/// </returns>
object Copy(CopyReason reason);
}
/// <summary>
/// Provides methods for printing structured variable content in a several different formats.
/// </summary>
public interface IPhpPrintable
{
/// <summary>
/// Prints values only.
/// </summary>
/// <param name="output">The output stream.</param>
/// <remarks>Implementations should write an eoln after the variable's data.</remarks>
void Print(TextWriter output);
/// <summary>
/// Prints types and values.
/// </summary>
/// <param name="output">The output stream.</param>
/// <remarks>Implementations should write an eoln after the variable's data.</remarks>
void Dump(TextWriter output);
/// <summary>
/// Prints object's definition in PHP language.
/// </summary>
/// <param name="output">The output stream.</param>
/// <remarks>Implementations should write an eoln after the variable's data only on the top level.</remarks>
void Export(TextWriter output);
}
/// <summary>
/// Called back by <see cref="IPhpObjectGraphNode.Walk"/> when walking an object graph.
/// </summary>
/// <remarks>
/// The parameter represents the node that is being visited. Return value represents the new
/// node value that the original node will be replaced with in its container.
/// </remarks>
public delegate object PhpWalkCallback(IPhpObjectGraphNode node, ScriptContext context);
/// <summary>
/// Implemented by variable types that represent notable nodes in object graphs.
/// </summary>
public interface IPhpObjectGraphNode
{
/// <summary>
/// Walks the object graph rooted in this node. All subnodes supporting the <see cref="IPhpObjectGraphNode"/>
/// interface will be visited and <pararef name="callback"/> called.
/// </summary>
/// <param name="callback">Designates the method that should be invoked for each graph node.</param>
/// <param name="context">Current <see cref="ScriptContext"/> (optimization).</param>
/// <remarks><paramref name="callback"/> will not be called for this very object - that is its container's
/// responsibility.</remarks>
void Walk(PhpWalkCallback callback, ScriptContext context);
}
/// <summary>
/// Represents enumerator which
/// </summary>
public interface IPhpEnumerator : IDictionaryEnumerator
{
/// <summary>
/// Moves the enumerator to the last entry of the dictionary.
/// </summary>
/// <returns>Whether the enumerator has been sucessfully moved to the last entry.</returns>
bool MoveLast();
/// <summary>
/// Moves the enumerator to the first entry of the dictionary.
/// </summary>
/// <returns>Whether the enumerator has been sucessfully moved to the first entry.</returns>
bool MoveFirst();
/// <summary>
/// Moves the enumerator to the previous entry of the dictionary.
/// </summary>
/// <returns>Whether the enumerator has been sucessfully moved to the previous entry.</returns>
bool MovePrevious();
/// <summary>
/// Gets whether the enumeration has ended and the enumerator points behind the last element.
/// </summary>
bool AtEnd { get; }
}
/// <summary>
/// Provides methods which allows implementor to be used in PHP foreach statement as a source of enumeration.
/// </summary>
public interface IPhpEnumerable
{
/// <summary>
/// Implementor's intrinsic enumerator which will be advanced during enumeration.
/// </summary>
IPhpEnumerator IntrinsicEnumerator { get; }
/// <summary>
/// Creates an enumerator used in foreach statement.
/// </summary>
/// <param name="keyed">Whether the foreach statement uses keys.</param>
/// <param name="aliasedValues">Whether the values returned by enumerator are assigned by reference.</param>
/// <param name="caller">Type <see cref="Reflection.DTypeDesc"/> of the class in whose context the caller operates.</param>
/// <returns>The dictionary enumerator.</returns>
/// <remarks>
/// <see cref="IDictionaryEnumerator.Value"/> should return <see cref="PhpReference"/>
/// iff <paramref name="aliasedValues"/>.
/// </remarks>
[Emitted]
IDictionaryEnumerator GetForeachEnumerator(bool keyed, bool aliasedValues, Reflection.DTypeDesc caller);
}
#endregion
/// <summary>
/// Methods manipulating PHP variables.
/// </summary>
/// <remarks>
/// <para>Implements some IPhp* interfaces for objects of arbitrary PHP.NET type particularly for CLR types.</para>
/// </remarks>
[DebuggerNonUserCode]
public static class PhpVariable
{
public static readonly object LiteralNull = null;
public static readonly object LiteralTrue = true;
public static readonly object LiteralFalse = false;
public static readonly object LiteralIntSize = sizeof(int);
internal static readonly Type/*!*/ RTVariablesTableType = typeof(Dictionary<string, object>);
internal static readonly ConstructorInfo/*!*/ RTVariablesTableCtor = RTVariablesTableType.GetConstructor(Types.Int);
internal static readonly MethodInfo/*!*/ RTVariablesTableAdder = RTVariablesTableType.GetProperty("Item").GetSetMethod();//RTVariablesTableType.GetMethod("Add");
#region GlobalInfo
private class StaticInfo
{
/// <summary>
/// Auxiliary variable holding the current level of indentation while printing a variable.
/// </summary>
public int PrintIndentationLevel = 0;
public static StaticInfo Get
{
get
{
StaticInfo info;
var properties = ThreadStatic.Properties;
if (properties.TryGetProperty<StaticInfo>(out info) == false || info == null)
{
properties.SetProperty(info = new StaticInfo());
}
return info;
}
}
}
#endregion
#region IPhpPrintable
/// <summary>
/// Auxiliary variable holding the current level of indentation while printing a variable.
/// </summary>
internal static int PrintIndentationLevel
{
get { return StaticInfo.Get.PrintIndentationLevel; }
set { StaticInfo.Get.PrintIndentationLevel = value; }
}
/// <summary>
/// Writes indentation spaces to <see cref="TextWriter"/> according to <see cref="PrintIndentationLevel"/>.
/// </summary>
/// <param name="output">The <see cref="TextWriter"/> where to write spaces.</param>
internal static void PrintIndentation(TextWriter output)
{
var level = PrintIndentationLevel;
if (level > 0)
{
output.Write(' ');
output.Write(' ');
}
}
/// <summary>
/// Prints a content of the given variable.
/// </summary>
/// <param name="output">The output text stream.</param>
/// <param name="obj">The variable to be printed.</param>
/// <returns>Always returns true.</returns>
public static void Print(TextWriter output, object obj)
{
IPhpPrintable printable = obj as IPhpPrintable;
if (printable != null)
printable.Print(output);
else
output.Write(Convert.ObjectToString(obj));
}
/// <summary>
/// Prints the variable to the console.
/// </summary>
/// <param name="obj">The variable to print.</param>
public static void Print(object obj)
{
Print(Console.Out, obj);
}
/// <summary>
/// Prints a content of the given variable and its type.
/// </summary>
/// <param name="output">The output text stream.</param>
/// <param name="obj">The variable to be printed.</param>
public static void Dump(TextWriter output, object obj)
{
string s;
IPhpPrintable printable;
if ((printable = obj as IPhpPrintable) != null)
{
printable.Dump(output);
}
else if ((s = obj as string) != null)
{
output.WriteLine(TypeNameString + "({0}) \"{1}\"", s.Length, s);
}
else if (obj is double)
{
output.WriteLine(TypeNameFloat + "({0})", Convert.DoubleToString((double)obj));
}
else if (obj is bool)
{
output.WriteLine(TypeNameBool + "({0})", (bool)obj ? True : False);
}
else if (obj is int)
{
output.WriteLine(TypeNameInt + "({0})", (int)obj);
}
else if (obj is long)
{
output.WriteLine(TypeNameLongInteger + "({0})", (long)obj);
}
else if (obj == null)
{
output.WriteLine(PhpVariable.TypeNameNull);
}
else
{
output.WriteLine("{0}({1})", PhpVariable.GetTypeName(obj), obj.ToString());
}
}
/// <summary>
/// Dumps the variable to the console.
/// </summary>
/// <param name="obj">The variable to dump.</param>
public static void Dump(object obj)
{
Dump(Console.Out, obj);
}
/// <summary>
/// Prints a content of the given variable in PHP language.
/// </summary>
/// <param name="output">The output text stream.</param>
/// <param name="obj">The variable to be printed.</param>
public static void Export(TextWriter output, object obj)
{
IPhpPrintable printable;
string s;
if ((printable = obj as IPhpPrintable) != null)
{
printable.Export(output);
}
else if ((s = obj as string) != null)
{
output.Write("'{0}'", StringUtils.AddCSlashes(s, true, false));
}
else if (obj is int)
{
output.Write((int)obj);
}
else if (obj is long)
{
output.Write((long)obj);
}
else if (obj is double)
{
output.Write(Convert.DoubleToString((double)obj));
}
else if (obj is bool)
{
output.Write((bool)obj ? True : False);
}
else
{
output.Write(TypeNameNull);
}
// prints an eoln if we are on the top level:
//if (PrintIndentationLevel == 0)
// output.WriteLine();
}
/// <summary>
/// Exports the variable to the console.
/// </summary>
/// <param name="obj">The variable to export.</param>
public static void Export(object obj)
{
Export(Console.Out, obj);
}
#endregion
#region IPhpCloneable Interface
/// <summary>
/// Creates a deep copy of specified PHP variable.
/// </summary>
/// <param name="obj">The variable to copy.</param>
/// <returns>
/// A deep copy of <paramref name="obj"/> if it is of arbitrary PHP.NET type or
/// implements <see cref="IPhpCloneable"/> interface. Otherwise, only a shallow copy can be made.
/// </returns>
public static object DeepCopy(object obj)
{
// cloneable types:
IPhpCloneable php_cloneable;
if ((php_cloneable = obj as IPhpCloneable) != null)
return php_cloneable.DeepCopy();
// string, bool, int, double, null:
return obj;
}
/// <summary>
/// Depending on the copy reason and configuration, makes
/// inplace copy, shallow copy, or a deep copy of a specified PHP variable.
/// </summary>
[Emitted]
public static object Copy(object obj, CopyReason reason)
{
// cloneable types:
IPhpCloneable php_cloneable;
if ((php_cloneable = obj as IPhpCloneable) != null)
return php_cloneable.Copy(reason);
// string, bool, int, double, null:
return obj;
}
public static IEnumerable<KeyValuePair<K, object>>/*!*/ EnumerateDeepCopies<K>(
IEnumerable<KeyValuePair<K, object>>/*!*/ enumerable)
{
if (enumerable == null)
throw new ArgumentNullException("enumerable");
foreach (KeyValuePair<K, object> entry in enumerable)
yield return new KeyValuePair<K, object>(entry.Key, DeepCopy(entry.Value));
}
public static IEnumerable<object>/*!*/ EnumerateDeepCopies<K>(IEnumerable<object>/*!*/ enumerable)
{
if (enumerable == null)
throw new ArgumentNullException("enumerable");
foreach (object item in enumerable)
yield return DeepCopy(item);
}
#endregion
#region IPhpVariable Interface: GetTypeName, IsEmpty, IsScalar
/// <summary>
/// Implements empty language construct.
/// </summary>
/// <param name="obj">The variable.</param>
/// <returns>Whether the variable is empty according to PHP rules.</returns>
/// <remarks>
/// A variable is considered to be empty if it is undefined, <b>null</b>, 0, 0.0, <b>false</b>, "0",
/// empty string or empty string of bytes, object without properties,
/// </remarks>
/// <exception cref="InvalidCastException">If <paramref name="obj"/> is not of PHP.NET type.</exception>
[Emitted]
public static bool IsEmpty(object obj)
{
if (obj == null) return true;
if (obj.GetType() == typeof(int)) return (int)obj == 0;
if (obj.GetType() == typeof(string)) return !Convert.StringToBoolean((string)obj);
if (obj.GetType() == typeof(bool)) return !(bool)obj;
if (obj.GetType() == typeof(double)) return (double)obj == 0.0;
if (obj.GetType() == typeof(long)) return (long)obj == 0;
Debug.Assert(obj is IPhpVariable, "Object should be wrapped when calling IsEmpty");
return ((IPhpVariable)obj).IsEmpty();
}
/// <summary>
/// Checks whether a specified object is of scalar type.
/// </summary>
/// <param name="obj">The variable.</param>
/// <returns>Whether <paramref name="obj"/> is either <see cref="int"/>, <see cref="double"/>,
/// <see cref="bool"/>, <see cref="long"/>, <see cref="string"/> or <see cref="IPhpVariable.IsScalar"/>.</returns>
public static bool IsScalar(object obj)
{
if (obj == null)
return false;
if (obj.GetType() == typeof(int) ||
obj.GetType() == typeof(double) ||
obj.GetType() == typeof(bool) ||
obj.GetType() == typeof(long) ||
obj.GetType() == typeof(string) ||
obj.GetType() == typeof(PhpString) || // handled also in IPhpVariable, but this is faster
obj.GetType() == typeof(PhpBytes) // handled also in IPhpVariable, but this is faster
)
return true;
IPhpVariable php_var = obj as IPhpVariable;
if (php_var != null) return php_var.IsScalar();
return false;
}
#endregion
#region Types
/// <summary>
/// PHP name for <see cref="int"/>.
/// </summary>
public const string TypeNameInt = "int";
public const string TypeNameInteger = "integer";
/// <summary>
/// PHP name for <see cref="long"/>.
/// </summary>
public const string TypeNameLongInteger = "int64";
/// <summary>
/// PHP name for <see cref="double"/>.
/// </summary>
public const string TypeNameDouble = "double";
public const string TypeNameFloat = "float";
/// <summary>
/// PHP name for <see cref="bool"/>.
/// </summary>
public const string TypeNameBool = "bool";
public const string TypeNameBoolean = "boolean";
/// <summary>
/// PHP name for <see cref="string"/>.
/// </summary>
public const string TypeNameString = "string";
/// <summary>
/// PHP name for <see cref="System.Void"/>.
/// </summary>
public const string TypeNameVoid = "void";
/// <summary>
/// PHP name for <see cref="System.Object"/>.
/// </summary>
public const string TypeNameObject = "mixed";
/// <summary>
/// PHP name for <B>null</B>.
/// </summary>
public const string TypeNameNull = "NULL";
/// <summary>
/// PHP name for <B>true</B> constant.
/// </summary>
public const string True = "true";
/// <summary>
/// PHP name for <B>true</B> constant.
/// </summary>
public const string False = "false";
/// <summary>
/// Gets the PHP name of a type of a specified object.
/// </summary>
/// <param name="obj">The object which type name to get.</param>
/// <returns>The PHP name of the type of <paramref name="obj"/>.</returns>
/// <remarks>Returns CLR type name for variables of unknown type.</remarks>
public static string GetTypeName(object obj)
{
IPhpVariable php_var;
if (obj is int) return TypeNameInteger;
else if (obj is double) return TypeNameDouble;
else if (obj is bool) return TypeNameBoolean;
else if (obj is string) return TypeNameString;
else if (obj is long) return TypeNameLongInteger;
else if ((php_var = obj as IPhpVariable) != null) return php_var.GetTypeName();
else if (obj == null) return TypeNameNull;
else return obj.GetType().Name;
}
/// <summary>
/// Gets the PHP name of a specified PHP non-primitive type.
/// </summary>
/// <param name="type">The PHP non-primitive type.</param>
/// <returns>The PHP name of the <paramref name="type"/>.</returns>
/// <remarks>Returns CLR type name for primitive types.</remarks>
/// <exception cref="ArgumentNullException"><paramref name="type"/> is a <B>null</B>.</exception>
public static string/*!*/ GetTypeName(Type/*!*/ type)
{
if (type == null)
throw new ArgumentNullException("type");
string result = PrimitiveTypeDesc.GetPrimitiveName(type);
if (result != null) return result;
if (type == typeof(void))
return TypeNameVoid;
if (type == typeof(PhpReference))
return PhpReference.PhpTypeName;
return type.Name;
}
/// <summary>
/// Determines whether a type of a specified variable is PHP/CLR primitive type.
/// Doesn't check for <c>object</c> primitive type as is is only a compiler construction.
/// </summary>
public static bool HasPrimitiveType(object variable)
{
return HasLiteralPrimitiveType(variable) || variable is PhpArray || variable is PhpResource;
}
/// <summary>
/// Determines whether a type of a specified variable is PHP/CLR primitive literal type.
/// </summary>
public static bool HasLiteralPrimitiveType(object variable)
{
return
variable == null ||
variable.GetType() == typeof(bool) ||
variable.GetType() == typeof(int) ||
variable.GetType() == typeof(double) ||
variable.GetType() == typeof(long) ||
IsString(variable);
}
public static bool IsPrimitiveType(Type/*!*/ type)
{
return IsLiteralPrimitiveType(type) || type == typeof(PhpArray) || type.IsSubclassOf(typeof(PhpResource));
}
/// <summary>
/// Checks whether the type is among Phalanger primitive ones.
/// </summary>
/// <param name="type">The type to be checked.</param>
/// <exception cref="NullReferenceException"><paramref name="type"/> is a <B>null</B> reference.</exception>
public static bool IsLiteralPrimitiveType(Type/*!*/ type)
{
return type == typeof(bool) || type == typeof(int) || type == typeof(double) || type == typeof(long)
|| IsStringType(type);
}
/// <summary>
/// Gets the PHP name of a specified PHP non-primitive type.
/// </summary>
/// <param name="type">The PHP non-primitive type.</param>
/// <returns>The PHP name of the <paramref name="type"/> or the type which can be assigned from its.</returns>
/// <remarks>Returns CLR type name for primitive types.</remarks>
/// <exception cref="NullReferenceException"><paramref name="type"/> is a <B>null</B> exception.</exception>
public static string GetAssignableTypeName(Type type)
{
if (type.IsAssignableFrom(typeof(PhpArray))) return PhpArray.PhpTypeName;
if (type.IsAssignableFrom(typeof(PhpObject))) return PhpObject.PhpTypeName;
if (type.IsAssignableFrom(typeof(PhpResource))) return PhpResource.PhpTypeName;
if (type.IsAssignableFrom(typeof(PhpReference))) return PhpReference.PhpTypeName;
if (type.IsAssignableFrom(typeof(PhpBytes))) return PhpBytes.PhpTypeName;
if (type.IsAssignableFrom(typeof(PhpString))) return PhpString.PhpTypeName;
return type.Name;
}
/// <summary>
/// Returns <see cref="PhpTypeCode"/> of specified object of arbitrary PHP.NET type.
/// </summary>
/// <param name="obj">The object of one of the PHP.NET Framework type.</param>
/// <returns>The <see cref="PhpTypeCode"/> of the <paramref name="obj"/></returns>
public static PhpTypeCode GetTypeCode(object obj)
{
IPhpConvertible conv;
if (obj == null) return PhpTypeCode.Object;
else if (obj.GetType() == typeof(int)) return PhpTypeCode.Integer;
else if (obj.GetType() == typeof(bool)) return PhpTypeCode.Boolean;
else if (obj.GetType() == typeof(double)) return PhpTypeCode.Double;
else if (obj.GetType() == typeof(string)) return PhpTypeCode.String;
else if (obj.GetType() == typeof(long)) return PhpTypeCode.LongInteger;
else if ((conv = obj as IPhpConvertible) != null) return conv.GetTypeCode();
else return PhpTypeCode.Invalid;
}
#endregion
#region AsString, IsString, AsBytes, Dereference, MakeReference, AsArray, Unwrap
/// <summary>
/// Casts or converts a specified variable representing a string in PHP into a string.
/// </summary>
/// <param name="variable">The variable.</param>
/// <returns>
/// The string representation of <paramref name="variable"/> or
/// a <B>null</B> reference if the variable doesn't represent PHP string.
/// </returns>
/// <remarks>
/// <para>
/// The method should be used by the Class Library functions instead of
/// <c>variable <B>as</B> <see cref="string"/></c>.
/// </para>
/// <para>
/// Converts only types which represents a string in PHP.
/// These are <see cref="string"/>, <see cref="PhpString"/>, and <see cref="PhpBytes"/>.
/// Types like <see cref="int"/>, <see cref="bool"/> are not converted.
/// </para>
/// </remarks>
[Emitted]
public static string AsString(object variable)
{
if (object.ReferenceEquals(variable, null))
return null;
if (variable.GetType() == typeof(string))
return (string)variable;
if (variable.GetType() == typeof(PhpString))
return ((PhpString)variable).ToString();
if (variable.GetType() == typeof(PhpBytes))
return ((PhpBytes)variable).ToString();
return null;
}
/// <summary>
/// Checks whether a variable represents a string in PHP.
/// </summary>
/// <param name="variable">The variable.</param>
/// <returns>Whether a variable represents PHP string.</returns>
/// <remarks>
/// The method should be used by the Class Library functions instead of
/// <c>variable <B>is</B> <see cref="string"/></c>.
/// </remarks>
[Emitted]
public static bool IsString(object variable)
{
if (variable == null)
return false;
return
variable.GetType() == typeof(string) ||
variable.GetType() == typeof(PhpBytes) ||
variable.GetType() == typeof(PhpString);
}
public static bool IsStringType(Type/*!*/ type)
{
return type == typeof(string) || type == typeof(PhpBytes) || type == typeof(PhpString);
}
/// <summary>
/// Casts or converts a specified variable into binary string.
/// The method should be used by the Class Library functions instead of
/// <c>variable <B>as</B> <see cref="PhpBytes"/></c>.
/// </summary>
/// <param name="variable">The variable.</param>
/// <returns>The binary representation of <paramref name="variable"/> or a <B>null</B> reference.</returns>
public static PhpBytes AsBytes(object variable)
{
if (variable == null)
return null;
if (variable.GetType() == typeof(PhpBytes))
return (PhpBytes)variable;
if (variable.GetType() == typeof(string))
return new PhpBytes((string)variable);
if (variable.GetType() == typeof(PhpString))
return ((PhpString)variable).ToPhpBytes();
return null;
}
/// <summary>
/// Dereferences a reference (if applicable).
/// </summary>
/// <returns></returns>
public static object Dereference(object variable)
{
if (variable != null)
{
if (variable.GetType() == typeof(PhpReference))
return ((PhpReference)variable).Value;
else if (variable.GetType() == typeof(PhpSmartReference))
return ((PhpSmartReference)variable).Value;
}
return variable;
}
/// <summary>
/// Dereferences a reference and returns the <see cref="PhpReference"/>.
/// </summary>
/// <param name="variable">The variable to dereference, receives the dereferenced value.</param>
/// <returns>The <paramref name="variable"/> as <see cref="PhpReference"/>.</returns>
public static PhpReference Dereference(ref object variable)
{
if (variable != null)
{
if (variable.GetType() == typeof(PhpReference))
{
var reference = (PhpReference)variable;
variable = reference.Value;
return reference;
}
else if (variable.GetType() == typeof(PhpSmartReference))
{
var reference = (PhpSmartReference)variable;
variable = reference.Value;
return reference;
}
}
return null;
}
/// <summary>
/// Boxes variable into a reference if it is not yet a reference.
/// </summary>
/// <param name="variable">The instance to box.</param>
/// <returns>The reference.</returns>
/// <remarks>
/// Note that there has to be no other CLR reference pointing to the <paramref name="variable"/>
/// if it is reachable from PHP. In a case there is such a reference a deep copy has to take place.
/// </remarks>
public static PhpReference MakeReference(object variable)
{
if (variable != null)
{
if (variable.GetType() == typeof(PhpReference))
return (PhpReference)variable;
else if (variable.GetType() == typeof(PhpSmartReference))
return (PhpSmartReference)variable;
}
return new PhpReference(variable);
}
/// <summary>
/// Unwraps a <see cref="Reflection.DObject"/>, <see cref="PhpBytes"/>, and <see cref="PhpString"/>
/// returning their real object.
/// </summary>
/// <param name="var">The object of a PHP type.</param>
/// <returns>The real <paramref name="var"/>'s value (free of PHP-specific types).</returns>
public static object Unwrap(object var)
{
if (object.ReferenceEquals(var, null))
return null;
Reflection.DObject dobj = var as Reflection.DObject;
if (dobj != null) return dobj.RealObject;
if (var.GetType() == typeof(PhpBytes))
return ((PhpBytes)var).Data;
if (var.GetType() == typeof(PhpString))
return ((PhpString)var).ToString();
return var;
}
#endregion
#region IsValidName
/// <summary>
/// Checks whether a string is "valid" PHP variable identifier.
/// </summary>
/// <param name="name">The variable name.</param>
/// <returns>
/// Whether <paramref name="name"/> is "valid" name of variable, i.e. [_[:alpha:]][_0-9[:alpha:]]*.
/// This doesn't say anything about whether a variable of such name can be used in PHP, e.g. <c>${0}</c> is ok.
/// </returns>
public static bool IsValidName(string name)
{
if (string.IsNullOrEmpty(name)) return false;
// first char:
if (!Char.IsLetter(name[0]) && name[0] != '_') return false;
// next chars:
for (int i = 1; i < name.Length; i++)
{
if (!Char.IsLetterOrDigit(name[i]) && name[i] != '_') return false;
}
return true;
}
#endregion
}
#region PhpArgument
/// <summary>
/// Methods used for checking arguments of Class Library functions.
/// </summary>
public sealed class PhpArgument
{
/// <summary>
/// Checks whether a target of callback argument can be invoked.
/// </summary>
/// <param name="callback">The callback to check.</param>
/// <param name="caller">The class context used to bind the callback function.</param>
/// <param name="argIndex">The index of argument starting from 1 or 0 if not applicable.</param>
/// <param name="argName">A name of the argument or <B>null</B> reference if not applicable.</param>
/// <param name="emptyAllowed">Whether an empty callback is allowed.</param>
/// <returns>Whether the callback can be bound to its target or it is empty and that is allowed.</returns>
/// <remarks>The callback is bound if it can be.</remarks>
public static bool CheckCallback(PhpCallback callback, DTypeDesc caller, string argName, int argIndex, bool emptyAllowed)
{
// error has already been reported by Convert.ObjectToCallback:
if (callback == PhpCallback.Invalid)
return false;
// callback is empty:
if (callback == null)
return emptyAllowed;
// callback is bindable:
if (callback.Bind(true, caller, null))
return true;
if (argName != null)
argName = String.Concat('\'', argName, '\'');
else
argName = "#" + argIndex;
PhpException.Throw(PhpError.Warning, CoreResources.GetString("noncallable_callback",
((IPhpConvertible)callback).ToString(), argName));
return false;
}
}
#endregion
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.Msagl.Core.DataStructures;
using Microsoft.Msagl.Core.Geometry;
using Microsoft.Msagl.Core.Geometry.Curves;
using Microsoft.Msagl.Core.Layout;
using Microsoft.Msagl.Core.Routing;
using Microsoft.Msagl.DebugHelpers;
using Microsoft.Msagl.Routing.ConstrainedDelaunayTriangulation;
namespace Microsoft.Msagl.Routing.Spline.Bundling {
/// <summary>
/// Wrapper for geometry graph with coinciding edges:
/// 'real' nodes stand for edge ends (source,target)
/// 'virtual' nodes stand for polyline control points
///
/// 'real' edges are original graph edges
/// 'virtual' edges are polyline segments
/// </summary>
internal class MetroGraphData {
internal Set<Station> Stations;
/// info on the edges passing through a couple
Dictionary<Tuple<Station, Station>, StationEdgeInfo> edgeInfoDictionary;
/// current ink
double ink;
/// Edges
List<Metroline> metrolines;
/// position -> (node)
internal Dictionary<Point, Station> PointToStations;
readonly EdgeGeometry[] regularEdges;
/// objects to check crossings and calculate distances
internal Intersections looseIntersections;
internal Intersections tightIntersections;
/// objects to check crossings and calculate distances
internal CdtIntersections cdtIntersections;
Dictionary<EdgeGeometry, Set<Polyline>> EdgeLooseEnterable { get; set; }
Dictionary<EdgeGeometry, Set<Polyline>> EdgeTightEnterable { get; set; }
internal Func<Port, Polyline> LoosePolylineOfPort;
/// <summary>
/// triangulation
/// </summary>
internal Cdt Cdt;
internal MetroGraphData(EdgeGeometry[] regularEdges,
RectangleNode<Polyline> looseTree, RectangleNode<Polyline> tightTree,
BundlingSettings bundlingSettings, Cdt cdt,
Dictionary<EdgeGeometry, Set<Polyline>> edgeLooseEnterable, Dictionary<EdgeGeometry, Set<Polyline>> edgeTightEnterable, Func<Port, Polyline> loosePolylineOfPort) {
//Debug.Assert(cdt != null);
this.regularEdges = regularEdges;
if (cdt != null)
Cdt = cdt;
else
Cdt = BundleRouter.CreateConstrainedDelaunayTriangulation(looseTree);
EdgeLooseEnterable = edgeLooseEnterable;
EdgeTightEnterable = edgeTightEnterable;
LoosePolylineOfPort = loosePolylineOfPort;
looseIntersections = new Intersections(this, bundlingSettings, looseTree, station => station.EnterableLoosePolylines);
tightIntersections = new Intersections(this, bundlingSettings, tightTree, station => station.EnterableTightPolylines);
cdtIntersections = new CdtIntersections(this, bundlingSettings);
Initialize(false);
}
internal double Ink {
get { return ink; }
}
internal EdgeGeometry[] Edges {
get { return regularEdges; }
}
internal IEnumerable<Station> VirtualNodes() {
return Stations.Where(s => !s.IsRealNode);
}
internal List<Metroline> Metrolines { get { return metrolines; } }
internal RectangleNode<Polyline> LooseTree { get { return looseIntersections.obstacleTree; } }
internal RectangleNode<Polyline> TightTree { get { return tightIntersections.obstacleTree; } }
internal IEnumerable<Tuple<Station, Station>> VirtualEdges() {
return edgeInfoDictionary.Keys;
}
/// <summary>
/// number of real edges passing the node
/// </summary>
internal int RealEdgeCount(Station node) {
return node.MetroNodeInfos.Count;
}
/// <summary>
/// number of real edges passing the edge uv
/// </summary>
internal int RealEdgeCount(Station u, Station v) {
var couple = u < v ? new Tuple<Station, Station>(u, v) : new Tuple<Station, Station>(v, u);
StationEdgeInfo cw;
if (edgeInfoDictionary.TryGetValue(couple, out cw))
return cw.Count;
return 0;
}
/// <summary>
/// real edges passing the node
/// </summary>
internal List<MetroNodeInfo> MetroNodeInfosOfNode(Station node) {
return node.MetroNodeInfos;
}
/// <summary>
/// real edges passing the edge uv
/// </summary>
internal StationEdgeInfo GetIjInfo(Station u, Station v) {
var couple = u < v ? new Tuple<Station, Station>(u, v) : new Tuple<Station, Station>(v, u);
return edgeInfoDictionary[couple];
}
/// <summary>
/// Move node to the specified position
/// </summary>
internal void MoveNode(Station node, Point newPosition) {
Point oldPosition = node.Position;
PointToStations.Remove(oldPosition);
PointToStations.Add(newPosition, node);
node.Position = newPosition;
//move curves
foreach (MetroNodeInfo metroNodeInfo in MetroNodeInfosOfNode(node))
metroNodeInfo.PolyPoint.Point = newPosition;
//update lengths
foreach (MetroNodeInfo e in MetroNodeInfosOfNode(node)) {
var metroLine = e.Metroline;
var prev = e.PolyPoint.Prev.Point;
var succ = e.PolyPoint.Next.Point;
metroLine.Length += (succ - newPosition).Length + (prev - newPosition).Length
- (succ - oldPosition).Length - (prev - oldPosition).Length;
}
//update ink
foreach (var adj in node.Neighbors) {
ink += (newPosition - adj.Position).Length - (oldPosition - adj.Position).Length;
}
//update neighbors order
SortNeighbors(node);
foreach (var adj in node.Neighbors)
SortNeighbors(adj);
}
internal double GetWidth(Station u, Station v, double edgeSeparation) {
var couple = u < v ? new Tuple<Station, Station>(u, v) : new Tuple<Station, Station>(v, u);
StationEdgeInfo cw;
if (edgeInfoDictionary.TryGetValue(couple, out cw))
return cw.Width + (cw.Count - 1) * edgeSeparation;
return 0;
}
internal double GetWidth(IEnumerable<Metroline> metrolines, double edgeSeparation) {
double width = 0;
foreach (var metroline in metrolines) {
width += metroline.Width;
}
int count = metrolines.Count();
width += count > 0 ? (count - 1) * edgeSeparation : 0;
Debug.Assert(ApproximateComparer.GreaterOrEqual(width, 0));
return width;
}
/// <summary>
/// Initialize data
/// </summary>
internal void Initialize() {
Initialize(true);
}
/// <summary>
/// Initialize data
/// </summary>
internal void Initialize(bool initTightTree) {
//TimeMeasurer.DebugOutput("bundle graph data initializing...");
SimplifyRegularEdges();
InitializeNodeData();
InitializeEdgeData();
InitializeVirtualGraph();
InitializeEdgeNodeInfo(initTightTree);
InitializeCdtInfo();
// Debug.Assert(looseIntersections.HubPositionsAreOK());
// Debug.Assert(tightIntersections.HubPositionsAreOK());
}
/// <summary>
/// remove self-cycles
/// </summary>
void SimplifyRegularEdges() {
foreach (var edge in regularEdges)
SimplifyRegularEdge(edge);
}
/// <summary>
/// change the polyline by removing cycles
/// </summary>
void SimplifyRegularEdge(EdgeGeometry edge) {
Polyline polyline = (Polyline)edge.Curve;
var stack = new Stack<Point>();
var seen = new Set<Point>();
for (var p = polyline.EndPoint; p != null; p = p.Prev) {
var v = p.Point;
if (seen.Contains(p.Point)) {
var pp = p.Next;
do {
var u = stack.Peek();
if (u != v) {
seen.Remove(u);
stack.Pop();
pp = pp.Next;
}
else
break;
} while (true);
pp.Prev = p.Prev;
pp.Prev.Next = pp;
}
else {
stack.Push(v);
seen.Insert(v);
}
}
}
void InitializeNodeData() {
Stations = new Set<Station>();
//create indexes
PointToStations = new Dictionary<Point, Station>();
int i = 0;
foreach (var edge in regularEdges) {
Polyline poly = (Polyline)edge.Curve;
i = ProcessPolylinePoints(i, poly);
}
}
int ProcessPolylinePoints(int i, Polyline poly) {
var pp = poly.StartPoint;
i = RegisterStation(i, pp, true);
for (pp = pp.Next; pp != poly.EndPoint; pp = pp.Next)
i = RegisterStation(i, pp, false);
i = RegisterStation(i, pp, true);
return i;
}
int RegisterStation(int i, PolylinePoint pp, bool isRealNode) {
if (!PointToStations.ContainsKey(pp.Point)) {
Station station;
PointToStations[pp.Point] = station = new Station(i++, isRealNode, pp.Point);
Stations.Insert(station);
}
else {
#if DEBUG && TEST_MSAGL
var s = PointToStations[pp.Point];
Debug.Assert(s.IsRealNode == isRealNode);
#endif
}
return i;
}
void InitializeEdgeData() {
metrolines = new List<Metroline>();
for (int i = 0; i < regularEdges.Length; i++) {
EdgeGeometry geomEdge=regularEdges[i];
InitEdgeData(geomEdge, i);
}
}
void InitEdgeData(EdgeGeometry geomEdge, int index) {
var metroEdge = new Metroline((Polyline)geomEdge.Curve, geomEdge.LineWidth, EdgeSourceAndTargetFunc(geomEdge), index);
metrolines.Add(metroEdge);
PointToStations[metroEdge.Polyline.Start].BoundaryCurve = geomEdge.SourcePort.Curve;
PointToStations[metroEdge.Polyline.End].BoundaryCurve = geomEdge.TargetPort.Curve;
}
internal Func<Tuple<Polyline, Polyline>> EdgeSourceAndTargetFunc(EdgeGeometry geomEdge) {
return
() =>
new Tuple<Polyline, Polyline>(LoosePolylineOfPort(geomEdge.SourcePort),
LoosePolylineOfPort(geomEdge.TargetPort));
}
/// <summary>
/// Initialize graph comprised of stations and their neighbors
/// </summary>
void InitializeVirtualGraph() {
Dictionary<Station, Set<Station>> neighbors = new Dictionary<Station, Set<Station>>();
foreach (var metroline in metrolines) {
Station u = PointToStations[metroline.Polyline.Start];
Station v;
for (var p = metroline.Polyline.StartPoint; p.Next != null; p = p.Next, u = v) {
v = PointToStations[p.Next.Point];
CollectionUtilities.AddToMap(neighbors, u, v);
CollectionUtilities.AddToMap(neighbors, v, u);
}
}
foreach (var s in Stations) {
s.Neighbors = neighbors[s].ToArray();
}
}
StationEdgeInfo GetUnorderedIjInfo(Station i, Station j) {
Debug.Assert(i != j);
return (i < j ? GetOrderedIjInfo(i, j) : GetOrderedIjInfo(j, i));
}
StationEdgeInfo GetOrderedIjInfo(Station i, Station j) {
Debug.Assert(i < j);
var couple = new Tuple<Station, Station>(i, j);
StationEdgeInfo cw;
if (edgeInfoDictionary.TryGetValue(couple, out cw))
return cw;
edgeInfoDictionary[couple] = cw = new StationEdgeInfo(i.Position, j.Position);
return cw;
}
void InitializeEdgeNodeInfo(bool initTightTree) {
edgeInfoDictionary = new Dictionary<Tuple<Station, Station>, StationEdgeInfo>();
InitMetroNodeInfos(initTightTree);
SortNeighbors();
InitEdgeIjInfos();
ink = 0;
foreach (var edge in VirtualEdges())
ink += (edge.Item1.Position - edge.Item2.Position).Length;
}
void InitMetroNodeInfos(bool initTightTree) {
for (int i = 0; i < metrolines.Count; i++) {
var metroline = metrolines[i];
InitMetroNodeInfos(metroline);
InitNodeEnterableLoosePolylines(metroline, regularEdges[i]);
if (initTightTree)
InitNodeEnterableTightPolylines(metroline, regularEdges[i]);
metroline.UpdateLengths();
}
}
void InitMetroNodeInfos(Metroline metroline) {
for (var pp = metroline.Polyline.StartPoint; pp != null; pp = pp.Next) {
Station station = PointToStations[pp.Point];
station.MetroNodeInfos.Add(new MetroNodeInfo(metroline, station, pp));
}
}
void InitNodeEnterableLoosePolylines(Metroline metroline, EdgeGeometry regularEdge) {
//If we have groups, EdgeLooseEnterable are precomputed.
var metrolineEnterable = EdgeLooseEnterable != null ? EdgeLooseEnterable[regularEdge] : new Set<Polyline>();
for (var p = metroline.Polyline.StartPoint.Next; p!=null && p.Next != null; p = p.Next) {
var v = PointToStations[p.Point];
if (v.EnterableLoosePolylines != null)
v.EnterableLoosePolylines *= metrolineEnterable;
else
v.EnterableLoosePolylines = new Set<Polyline>(metrolineEnterable);
}
AddLooseEnterableForMetrolineStartEndPoints(metroline);
}
void AddLooseEnterableForMetrolineStartEndPoints(Metroline metroline) {
AddLooseEnterableForEnd(metroline.Polyline.Start);
AddLooseEnterableForEnd(metroline.Polyline.End);
}
void AddTightEnterableForMetrolineStartEndPoints(Metroline metroline) {
AddTightEnterableForEnd(metroline.Polyline.Start);
AddTightEnterableForEnd(metroline.Polyline.End);
}
Dictionary<Point, Set<Polyline>> cachedEnterableLooseForEnd = new Dictionary<Point, Set<Polyline>>();
void AddLooseEnterableForEnd(Point point) {
Station station = PointToStations[point];
if (!cachedEnterableLooseForEnd.ContainsKey(point)) {
foreach (var poly in LooseTree.AllHitItems(point))
if (Curve.PointRelativeToCurveLocation(point, poly) == PointLocation.Inside)
station.AddEnterableLoosePolyline(poly);
cachedEnterableLooseForEnd.Add(point, station.EnterableLoosePolylines);
}
else {
station.EnterableLoosePolylines = cachedEnterableLooseForEnd[point];
}
//foreach (var poly in LooseTree.AllHitItems(point))
// if (Curve.PointRelativeToCurveLocation(point, poly) == PointLocation.Inside)
// station.EnterableLoosePolylines.Insert(poly);
}
void AddTightEnterableForEnd(Point point) {
Station station = PointToStations[point];
foreach (var poly in TightTree.AllHitItems(point))
if (Curve.PointRelativeToCurveLocation(point, poly) == PointLocation.Inside)
station.AddEnterableTightPolyline(poly);
}
void InitNodeEnterableTightPolylines(Metroline metroline, EdgeGeometry regularEdge) {
//If we have groups, EdgeTightEnterable are precomputed.
var metrolineEnterable = EdgeTightEnterable != null ? EdgeTightEnterable[regularEdge] : new Set<Polyline>();
for (var p = metroline.Polyline.StartPoint.Next; p!=null && p.Next != null; p = p.Next) {
var v = PointToStations[p.Point];
Set<Polyline> nodeEnterable = v.EnterableTightPolylines;
if (nodeEnterable != null)
v.EnterableTightPolylines = nodeEnterable * metrolineEnterable;
else
v.EnterableTightPolylines = new Set<Polyline>(metrolineEnterable);
}
AddTightEnterableForMetrolineStartEndPoints(metroline);
}
void SortNeighbors() {
//counter-clockwise sorting
foreach (var station in Stations)
SortNeighbors(station);
}
void SortNeighbors(Station station) {
//nothing to sort
if (station.Neighbors.Length <= 2) return;
Point pivot = station.Neighbors[0].Position;
Point center = station.Position;
Array.Sort(station.Neighbors, delegate(Station u, Station v) {
return Point.GetOrientationOf3Vectors(pivot - center, u.Position - center, v.Position - center);
});
}
void InitEdgeIjInfos() {
foreach (Metroline metroLine in metrolines) {
var poly = metroLine.Polyline;
var u = PointToStations[poly.Start];
Station v;
for (var p = metroLine.Polyline.StartPoint; p.Next != null; p = p.Next, u = v) {
v = PointToStations[p.Next.Point];
var info = GetUnorderedIjInfo(u, v);
info.Count++;
info.Width += metroLine.Width;
info.Metrolines.Add(metroLine);
}
}
}
void InitializeCdtInfo() {
RectangleNode<CdtTriangle> cdtTree = Cdt.GetCdtTree();
foreach (var station in Stations) {
station.CdtTriangle = cdtTree.FirstHitNode(station.Position, IntersectionCache.Test).UserData;
Debug.Assert(station.CdtTriangle != null);
}
}
internal bool PointIsAcceptableForEdge(Metroline metroline, Point point) {
if (LoosePolylineOfPort == null)
return true;
var polys = metroline.sourceAndTargetLoosePolylines();
return Curve.PointRelativeToCurveLocation(point, polys.Item1) == PointLocation.Outside &&
Curve.PointRelativeToCurveLocation(point, polys.Item2) == PointLocation.Outside;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="Configuration.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using ClassConfiguration = System.Configuration.Configuration;
using System.Collections;
using System.Configuration;
using System.Configuration.Internal;
using System.IO;
using System.Reflection;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using System.Runtime.Versioning;
namespace System.Configuration {
//
// An instance of the Configuration class represents a single level
// in the configuration hierarchy. Its contents can be edited and
// saved to disk.
//
// It is not thread safe for writing.
//
public sealed class Configuration {
private Type _typeConfigHost; // type of config host
private object[] _hostInitConfigurationParams; // params to init config host
private InternalConfigRoot _configRoot; // root of this configuration hierarchy
private MgmtConfigurationRecord _configRecord; // config record for this level in the hierarchy
private ConfigurationSectionGroup _rootSectionGroup; // section group for the root of all sections
private ConfigurationLocationCollection _locations; // support for ConfigurationLocationsCollection
private ContextInformation _evalContext; // evaluation context
private Func<string, string> _TypeStringTransformer = null;
private Func<string, string> _AssemblyStringTransformer = null;
private bool _TypeStringTransformerIsSet = false;
private bool _AssemblyStringTransformerIsSet = false;
private FrameworkName _TargetFramework = null;
private Stack _SectionsStack = null;
internal Configuration(string locationSubPath, Type typeConfigHost, params object[] hostInitConfigurationParams) {
_typeConfigHost = typeConfigHost;
_hostInitConfigurationParams = hostInitConfigurationParams;
_configRoot = new InternalConfigRoot(this);
IInternalConfigHost configHost = (IInternalConfigHost) TypeUtil.CreateInstanceWithReflectionPermission(typeConfigHost);
// Wrap the host with the UpdateConfigHost to support SaveAs.
IInternalConfigHost updateConfigHost = new UpdateConfigHost(configHost);
((IInternalConfigRoot)_configRoot).Init(updateConfigHost, true);
//
// Set the configuration paths for this Configuration.
// We do this in a separate step so that the WebConfigurationHost
// can use this object's _configRoot to get the <sites> section,
// which is used in it's MapPath implementation.
//
string configPath, locationConfigPath;
configHost.InitForConfiguration(ref locationSubPath, out configPath, out locationConfigPath, _configRoot, hostInitConfigurationParams);
if (!String.IsNullOrEmpty(locationSubPath) && !updateConfigHost.SupportsLocation) {
throw ExceptionUtil.UnexpectedError("Configuration::ctor");
}
if (String.IsNullOrEmpty(locationSubPath) != String.IsNullOrEmpty(locationConfigPath)) {
throw ExceptionUtil.UnexpectedError("Configuration::ctor");
}
// Get the configuration record for this config file.
_configRecord = (MgmtConfigurationRecord) _configRoot.GetConfigRecord(configPath);
//
// Create another MgmtConfigurationRecord for the location that is a child of the above record.
// Note that this does not match the resolution hiearchy that is used at runtime.
//
if (!String.IsNullOrEmpty(locationSubPath)) {
_configRecord = MgmtConfigurationRecord.Create(
_configRoot, _configRecord, locationConfigPath, locationSubPath);
}
//
// Throw if the config record we created contains global errors.
//
_configRecord.ThrowIfInitErrors();
}
//
// Create a new instance of Configuration for the locationSubPath,
// with the initialization parameters that were used to create this configuration.
//
internal Configuration OpenLocationConfiguration(string locationSubPath) {
return new Configuration(locationSubPath, _typeConfigHost, _hostInitConfigurationParams);
}
// public properties
public AppSettingsSection AppSettings {
get {
return (AppSettingsSection) GetSection("appSettings");
}
}
public ConnectionStringsSection ConnectionStrings {
get {
return (ConnectionStringsSection) GetSection("connectionStrings");
}
}
public string FilePath {
get {
return _configRecord.ConfigurationFilePath;
}
}
public bool HasFile {
get {
return _configRecord.HasStream;
}
}
public ConfigurationLocationCollection Locations {
get {
if (_locations == null) {
_locations = _configRecord.GetLocationCollection(this);
}
return _locations;
}
}
public ContextInformation EvaluationContext {
get {
if (_evalContext == null) {
_evalContext = new ContextInformation(_configRecord);
}
return _evalContext;
}
}
public ConfigurationSectionGroup RootSectionGroup {
get {
if (_rootSectionGroup == null) {
_rootSectionGroup = new ConfigurationSectionGroup();
_rootSectionGroup.RootAttachToConfigurationRecord(_configRecord);
}
return _rootSectionGroup;
}
}
public ConfigurationSectionCollection Sections {
get {
return RootSectionGroup.Sections;
}
}
public ConfigurationSectionGroupCollection SectionGroups {
get {
return RootSectionGroup.SectionGroups;
}
}
// public methods
public ConfigurationSection GetSection(string sectionName) {
ConfigurationSection section = (ConfigurationSection) _configRecord.GetSection(sectionName);
return section;
}
public ConfigurationSectionGroup GetSectionGroup(string sectionGroupName) {
ConfigurationSectionGroup sectionGroup = _configRecord.GetSectionGroup(sectionGroupName);
return sectionGroup;
}
// NamespaceDeclared
//
// Is the namespace declared in the file or not?
//
// ie. xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"
// (currently this is the only one we allow)
//
// get - Return if it was declared in the file.
// set - Set if we should save the namespace or not
//
public bool NamespaceDeclared {
get {
return _configRecord.NamespacePresent;
}
set {
_configRecord.NamespacePresent = value;
}
}
public void Save() {
SaveAsImpl(null, ConfigurationSaveMode.Modified, false);
}
public void Save(ConfigurationSaveMode saveMode) {
SaveAsImpl(null, saveMode, false);
}
public void Save(ConfigurationSaveMode saveMode, bool forceSaveAll) {
SaveAsImpl(null, saveMode, forceSaveAll);
}
public void SaveAs(string filename) {
SaveAs(filename, ConfigurationSaveMode.Modified, false);
}
public void SaveAs(string filename, ConfigurationSaveMode saveMode) {
SaveAs(filename, saveMode, false);
}
public void SaveAs(string filename, ConfigurationSaveMode saveMode, bool forceSaveAll) {
if (String.IsNullOrEmpty(filename)) {
throw ExceptionUtil.ParameterNullOrEmpty("filename");
}
SaveAsImpl(filename, saveMode, forceSaveAll);
}
private void SaveAsImpl(string filename, ConfigurationSaveMode saveMode, bool forceSaveAll) {
if (String.IsNullOrEmpty(filename)) {
filename = null;
}
else {
filename = System.IO.Path.GetFullPath(filename);
}
if (forceSaveAll) {
ForceGroupsRecursive(RootSectionGroup);
}
_configRecord.SaveAs(filename, saveMode, forceSaveAll);
}
// Force all sections and section groups to be instantiated.
private void ForceGroupsRecursive(ConfigurationSectionGroup group) {
foreach (ConfigurationSection configSection in group.Sections) {
// Force the section to be read into the cache
ConfigurationSection section = group.Sections[configSection.SectionInformation.Name];
}
foreach (ConfigurationSectionGroup sectionGroup in group.SectionGroups) {
ForceGroupsRecursive(group.SectionGroups[sectionGroup.Name]);
}
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
public System.Func<string, string> TypeStringTransformer {
get {
return _TypeStringTransformer;
}
[ConfigurationPermission(SecurityAction.Demand, Unrestricted=true)]
set {
if (_TypeStringTransformer != value) {
_TypeStringTransformerIsSet = (value != null);
_TypeStringTransformer = value;
}
}
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
public System.Func<string, string> AssemblyStringTransformer {
get {
return _AssemblyStringTransformer;
}
[ConfigurationPermission(SecurityAction.Demand, Unrestricted=true)]
set {
if (_AssemblyStringTransformer != value) {
_AssemblyStringTransformerIsSet = (value != null);
_AssemblyStringTransformer = value;
}
}
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
public FrameworkName TargetFramework {
get {
return _TargetFramework;
}
[ConfigurationPermission(SecurityAction.Demand, Unrestricted=true)]
set {
_TargetFramework = value;
}
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
internal bool TypeStringTransformerIsSet { get { return _TypeStringTransformerIsSet; }}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
internal bool AssemblyStringTransformerIsSet { get { return _AssemblyStringTransformerIsSet; }}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
internal Stack SectionsStack {
get {
if (_SectionsStack == null)
_SectionsStack = new Stack();
return _SectionsStack;
}
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Runtime.InteropServices;
namespace HWD.HWDKernel.CabinetFile
{
public class TCabinetFile : CollectionBase, IBindingList
{
/// <summary>
/// The FileCallback callback function is used by a number of the setup functions. The PSP_FILE_CALLBACK type defines a pointer to this callback function. FileCallback is a placeholder for the application-defined function name.
/// Platform SDK: Setup API
/// </summary>
private uint CallBack(uint context, uint notification, IntPtr param1, IntPtr param2)
{
uint rtnValue = SetupApiWrapper.NO_ERROR;
switch (notification)
{
case SetupApiWrapper.SPFILENOTIFY_FILEINCABINET:
rtnValue = OnFileFound(context, notification, param1, param2);
break;
case SetupApiWrapper.SPFILENOTIFY_FILEEXTRACTED:
rtnValue = OnFileExtractComplete(param1);
break;
case SetupApiWrapper.SPFILENOTIFY_NEEDNEWCABINET:
rtnValue = SetupApiWrapper.NO_ERROR;
break;
}
return rtnValue;
}
public TCabinetFile()
{
}
public TCabinetFile(string sCabFileName)
{
this.Name = sCabFileName;
}
/// <summary>
/// Cabinet file name
/// </summary>
private string m_Name = "";
public string Name
{
set
{
if (!System.IO.File.Exists(value))
throw new System.Exception("This CabFile doesn't exist");
PSP_FILE_CALLBACK callback = new PSP_FILE_CALLBACK(this.CallBack);
uint setupIterateCabinetAction = (uint)SetupIterateCabinetAction.Iterate;
if (!SetupApiWrapper.SetupIterateCabinet(value, 0, callback, setupIterateCabinetAction))
{
string errMsg = new Win32Exception((int)KernelApiWrapper.GetLastError()).Message;
System.Windows.Forms.MessageBox.Show(errMsg);
}
m_Name = value;
}
get { return m_Name;}
}
/// <summary>
/// output directory
/// </summary>
private string m_OutputDirectory = "";
public string OutputDirectory
{
set
{
if (!System.IO.Directory.Exists(value))
throw new System.Exception("The Output directory doesn't exist.");
m_OutputDirectory = value;
}
get
{
if (m_OutputDirectory.Length <=0 )
return System.IO.Directory.GetCurrentDirectory();
return m_OutputDirectory;
}
}
/// <summary>
/// if true, extract file without path in cabinet
/// </summary>
private bool m_IgnoreInsidePath = false;
public bool IgnoreInsidePath
{
set { m_IgnoreInsidePath = value;}
get { return m_IgnoreInsidePath;}
}
#region Events
private ListChangedEventHandler m_ListChanged;
public event ListChangedEventHandler ListChanged
{
add
{
m_ListChanged += value;
}
remove
{
m_ListChanged -= value;
}
}
private ListChangedEventArgs resetEvent = new ListChangedEventArgs(ListChangedType.Reset, -1);
private EventHandler m_FileFound;
public event EventHandler FileFound
{
add
{
m_FileFound += value;
}
remove
{
m_FileFound -= value;
}
}
private EventHandler m_FileExtractBefore;
public event EventHandler FileExtractBefore
{
add
{
m_FileExtractBefore += value;
}
remove
{
m_FileExtractBefore -= value;
}
}
private EventHandler m_FileExtractComplete;
public event EventHandler FileExtractComplete
{
add
{
m_FileExtractComplete += value;
}
remove
{
m_FileExtractComplete -= value;
}
}
#endregion
#region CollectionBase Method
public int Add(TFile item)
{
throw new NotSupportedException();
// return (List.Add(item));
}
public int IndexOf(TFile item)
{
return( List.IndexOf( item ) );
}
public void Insert(int index, TFile item)
{
throw new NotSupportedException();
// List.Insert(index, item);
}
public void Remove(TFile item)
{
throw new NotSupportedException();
// List.Remove(item);
}
public bool Contains(TFile item)
{
return( List.Contains( item ) );
}
public TFile this[int index]
{
get { return (TFile)List[index] ; }
set
{
throw new NotSupportedException();
// List[index] = value;
}
}
public override string ToString()
{
return this.Name;
}
public override int GetHashCode()
{
return (this.Count);
}
public override bool Equals(object obj)
{
if (obj==null) return false;
if (this.GetType() != obj.GetType()) return false;
TCabinetFile other = (TCabinetFile)obj;
return (string.Compare(this.Name, other.Name, true)==0);
}
public static bool operator ==(TCabinetFile a, TCabinetFile b)
{
if ((object)a == null) return false;
return a.Equals(b);
}
public static bool operator !=(TCabinetFile a, TCabinetFile b)
{
return !(a==b);
}
#endregion
protected virtual uint OnFileFound(uint context, uint notification, IntPtr param1, IntPtr param2)
{
uint fileOperation = SetupApiWrapper.NO_ERROR;
FILE_IN_CABINET_INFO fileInCabinetInfo = (FILE_IN_CABINET_INFO)Marshal.PtrToStructure(param1, typeof(FILE_IN_CABINET_INFO));
TFile file = new TFile(fileInCabinetInfo);
switch(context)
{
case (uint)SetupIterateCabinetAction.Iterate:
List.Add(file);
if (m_FileFound != null)
m_FileFound(file, System.EventArgs.Empty);
fileOperation = (uint)FILEOP.FILEOP_SKIP;
break;
case (uint)SetupIterateCabinetAction.Extract:
if (this.m_ExtractAll)
this.m_ExtractFileIndex = this.IndexOf(file);
fileOperation = OnFileExtractBefore(file);
if (fileOperation == (uint)FILEOP.FILEOP_DOIT)
{
fileInCabinetInfo.FullTargetName = MakeExtractFileName(file);
Marshal.StructureToPtr(fileInCabinetInfo, param1, true);
}
break;
}
return fileOperation;
}
protected virtual uint OnFileExtractBefore(TFile file)
{
bool cancel = false;
if (file != (TFile)this.List[m_ExtractFileIndex])
return (uint)FILEOP.FILEOP_SKIP;
if (m_FileExtractBefore != null)
{
System.ComponentModel.CancelEventArgs arg = new CancelEventArgs(false);
m_FileExtractBefore(file, arg);
cancel = arg.Cancel;
}
if (cancel)
return (uint)FILEOP.FILEOP_SKIP;
return (uint)FILEOP.FILEOP_DOIT;
}
protected virtual uint OnFileExtractComplete(IntPtr param1)
{
FILEPATHS filePaths =
(FILEPATHS)Marshal.PtrToStructure(param1, typeof(FILEPATHS));
if (m_FileExtractComplete != null && filePaths.Win32Error == SetupApiWrapper.NO_ERROR)
m_FileExtractComplete(filePaths.Target, System.EventArgs.Empty);
return filePaths.Win32Error;
}
#region Envent Handler for collection
protected virtual void OnListChanged(ListChangedEventArgs ev)
{
if (m_ListChanged != null)
m_ListChanged(this, ev);
}
protected override void OnClear()
{
throw new NotSupportedException();
// base.OnClear ();
}
protected override void OnClearComplete()
{
OnListChanged(resetEvent);
}
// protected override void OnInsert(int index, object value)
// {
// throw new NotSupportedException();
//// base.OnInsert (index, value);
// }
protected override void OnInsertComplete(int index, object value)
{
OnListChanged(new ListChangedEventArgs(ListChangedType.ItemAdded, index));
}
protected override void OnRemove(int index, object value)
{
throw new NotSupportedException();
// base.OnRemove (index, value);
}
protected override void OnRemoveComplete(int index, object value)
{
OnListChanged(new ListChangedEventArgs(ListChangedType.ItemDeleted, index));
}
protected override void OnSetComplete(int index, object oldValue, object newValue)
{
if(oldValue != newValue)
OnListChanged(new ListChangedEventArgs(ListChangedType.ItemAdded, index));
}
#endregion
#region IBindingList Implements
bool IBindingList.AllowEdit
{
get {return false;}
}
bool IBindingList.AllowNew
{
get {return false;}
}
bool IBindingList.AllowRemove
{
get {return false;}
}
bool IBindingList.SupportsChangeNotification
{
get {return true;}
}
bool IBindingList.SupportsSearching
{
get {return false;}
}
bool IBindingList.SupportsSorting
{
get {return false;}
}
object IBindingList.AddNew()
{
throw new NotSupportedException();
// TFile file = new TFile();
// List.Add(file);
// return file;
}
bool IBindingList.IsSorted
{
get { throw new NotSupportedException(); }
}
ListSortDirection IBindingList.SortDirection
{
get { throw new NotSupportedException(); }
}
PropertyDescriptor IBindingList.SortProperty
{
get { throw new NotSupportedException(); }
}
void IBindingList.AddIndex(PropertyDescriptor property)
{
throw new NotSupportedException();
}
void IBindingList.ApplySort(PropertyDescriptor property, ListSortDirection direction)
{
throw new NotSupportedException();
}
int IBindingList.Find(PropertyDescriptor property, object key)
{
throw new NotSupportedException();
}
void IBindingList.RemoveIndex(PropertyDescriptor property)
{
throw new NotSupportedException();
}
void IBindingList.RemoveSort()
{
throw new NotSupportedException();
}
#endregion
private int m_ExtractFileIndex = -1; // Target file index for extracting
private bool m_ExtractAll = false; // if true, extract all
public void ExtractAll()
{
m_ExtractAll = true;
m_ExtractFileIndex = 0;
PSP_FILE_CALLBACK callback = new PSP_FILE_CALLBACK(this.CallBack);
uint setupIterateCabinetAction = (uint)SetupIterateCabinetAction.Extract;
if (!SetupApiWrapper.SetupIterateCabinet(this.Name, 0, callback, setupIterateCabinetAction))
{
string errMsg = new Win32Exception((int)KernelApiWrapper.GetLastError()).Message;
System.Windows.Forms.MessageBox.Show(errMsg);
}
}
public void Extract(string sFile)
{
int intI = 0;
foreach(TFile file in this)
{
if (string.Compare(file.FullName, sFile, true)==0)
{
Extract(intI);
return;
}
intI++;
}
}
public void Extract(TFile file)
{
int intI = this.IndexOf(file);
Extract(intI);
}
public void Extract(int index)
{
m_ExtractAll = false;
m_ExtractFileIndex = index;
PSP_FILE_CALLBACK callback = new PSP_FILE_CALLBACK(this.CallBack);
uint setupIterateCabinetAction = (uint)SetupIterateCabinetAction.Extract;
if (!SetupApiWrapper.SetupIterateCabinet(this.Name, 0, callback, setupIterateCabinetAction))
{
string errMsg = new Win32Exception((int)KernelApiWrapper.GetLastError()).Message;
System.Windows.Forms.MessageBox.Show(errMsg);
}
}
private string MakeExtractFileName(TFile file)
{
string sFile = this.OutputDirectory;
if (!this.IgnoreInsidePath && file.Path.Length >0)
{
sFile += System.IO.Path.DirectorySeparatorChar.ToString() + file.Path;
if (!System.IO.Directory.Exists(sFile))
System.IO.Directory.CreateDirectory(sFile);
}
sFile += System.IO.Path.DirectorySeparatorChar.ToString() + file.Name;
sFile = sFile.Replace(@"\\", @"\");
return sFile;
}
}
/// <summary>
/// The FILE_IN_CABINET_INFO class provides information about a file found in the cabinet.
/// Platform SDK: Setup API
/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
public class FILE_IN_CABINET_INFO
{
public String NameInCabinet;
public uint FileSize;
public uint Win32Error;
public ushort DosDate;
public ushort DosTime;
public ushort DosAttribs;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=260)]
public System.String FullTargetName;
}
/// <summary>
/// The FILEPATHS structure stores source and target path information.
/// Platform SDK: Setup API
/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
public class FILEPATHS
{
public String Target;
public String Source;
public uint Win32Error;
public uint Flags;
}
/// <summary>
/// The FILETIME structure is a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (UTC).
/// Platform SDK: Windows System Information
/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
public class FILETIME
{
public uint dwLowDateTime;
public uint dwHighDateTime;
}
/// <summary>
/// The SYSTEMTIME structure represents a date and time using individual members for the month, day, year, weekday, hour, minute, second, and millisecond.
/// Platform SDK: Windows System Information
/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
public class SYSTEMTIME
{
public ushort wYear;
public ushort wMonth;
public ushort wDayOfWeek;
public ushort wDay;
public ushort wHour;
public ushort wMinute;
public ushort wSecond;
public ushort wMilliseconds;
}
public enum FILEOP:uint
{
FILEOP_ABORT=0, // Abort cabinet processing.
FILEOP_DOIT, // Extract the current file.
FILEOP_SKIP // Skip the current file.
}
public enum SetupIterateCabinetAction:uint
{
Iterate=0, Extract
}
/// <summary>
/// The FileCallback callback function is used by a number of the setup functions. The PSP_FILE_CALLBACK type defines a pointer to this callback function. FileCallback is a placeholder for the application-defined function name.
/// Platform SDK: Setup API
/// </summary>
public delegate uint PSP_FILE_CALLBACK(uint context, uint notification, IntPtr param1, IntPtr param2);
/// <summary>
/// SetupApi Wrapper class
/// Platform SDK: Setup API
/// </summary>
public class SetupApiWrapper
{
public const uint SPFILENOTIFY_FILEINCABINET = 0x00000011; // The file has been extracted from the cabinet.
public const uint SPFILENOTIFY_NEEDNEWCABINET = 0x00000012; // file is encountered in the cabinet.
public const uint SPFILENOTIFY_FILEEXTRACTED = 0x00000013; // The current file is continued in the next cabinet.
public const uint NO_ERROR = 0;
/// <summary>
/// The SetupIterateCabinet function iterates through all the files in a cabinet and sends a notification to a callback function for each file found.
/// Platform SDK: Setup API
/// </summary>
[DllImport("SetupApi.dll", CharSet=CharSet.Auto)]
public static extern bool SetupIterateCabinet(string cabinetFile, uint reserved, PSP_FILE_CALLBACK callBack, uint context);
}
public class KernelApiWrapper
{
[DllImport("Kernel32.dll", CharSet=CharSet.Auto)]
public static extern uint GetLastError();
}
public class DateTimeConvert
{
[DllImport("Kernel32.dll", CharSet=CharSet.Auto)]
public static extern uint GetLastError();
[DllImport("Kernel32.dll", CharSet=CharSet.Auto)]
public static extern bool DosDateTimeToFileTime (ushort wFatDate, ushort wFatTime, FILETIME lpFileTime );
[DllImport("Kernel32.dll", CharSet=CharSet.Auto)]
public static extern bool FileTimeToLocalFileTime (FILETIME lpFileTime, FILETIME lpLocalFileTime );
[DllImport("Kernel32.dll", CharSet=CharSet.Auto)]
public static extern bool FileTimeToSystemTime (FILETIME lpFileTime, SYSTEMTIME lpSystemTime );
}
public class TFile
{
public TFile(FILE_IN_CABINET_INFO fileInCabinetInfo)
{
this.Name = System.IO.Path.GetFileName(fileInCabinetInfo.NameInCabinet);
this.Path = System.IO.Path.GetDirectoryName(fileInCabinetInfo.NameInCabinet);
this.Size = fileInCabinetInfo.FileSize;
this.Date = GetDateTime(fileInCabinetInfo.DosDate, fileInCabinetInfo.DosTime);
}
public TFile()
{
throw new NotSupportedException();
}
/// <summary>
/// file name
/// </summary>
private string m_Name = "";
public string Name
{
get { return m_Name;}
set { m_Name = value;}
}
/// <summary>
/// last modifed time
/// </summary>
private System.DateTime m_Date;
public System.DateTime Date
{
get { return m_Date;}
set { m_Date = value;}
}
/// <summary>
/// size of file
/// </summary>
private uint m_Size = 0;
public uint Size
{
get { return m_Size;}
set { m_Size = value;}
}
/// <summary>
/// file path in cabinet
/// </summary>
private string m_Path = "";
public string Path
{
get { return m_Path;}
set { m_Path = value;}
}
/// <summary>
/// full path of file in cabinet
/// </summary>
public string FullName
{
get { return this.Path + System.IO.Path.DirectorySeparatorChar.ToString() + this.Name;}
}
public override string ToString()
{
return FullName;
}
public override int GetHashCode()
{
return (this.Size > int.MaxValue ? int.MaxValue : (int)this.Size );
}
public override bool Equals(object obj)
{
if (obj==null) return false;
if (this.GetType() != obj.GetType()) return false;
TFile other = (TFile)obj;
return ( string.Compare(this.Path, other.Path, true) == 0 && string.Compare(this.Name, other.Name, true)==0);
}
public static bool operator ==(TFile a, TFile b)
{
if ((object)a == null) return false;
return a.Equals(b);
}
public static bool operator !=(TFile a, TFile b)
{
return !(a==b);
}
private DateTime GetDateTime(ushort date, ushort time)
{
FILETIME lpFileTime = new FILETIME();
SYSTEMTIME lpSystemTime = new SYSTEMTIME();
DateTimeConvert.DosDateTimeToFileTime(date, time, lpFileTime);
DateTimeConvert.FileTimeToSystemTime(lpFileTime, lpSystemTime);
DateTime dateTime = new DateTime(lpSystemTime.wYear, lpSystemTime.wMonth, lpSystemTime.wDay,
lpSystemTime.wHour, lpSystemTime.wMinute, lpSystemTime.wSecond, lpSystemTime.wMilliseconds);
return dateTime;
}
}
}
| |
/*
* Location Intelligence APIs
*
* Incorporate our extensive geodata into everyday applications, business processes and workflows.
*
* OpenAPI spec version: 8.5.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace pb.locationIntelligence.Model
{
/// <summary>
/// TaxPlace
/// </summary>
[DataContract]
public partial class TaxPlace : IEquatable<TaxPlace>
{
/// <summary>
/// Initializes a new instance of the <see cref="TaxPlace" /> class.
/// </summary>
/// <param name="Name">Name.</param>
/// <param name="Code">Code.</param>
/// <param name="GnisCode">GnisCode.</param>
/// <param name="SelfCollected">SelfCollected.</param>
/// <param name="ClassCode">ClassCode.</param>
/// <param name="IncorporatedFlag">IncorporatedFlag.</param>
/// <param name="LastAnnexedDate">LastAnnexedDate.</param>
/// <param name="LastUpdatedDate">LastUpdatedDate.</param>
/// <param name="LastVerifiedDate">LastVerifiedDate.</param>
public TaxPlace(string Name = null, string Code = null, string GnisCode = null, bool? SelfCollected = null, string ClassCode = null, string IncorporatedFlag = null, string LastAnnexedDate = null, string LastUpdatedDate = null, string LastVerifiedDate = null)
{
this.Name = Name;
this.Code = Code;
this.GnisCode = GnisCode;
this.SelfCollected = SelfCollected;
this.ClassCode = ClassCode;
this.IncorporatedFlag = IncorporatedFlag;
this.LastAnnexedDate = LastAnnexedDate;
this.LastUpdatedDate = LastUpdatedDate;
this.LastVerifiedDate = LastVerifiedDate;
}
/// <summary>
/// Gets or Sets Name
/// </summary>
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
/// <summary>
/// Gets or Sets Code
/// </summary>
[DataMember(Name="code", EmitDefaultValue=false)]
public string Code { get; set; }
/// <summary>
/// Gets or Sets GnisCode
/// </summary>
[DataMember(Name="gnisCode", EmitDefaultValue=false)]
public string GnisCode { get; set; }
/// <summary>
/// Gets or Sets SelfCollected
/// </summary>
[DataMember(Name="selfCollected", EmitDefaultValue=false)]
public bool? SelfCollected { get; set; }
/// <summary>
/// Gets or Sets ClassCode
/// </summary>
[DataMember(Name="classCode", EmitDefaultValue=false)]
public string ClassCode { get; set; }
/// <summary>
/// Gets or Sets IncorporatedFlag
/// </summary>
[DataMember(Name="incorporatedFlag", EmitDefaultValue=false)]
public string IncorporatedFlag { get; set; }
/// <summary>
/// Gets or Sets LastAnnexedDate
/// </summary>
[DataMember(Name="lastAnnexedDate", EmitDefaultValue=false)]
public string LastAnnexedDate { get; set; }
/// <summary>
/// Gets or Sets LastUpdatedDate
/// </summary>
[DataMember(Name="lastUpdatedDate", EmitDefaultValue=false)]
public string LastUpdatedDate { get; set; }
/// <summary>
/// Gets or Sets LastVerifiedDate
/// </summary>
[DataMember(Name="lastVerifiedDate", EmitDefaultValue=false)]
public string LastVerifiedDate { 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 TaxPlace {\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" Code: ").Append(Code).Append("\n");
sb.Append(" GnisCode: ").Append(GnisCode).Append("\n");
sb.Append(" SelfCollected: ").Append(SelfCollected).Append("\n");
sb.Append(" ClassCode: ").Append(ClassCode).Append("\n");
sb.Append(" IncorporatedFlag: ").Append(IncorporatedFlag).Append("\n");
sb.Append(" LastAnnexedDate: ").Append(LastAnnexedDate).Append("\n");
sb.Append(" LastUpdatedDate: ").Append(LastUpdatedDate).Append("\n");
sb.Append(" LastVerifiedDate: ").Append(LastVerifiedDate).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 TaxPlace);
}
/// <summary>
/// Returns true if TaxPlace instances are equal
/// </summary>
/// <param name="other">Instance of TaxPlace to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(TaxPlace other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Name == other.Name ||
this.Name != null &&
this.Name.Equals(other.Name)
) &&
(
this.Code == other.Code ||
this.Code != null &&
this.Code.Equals(other.Code)
) &&
(
this.GnisCode == other.GnisCode ||
this.GnisCode != null &&
this.GnisCode.Equals(other.GnisCode)
) &&
(
this.SelfCollected == other.SelfCollected ||
this.SelfCollected != null &&
this.SelfCollected.Equals(other.SelfCollected)
) &&
(
this.ClassCode == other.ClassCode ||
this.ClassCode != null &&
this.ClassCode.Equals(other.ClassCode)
) &&
(
this.IncorporatedFlag == other.IncorporatedFlag ||
this.IncorporatedFlag != null &&
this.IncorporatedFlag.Equals(other.IncorporatedFlag)
) &&
(
this.LastAnnexedDate == other.LastAnnexedDate ||
this.LastAnnexedDate != null &&
this.LastAnnexedDate.Equals(other.LastAnnexedDate)
) &&
(
this.LastUpdatedDate == other.LastUpdatedDate ||
this.LastUpdatedDate != null &&
this.LastUpdatedDate.Equals(other.LastUpdatedDate)
) &&
(
this.LastVerifiedDate == other.LastVerifiedDate ||
this.LastVerifiedDate != null &&
this.LastVerifiedDate.Equals(other.LastVerifiedDate)
);
}
/// <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.Name != null)
hash = hash * 59 + this.Name.GetHashCode();
if (this.Code != null)
hash = hash * 59 + this.Code.GetHashCode();
if (this.GnisCode != null)
hash = hash * 59 + this.GnisCode.GetHashCode();
if (this.SelfCollected != null)
hash = hash * 59 + this.SelfCollected.GetHashCode();
if (this.ClassCode != null)
hash = hash * 59 + this.ClassCode.GetHashCode();
if (this.IncorporatedFlag != null)
hash = hash * 59 + this.IncorporatedFlag.GetHashCode();
if (this.LastAnnexedDate != null)
hash = hash * 59 + this.LastAnnexedDate.GetHashCode();
if (this.LastUpdatedDate != null)
hash = hash * 59 + this.LastUpdatedDate.GetHashCode();
if (this.LastVerifiedDate != null)
hash = hash * 59 + this.LastVerifiedDate.GetHashCode();
return hash;
}
}
}
}
| |
// StreamUtils.cs
//
// Copyright 2005 John Reilly
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
// 2010-08-13 Sky Sanders - Modified for Silverlight 3/4 and Windows Phone 7
using System;
using System.IO;
namespace ICSharpCode.SharpZipLib.Core
{
/// <summary>
/// Provides simple <see cref="Stream"/>" utilities.
/// </summary>
internal sealed class StreamUtils
{
/// <summary>
/// Read from a <see cref="Stream"/> ensuring all the required data is read.
/// </summary>
/// <param name="stream">The stream to read.</param>
/// <param name="buffer">The buffer to fill.</param>
/// <seealso cref="ReadFully(Stream,byte[],int,int)"/>
static public void ReadFully(Stream stream, byte[] buffer)
{
ReadFully(stream, buffer, 0, buffer.Length);
}
/// <summary>
/// Read from a <see cref="Stream"/>" ensuring all the required data is read.
/// </summary>
/// <param name="stream">The stream to read data from.</param>
/// <param name="buffer">The buffer to store data in.</param>
/// <param name="offset">The offset at which to begin storing data.</param>
/// <param name="count">The number of bytes of data to store.</param>
/// <exception cref="ArgumentNullException">Required parameter is null</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="offset"/> and or <paramref name="count"/> are invalid.</exception>
/// <exception cref="EndOfStreamException">End of stream is encountered before all the data has been read.</exception>
static public void ReadFully(Stream stream, byte[] buffer, int offset, int count)
{
if ( stream == null ) {
throw new ArgumentNullException("stream");
}
if ( buffer == null ) {
throw new ArgumentNullException("buffer");
}
// Offset can equal length when buffer and count are 0.
if ( (offset < 0) || (offset > buffer.Length) ) {
throw new ArgumentOutOfRangeException("offset");
}
if ( (count < 0) || (offset + count > buffer.Length) ) {
throw new ArgumentOutOfRangeException("count");
}
while ( count > 0 ) {
int readCount = stream.Read(buffer, offset, count);
if ( readCount <= 0 ) {
throw new EndOfStreamException();
}
offset += readCount;
count -= readCount;
}
}
/// <summary>
/// Copy the contents of one <see cref="Stream"/> to another.
/// </summary>
/// <param name="source">The stream to source data from.</param>
/// <param name="destination">The stream to write data to.</param>
/// <param name="buffer">The buffer to use during copying.</param>
static public void Copy(Stream source, Stream destination, byte[] buffer)
{
if (source == null) {
throw new ArgumentNullException("source");
}
if (destination == null) {
throw new ArgumentNullException("destination");
}
if (buffer == null) {
throw new ArgumentNullException("buffer");
}
// Ensure a reasonable size of buffer is used without being prohibitive.
if (buffer.Length < 128) {
throw new ArgumentException("Buffer is too small", "buffer");
}
bool copying = true;
while (copying) {
int bytesRead = source.Read(buffer, 0, buffer.Length);
if (bytesRead > 0) {
destination.Write(buffer, 0, bytesRead);
}
else {
destination.Flush();
copying = false;
}
}
}
/// <summary>
/// Copy the contents of one <see cref="Stream"/> to another.
/// </summary>
/// <param name="source">The stream to source data from.</param>
/// <param name="destination">The stream to write data to.</param>
/// <param name="buffer">The buffer to use during copying.</param>
/// <param name="progressHandler">The <see cref="ProgressHandler">progress handler delegate</see> to use.</param>
/// <param name="updateInterval">The minimum <see cref="TimeSpan"/> between progress updates.</param>
/// <param name="sender">The source for this event.</param>
/// <param name="name">The name to use with the event.</param>
/// <remarks>This form is specialised for use within #Zip to support events during archive operations.</remarks>
static public void Copy(Stream source, Stream destination,
byte[] buffer, ProgressHandler progressHandler, TimeSpan updateInterval, object sender, string name)
{
Copy(source, destination, buffer, progressHandler, updateInterval, sender, name, -1);
}
/// <summary>
/// Copy the contents of one <see cref="Stream"/> to another.
/// </summary>
/// <param name="source">The stream to source data from.</param>
/// <param name="destination">The stream to write data to.</param>
/// <param name="buffer">The buffer to use during copying.</param>
/// <param name="progressHandler">The <see cref="ProgressHandler">progress handler delegate</see> to use.</param>
/// <param name="updateInterval">The minimum <see cref="TimeSpan"/> between progress updates.</param>
/// <param name="sender">The source for this event.</param>
/// <param name="name">The name to use with the event.</param>
/// <param name="fixedTarget">A predetermined fixed target value to use with progress updates.
/// If the value is negative the target is calculated by looking at the stream.</param>
/// <remarks>This form is specialised for use within #Zip to support events during archive operations.</remarks>
static public void Copy(Stream source, Stream destination,
byte[] buffer,
ProgressHandler progressHandler, TimeSpan updateInterval,
object sender, string name, long fixedTarget)
{
if (source == null) {
throw new ArgumentNullException("source");
}
if (destination == null) {
throw new ArgumentNullException("destination");
}
if (buffer == null) {
throw new ArgumentNullException("buffer");
}
// Ensure a reasonable size of buffer is used without being prohibitive.
if (buffer.Length < 128) {
throw new ArgumentException("Buffer is too small", "buffer");
}
if (progressHandler == null) {
throw new ArgumentNullException("progressHandler");
}
bool copying = true;
DateTime marker = DateTime.Now;
long processed = 0;
long target = 0;
if (fixedTarget >= 0) {
target = fixedTarget;
}
else if (source.CanSeek) {
target = source.Length - source.Position;
}
// Always fire 0% progress..
ProgressEventArgs args = new ProgressEventArgs(name, processed, target);
progressHandler(sender, args);
bool progressFired = true;
while (copying) {
int bytesRead = source.Read(buffer, 0, buffer.Length);
if (bytesRead > 0) {
processed += bytesRead;
progressFired = false;
destination.Write(buffer, 0, bytesRead);
}
else {
destination.Flush();
copying = false;
}
if (DateTime.Now - marker > updateInterval) {
progressFired = true;
marker = DateTime.Now;
args = new ProgressEventArgs(name, processed, target);
progressHandler(sender, args);
copying = args.ContinueRunning;
}
}
if (!progressFired) {
args = new ProgressEventArgs(name, processed, target);
progressHandler(sender, args);
}
}
/// <summary>
/// Initialise an instance of <see cref="StreamUtils"></see>
/// </summary>
private StreamUtils()
{
// Do nothing.
}
}
}
| |
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 ConAgendaBloqueo class.
/// </summary>
[Serializable]
public partial class ConAgendaBloqueoCollection : ActiveList<ConAgendaBloqueo, ConAgendaBloqueoCollection>
{
public ConAgendaBloqueoCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>ConAgendaBloqueoCollection</returns>
public ConAgendaBloqueoCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
ConAgendaBloqueo 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 CON_AgendaBloqueo table.
/// </summary>
[Serializable]
public partial class ConAgendaBloqueo : ActiveRecord<ConAgendaBloqueo>, IActiveRecord
{
#region .ctors and Default Settings
public ConAgendaBloqueo()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public ConAgendaBloqueo(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public ConAgendaBloqueo(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public ConAgendaBloqueo(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("CON_AgendaBloqueo", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdBloqueo = new TableSchema.TableColumn(schema);
colvarIdBloqueo.ColumnName = "idBloqueo";
colvarIdBloqueo.DataType = DbType.Int32;
colvarIdBloqueo.MaxLength = 0;
colvarIdBloqueo.AutoIncrement = true;
colvarIdBloqueo.IsNullable = false;
colvarIdBloqueo.IsPrimaryKey = true;
colvarIdBloqueo.IsForeignKey = false;
colvarIdBloqueo.IsReadOnly = false;
colvarIdBloqueo.DefaultSetting = @"";
colvarIdBloqueo.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdBloqueo);
TableSchema.TableColumn colvarIdAgenda = new TableSchema.TableColumn(schema);
colvarIdAgenda.ColumnName = "idAgenda";
colvarIdAgenda.DataType = DbType.Int32;
colvarIdAgenda.MaxLength = 0;
colvarIdAgenda.AutoIncrement = false;
colvarIdAgenda.IsNullable = false;
colvarIdAgenda.IsPrimaryKey = false;
colvarIdAgenda.IsForeignKey = true;
colvarIdAgenda.IsReadOnly = false;
colvarIdAgenda.DefaultSetting = @"";
colvarIdAgenda.ForeignKeyTableName = "CON_Agenda";
schema.Columns.Add(colvarIdAgenda);
TableSchema.TableColumn colvarIdUsuario = new TableSchema.TableColumn(schema);
colvarIdUsuario.ColumnName = "idUsuario";
colvarIdUsuario.DataType = DbType.Int32;
colvarIdUsuario.MaxLength = 0;
colvarIdUsuario.AutoIncrement = false;
colvarIdUsuario.IsNullable = false;
colvarIdUsuario.IsPrimaryKey = false;
colvarIdUsuario.IsForeignKey = false;
colvarIdUsuario.IsReadOnly = false;
colvarIdUsuario.DefaultSetting = @"";
colvarIdUsuario.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdUsuario);
TableSchema.TableColumn colvarFechaActivacion = new TableSchema.TableColumn(schema);
colvarFechaActivacion.ColumnName = "fechaActivacion";
colvarFechaActivacion.DataType = DbType.DateTime;
colvarFechaActivacion.MaxLength = 0;
colvarFechaActivacion.AutoIncrement = false;
colvarFechaActivacion.IsNullable = false;
colvarFechaActivacion.IsPrimaryKey = false;
colvarFechaActivacion.IsForeignKey = false;
colvarFechaActivacion.IsReadOnly = false;
colvarFechaActivacion.DefaultSetting = @"";
colvarFechaActivacion.ForeignKeyTableName = "";
schema.Columns.Add(colvarFechaActivacion);
TableSchema.TableColumn colvarAgendaActivada = new TableSchema.TableColumn(schema);
colvarAgendaActivada.ColumnName = "agendaActivada";
colvarAgendaActivada.DataType = DbType.Boolean;
colvarAgendaActivada.MaxLength = 0;
colvarAgendaActivada.AutoIncrement = false;
colvarAgendaActivada.IsNullable = false;
colvarAgendaActivada.IsPrimaryKey = false;
colvarAgendaActivada.IsForeignKey = false;
colvarAgendaActivada.IsReadOnly = false;
colvarAgendaActivada.DefaultSetting = @"((0))";
colvarAgendaActivada.ForeignKeyTableName = "";
schema.Columns.Add(colvarAgendaActivada);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("CON_AgendaBloqueo",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdBloqueo")]
[Bindable(true)]
public int IdBloqueo
{
get { return GetColumnValue<int>(Columns.IdBloqueo); }
set { SetColumnValue(Columns.IdBloqueo, value); }
}
[XmlAttribute("IdAgenda")]
[Bindable(true)]
public int IdAgenda
{
get { return GetColumnValue<int>(Columns.IdAgenda); }
set { SetColumnValue(Columns.IdAgenda, value); }
}
[XmlAttribute("IdUsuario")]
[Bindable(true)]
public int IdUsuario
{
get { return GetColumnValue<int>(Columns.IdUsuario); }
set { SetColumnValue(Columns.IdUsuario, value); }
}
[XmlAttribute("FechaActivacion")]
[Bindable(true)]
public DateTime FechaActivacion
{
get { return GetColumnValue<DateTime>(Columns.FechaActivacion); }
set { SetColumnValue(Columns.FechaActivacion, value); }
}
[XmlAttribute("AgendaActivada")]
[Bindable(true)]
public bool AgendaActivada
{
get { return GetColumnValue<bool>(Columns.AgendaActivada); }
set { SetColumnValue(Columns.AgendaActivada, value); }
}
#endregion
#region ForeignKey Properties
/// <summary>
/// Returns a ConAgenda ActiveRecord object related to this ConAgendaBloqueo
///
/// </summary>
public DalSic.ConAgenda ConAgenda
{
get { return DalSic.ConAgenda.FetchByID(this.IdAgenda); }
set { SetColumnValue("idAgenda", value.IdAgenda); }
}
#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 varIdAgenda,int varIdUsuario,DateTime varFechaActivacion,bool varAgendaActivada)
{
ConAgendaBloqueo item = new ConAgendaBloqueo();
item.IdAgenda = varIdAgenda;
item.IdUsuario = varIdUsuario;
item.FechaActivacion = varFechaActivacion;
item.AgendaActivada = varAgendaActivada;
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 varIdBloqueo,int varIdAgenda,int varIdUsuario,DateTime varFechaActivacion,bool varAgendaActivada)
{
ConAgendaBloqueo item = new ConAgendaBloqueo();
item.IdBloqueo = varIdBloqueo;
item.IdAgenda = varIdAgenda;
item.IdUsuario = varIdUsuario;
item.FechaActivacion = varFechaActivacion;
item.AgendaActivada = varAgendaActivada;
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 IdBloqueoColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn IdAgendaColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn IdUsuarioColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn FechaActivacionColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn AgendaActivadaColumn
{
get { return Schema.Columns[4]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdBloqueo = @"idBloqueo";
public static string IdAgenda = @"idAgenda";
public static string IdUsuario = @"idUsuario";
public static string FechaActivacion = @"fechaActivacion";
public static string AgendaActivada = @"agendaActivada";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.